<commit_before>"use strict";
/* -*- js-indent-level: 8 -*- */
/* jshint -W097, -W040 */
/*
 * 	@author Tapani Jamsa
 */
/* global window, THREE, console,
   Player, Ammo, keyboard */

function PlayerArea(position, rotation, id, racketGeometry) {
	// Pointers to globals
	this.p2pCtrl = p2pCtrl;
	this.sceneCtrl = sceneCtrl;
	this.touchController = touchController;
	this.keyboard = keyboard;

	// PLAYER INFO
	if (this.p2pCtrl.netRole && p2pCtrl.playerArray[id]) {
		// online
		this.player = p2pCtrl.playerArray[id];
	} else {
		// offline
		var randomColor = this.sceneCtrl.getRandomColor();
		this.player = new Player(id, id, randomColor);
	}

	// PLAYER AREA
	this.id = id;

	this.group = new THREE.Object3D(); //create an empty container

	this.group.rotation.y = rotation;
	this.group.position = position;

	this.rotation = rotation;

	this.bottomTopWidth = this.sceneCtrl.playerAreaWidth;
	this.bottomTopHeight = 10;
	this.bottomTopGeometry = new THREE.CubeGeometry(this.bottomTopWidth, this.bottomTopHeight, this.bottomTopHeight, 1, 1, 1);
	this.leftWidth = 120;
	this.leftHeight = 10;
	this.leftGeometry = new THREE.CubeGeometry(this.leftWidth, this.bottomTopHeight, this.bottomTopHeight, 1, 1, 1);

	this.material = new THREE.MeshLambertMaterial({
		color: this.player.color
	});

	// BORDER BOTTOM
	// Create mesh
	this.borderBottom = new THREE.Mesh(this.bottomTopGeometry, this.material);
	this.borderBottom.position.set(41.73959, 0, 55);
	this.borderBottom.rotation.y = 180 * (Math.PI / 180);
	this.borderBottom.name = "bottom";
	this.borderBottom.type = "box";

	// Create a physics model
	this.createPhysicsModel(this.bottomTopWidth, this.bottomTopHeight, this.borderBottom, false);

	// BORDER LEFT
	this.borderLeft = new THREE.Mesh(this.leftGeometry, this.material);
	this.borderLeft.position.set(96.05561, 0, 0);
	this.borderLeft.rotation.y = 270 * (Math.PI / 180);
	this.borderLeft.name = "left";
	this.borderLeft.type = "box";
	this.borderLeft.parentNode = this;

	// Create a physics model
	this.createPhysicsModel(this.leftWidth, this.leftHeight, this.borderLeft, false);
	// set it as ghost object
	this.borderLeft.collider.setCollisionFlags(4);

	// BORDER TOP
	this.borderTop = new THREE.Mesh(this.bottomTopGeometry, this.material);
	this.borderTop.position.set(41.73959, 0, -55);
	this.borderTop.rotation.y = 360 * (Math.PI / 180);
	this.borderTop.name = "top";
	this.borderTop.type = "box";

	// Create a physics model
	this.createPhysicsModel(this.bottomTopWidth, this.bottomTopHeight, this.borderTop, false);

	// PLAYER RACKET
	this.racketWidth = 30;
	this.racketHeight = 20;
	this.racketMesh = new THREE.Mesh(racketGeometry, this.material);
	this.racketMesh.position.set(76, 0, 4);
	this.racketMesh.rotation.y = 180 * (Math.PI / 180);
	this.racketMesh.name = "racket";
	this.racketMesh.type = "box";

	// Create a physics model
	this.racketSpeed = 80;
	this.racketTopStop = this.borderTop.position.z + (this.racketWidth / 2);
	this.racketBottomStop = this.borderBottom.position.z - (this.racketWidth / 2);
	this.createPhysicsModel(this.racketWidth, this.racketHeight, this.racketMesh, true);

	// GROUP
	this.groupMeshes = [];
	this.groupMeshes.push(this.borderBottom);
	this.groupMeshes.push(this.borderLeft);
	this.groupMeshes.push(this.borderTop);

	// CAMERA POSITION (for the server. client camera.lookAt in pong.js)
	if (this.p2pCtrl.netRole && this.p2pCtrl.playerArray[id] && this.p2pCtrl.serverID == this.player.id) {
		var worldPos = new THREE.Vector3();
		worldPos.getPositionFromMatrix(this.borderLeft.matrixWorld);
		// console.log("set camera position");
		// console.log("position.x: " + worldPos.x);
		// console.log("position.z: " + worldPos.z);
		this.sceneCtrl.camera.position.x = worldPos.x;
		this.sceneCtrl.camera.position.z = worldPos.z;
		this.sceneCtrl.camera.lookAt(position);
	}
}

PlayerArea.prototype.createPhysicsModel = function(width, height, mesh, racket) {
	var mass = width * height * height;
	var localInertia = new Ammo.btVector3(0, 0, 0);
	var w = width / 2;
	var h = height / 2;

	var shape = null;
	if (racket) {
		var point, shape = new Ammo.btConvexHullShape;
		for (var i = 0; i < mesh.geometry.vertices.length; i++) {
			point = mesh.geometry.vertices[i];

			shape.addPoint(new Ammo.btVector3(point.x, point.y, point.z));
		}
	} else {
		shape = new Ammo.btBoxShape(new Ammo.btVector3(w, h, h));
	}
	shape.calculateLocalInertia(mass, localInertia);

	// Local to world pos
	this.group.add(mesh);
	this.group.updateMatrixWorld();
	var worldPos = new THREE.Vector3();
	worldPos.getPositionFromMatrix(mesh.matrixWorld);
	var startTransform = new Ammo.btTransform();
	startTransform.setIdentity();
	startTransform.setOrigin(new Ammo.btVector3(worldPos.x, 0, worldPos.z));

	// Set rotation
	var worldRot = mesh.rotation.y + this.group.rotation.y;
	var quat = new Ammo.btQuaternion();
	quat.setEuler(worldRot, 0, 0); //or quat.setEulerZYX depending on the ordering you want
	startTransform.setRotation(quat);

	// Create collision object
	var boxAmmo = new Ammo.btCollisionObject();
	boxAmmo.setWorldTransform(startTransform);
	boxAmmo.setCollisionShape(shape);
	this.sceneCtrl.btWorld.addCollisionObject(boxAmmo);
	boxAmmo.mesh = mesh;
	boxAmmo.setRestitution(1);
	boxAmmo.setFriction(0);
	mesh.collider = boxAmmo;
};

// ONLINE game mode
PlayerArea.prototype.serverUpdate = function(delta, clientKeyboard, clientTouch, playerID, i) {
	var lastPosition = this.racketMesh.position.clone();

	function checkPressed(scope, keyname, serverID, areaPlayerID) {
		if (keyname === null)
			return false;
		if (serverID == areaPlayerID) {
			return scope.keyboard.pressed(keyname);
		} else if (playerID == areaPlayerID) {
			return clientKeyboard.indexOf(keyname) != -1;
		}
		return false;
	}

	function checkTouch(scope, serverID, areaPlayerID) {
		if (serverID == areaPlayerID) {
			return scope.touchController.deltaPosition.x * scope.touchController.swipeSpeed;
		} else if (playerID == areaPlayerID) {
			return clientTouch;
		}
		return false;
	}

	// Racket controls
	var left_key = 'left',
		right_key = 'right';

	var racketForward = new THREE.Vector3();

	var rotation = this.racketMesh.rotation.y + (90 * (Math.PI / 180));

	// Angle to vector3
	racketForward.x = Math.cos(rotation * -1);
	racketForward.z = Math.sin(rotation * -1);

	racketForward.normalize();

	// Racket's speed
	racketForward.multiplyScalar(this.racketSpeed * delta);

	if (checkPressed(this, left_key, this.p2pCtrl.serverID, this.player.id)) {
		this.racketMesh.position.add(racketForward);
	} else if (checkPressed(this, right_key, this.p2pCtrl.serverID, this.player.id)) {
		this.racketMesh.position.sub(racketForward);
	}
	// Touch / Mouse
	else {
		var touchSpeedModifier = checkTouch(this, this.p2pCtrl.serverID, this.player.id);
		if (touchSpeedModifier !== 0) {
			racketForward.multiplyScalar(touchSpeedModifier);

			this.racketMesh.position.add(racketForward);
		}
	}

	// Local to world position
	var worldPos = new THREE.Vector3();
	worldPos.getPositionFromMatrix(this.racketMesh.matrixWorld);
	var transform = this.racketMesh.collider.getWorldTransform();
	transform.setOrigin(new Ammo.btVector3(worldPos.x, 0, worldPos.z));
	this.racketMesh.collider.setWorldTransform(transform);

	if (this.racketMesh.position.z < this.racketTopStop || this.racketMesh.position.z > this.racketBottomStop) {
		this.racketMesh.position = lastPosition;
	}
};

// ONLINE game mode
PlayerArea.prototype.clientUpdate = function(msg) {
	var newpos = msg.racketspos[this.id];
	if (newpos !== undefined)
		this.racketMesh.position = newpos;
	else
		console.log("undefined position for racket");
};

// OFFLINE game mode
PlayerArea.prototype.offlineUpdate = function(delta) {

	var lastPosition = this.racketMesh.position.clone();

	// Racket controls
	if (this.keyboard.pressed("left") || this.keyboard.pressed("right") || this.keyboard.pressed("a") || this.keyboard.pressed("d") || (this.touchController.swiping && delta.x !== 0)) {
		var racketForward = new THREE.Vector3();

		var rotation = this.racketMesh.rotation.y + (90 * (Math.PI / 180));

		// Angle to vector3
		racketForward.x = Math.cos(rotation * -1);
		racketForward.z = Math.sin(rotation * -1);

		racketForward.normalize();

		// Racket's speed
		if (this.touchController.swiping) {
			// Touch / Mouse
			racketForward.multiplyScalar(this.racketSpeed * this.touchController.deltaPosition.x * this.touchController.swipeSpeed * delta);
		} else {
			// Keyboard
			racketForward.multiplyScalar(this.racketSpeed * delta);
		}

		// Keyboard
		if (this.player.id == 1) {
			if (this.keyboard.pressed("left")) {
				this.racketMesh.position.add(racketForward);
			}
			if (this.keyboard.pressed("right")) {
				this.racketMesh.position.sub(racketForward);
			}

			// Touch
			if (this.touchController.swiping) {
				this.racketMesh.position.add(racketForward);
			}
		} else {
			if (this.keyboard.pressed("a")) {
				this.racketMesh.position.add(racketForward);
			}
			if (this.keyboard.pressed("d")) {
				this.racketMesh.position.sub(racketForward);
			}
		}

		// Local to world position
		var worldPos = new THREE.Vector3();
		worldPos.getPositionFromMatrix(this.racketMesh.matrixWorld);
		var transform = this.racketMesh.collider.getWorldTransform();
		transform.setOrigin(new Ammo.btVector3(worldPos.x, 0, worldPos.z));
		this.racketMesh.collider.setWorldTransform(transform);

		if (this.racketMesh.position.z < this.racketTopStop || this.racketMesh.position.z > this.racketBottomStop) {
			this.racketMesh.position = lastPosition;
		}
	}

};<commit_msg>Clean<commit_after>"use strict";
/* -*- js-indent-level: 8 -*- */
/* jshint -W097, -W040 */
/*
 *	@author Tapani Jamsa
 */
/* global window, THREE, console,
   Player, Ammo, keyboard */

function PlayerArea(position, rotation, id, racketGeometry) {
	// Pointers to globals
	this.p2pCtrl = p2pCtrl;
	this.sceneCtrl = sceneCtrl;
	this.touchController = touchController;
	this.keyboard = keyboard;

	// PLAYER INFO
	if (this.p2pCtrl.netRole && p2pCtrl.playerArray[id]) {
		// online
		this.player = p2pCtrl.playerArray[id];
	} else {
		// offline
		var randomColor = this.sceneCtrl.getRandomColor();
		this.player = new Player(id, id, randomColor);
	}

	// PLAYER AREA
	this.id = id;

	this.group = new THREE.Object3D(); //create an empty container

	this.group.rotation.y = rotation;
	this.group.position = position;

	this.rotation = rotation;

	this.bottomTopWidth = this.sceneCtrl.playerAreaWidth;
	this.bottomTopHeight = 10;
	this.bottomTopGeometry = new THREE.CubeGeometry(this.bottomTopWidth, this.bottomTopHeight, this.bottomTopHeight, 1, 1, 1);
	this.leftWidth = 120;
	this.leftHeight = 10;
	this.leftGeometry = new THREE.CubeGeometry(this.leftWidth, this.bottomTopHeight, this.bottomTopHeight, 1, 1, 1);

	this.material = new THREE.MeshLambertMaterial({
		color: this.player.color
	});

	// BORDER BOTTOM
	// Create mesh
	this.borderBottom = new THREE.Mesh(this.bottomTopGeometry, this.material);
	this.borderBottom.position.set(41.73959, 0, 55);
	this.borderBottom.rotation.y = 180 * (Math.PI / 180);
	this.borderBottom.name = "bottom";
	this.borderBottom.type = "box";

	// Create a physics model
	this.createPhysicsModel(this.bottomTopWidth, this.bottomTopHeight, this.borderBottom, false);

	// BORDER LEFT
	this.borderLeft = new THREE.Mesh(this.leftGeometry, this.material);
	this.borderLeft.position.set(96.05561, 0, 0);
	this.borderLeft.rotation.y = 270 * (Math.PI / 180);
	this.borderLeft.name = "left";
	this.borderLeft.type = "box";
	this.borderLeft.parentNode = this;

	// Create a physics model
	this.createPhysicsModel(this.leftWidth, this.leftHeight, this.borderLeft, false);
	// set it as ghost object
	this.borderLeft.collider.setCollisionFlags(4);

	// BORDER TOP
	this.borderTop = new THREE.Mesh(this.bottomTopGeometry, this.material);
	this.borderTop.position.set(41.73959, 0, -55);
	this.borderTop.rotation.y = 360 * (Math.PI / 180);
	this.borderTop.name = "top";
	this.borderTop.type = "box";

	// Create a physics model
	this.createPhysicsModel(this.bottomTopWidth, this.bottomTopHeight, this.borderTop, false);

	// PLAYER RACKET
	this.racketWidth = 30;
	this.racketHeight = 20;
	this.racketMesh = new THREE.Mesh(racketGeometry, this.material);
	this.racketMesh.position.set(76, 0, 4);
	this.racketMesh.rotation.y = 180 * (Math.PI / 180);
	this.racketMesh.name = "racket";
	this.racketMesh.type = "box";

	// Create a physics model
	this.racketSpeed = 80;
	this.racketTopStop = this.borderTop.position.z + (this.racketWidth / 2);
	this.racketBottomStop = this.borderBottom.position.z - (this.racketWidth / 2);
	this.createPhysicsModel(this.racketWidth, this.racketHeight, this.racketMesh, true);

	// GROUP
	this.groupMeshes = [];
	this.groupMeshes.push(this.borderBottom);
	this.groupMeshes.push(this.borderLeft);
	this.groupMeshes.push(this.borderTop);

	// CAMERA POSITION (for the server. client camera.lookAt in pong.js)
	if (this.p2pCtrl.netRole && this.p2pCtrl.playerArray[id] && this.p2pCtrl.serverID == this.player.id) {
		var worldPos = new THREE.Vector3();
		worldPos.getPositionFromMatrix(this.borderLeft.matrixWorld);
		this.sceneCtrl.camera.position.x = worldPos.x;
		this.sceneCtrl.camera.position.z = worldPos.z;
		this.sceneCtrl.camera.lookAt(position);
	}
}

PlayerArea.prototype.createPhysicsModel = function(width, height, mesh, racket) {
	var mass = width * height * height;
	var localInertia = new Ammo.btVector3(0, 0, 0);
	var w = width / 2;
	var h = height / 2;

	var shape = null;
	if (racket) {
		shape = new Ammo.btConvexHullShape();
		for (var i = 0; i < mesh.geometry.vertices.length; i++) {
			var point = mesh.geometry.vertices[i];

			shape.addPoint(new Ammo.btVector3(point.x, point.y, point.z));
		}
	} else {
		shape = new Ammo.btBoxShape(new Ammo.btVector3(w, h, h));
	}
	shape.calculateLocalInertia(mass, localInertia);

	// Local to world pos
	this.group.add(mesh);
	this.group.updateMatrixWorld();
	var worldPos = new THREE.Vector3();
	worldPos.getPositionFromMatrix(mesh.matrixWorld);
	var startTransform = new Ammo.btTransform();
	startTransform.setIdentity();
	startTransform.setOrigin(new Ammo.btVector3(worldPos.x, 0, worldPos.z));

	// Set rotation
	var worldRot = mesh.rotation.y + this.group.rotation.y;
	var quat = new Ammo.btQuaternion();
	quat.setEuler(worldRot, 0, 0); //or quat.setEulerZYX depending on the ordering you want
	startTransform.setRotation(quat);

	// Create a collision object
	var collisionObject = new Ammo.btCollisionObject();
	collisionObject.setWorldTransform(startTransform);
	collisionObject.setCollisionShape(shape);
	this.sceneCtrl.btWorld.addCollisionObject(collisionObject);
	collisionObject.mesh = mesh;
	collisionObject.setRestitution(1);
	collisionObject.setFriction(0);
	mesh.collider = collisionObject;
};

// ONLINE game mode
PlayerArea.prototype.serverUpdate = function(delta, clientKeyboard, clientTouch, playerID, i) {
	var lastPosition = this.racketMesh.position.clone();

	function checkPressed(scope, keyname, serverID, areaPlayerID) {
		if (keyname === null)
			return false;
		if (serverID == areaPlayerID) {
			return scope.keyboard.pressed(keyname);
		} else if (playerID == areaPlayerID) {
			return clientKeyboard.indexOf(keyname) != -1;
		}
		return false;
	}

	function checkTouch(scope, serverID, areaPlayerID) {
		if (serverID == areaPlayerID) {
			return scope.touchController.deltaPosition.x * scope.touchController.swipeSpeed;
		} else if (playerID == areaPlayerID) {
			return clientTouch;
		}
		return false;
	}

	// Racket controls
	var left_key = 'left',
		right_key = 'right';

	var racketForward = new THREE.Vector3();

	var rotation = this.racketMesh.rotation.y + (90 * (Math.PI / 180));

	// Angle to vector3
	racketForward.x = Math.cos(rotation * -1);
	racketForward.z = Math.sin(rotation * -1);

	racketForward.normalize();

	// Racket's speed
	racketForward.multiplyScalar(this.racketSpeed * delta);

	if (checkPressed(this, left_key, this.p2pCtrl.serverID, this.player.id)) {
		this.racketMesh.position.add(racketForward);
	} else if (checkPressed(this, right_key, this.p2pCtrl.serverID, this.player.id)) {
		this.racketMesh.position.sub(racketForward);
	}
	// Touch / Mouse
	else {
		var touchSpeedModifier = checkTouch(this, this.p2pCtrl.serverID, this.player.id);
		if (touchSpeedModifier !== 0) {
			racketForward.multiplyScalar(touchSpeedModifier);

			this.racketMesh.position.add(racketForward);
		}
	}

	// Local to world position
	var worldPos = new THREE.Vector3();
	worldPos.getPositionFromMatrix(this.racketMesh.matrixWorld);
	var transform = this.racketMesh.collider.getWorldTransform();
	transform.setOrigin(new Ammo.btVector3(worldPos.x, 0, worldPos.z));
	this.racketMesh.collider.setWorldTransform(transform);

	if (this.racketMesh.position.z < this.racketTopStop || this.racketMesh.position.z > this.racketBottomStop) {
		this.racketMesh.position = lastPosition;
	}
};

// ONLINE game mode
PlayerArea.prototype.clientUpdate = function(msg) {
	var newpos = msg.racketspos[this.id];
	if (newpos !== undefined)
		this.racketMesh.position = newpos;
	else
		console.log("undefined position for racket");
};

// OFFLINE game mode
PlayerArea.prototype.offlineUpdate = function(delta) {

	var lastPosition = this.racketMesh.position.clone();

	// Racket controls
	if (this.keyboard.pressed("left") || this.keyboard.pressed("right") || this.keyboard.pressed("a") || this.keyboard.pressed("d") || (this.touchController.swiping && delta.x !== 0)) {
		var racketForward = new THREE.Vector3();

		var rotation = this.racketMesh.rotation.y + (90 * (Math.PI / 180));

		// Angle to vector3
		racketForward.x = Math.cos(rotation * -1);
		racketForward.z = Math.sin(rotation * -1);

		racketForward.normalize();

		// Racket's speed
		if (this.touchController.swiping) {
			// Touch / Mouse
			racketForward.multiplyScalar(this.racketSpeed * this.touchController.deltaPosition.x * this.touchController.swipeSpeed * delta);
		} else {
			// Keyboard
			racketForward.multiplyScalar(this.racketSpeed * delta);
		}

		// Keyboard
		if (this.player.id == 1) {
			if (this.keyboard.pressed("left")) {
				this.racketMesh.position.add(racketForward);
			}
			if (this.keyboard.pressed("right")) {
				this.racketMesh.position.sub(racketForward);
			}

			// Touch
			if (this.touchController.swiping) {
				this.racketMesh.position.add(racketForward);
			}
		} else {
			if (this.keyboard.pressed("a")) {
				this.racketMesh.position.add(racketForward);
			}
			if (this.keyboard.pressed("d")) {
				this.racketMesh.position.sub(racketForward);
			}
		}

		// Local to world position
		var worldPos = new THREE.Vector3();
		worldPos.getPositionFromMatrix(this.racketMesh.matrixWorld);
		var transform = this.racketMesh.collider.getWorldTransform();
		transform.setOrigin(new Ammo.btVector3(worldPos.x, 0, worldPos.z));
		this.racketMesh.collider.setWorldTransform(transform);

		if (this.racketMesh.position.z < this.racketTopStop || this.racketMesh.position.z > this.racketBottomStop) {
			this.racketMesh.position = lastPosition;
		}
	}

};<|endoftext|>


<commit_before>#!/usr/bin/env node
import '../../server/env';

import { assign, get, isArray, orderBy, pick } from 'lodash';

import models from '../../server/models';
import logger from '../../server/lib/logger';
import * as github from '../../server/lib/github';

const { Collective } = models;

// TODO: As number of collectives grow, we need to consider fetching 100 at a time,
// otherwise, we end up fetching a lot of data.
// Note: Picking attributes doesn't work with Histories table because Histories
// ends up recording on the attributes that were pulled out

const noContentToArray = value => (isArray(value) ? value : []);

const sortObjectByValue = obj => {
  const sortable = [];
  for (const key in obj) {
    sortable.push([key, obj[key]]);
  }

  sortable.sort((a, b) => {
    return a[1] > b[1] ? -1 : a[1] < b[1] ? 1 : 0;
  });

  const orderedList = {};
  for (let i = 0; i < sortable.length; i++) {
    orderedList[sortable[i][0]] = sortable[i][1];
  }

  return orderedList;
};

const getAllContributors = async repo => {
  const octokit = github.getOctokit();

  const fetchParameters = { page: 1, per_page: 100 };

  let repos = [];
  let fetchContributors;
  do {
    // https://octokit.github.io/rest.js/#api-Repos-listContributors
    // https://developer.github.com/v3/repos/#list-contributors
    fetchContributors = await octokit.repos
      .listContributors(repo, fetchParameters)
      .then(res => res.data)
      .then(noContentToArray)
      .then(repos => repos.map(repo => pick(repo, ['login', 'contributions'])));
    repos = [...repos, ...fetchContributors];
    fetchParameters.page++;
  } while (fetchContributors.length === fetchParameters.per_page);

  return repos;
};

const getRepoData = repo => {
  return getAllContributors(repo).then(contributors => {
    const contributorData = {};
    for (const contributor of contributors) {
      contributorData[contributor.login] = contributor.contributions;
    }
    return { contributorData };
  });
};

const getOrgData = org => {
  return github.getAllOrganizationPublicRepos(org).then(async repos => {
    const contributorData = [];
    const repoData = {};
    for (const repo of repos) {
      if (repo.fork) {
        continue;
      }
      const contributors = await getAllContributors({ owner: repo.owner.login, repo: repo.name });
      for (const contributor of contributors) {
        if (contributorData[contributor.login]) {
          contributorData[contributor.login] += contributor.contributions;
        } else {
          contributorData[contributor.login] = contributor.contributions;
        }
      }
      repoData[repo.name] = { stars: repo.stargazers_count };
    }
    return { contributorData, repoData };
  });
};

const run = async () => {
  let collectives = await Collective.findAll({
    where: {
      type: 'COLLECTIVE',
    },
  });

  logger.info(`Found ${collectives.length} total collective(s)`);

  collectives = collectives
    .filter(collective => get(collective, 'settings.githubOrg') || get(collective, 'settings.githubRepo'))
    .filter(collective => collective.isActive);

  logger.info(`Found ${collectives.length} active collective(s) with GitHub settings`);

  for (const collective of collectives) {
    const org = get(collective, 'settings.githubOrg');
    const repo = get(collective, 'settings.githubRepo');

    let githubData;

    if (org) {
      try {
        githubData = await getOrgData(org);
      } catch (e) {
        logger.error(`Error while fetching org data for collective '${collective.slug}'`);
        continue;
      }
    } else {
      const split = repo.split('/');
      if (split.length !== 2) {
        logger.warn(collective.name, 'Incorrect format of githubRepo');
        continue;
      }
      const options = {
        owner: split[0],
        repo: split[1],
      };
      try {
        githubData = await getRepoData(options);
      } catch (e) {
        logger.error(`Error while fetching ${options.owner}/${options.repo} for collective '${collective.slug}'`);
        continue;
      }
    }

    if (githubData) {
      const data = assign(collective.data || {}, {
        githubContributors: sortObjectByValue(githubData.contributorData),
      });

      if (githubData.repoData) {
        data.repos = orderBy(githubData.repoData, ['stars', 'desc']);
      }

      await collective.update({ data });

      logger.info(`Successfully updated contribution data for '${collective.name}'`);
    }
  }
};

run();
<commit_msg>fix: ordering of repos (by stars)<commit_after>#!/usr/bin/env node
import '../../server/env';

import { assign, get, isArray, pick } from 'lodash';

import models from '../../server/models';
import logger from '../../server/lib/logger';
import * as github from '../../server/lib/github';

const { Collective } = models;

// TODO: As number of collectives grow, we need to consider fetching 100 at a time,
// otherwise, we end up fetching a lot of data.
// Note: Picking attributes doesn't work with Histories table because Histories
// ends up recording on the attributes that were pulled out

const noContentToArray = value => (isArray(value) ? value : []);

const sortObjectByValue = (obj, path) => {
  const sortable = [];
  for (const key in obj) {
    sortable.push([key, obj[key], path ? get(obj[key], path) : obj[key]]);
  }

  sortable.sort((a, b) => {
    return a[2] > b[2] ? -1 : a[2] < b[2] ? 1 : 0;
  });

  const orderedList = {};
  for (let i = 0; i < sortable.length; i++) {
    orderedList[sortable[i][0]] = sortable[i][1];
  }

  return orderedList;
};

const getAllContributors = async repo => {
  const octokit = github.getOctokit();

  const fetchParameters = { page: 1, per_page: 100 };

  let repos = [];
  let fetchContributors;
  do {
    // https://octokit.github.io/rest.js/#api-Repos-listContributors
    // https://developer.github.com/v3/repos/#list-contributors
    fetchContributors = await octokit.repos
      .listContributors(repo, fetchParameters)
      .then(res => res.data)
      .then(noContentToArray)
      .then(repos => repos.map(repo => pick(repo, ['login', 'contributions'])));
    repos = [...repos, ...fetchContributors];
    fetchParameters.page++;
  } while (fetchContributors.length === fetchParameters.per_page);

  return repos;
};

const getRepoData = repo => {
  return getAllContributors(repo).then(contributors => {
    const contributorData = {};
    for (const contributor of contributors) {
      contributorData[contributor.login] = contributor.contributions;
    }
    return { contributorData };
  });
};

const getOrgData = org => {
  return github.getAllOrganizationPublicRepos(org).then(async repos => {
    const contributorData = [];
    const repoData = {};
    for (const repo of repos) {
      if (repo.fork) {
        continue;
      }
      const contributors = await getAllContributors({ owner: repo.owner.login, repo: repo.name });
      for (const contributor of contributors) {
        if (contributorData[contributor.login]) {
          contributorData[contributor.login] += contributor.contributions;
        } else {
          contributorData[contributor.login] = contributor.contributions;
        }
      }
      repoData[repo.name] = { stars: repo.stargazers_count };
    }
    return { contributorData, repoData };
  });
};

const run = async () => {
  let collectives = await Collective.findAll({
    where: {
      type: 'COLLECTIVE',
    },
  });

  logger.info(`Found ${collectives.length} total collective(s)`);

  collectives = collectives
    .filter(collective => get(collective, 'settings.githubOrg') || get(collective, 'settings.githubRepo'))
    .filter(collective => collective.isActive);

  logger.info(`Found ${collectives.length} active collective(s) with GitHub settings`);

  for (const collective of collectives) {
    const org = get(collective, 'settings.githubOrg');
    const repo = get(collective, 'settings.githubRepo');

    let githubData;

    if (org) {
      try {
        githubData = await getOrgData(org);
      } catch (e) {
        logger.error(`Error while fetching org data for collective '${collective.slug}'`);
        continue;
      }
    } else {
      const split = repo.split('/');
      if (split.length !== 2) {
        logger.warn(collective.name, 'Incorrect format of githubRepo');
        continue;
      }
      const options = {
        owner: split[0],
        repo: split[1],
      };
      try {
        githubData = await getRepoData(options);
      } catch (e) {
        logger.error(`Error while fetching ${options.owner}/${options.repo} for collective '${collective.slug}'`);
        continue;
      }
    }

    if (githubData) {
      const data = assign(collective.data || {}, {
        githubContributors: sortObjectByValue(githubData.contributorData),
      });

      if (githubData.repoData) {
        data.repos = sortObjectByValue(githubData.repoData, 'stars');
      }

      await collective.update({ data });

      logger.info(`Successfully updated contribution data for '${collective.name}'`);
    }
  }
};

run();
<|endoftext|>


<commit_before>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var React = require('react');
var sdk = require('../../index');

/* (almost) stateless UI component which builds the event tiles in the room timeline.
 */
module.exports = React.createClass({
    displayName: 'MessagePanel',

    propTypes: {
        // true to give the component a 'display: none' style.
        hidden: React.PropTypes.bool,

        // the list of MatrixEvents to display
        events: React.PropTypes.array.isRequired,

        // ID of an event to highlight. If undefined, no event will be highlighted.
        highlightedEventId: React.PropTypes.string,

        // event after which we should show a read marker
        readMarkerEventId: React.PropTypes.string,

        // the userid of our user. This is used to suppress the read marker
        // for pending messages.
        ourUserId: React.PropTypes.string,

        // true to suppress the date at the start of the timeline
        suppressFirstDateSeparator: React.PropTypes.bool,

        // true if updates to the event list should cause the scroll panel to
        // scroll down when we are at the bottom of the window. See ScrollPanel
        // for more details.
        stickyBottom: React.PropTypes.bool,

        // callback which is called when the panel is scrolled.
        onScroll: React.PropTypes.func,

        // callback which is called when more content is needed.
        onFillRequest: React.PropTypes.func,
    },

    componentWillMount: function() {
        // the event after which we put a visible unread marker on the last
        // render cycle; null if readMarkerVisible was false or the RM was
        // suppressed (eg because it was at the end of the timeline)
        this.currentReadMarkerEventId = null;

        // the event after which we are showing a disappearing read marker
        // animation
        this.currentGhostEventId = null;
    },

    /* get the DOM node representing the given event */
    getNodeForEventId: function(eventId) {
        if (!this.eventNodes) {
            return undefined;
        }

        return this.eventNodes[eventId];
    },

    /* return true if the content is fully scrolled down right now; else false.
     */
    isAtBottom: function() {
        return this.refs.scrollPanel
            && this.refs.scrollPanel.isAtBottom();
    },

    /* get the current scroll state. See ScrollPanel.getScrollState for
     * details.
     *
     * returns null if we are not mounted.
     */
    getScrollState: function() {
        if (!this.refs.scrollPanel) { return null; }
        return this.refs.scrollPanel.getScrollState();
    },

    /* jump to the bottom of the content.
     */
    scrollToBottom: function() {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollToBottom();
        }
    },

    /* jump to the given event id.
     *
     * pixelOffset gives the number of pixels between the bottom of the node
     * and the bottom of the container. If undefined, it will put the node
     * in the middle of the container.
     */
    scrollToEvent: function(eventId, pixelOffset) {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollToToken(eventId, pixelOffset);
        }
    },

    /* check the scroll state and send out pagination requests if necessary.
     */
    checkFillState: function() {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.checkFillState();
        }
    },

    _getEventTiles: function() {
        var EventTile = sdk.getComponent('rooms.EventTile');

        this.eventNodes = {};

        var i;

        // first figure out which is the last event in the list which we're
        // actually going to show; this allows us to behave slightly
        // differently for the last event in the list.
        for (i = this.props.events.length-1; i >= 0; i--) {
            var mxEv = this.props.events[i];
            if (!EventTile.haveTileForEvent(mxEv)) {
                continue;
            }

            break;
        }
        var lastShownEventIndex = i;

        var ret = [];

        var prevEvent = null; // the last event we showed

        // assume there is no read marker until proven otherwise
        var readMarkerVisible = false;

        for (i = 0; i < this.props.events.length; i++) {
            var mxEv = this.props.events[i];
            var wantTile = true;
            var eventId = mxEv.getId();

            if (!EventTile.haveTileForEvent(mxEv)) {
                wantTile = false;
            }

            var last = (i == lastShownEventIndex);

            if (wantTile) {
                ret.push(this._getTilesForEvent(prevEvent, mxEv, last));
            } else if (!mxEv.status) {
                // if we aren't showing the event, put in a dummy scroll token anyway, so
                // that we can scroll to the right place.
                ret.push(
);
            }

            if (eventId == this.props.readMarkerEventId && i < lastShownEventIndex) {
                // suppress the read marker if the next event is sent by us; this
                // is a nonsensical and temporary situation caused by the delay between
                // us sending a message and receiving the synthesized receipt.
                var nextEvent = this.props.events[i+1];
                if (nextEvent.sender && nextEvent.sender.userId != this.props.ourUserId) {
                    ret.push(this._getReadMarkerTile());
                    readMarkerVisible = true;
                }
            } else if (eventId == this.currentReadMarkerEventId && !this.currentGhostEventId) {
                // there is currently a read-up-to marker at this point, but no
                // more. Show an animation of it disappearing.
                ret.push(this._getReadMarkerGhostTile());
                this.currentGhostEventId = eventId;
            } else if (eventId == this.currentGhostEventId) {
                // if we're showing an animation, continue to show it.
                ret.push(this._getReadMarkerGhostTile());
            }
        }

        this.currentReadMarkerEventId = readMarkerVisible ? this.props.readMarkerEventId : null;
        return ret;
    },

    _getTilesForEvent: function(prevEvent, mxEv, last) {
        var EventTile = sdk.getComponent('rooms.EventTile');
        var DateSeparator = sdk.getComponent('messages.DateSeparator');
        var ret = [];

        // is this a continuation of the previous message?
        var continuation = false;
        if (prevEvent !== null && prevEvent.sender && mxEv.sender
                && mxEv.sender.userId === prevEvent.sender.userId
                && mxEv.getType() == prevEvent.getType()) {
            continuation = true;
        }

        // do we need a date separator since the last event?
        var ts1 = mxEv.getTs();
        if ((prevEvent == null && !this.props.suppressFirstDateSeparator) ||
                (prevEvent != null &&
                     new Date(prevEvent.getTs()).toDateString()
                          !== new Date(ts1).toDateString())) {
            var dateSeparator =
<DateSeparator key={ts1} ts={ts1}/>
;
            ret.push(dateSeparator);
            continuation = false;
        }

        var eventId = mxEv.getId();
        var highlight = (eventId == this.props.highlightedEventId);

        // we can't use local echoes as scroll tokens, because their event IDs change.
        // Local echos have a send "status".
        var scrollToken = mxEv.status ? undefined : eventId;

        ret.push(

                    <EventTile mxEvent={mxEv} continuation={continuation}
                        last={last} isSelectedEvent={highlight}
                        onImageLoad={this._onImageLoad} />

        );

        return ret;
    },

    _getReadMarkerTile: function() {
        var hr;
        hr =
;

        return (

                {hr}

        );
    },

    _getReadMarkerGhostTile: function() {
        // reset the ghostEventId when the animation finishes, so that
        // we can make a new one (and so that we don't run the
        // animation code every time we render)
        var completeFunc = () => {
            this.currentGhostEventId = null;
        };

        var hr =
;

        // give it a key which depends on the event id. That will ensure that
        // we get a new DOM node (restarting the animation) when the ghost
        // moves to a different event.
        return (

                {hr}

        );
    },

    _collectEventNode: function(eventId, node) {
        this.eventNodes[eventId] = node;
    },

    // once images in the events load, make the scrollPanel check the
    // scroll offsets.
    _onImageLoad: function() {
        var scrollPanel = this.refs.messagePanel;
        if (scrollPanel) {
            scrollPanel.checkScroll();
        }
    },

    render: function() {
        var ScrollPanel = sdk.getComponent("structures.ScrollPanel");
        return (
            <ScrollPanel ref="scrollPanel" className="mx_RoomView_messagePanel"
                    onScroll={ this.props.onScroll }
                    onFillRequest={ this.props.onFillRequest }
                    style={ this.props.hidden ? { display: 'none' } : {} }
                    stickyBottom={ this.props.stickyBottom }>
                {this._getEventTiles()}
            </ScrollPanel>
        );
    },
});
<commit_msg>reinstate event-continuation logic<commit_after>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var React = require('react');
var sdk = require('../../index');

/* (almost) stateless UI component which builds the event tiles in the room timeline.
 */
module.exports = React.createClass({
    displayName: 'MessagePanel',

    propTypes: {
        // true to give the component a 'display: none' style.
        hidden: React.PropTypes.bool,

        // the list of MatrixEvents to display
        events: React.PropTypes.array.isRequired,

        // ID of an event to highlight. If undefined, no event will be highlighted.
        highlightedEventId: React.PropTypes.string,

        // event after which we should show a read marker
        readMarkerEventId: React.PropTypes.string,

        // the userid of our user. This is used to suppress the read marker
        // for pending messages.
        ourUserId: React.PropTypes.string,

        // true to suppress the date at the start of the timeline
        suppressFirstDateSeparator: React.PropTypes.bool,

        // true if updates to the event list should cause the scroll panel to
        // scroll down when we are at the bottom of the window. See ScrollPanel
        // for more details.
        stickyBottom: React.PropTypes.bool,

        // callback which is called when the panel is scrolled.
        onScroll: React.PropTypes.func,

        // callback which is called when more content is needed.
        onFillRequest: React.PropTypes.func,
    },

    componentWillMount: function() {
        // the event after which we put a visible unread marker on the last
        // render cycle; null if readMarkerVisible was false or the RM was
        // suppressed (eg because it was at the end of the timeline)
        this.currentReadMarkerEventId = null;

        // the event after which we are showing a disappearing read marker
        // animation
        this.currentGhostEventId = null;
    },

    /* get the DOM node representing the given event */
    getNodeForEventId: function(eventId) {
        if (!this.eventNodes) {
            return undefined;
        }

        return this.eventNodes[eventId];
    },

    /* return true if the content is fully scrolled down right now; else false.
     */
    isAtBottom: function() {
        return this.refs.scrollPanel
            && this.refs.scrollPanel.isAtBottom();
    },

    /* get the current scroll state. See ScrollPanel.getScrollState for
     * details.
     *
     * returns null if we are not mounted.
     */
    getScrollState: function() {
        if (!this.refs.scrollPanel) { return null; }
        return this.refs.scrollPanel.getScrollState();
    },

    /* jump to the bottom of the content.
     */
    scrollToBottom: function() {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollToBottom();
        }
    },

    /* jump to the given event id.
     *
     * pixelOffset gives the number of pixels between the bottom of the node
     * and the bottom of the container. If undefined, it will put the node
     * in the middle of the container.
     */
    scrollToEvent: function(eventId, pixelOffset) {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollToToken(eventId, pixelOffset);
        }
    },

    /* check the scroll state and send out pagination requests if necessary.
     */
    checkFillState: function() {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.checkFillState();
        }
    },

    _getEventTiles: function() {
        var EventTile = sdk.getComponent('rooms.EventTile');

        this.eventNodes = {};

        var i;

        // first figure out which is the last event in the list which we're
        // actually going to show; this allows us to behave slightly
        // differently for the last event in the list.
        for (i = this.props.events.length-1; i >= 0; i--) {
            var mxEv = this.props.events[i];
            if (!EventTile.haveTileForEvent(mxEv)) {
                continue;
            }

            break;
        }
        var lastShownEventIndex = i;

        var ret = [];

        var prevEvent = null; // the last event we showed

        // assume there is no read marker until proven otherwise
        var readMarkerVisible = false;

        for (i = 0; i < this.props.events.length; i++) {
            var mxEv = this.props.events[i];
            var wantTile = true;
            var eventId = mxEv.getId();

            if (!EventTile.haveTileForEvent(mxEv)) {
                wantTile = false;
            }

            var last = (i == lastShownEventIndex);

            if (wantTile) {
                ret.push(this._getTilesForEvent(prevEvent, mxEv, last));
                prevEvent = mxEv;
            } else if (!mxEv.status) {
                // if we aren't showing the event, put in a dummy scroll token anyway, so
                // that we can scroll to the right place.
                ret.push(
);
            }

            if (eventId == this.props.readMarkerEventId && i < lastShownEventIndex) {
                // suppress the read marker if the next event is sent by us; this
                // is a nonsensical and temporary situation caused by the delay between
                // us sending a message and receiving the synthesized receipt.
                var nextEvent = this.props.events[i+1];
                if (nextEvent.sender && nextEvent.sender.userId != this.props.ourUserId) {
                    ret.push(this._getReadMarkerTile());
                    readMarkerVisible = true;
                }
            } else if (eventId == this.currentReadMarkerEventId && !this.currentGhostEventId) {
                // there is currently a read-up-to marker at this point, but no
                // more. Show an animation of it disappearing.
                ret.push(this._getReadMarkerGhostTile());
                this.currentGhostEventId = eventId;
            } else if (eventId == this.currentGhostEventId) {
                // if we're showing an animation, continue to show it.
                ret.push(this._getReadMarkerGhostTile());
            }
        }

        this.currentReadMarkerEventId = readMarkerVisible ? this.props.readMarkerEventId : null;
        return ret;
    },

    _getTilesForEvent: function(prevEvent, mxEv, last) {
        var EventTile = sdk.getComponent('rooms.EventTile');
        var DateSeparator = sdk.getComponent('messages.DateSeparator');
        var ret = [];

        // is this a continuation of the previous message?
        var continuation = false;
        if (prevEvent !== null && prevEvent.sender && mxEv.sender
                && mxEv.sender.userId === prevEvent.sender.userId
                && mxEv.getType() == prevEvent.getType()) {
            continuation = true;
        }

        // do we need a date separator since the last event?
        var ts1 = mxEv.getTs();
        if ((prevEvent == null && !this.props.suppressFirstDateSeparator) ||
                (prevEvent != null &&
                     new Date(prevEvent.getTs()).toDateString()
                          !== new Date(ts1).toDateString())) {
            var dateSeparator =
<DateSeparator key={ts1} ts={ts1}/>
;
            ret.push(dateSeparator);
            continuation = false;
        }

        var eventId = mxEv.getId();
        var highlight = (eventId == this.props.highlightedEventId);

        // we can't use local echoes as scroll tokens, because their event IDs change.
        // Local echos have a send "status".
        var scrollToken = mxEv.status ? undefined : eventId;

        ret.push(

                    <EventTile mxEvent={mxEv} continuation={continuation}
                        last={last} isSelectedEvent={highlight}
                        onImageLoad={this._onImageLoad} />

        );

        return ret;
    },

    _getReadMarkerTile: function() {
        var hr;
        hr =
;

        return (

                {hr}

        );
    },

    _getReadMarkerGhostTile: function() {
        // reset the ghostEventId when the animation finishes, so that
        // we can make a new one (and so that we don't run the
        // animation code every time we render)
        var completeFunc = () => {
            this.currentGhostEventId = null;
        };

        var hr =
;

        // give it a key which depends on the event id. That will ensure that
        // we get a new DOM node (restarting the animation) when the ghost
        // moves to a different event.
        return (

                {hr}

        );
    },

    _collectEventNode: function(eventId, node) {
        this.eventNodes[eventId] = node;
    },

    // once images in the events load, make the scrollPanel check the
    // scroll offsets.
    _onImageLoad: function() {
        var scrollPanel = this.refs.messagePanel;
        if (scrollPanel) {
            scrollPanel.checkScroll();
        }
    },

    render: function() {
        var ScrollPanel = sdk.getComponent("structures.ScrollPanel");
        return (
            <ScrollPanel ref="scrollPanel" className="mx_RoomView_messagePanel"
                    onScroll={ this.props.onScroll }
                    onFillRequest={ this.props.onFillRequest }
                    style={ this.props.hidden ? { display: 'none' } : {} }
                    stickyBottom={ this.props.stickyBottom }>
                {this._getEventTiles()}
            </ScrollPanel>
        );
    },
});
<|endoftext|>


<commit_before>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var React = require('react');
var ReactDOM = require("react-dom");
var dis = require("../../dispatcher");
var sdk = require('../../index');

/* (almost) stateless UI component which builds the event tiles in the room timeline.
 */
module.exports = React.createClass({
    displayName: 'MessagePanel',

    propTypes: {
        // true to give the component a 'display: none' style.
        hidden: React.PropTypes.bool,

        // true to show a spinner at the top of the timeline to indicate
        // back-pagination in progress
        backPaginating: React.PropTypes.bool,

        // true to show a spinner at the end of the timeline to indicate
        // forward-pagination in progress
        forwardPaginating: React.PropTypes.bool,

        // the list of MatrixEvents to display
        events: React.PropTypes.array.isRequired,

        // ID of an event to highlight. If undefined, no event will be highlighted.
        highlightedEventId: React.PropTypes.string,

        // event after which we should show a read marker
        readMarkerEventId: React.PropTypes.string,

        // whether the read marker should be visible
        readMarkerVisible: React.PropTypes.bool,

        // the userid of our user. This is used to suppress the read marker
        // for pending messages.
        ourUserId: React.PropTypes.string,

        // true to suppress the date at the start of the timeline
        suppressFirstDateSeparator: React.PropTypes.bool,

        // true if updates to the event list should cause the scroll panel to
        // scroll down when we are at the bottom of the window. See ScrollPanel
        // for more details.
        stickyBottom: React.PropTypes.bool,

        // callback which is called when the panel is scrolled.
        onScroll: React.PropTypes.func,

        // callback which is called when more content is needed.
        onFillRequest: React.PropTypes.func,
    },

    componentWillMount: function() {
        // the event after which we put a visible unread marker on the last
        // render cycle; null if readMarkerVisible was false or the RM was
        // suppressed (eg because it was at the end of the timeline)
        this.currentReadMarkerEventId = null;

        // the event after which we are showing a disappearing read marker
        // animation
        this.currentGhostEventId = null;
    },

    /* get the DOM node representing the given event */
    getNodeForEventId: function(eventId) {
        if (!this.eventNodes) {
            return undefined;
        }

        return this.eventNodes[eventId];
    },

    /* return true if the content is fully scrolled down right now; else false.
     */
    isAtBottom: function() {
        return this.refs.scrollPanel
            && this.refs.scrollPanel.isAtBottom();
    },

    /* get the current scroll state. See ScrollPanel.getScrollState for
     * details.
     *
     * returns null if we are not mounted.
     */
    getScrollState: function() {
        if (!this.refs.scrollPanel) { return null; }
        return this.refs.scrollPanel.getScrollState();
    },

    // returns one of:
    //
    //  null: there is no read marker
    //  -1: read marker is above the window
    //   0: read marker is within the window
    //  +1: read marker is below the window
    getReadMarkerPosition: function() {
        var readMarker = this.refs.readMarkerNode;
        var messageWrapper = this.refs.scrollPanel;

        if (!readMarker || !messageWrapper) {
            return null;
        }

        var wrapperRect = ReactDOM.findDOMNode(messageWrapper).getBoundingClientRect();
        var readMarkerRect = readMarker.getBoundingClientRect();

        // the read-marker pretends to have zero height when it is actually
        // two pixels high; +2 here to account for that.
        if (readMarkerRect.bottom + 2 < wrapperRect.top) {
            return -1;
        } else if (readMarkerRect.top < wrapperRect.bottom) {
            return 0;
        } else {
            return 1;
        }
    },

    /* jump to the top of the content.
     */
    scrollToTop: function() {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollToTop();
        }
    },

    /* jump to the bottom of the content.
     */
    scrollToBottom: function() {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollToBottom();
        }
    },

    /**
     * Page up/down.
     *
     * mult: -1 to page up, +1 to page down
     */
    scrollRelative: function(mult) {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollRelative(mult);
        }
    },

    /**
     * Scroll up/down in response to a scroll key
     */
    handleScrollKey: function(ev) {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.handleScrollKey(ev);
        }
    },

    /* jump to the given event id.
     *
     * offsetBase gives the reference point for the pixelOffset. 0 means the
     * top of the container, 1 means the bottom, and fractional values mean
     * somewhere in the middle. If omitted, it defaults to 0.
     *
     * pixelOffset gives the number of pixels *above* the offsetBase that the
     * node (specifically, the bottom of it) will be positioned. If omitted, it
     * defaults to 0.
     */
    scrollToEvent: function(eventId, pixelOffset, offsetBase) {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollToToken(eventId, pixelOffset, offsetBase);
        }
    },

    /* check the scroll state and send out pagination requests if necessary.
     */
    checkFillState: function() {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.checkFillState();
        }
    },

    _getEventTiles: function() {
        var EventTile = sdk.getComponent('rooms.EventTile');

        this.eventNodes = {};

        var i;

        // first figure out which is the last event in the list which we're
        // actually going to show; this allows us to behave slightly
        // differently for the last event in the list.
        //
        // we also need to figure out which is the last event we show which isn't
        // a local echo, to manage the read-marker.
        var lastShownEventIndex = -1;
        var lastShownNonLocalEchoIndex = -1;
        for (i = this.props.events.length-1; i >= 0; i--) {
            var mxEv = this.props.events[i];
            if (!EventTile.haveTileForEvent(mxEv)) {
                continue;
            }

            if (lastShownEventIndex < 0) {
                lastShownEventIndex = i;
            }

            if (mxEv.status) {
                // this is a local echo
                continue;
            }

            lastShownNonLocalEchoIndex = i;
            break;
        }

        var ret = [];

        var prevEvent = null; // the last event we showed

        // assume there is no read marker until proven otherwise
        var readMarkerVisible = false;

        // if the readmarker has moved, cancel any active ghost.
        if (this.currentReadMarkerEventId && this.props.readMarkerEventId &&
                this.props.readMarkerVisible &&
                this.currentReadMarkerEventId != this.props.readMarkerEventId) {
            this.currentGhostEventId = null;
        }

        for (i = 0; i < this.props.events.length; i++) {
            var mxEv = this.props.events[i];
            var wantTile = true;
            var eventId = mxEv.getId();

            if (!EventTile.haveTileForEvent(mxEv)) {
                wantTile = false;
            }

            var last = (i == lastShownEventIndex);

            if (wantTile) {
                // make sure we unpack the array returned by _getTilesForEvent,
                // otherwise react will auto-generate keys and we will end up
                // replacing all of the DOM elements every time we paginate.
                ret.push(...this._getTilesForEvent(prevEvent, mxEv, last));
                prevEvent = mxEv;
            } else if (!mxEv.status) {
                // if we aren't showing the event, put in a dummy scroll token anyway, so
                // that we can scroll to the right place.
                ret.push(
);
            }

            var isVisibleReadMarker = false;

            if (eventId == this.props.readMarkerEventId) {
                var visible = this.props.readMarkerVisible;

                // if the read marker comes at the end of the timeline (except
                // for local echoes, which are excluded from RMs, because they
                // don't have useful event ids), we don't want to show it, but
                // we still want to create the
 for it so that the
                // algorithms which depend on its position on the screen aren't
                // confused.
                if (i >= lastShownNonLocalEchoIndex) {
                    visible = false;
                }
                ret.push(this._getReadMarkerTile(visible));
                readMarkerVisible = visible;
                isVisibleReadMarker = visible;
            }

            if (eventId == this.currentGhostEventId) {
                // if we're showing an animation, continue to show it.
                ret.push(this._getReadMarkerGhostTile());
            } else if (!isVisibleReadMarker &&
                       eventId == this.currentReadMarkerEventId) {
                // there is currently a read-up-to marker at this point, but no
                // more. Show an animation of it disappearing.
                ret.push(this._getReadMarkerGhostTile());
                this.currentGhostEventId = eventId;
            }
        }

        this.currentReadMarkerEventId = readMarkerVisible ? this.props.readMarkerEventId : null;
        return ret;
    },

    _getTilesForEvent: function(prevEvent, mxEv, last) {
        var EventTile = sdk.getComponent('rooms.EventTile');
        var DateSeparator = sdk.getComponent('messages.DateSeparator');
        var ret = [];

        // is this a continuation of the previous message?
        var continuation = false;
        if (prevEvent !== null && prevEvent.sender && mxEv.sender
                && mxEv.sender.userId === prevEvent.sender.userId
                && mxEv.getType() == prevEvent.getType()) {
            continuation = true;
        }

        // local echoes have a fake date, which could even be yesterday. Treat them
        // as 'today' for the date separators.
        var ts1 = mxEv.getTs();
        if (mxEv.status) {
            ts1 = new Date();
        }

        // do we need a date separator since the last event?
        if (this._wantsDateSeparator(prevEvent, ts1)) {
            var dateSeparator =
<DateSeparator key={ts1} ts={ts1}/>
;
            ret.push(dateSeparator);
            continuation = false;
        }

        var eventId = mxEv.getId();
        var highlight = (eventId == this.props.highlightedEventId);

        // we can't use local echoes as scroll tokens, because their event IDs change.
        // Local echos have a send "status".
        var scrollToken = mxEv.status ? undefined : eventId;

        ret.push(

                    <EventTile mxEvent={mxEv} continuation={continuation}
                        onWidgetLoad={this._onWidgetLoad}
                        last={last} isSelectedEvent={highlight} />

        );

        return ret;
    },

    _wantsDateSeparator: function(prevEvent, nextEventTs) {
        if (prevEvent == null) {
            // first event in the panel: depends if we could back-paginate from
            // here.
            return !this.props.suppressFirstDateSeparator;
        }

        return (new Date(prevEvent.getTs()).toDateString()
                !== new Date(nextEventTs).toDateString());
    },

    _getReadMarkerTile: function(visible) {
        var hr;
        if (visible) {
            hr =
;
        }

        return (

                {hr}

        );
    },

    _startAnimation: function(ghostNode) {
        Velocity(ghostNode, {opacity: '0', width: '10%'},
                 {duration: 400, easing: 'easeInSine',
                  delay: 1000});
    },

    _getReadMarkerGhostTile: function() {
        var hr =
;

        // give it a key which depends on the event id. That will ensure that
        // we get a new DOM node (restarting the animation) when the ghost
        // moves to a different event.
        return (

                {hr}

        );
    },

    _collectEventNode: function(eventId, node) {
        this.eventNodes[eventId] = node;
    },

    // once dynamic content in the events load, make the scrollPanel check the
    // scroll offsets.
    _onWidgetLoad: function() {
        var scrollPanel = this.refs.scrollPanel;
        if (scrollPanel) {
            scrollPanel.checkScroll();
            scrollPanel.forceUpdate();
        }
    },

    onResize: function() {
        dis.dispatch({ action: 'timeline_resize' }, true);
    },

    render: function() {
        var ScrollPanel = sdk.getComponent("structures.ScrollPanel");
        var Spinner = sdk.getComponent("elements.Spinner");
        var topSpinner, bottomSpinner;
        if (this.props.backPaginating) {
            topSpinner =
<Spinner />
;
        }
        if (this.props.forwardPaginating) {
            bottomSpinner =
<Spinner />
;
        }

        return (
            <ScrollPanel ref="scrollPanel" className="mx_RoomView_messagePanel"
                    onScroll={ this.props.onScroll }
                    onResize={ this.onResize }
                    onFillRequest={ this.props.onFillRequest }
                    style={ this.props.hidden ? { display: 'none' } : {} }
                    stickyBottom={ this.props.stickyBottom }>
                {topSpinner}
                {this._getEventTiles()}
                {bottomSpinner}
            </ScrollPanel>
        );
    },
});
<commit_msg>apparently we don't need this. i'm lost now<commit_after>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var React = require('react');
var ReactDOM = require("react-dom");
var dis = require("../../dispatcher");
var sdk = require('../../index');

/* (almost) stateless UI component which builds the event tiles in the room timeline.
 */
module.exports = React.createClass({
    displayName: 'MessagePanel',

    propTypes: {
        // true to give the component a 'display: none' style.
        hidden: React.PropTypes.bool,

        // true to show a spinner at the top of the timeline to indicate
        // back-pagination in progress
        backPaginating: React.PropTypes.bool,

        // true to show a spinner at the end of the timeline to indicate
        // forward-pagination in progress
        forwardPaginating: React.PropTypes.bool,

        // the list of MatrixEvents to display
        events: React.PropTypes.array.isRequired,

        // ID of an event to highlight. If undefined, no event will be highlighted.
        highlightedEventId: React.PropTypes.string,

        // event after which we should show a read marker
        readMarkerEventId: React.PropTypes.string,

        // whether the read marker should be visible
        readMarkerVisible: React.PropTypes.bool,

        // the userid of our user. This is used to suppress the read marker
        // for pending messages.
        ourUserId: React.PropTypes.string,

        // true to suppress the date at the start of the timeline
        suppressFirstDateSeparator: React.PropTypes.bool,

        // true if updates to the event list should cause the scroll panel to
        // scroll down when we are at the bottom of the window. See ScrollPanel
        // for more details.
        stickyBottom: React.PropTypes.bool,

        // callback which is called when the panel is scrolled.
        onScroll: React.PropTypes.func,

        // callback which is called when more content is needed.
        onFillRequest: React.PropTypes.func,
    },

    componentWillMount: function() {
        // the event after which we put a visible unread marker on the last
        // render cycle; null if readMarkerVisible was false or the RM was
        // suppressed (eg because it was at the end of the timeline)
        this.currentReadMarkerEventId = null;

        // the event after which we are showing a disappearing read marker
        // animation
        this.currentGhostEventId = null;
    },

    /* get the DOM node representing the given event */
    getNodeForEventId: function(eventId) {
        if (!this.eventNodes) {
            return undefined;
        }

        return this.eventNodes[eventId];
    },

    /* return true if the content is fully scrolled down right now; else false.
     */
    isAtBottom: function() {
        return this.refs.scrollPanel
            && this.refs.scrollPanel.isAtBottom();
    },

    /* get the current scroll state. See ScrollPanel.getScrollState for
     * details.
     *
     * returns null if we are not mounted.
     */
    getScrollState: function() {
        if (!this.refs.scrollPanel) { return null; }
        return this.refs.scrollPanel.getScrollState();
    },

    // returns one of:
    //
    //  null: there is no read marker
    //  -1: read marker is above the window
    //   0: read marker is within the window
    //  +1: read marker is below the window
    getReadMarkerPosition: function() {
        var readMarker = this.refs.readMarkerNode;
        var messageWrapper = this.refs.scrollPanel;

        if (!readMarker || !messageWrapper) {
            return null;
        }

        var wrapperRect = ReactDOM.findDOMNode(messageWrapper).getBoundingClientRect();
        var readMarkerRect = readMarker.getBoundingClientRect();

        // the read-marker pretends to have zero height when it is actually
        // two pixels high; +2 here to account for that.
        if (readMarkerRect.bottom + 2 < wrapperRect.top) {
            return -1;
        } else if (readMarkerRect.top < wrapperRect.bottom) {
            return 0;
        } else {
            return 1;
        }
    },

    /* jump to the top of the content.
     */
    scrollToTop: function() {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollToTop();
        }
    },

    /* jump to the bottom of the content.
     */
    scrollToBottom: function() {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollToBottom();
        }
    },

    /**
     * Page up/down.
     *
     * mult: -1 to page up, +1 to page down
     */
    scrollRelative: function(mult) {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollRelative(mult);
        }
    },

    /**
     * Scroll up/down in response to a scroll key
     */
    handleScrollKey: function(ev) {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.handleScrollKey(ev);
        }
    },

    /* jump to the given event id.
     *
     * offsetBase gives the reference point for the pixelOffset. 0 means the
     * top of the container, 1 means the bottom, and fractional values mean
     * somewhere in the middle. If omitted, it defaults to 0.
     *
     * pixelOffset gives the number of pixels *above* the offsetBase that the
     * node (specifically, the bottom of it) will be positioned. If omitted, it
     * defaults to 0.
     */
    scrollToEvent: function(eventId, pixelOffset, offsetBase) {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.scrollToToken(eventId, pixelOffset, offsetBase);
        }
    },

    /* check the scroll state and send out pagination requests if necessary.
     */
    checkFillState: function() {
        if (this.refs.scrollPanel) {
            this.refs.scrollPanel.checkFillState();
        }
    },

    _getEventTiles: function() {
        var EventTile = sdk.getComponent('rooms.EventTile');

        this.eventNodes = {};

        var i;

        // first figure out which is the last event in the list which we're
        // actually going to show; this allows us to behave slightly
        // differently for the last event in the list.
        //
        // we also need to figure out which is the last event we show which isn't
        // a local echo, to manage the read-marker.
        var lastShownEventIndex = -1;
        var lastShownNonLocalEchoIndex = -1;
        for (i = this.props.events.length-1; i >= 0; i--) {
            var mxEv = this.props.events[i];
            if (!EventTile.haveTileForEvent(mxEv)) {
                continue;
            }

            if (lastShownEventIndex < 0) {
                lastShownEventIndex = i;
            }

            if (mxEv.status) {
                // this is a local echo
                continue;
            }

            lastShownNonLocalEchoIndex = i;
            break;
        }

        var ret = [];

        var prevEvent = null; // the last event we showed

        // assume there is no read marker until proven otherwise
        var readMarkerVisible = false;

        // if the readmarker has moved, cancel any active ghost.
        if (this.currentReadMarkerEventId && this.props.readMarkerEventId &&
                this.props.readMarkerVisible &&
                this.currentReadMarkerEventId != this.props.readMarkerEventId) {
            this.currentGhostEventId = null;
        }

        for (i = 0; i < this.props.events.length; i++) {
            var mxEv = this.props.events[i];
            var wantTile = true;
            var eventId = mxEv.getId();

            if (!EventTile.haveTileForEvent(mxEv)) {
                wantTile = false;
            }

            var last = (i == lastShownEventIndex);

            if (wantTile) {
                // make sure we unpack the array returned by _getTilesForEvent,
                // otherwise react will auto-generate keys and we will end up
                // replacing all of the DOM elements every time we paginate.
                ret.push(...this._getTilesForEvent(prevEvent, mxEv, last));
                prevEvent = mxEv;
            } else if (!mxEv.status) {
                // if we aren't showing the event, put in a dummy scroll token anyway, so
                // that we can scroll to the right place.
                ret.push(
);
            }

            var isVisibleReadMarker = false;

            if (eventId == this.props.readMarkerEventId) {
                var visible = this.props.readMarkerVisible;

                // if the read marker comes at the end of the timeline (except
                // for local echoes, which are excluded from RMs, because they
                // don't have useful event ids), we don't want to show it, but
                // we still want to create the
 for it so that the
                // algorithms which depend on its position on the screen aren't
                // confused.
                if (i >= lastShownNonLocalEchoIndex) {
                    visible = false;
                }
                ret.push(this._getReadMarkerTile(visible));
                readMarkerVisible = visible;
                isVisibleReadMarker = visible;
            }

            if (eventId == this.currentGhostEventId) {
                // if we're showing an animation, continue to show it.
                ret.push(this._getReadMarkerGhostTile());
            } else if (!isVisibleReadMarker &&
                       eventId == this.currentReadMarkerEventId) {
                // there is currently a read-up-to marker at this point, but no
                // more. Show an animation of it disappearing.
                ret.push(this._getReadMarkerGhostTile());
                this.currentGhostEventId = eventId;
            }
        }

        this.currentReadMarkerEventId = readMarkerVisible ? this.props.readMarkerEventId : null;
        return ret;
    },

    _getTilesForEvent: function(prevEvent, mxEv, last) {
        var EventTile = sdk.getComponent('rooms.EventTile');
        var DateSeparator = sdk.getComponent('messages.DateSeparator');
        var ret = [];

        // is this a continuation of the previous message?
        var continuation = false;
        if (prevEvent !== null && prevEvent.sender && mxEv.sender
                && mxEv.sender.userId === prevEvent.sender.userId
                && mxEv.getType() == prevEvent.getType()) {
            continuation = true;
        }

        // local echoes have a fake date, which could even be yesterday. Treat them
        // as 'today' for the date separators.
        var ts1 = mxEv.getTs();
        if (mxEv.status) {
            ts1 = new Date();
        }

        // do we need a date separator since the last event?
        if (this._wantsDateSeparator(prevEvent, ts1)) {
            var dateSeparator =
<DateSeparator key={ts1} ts={ts1}/>
;
            ret.push(dateSeparator);
            continuation = false;
        }

        var eventId = mxEv.getId();
        var highlight = (eventId == this.props.highlightedEventId);

        // we can't use local echoes as scroll tokens, because their event IDs change.
        // Local echos have a send "status".
        var scrollToken = mxEv.status ? undefined : eventId;

        ret.push(

                    <EventTile mxEvent={mxEv} continuation={continuation}
                        onWidgetLoad={this._onWidgetLoad}
                        last={last} isSelectedEvent={highlight} />

        );

        return ret;
    },

    _wantsDateSeparator: function(prevEvent, nextEventTs) {
        if (prevEvent == null) {
            // first event in the panel: depends if we could back-paginate from
            // here.
            return !this.props.suppressFirstDateSeparator;
        }

        return (new Date(prevEvent.getTs()).toDateString()
                !== new Date(nextEventTs).toDateString());
    },

    _getReadMarkerTile: function(visible) {
        var hr;
        if (visible) {
            hr =
;
        }

        return (

                {hr}

        );
    },

    _startAnimation: function(ghostNode) {
        Velocity(ghostNode, {opacity: '0', width: '10%'},
                 {duration: 400, easing: 'easeInSine',
                  delay: 1000});
    },

    _getReadMarkerGhostTile: function() {
        var hr =
;

        // give it a key which depends on the event id. That will ensure that
        // we get a new DOM node (restarting the animation) when the ghost
        // moves to a different event.
        return (

                {hr}

        );
    },

    _collectEventNode: function(eventId, node) {
        this.eventNodes[eventId] = node;
    },

    // once dynamic content in the events load, make the scrollPanel check the
    // scroll offsets.
    _onWidgetLoad: function() {
        var scrollPanel = this.refs.scrollPanel;
        if (scrollPanel) {
            scrollPanel.forceUpdate();
        }
    },

    onResize: function() {
        dis.dispatch({ action: 'timeline_resize' }, true);
    },

    render: function() {
        var ScrollPanel = sdk.getComponent("structures.ScrollPanel");
        var Spinner = sdk.getComponent("elements.Spinner");
        var topSpinner, bottomSpinner;
        if (this.props.backPaginating) {
            topSpinner =
<Spinner />
;
        }
        if (this.props.forwardPaginating) {
            bottomSpinner =
<Spinner />
;
        }

        return (
            <ScrollPanel ref="scrollPanel" className="mx_RoomView_messagePanel"
                    onScroll={ this.props.onScroll }
                    onResize={ this.onResize }
                    onFillRequest={ this.props.onFillRequest }
                    style={ this.props.hidden ? { display: 'none' } : {} }
                    stickyBottom={ this.props.stickyBottom }>
                {topSpinner}
                {this._getEventTiles()}
                {bottomSpinner}
            </ScrollPanel>
        );
    },
});
<|endoftext|>


<commit_before>var BrowserWindow = require('electron').remote.BrowserWindow;
var UserStore = require('../../stores/user-store.js');

var win;

function open(url) {
  var cookies = UserStore.getWebSession().cookies;

  // if we don't have cookies, abort
  if(cookies.length === 0) {
    console.log('SteamCommunityWindow: cookies are missing');
    return;
  }

  if(win) {
    console.log('SteamCommunityWindow: reusing existing instance');
    win.loadURL(url);
    return win;
  }

  console.log('SteamCommunityWindow: creating');

  win = new BrowserWindow({
    width: 1024,
    height: 768,
    show: false,
    center: true,
    title: 'Loading...',
    webPreferences: {
      nodeIntegration: false
    },
    autoHideMenuBar: true
  });

  win.on('closed', function() {
    win = null;
  });

  win.webContents.on('new-window', function(event, newUrl) {
    event.preventDefault();
    console.log('SteamCommunityWindow: opening new url');
    win.loadURL(newUrl);
  });

  cookies.forEach(function(cookie) {
    var split = cookie.split('=');

    win.webContents.session.cookies.set({
      url : 'https://steamcommunity.com',
      name : split[0],
      value : split[1],
      session: split[0].indexOf('steamLogin') > -1 ? true : false,
      secure: split[0] === 'steamLoginSecure'
    }, function(){});

    win.webContents.session.cookies.set({
      url : 'https://store.steampowered.com',
      name : split[0],
      value : split[1],
      session: split[0].indexOf('steamLogin') > -1 ? true : false,
      secure: split[0] === 'steamLoginSecure'
    }, function(){});
  });

  win.loadURL(url);
  win.show();
}

var SteamCommunityWindow = {
  open: open
};

module.exports = SteamCommunityWindow;
<commit_msg>set user agent<commit_after>var BrowserWindow = require('electron').remote.BrowserWindow;
var UserStore = require('../../stores/user-store.js');

var win;
var USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; Valve Steam Client/1451445940; ) ' +
                 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.49 Safari/537.36';

function open(url) {
  var cookies = UserStore.getWebSession().cookies;

  // if we don't have cookies, abort
  if(cookies.length === 0) {
    console.log('SteamCommunityWindow: cookies are missing');
    return;
  }

  if(win) {
    console.log('SteamCommunityWindow: reusing existing instance');
    win.loadURL(url);
    return win;
  }

  console.log('SteamCommunityWindow: creating');

  win = new BrowserWindow({
    width: 1024,
    height: 768,
    show: false,
    center: true,
    title: 'Loading...',
    webPreferences: {
      nodeIntegration: false
    },
    autoHideMenuBar: true
  });

  win.on('closed', function() {
    win = null;
  });

  win.webContents.on('new-window', function(event, newUrl) {
    event.preventDefault();
    console.log('SteamCommunityWindow: opening new url');
    win.loadURL(newUrl);
  });

  cookies.forEach(function(cookie) {
    var split = cookie.split('=');

    win.webContents.session.cookies.set({
      url : 'https://steamcommunity.com',
      name : split[0],
      value : split[1],
      session: split[0].indexOf('steamLogin') > -1 ? true : false,
      secure: split[0] === 'steamLoginSecure'
    }, function(){});

    win.webContents.session.cookies.set({
      url : 'https://store.steampowered.com',
      name : split[0],
      value : split[1],
      session: split[0].indexOf('steamLogin') > -1 ? true : false,
      secure: split[0] === 'steamLoginSecure'
    }, function(){});
  });

  win.loadURL(url, { userAgent: USER_AGENT });
  win.show();
}

var SteamCommunityWindow = {
  open: open
};

module.exports = SteamCommunityWindow;
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

import { mount } from 'enzyme';

import { WeatherList } from './weather-list';

const exampleWeatherResponse = {
  coord: { lon: -122.09, lat: 37.39 },
  sys: {
    type: 3,
    id: 168940,
    message: 0.0297,
    country: 'US',
    sunrise: 1427723751,
    sunset: 1427768967
  },
  weather: [
    { id: 800, main: 'Clear', description: 'Sky is Clear', icon: '01n' }
  ],
  base: 'stations',
  main: {
    temp: 285.68,
    humidity: 74,
    pressure: 1016.8,
    temp_min: 284.82,
    temp_max: 286.48
  },
  wind: { speed: 0.96, deg: 285.001 },
  clouds: { all: 0 },
  dt: 1427700245,
  id: 0,
  name: 'Mountain View',
  cod: 200
};

const props = {
  weather: [],
  actions: {
    fetchWeatherFromLocalStorage: jest.fn(),
    fetchWeatherFromOpenWeather: jest.fn(),
    fetchForecastFromOpenWeather: jest.fn(),
    fetchForecastFromLocalStorage: jest.fn()
  }
};

const props2 = {
  weather: [exampleWeatherResponse],
  actions: {
    fetchWeatherUpdate: jest.fn(),
    fetchWeatherFromLocalStorage: jest.fn(),
    fetchWeatherFromOpenWeather: jest.fn(),
    fetchForecastFromOpenWeather: jest.fn(),
    fetchForecastFromLocalStorage: jest.fn()
  },
  options: {}
};

it('should load when there are no cities', () => {
  const wrapper = mount(<WeatherList {...props} />);
  expect(wrapper.text()).toBe('No cities here - search for one!');
});

it('should display a city when pass in as a prop', () => {
  const wrapper = mount(<WeatherList {...props2} />);
  expect(wrapper.text()).toMatch(/Mountain View/);
});

it('should call localstorage when a city is added', () => {
  let node = document.createElement('div');
  // Note that first time props is used, second time, props2!
  ReactDOM.render(<WeatherList {...props} />, node);
  ReactDOM.render(<WeatherList {...props2} />, node);
  expect(localStorage.setItem).toHaveBeenCalledTimes(1);
});
<commit_msg>add timeFetched, two tests<commit_after>import React from 'react';
import ReactDOM from 'react-dom';

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

import { mount } from 'enzyme';

import { WeatherList } from './weather-list';

const exampleWeatherResponse = {
  coord: { lon: -122.09, lat: 37.39 },
  sys: {
    type: 3,
    id: 168940,
    message: 0.0297,
    country: 'US',
    sunrise: 1427723751,
    sunset: 1427768967
  },
  weather: [
    { id: 800, main: 'Clear', description: 'Sky is Clear', icon: '01n' }
  ],
  base: 'stations',
  main: {
    temp: 285.68,
    humidity: 74,
    pressure: 1016.8,
    temp_min: 284.82,
    temp_max: 286.48
  },
  wind: { speed: 0.96, deg: 285.001 },
  clouds: { all: 0 },
  dt: 1427700245,
  id: 0,
  name: 'Mountain View',
  cod: 200,
  timeFetched: 0
};

const props = {
  weather: [],
  actions: {
    fetchWeatherFromLocalStorage: jest.fn(),
    fetchWeatherFromOpenWeather: jest.fn(),
    fetchForecastFromOpenWeather: jest.fn(),
    fetchForecastFromLocalStorage: jest.fn()
  }
};

const props2 = {
  weather: [exampleWeatherResponse],
  actions: {
    fetchWeatherUpdate: jest.fn(),
    fetchWeatherFromLocalStorage: jest.fn(),
    fetchWeatherFromOpenWeather: jest.fn(),
    fetchForecastFromOpenWeather: jest.fn(),
    fetchForecastFromLocalStorage: jest.fn()
  },
  options: {}
};

it('should load when there are no cities', () => {
  const wrapper = mount(<WeatherList {...props} />);
  expect(wrapper.text()).toBe('No cities here - search for one!');
});

it('should display a city when pass in as a prop', () => {
  const wrapper = mount(<WeatherList {...props2} />);
  expect(wrapper.text()).toMatch(/Mountain View/);
});

it('should call localstorage when a city is added', () => {
  let node = document.createElement('div');
  // Note that first time props is used, second time, props2!
  ReactDOM.render(<WeatherList {...props} />, node);
  ReactDOM.render(<WeatherList {...props2} />, node);
  expect(localStorage.setItem).toHaveBeenCalledTimes(1);
});

it('should fetchWeatherUpdate when weather is > 30 min old', () => {
  let node = document.createElement('div');
  ReactDOM.render(<WeatherList {...props2} />, node);
  expect(props2.actions.fetchWeatherUpdate).toHaveBeenLastCalledWith(
    exampleWeatherResponse.id
  );
});

it('should fetch weather, forecast from localstorage when mounted', () => {
  let node = document.createElement('div');
  // Note that first time props is used, second time, props2!
  ReactDOM.render(<WeatherList {...props} />, node);
  expect(props2.actions.fetchWeatherFromLocalStorage).toHaveBeenCalledWith();
  expect(props2.actions.fetchForecastFromLocalStorage).toHaveBeenCalledWith();
});
<|endoftext|>