<commit_before>const { Command } = require('discord.js-commando');

const UserRep = require('../../postgreSQL/models/UserRep');

module.exports = class RepPositiveCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'rep-add',
			aliases: ['add-rep', 'rep-pos', 'pos-rep', '++'],
			group: 'rep',
			memberName: 'positive',
			description: 'Add a positive reputation point to a user.',
			guildOnly: true,

			args: [
				{
					key: 'user',
					prompt: 'whom would you like to give a positive reputation point?',
					type: 'user'
				},
				{
					key: 'message',
					prompt: 'add a nice message.',
					type: 'string',
					max: 200,
					default: ''
				}
			]
		});
	}

	async run(msg, args) {
		const { user, message } = args;

		if (user.id === msg.author.id) return msg.reply('you can\'t change your own reputation like that!');

		const alreadyRepped = await UserRep.findOne({
			where: {
				userID: user.id,
				reputationBy: msg.author.id
			}
		});

		if (alreadyRepped && alreadyRepped.reputationType === '+') return msg.reply('you have already given a positive reputation point to this user.');
		if (alreadyRepped) await alreadyRepped.destroy();

		await UserRep.create({
			userID: user.id,
			reputationType: '+',
			reputationBy: msg.author.id,
			reputationMessage: message || null
		});

		return msg.reply(`you've successfully added a positive reputation point to ${user.member.displayName}.`);
	}
};
<commit_msg>Update positive.js<commit_after>const { Command } = require('discord.js-commando');

const UserRep = require('../../postgreSQL/models/UserRep');

module.exports = class RepPositiveCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'rep-add',
			aliases: ['add-rep', 'rep-pos', 'pos-rep', '++'],
			group: 'rep',
			memberName: 'positive',
			description: 'Add a positive reputation point to a user.',
			guildOnly: true,

			args: [
				{
					key: 'member',
					prompt: 'whom would you like to give a positive reputation point?',
					type: 'member'
				},
				{
					key: 'message',
					prompt: 'add a nice message.',
					type: 'string',
					max: 200,
					default: ''
				}
			]
		});
	}

	async run(msg, args) {
		const { member, message } = args;

		if (member.id === msg.author.id) return msg.reply('you can\'t change your own reputation like that!');

		const alreadyRepped = await UserRep.findOne({
			where: {
				userID: member.id,
				reputationBy: msg.author.id
			}
		});

		if (alreadyRepped && alreadyRepped.reputationType === '+') return msg.reply('you have already given a positive reputation point to this user.');
		if (alreadyRepped) await alreadyRepped.destroy();

		await UserRep.create({
			userID: member.id,
			reputationType: '+',
			reputationBy: msg.author.id,
			reputationMessage: message || null
		});

		return msg.reply(`you've successfully added a positive reputation point to ${member.displayName}.`);
	}
};
<|endoftext|>


<commit_before>"use strict";
var q = require("q");
var sdk = require("../..");
var MatrixClient = sdk.MatrixClient;
var utils = require("../test-utils");

describe("MatrixClient", function() {
    var userId = "@alice:bar";
    var identityServerUrl = "https://identity.server";
    var client, store, scheduler;

    var initialSyncData = {
        end: "s_5_3",
        presence: [],
        rooms: []
    };

    var eventData = {
        start: "s_START",
        end: "s_END",
        chunk: []
    };

    var PUSH_RULES_RESPONSE = {
        method: "GET", path: "/pushrules/", data: {}
    };

    var httpLookups = [
        // items are objects which look like:
        // {
        //   method: "GET",
        //   path: "/initialSync",
        //   data: {},
        //   error: { errcode: M_FORBIDDEN } // if present will reject promise,
        //   expectBody: {} // additional expects on the body
        // }
        // items are popped off when processed and block if no items left.
    ];
    var pendingLookup = null;
    function httpReq(cb, method, path, qp, data, prefix) {
        var next = httpLookups.shift();
        var logLine = (
            "MatrixClient[UT] RECV " + method + " " + path + "  " +
            "EXPECT " + (next ? next.method : next) + " " + (next ? next.path : next)
        );
        console.log(logLine);

        if (!next) { // no more things to return
            if (pendingLookup) {
                if (pendingLookup.method === method && pendingLookup.path === path) {
                    return pendingLookup.promise;
                }
                // >1 pending thing, and they are different, whine.
                expect(false).toBe(
                    true, ">1 pending request. You should probably handle them. " +
                    "PENDING: " + JSON.stringify(pendingLookup) + " JUST GOT: " +
                    method + " " + path
                );
            }
            pendingLookup = {
                promise: q.defer().promise,
                method: method,
                path: path
            };
            return pendingLookup.promise;
        }
        if (next.path === path && next.method === method) {
            console.log(
                "MatrixClient[UT] Matched. Returning " +
                (next.error ? "BAD" : "GOOD") + " response"
            );
            if (next.expectBody) {
                expect(next.expectBody).toEqual(data);
            }
            if (next.error) {
                return q.reject({
                    errcode: next.error.errcode,
                    name: next.error.errcode,
                    message: "Expected testing error",
                    data: next.error
                });
            }
            return q(next.data);
        }
        expect(true).toBe(false, "Expected different request. " + logLine);
        return q.defer().promise;
    }

    beforeEach(function() {
        utils.beforeEach(this);
        jasmine.Clock.useMock();
        scheduler = jasmine.createSpyObj("scheduler", [
            "getQueueForEvent", "queueEvent", "removeEventFromQueue",
            "setProcessFunction"
        ]);
        store = jasmine.createSpyObj("store", [
            "getRoom", "getRooms", "getUser", "getSyncToken", "scrollback",
            "setSyncToken", "storeEvents", "storeRoom", "storeUser"
        ]);
        client = new MatrixClient({
            baseUrl: "https://my.home.server",
            idBaseUrl: identityServerUrl,
            accessToken: "my.access.token",
            request: function() {}, // NOP
            store: store,
            scheduler: scheduler,
            userId: userId
        });
        // FIXME: We shouldn't be yanking _http like this.
        client._http = jasmine.createSpyObj("httpApi", [
            "authedRequest", "authedRequestWithPrefix", "getContentUri",
            "request", "requestWithPrefix", "uploadContent"
        ]);
        client._http.authedRequest.andCallFake(httpReq);
        client._http.authedRequestWithPrefix.andCallFake(httpReq);

        // set reasonable working defaults
        pendingLookup = null;
        httpLookups = [];
        httpLookups.push(PUSH_RULES_RESPONSE);
        httpLookups.push({
            method: "GET", path: "/initialSync", data: initialSyncData
        });
    });

    afterEach(function() {
        // need to re-stub the requests with NOPs because there are no guarantees
        // clients from previous tests will be GC'd before the next test. This
        // means they may call /events and then fail an expect() which will fail
        // a DIFFERENT test (pollution between tests!) - we return unresolved
        // promises to stop the client from continuing to run.
        client._http.authedRequest.andCallFake(function() {
            return q.defer().promise;
        });
        client._http.authedRequestWithPrefix.andCallFake(function() {
            return q.defer().promise;
        });
    });

    describe("getSyncState", function() {

        it("should return null if the client isn't started", function() {
            expect(client.getSyncState()).toBeNull();
        });

        it("should return the same sync state as emitted sync events", function(done) {
            client.on("sync", function(state) {
                expect(state).toEqual(client.getSyncState());
                if (state === "SYNCING") {
                    done();
                }
            });
            client.startClient();
        });
    });

    describe("retryImmediately", function() {
        it("should return false if there is no request waiting", function() {
            client.startClient();
            expect(client.retryImmediately()).toBe(false);
        });

        it("should work on /initialSync", function(done) {
            httpLookups = [];
            httpLookups.push(PUSH_RULES_RESPONSE);
            httpLookups.push({
                method: "GET", path: "/initialSync", error: { errcode: "NOPE_NOPE_NOPE" }
            });
            httpLookups.push({
                method: "GET", path: "/initialSync", error: { errcode: "NOPE_NOPE_NOPE" }
            });

            client.on("sync", function(state) {
                if (state === "ERROR" && httpLookups.length > 0) {
                    expect(httpLookups.length).toEqual(1);
                    expect(client.retryImmediately()).toBe(true);
                    expect(httpLookups.length).toEqual(0);
                    done();
                }
            });
            client.startClient();
        });

        it("should work on /events", function(done) {
            httpLookups.push({
                method: "GET", path: "/events", error: { errcode: "NOPE_NOPE_NOPE" }
            });
            httpLookups.push({
                method: "GET", path: "/events", data: eventData
            });

            client.on("sync", function(state) {
                if (state === "ERROR" && httpLookups.length > 0) {
                    expect(httpLookups.length).toEqual(1);
                    expect(client.retryImmediately()).toBe(true);
                    expect(httpLookups.length).toEqual(0);
                    done();
                }
            });
            client.startClient();
        });

        it("should work on /pushrules", function(done) {
            httpLookups = [];
            httpLookups.push({
                method: "GET", path: "/pushrules/", error: { errcode: "NOPE_NOPE_NOPE" }
            });
            httpLookups.push({
                method: "GET", path: "/pushrules/", error: { errcode: "NOPE_NOPE_NOPE" }
            });

            client.on("sync", function(state) {
                if (state === "ERROR" && httpLookups.length > 0) {
                    expect(httpLookups.length).toEqual(1);
                    expect(client.retryImmediately()).toBe(true);
                    expect(httpLookups.length).toEqual(0);
                    done();
                }
            });
            client.startClient();
        });
    });

    describe("emitted sync events", function() {
        var expectedStates;

        function syncChecker(done) {
            return function(state, old) {
                var expected = expectedStates.shift();
                console.log(
                    "'sync' curr=%s old=%s EXPECT=%s", state, old, expected
                );
                if (!expected) {
                    done();
                    return;
                }
                expect(state).toEqual(expected[0]);
                expect(old).toEqual(expected[1]);
                if (expectedStates.length === 0) {
                    done();
                }
                // standard retry time is 4s
                jasmine.Clock.tick(4001);
            };
        }

        beforeEach(function() {
            expectedStates = [
            //  [current, old]
            ];
        });

        it("should transition null -> PREPARED after /initialSync", function(done) {
            expectedStates.push(["PREPARED", null]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition null -> ERROR after a failed /initialSync", function(done) {
            httpLookups = [];
            httpLookups.push(PUSH_RULES_RESPONSE);
            httpLookups.push({
                method: "GET", path: "/initialSync", error: { errcode: "NOPE_NOPE_NOPE" }
            });
            expectedStates.push(["ERROR", null]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition ERROR -> PREPARED after /initialSync if prev failed",
        function(done) {
            httpLookups = [];
            httpLookups.push(PUSH_RULES_RESPONSE);
            httpLookups.push({
                method: "GET", path: "/initialSync", error: { errcode: "NOPE_NOPE_NOPE" }
            });
            httpLookups.push({
                method: "GET", path: "/initialSync", data: initialSyncData
            });

            expectedStates.push(["ERROR", null]);
            expectedStates.push(["PREPARED", "ERROR"]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition PREPARED -> SYNCING after /initialSync", function(done) {
            expectedStates.push(["PREPARED", null]);
            expectedStates.push(["SYNCING", "PREPARED"]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition SYNCING -> ERROR after a failed /events", function(done) {
            httpLookups.push({
                method: "GET", path: "/events", error: { errcode: "NONONONONO" }
            });

            expectedStates.push(["PREPARED", null]);
            expectedStates.push(["SYNCING", "PREPARED"]);
            expectedStates.push(["ERROR", "SYNCING"]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition ERROR -> SYNCING after /events if prev failed",
        function(done) {
            httpLookups.push({
                method: "GET", path: "/events", error: { errcode: "NONONONONO" }
            });
            httpLookups.push({
                method: "GET", path: "/events", data: eventData
            });

            expectedStates.push(["PREPARED", null]);
            expectedStates.push(["SYNCING", "PREPARED"]);
            expectedStates.push(["ERROR", "SYNCING"]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition ERROR -> ERROR if multiple /events fails", function(done) {
            httpLookups.push({
                method: "GET", path: "/events", error: { errcode: "NONONONONO" }
            });
            httpLookups.push({
                method: "GET", path: "/events", error: { errcode: "NONONONONO" }
            });

            expectedStates.push(["PREPARED", null]);
            expectedStates.push(["SYNCING", "PREPARED"]);
            expectedStates.push(["ERROR", "SYNCING"]);
            expectedStates.push(["ERROR", "ERROR"]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });
    });

    describe("inviteByEmail", function() {
        var roomId = "!foo:bar";

        it("should send an invite HTTP POST", function() {
            httpLookups = [{
                method: "POST",
                path: "/rooms/!foo%3Abar/invite",
                data: {},
                expectBody: {
                    id_server: identityServerUrl,
                    medium: "email",
                    address: "alice@gmail.com"
                }
            }];
            client.inviteByEmail(roomId, "alice@gmail.com");
            expect(httpLookups.length).toEqual(0);
        });

    });
});
<commit_msg>Guest rooms UTs<commit_after>"use strict";
var q = require("q");
var sdk = require("../..");
var MatrixClient = sdk.MatrixClient;
var utils = require("../test-utils");

describe("MatrixClient", function() {
    var userId = "@alice:bar";
    var identityServerUrl = "https://identity.server";
    var client, store, scheduler;

    var initialSyncData = {
        end: "s_5_3",
        presence: [],
        rooms: []
    };

    var eventData = {
        start: "s_START",
        end: "s_END",
        chunk: []
    };

    var PUSH_RULES_RESPONSE = {
        method: "GET", path: "/pushrules/", data: {}
    };

    var httpLookups = [
        // items are objects which look like:
        // {
        //   method: "GET",
        //   path: "/initialSync",
        //   data: {},
        //   error: { errcode: M_FORBIDDEN } // if present will reject promise,
        //   expectBody: {} // additional expects on the body
        //   expectQueryParams: {} // additional expects on query params
        //   thenCall: function(){} // function to call *AFTER* returning response.
        // }
        // items are popped off when processed and block if no items left.
    ];
    var pendingLookup = null;
    function httpReq(cb, method, path, qp, data, prefix) {
        var next = httpLookups.shift();
        var logLine = (
            "MatrixClient[UT] RECV " + method + " " + path + "  " +
            "EXPECT " + (next ? next.method : next) + " " + (next ? next.path : next)
        );
        console.log(logLine);

        if (!next) { // no more things to return
            if (pendingLookup) {
                if (pendingLookup.method === method && pendingLookup.path === path) {
                    return pendingLookup.promise;
                }
                // >1 pending thing, and they are different, whine.
                expect(false).toBe(
                    true, ">1 pending request. You should probably handle them. " +
                    "PENDING: " + JSON.stringify(pendingLookup) + " JUST GOT: " +
                    method + " " + path
                );
            }
            pendingLookup = {
                promise: q.defer().promise,
                method: method,
                path: path
            };
            return pendingLookup.promise;
        }
        if (next.path === path && next.method === method) {
            console.log(
                "MatrixClient[UT] Matched. Returning " +
                (next.error ? "BAD" : "GOOD") + " response"
            );
            if (next.expectBody) {
                expect(next.expectBody).toEqual(data);
            }
            if (next.expectQueryParams) {
                Object.keys(next.expectQueryParams).forEach(function(k) {
                    expect(qp[k]).toEqual(next.expectQueryParams[k]);
                });
            }

            if (next.thenCall) {
                process.nextTick(next.thenCall, 0); // next tick so we return first.
            }

            if (next.error) {
                return q.reject({
                    errcode: next.error.errcode,
                    name: next.error.errcode,
                    message: "Expected testing error",
                    data: next.error
                });
            }
            return q(next.data);
        }
        expect(true).toBe(false, "Expected different request. " + logLine);
        return q.defer().promise;
    }

    beforeEach(function() {
        utils.beforeEach(this);
        jasmine.Clock.useMock();
        scheduler = jasmine.createSpyObj("scheduler", [
            "getQueueForEvent", "queueEvent", "removeEventFromQueue",
            "setProcessFunction"
        ]);
        store = jasmine.createSpyObj("store", [
            "getRoom", "getRooms", "getUser", "getSyncToken", "scrollback",
            "setSyncToken", "storeEvents", "storeRoom", "storeUser"
        ]);
        client = new MatrixClient({
            baseUrl: "https://my.home.server",
            idBaseUrl: identityServerUrl,
            accessToken: "my.access.token",
            request: function() {}, // NOP
            store: store,
            scheduler: scheduler,
            userId: userId
        });
        // FIXME: We shouldn't be yanking _http like this.
        client._http = jasmine.createSpyObj("httpApi", [
            "authedRequest", "authedRequestWithPrefix", "getContentUri",
            "request", "requestWithPrefix", "uploadContent"
        ]);
        client._http.authedRequest.andCallFake(httpReq);
        client._http.authedRequestWithPrefix.andCallFake(httpReq);

        // set reasonable working defaults
        pendingLookup = null;
        httpLookups = [];
        httpLookups.push(PUSH_RULES_RESPONSE);
        httpLookups.push({
            method: "GET", path: "/initialSync", data: initialSyncData
        });
    });

    afterEach(function() {
        // need to re-stub the requests with NOPs because there are no guarantees
        // clients from previous tests will be GC'd before the next test. This
        // means they may call /events and then fail an expect() which will fail
        // a DIFFERENT test (pollution between tests!) - we return unresolved
        // promises to stop the client from continuing to run.
        client._http.authedRequest.andCallFake(function() {
            return q.defer().promise;
        });
        client._http.authedRequestWithPrefix.andCallFake(function() {
            return q.defer().promise;
        });
    });

    describe("getSyncState", function() {

        it("should return null if the client isn't started", function() {
            expect(client.getSyncState()).toBeNull();
        });

        it("should return the same sync state as emitted sync events", function(done) {
            client.on("sync", function(state) {
                expect(state).toEqual(client.getSyncState());
                if (state === "SYNCING") {
                    done();
                }
            });
            client.startClient();
        });
    });

    describe("retryImmediately", function() {
        it("should return false if there is no request waiting", function() {
            client.startClient();
            expect(client.retryImmediately()).toBe(false);
        });

        it("should work on /initialSync", function(done) {
            httpLookups = [];
            httpLookups.push(PUSH_RULES_RESPONSE);
            httpLookups.push({
                method: "GET", path: "/initialSync", error: { errcode: "NOPE_NOPE_NOPE" }
            });
            httpLookups.push({
                method: "GET", path: "/initialSync", error: { errcode: "NOPE_NOPE_NOPE" }
            });

            client.on("sync", function(state) {
                if (state === "ERROR" && httpLookups.length > 0) {
                    expect(httpLookups.length).toEqual(1);
                    expect(client.retryImmediately()).toBe(true);
                    expect(httpLookups.length).toEqual(0);
                    done();
                }
            });
            client.startClient();
        });

        it("should work on /events", function(done) {
            httpLookups.push({
                method: "GET", path: "/events", error: { errcode: "NOPE_NOPE_NOPE" }
            });
            httpLookups.push({
                method: "GET", path: "/events", data: eventData
            });

            client.on("sync", function(state) {
                if (state === "ERROR" && httpLookups.length > 0) {
                    expect(httpLookups.length).toEqual(1);
                    expect(client.retryImmediately()).toBe(true);
                    expect(httpLookups.length).toEqual(0);
                    done();
                }
            });
            client.startClient();
        });

        it("should work on /pushrules", function(done) {
            httpLookups = [];
            httpLookups.push({
                method: "GET", path: "/pushrules/", error: { errcode: "NOPE_NOPE_NOPE" }
            });
            httpLookups.push({
                method: "GET", path: "/pushrules/", error: { errcode: "NOPE_NOPE_NOPE" }
            });

            client.on("sync", function(state) {
                if (state === "ERROR" && httpLookups.length > 0) {
                    expect(httpLookups.length).toEqual(1);
                    expect(client.retryImmediately()).toBe(true);
                    expect(httpLookups.length).toEqual(0);
                    done();
                }
            });
            client.startClient();
        });
    });

    describe("emitted sync events", function() {
        var expectedStates;

        function syncChecker(done) {
            return function(state, old) {
                var expected = expectedStates.shift();
                console.log(
                    "'sync' curr=%s old=%s EXPECT=%s", state, old, expected
                );
                if (!expected) {
                    done();
                    return;
                }
                expect(state).toEqual(expected[0]);
                expect(old).toEqual(expected[1]);
                if (expectedStates.length === 0) {
                    done();
                }
                // standard retry time is 4s
                jasmine.Clock.tick(4001);
            };
        }

        beforeEach(function() {
            expectedStates = [
            //  [current, old]
            ];
        });

        it("should transition null -> PREPARED after /initialSync", function(done) {
            expectedStates.push(["PREPARED", null]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition null -> ERROR after a failed /initialSync", function(done) {
            httpLookups = [];
            httpLookups.push(PUSH_RULES_RESPONSE);
            httpLookups.push({
                method: "GET", path: "/initialSync", error: { errcode: "NOPE_NOPE_NOPE" }
            });
            expectedStates.push(["ERROR", null]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition ERROR -> PREPARED after /initialSync if prev failed",
        function(done) {
            httpLookups = [];
            httpLookups.push(PUSH_RULES_RESPONSE);
            httpLookups.push({
                method: "GET", path: "/initialSync", error: { errcode: "NOPE_NOPE_NOPE" }
            });
            httpLookups.push({
                method: "GET", path: "/initialSync", data: initialSyncData
            });

            expectedStates.push(["ERROR", null]);
            expectedStates.push(["PREPARED", "ERROR"]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition PREPARED -> SYNCING after /initialSync", function(done) {
            expectedStates.push(["PREPARED", null]);
            expectedStates.push(["SYNCING", "PREPARED"]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition SYNCING -> ERROR after a failed /events", function(done) {
            httpLookups.push({
                method: "GET", path: "/events", error: { errcode: "NONONONONO" }
            });

            expectedStates.push(["PREPARED", null]);
            expectedStates.push(["SYNCING", "PREPARED"]);
            expectedStates.push(["ERROR", "SYNCING"]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition ERROR -> SYNCING after /events if prev failed",
        function(done) {
            httpLookups.push({
                method: "GET", path: "/events", error: { errcode: "NONONONONO" }
            });
            httpLookups.push({
                method: "GET", path: "/events", data: eventData
            });

            expectedStates.push(["PREPARED", null]);
            expectedStates.push(["SYNCING", "PREPARED"]);
            expectedStates.push(["ERROR", "SYNCING"]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });

        it("should transition ERROR -> ERROR if multiple /events fails", function(done) {
            httpLookups.push({
                method: "GET", path: "/events", error: { errcode: "NONONONONO" }
            });
            httpLookups.push({
                method: "GET", path: "/events", error: { errcode: "NONONONONO" }
            });

            expectedStates.push(["PREPARED", null]);
            expectedStates.push(["SYNCING", "PREPARED"]);
            expectedStates.push(["ERROR", "SYNCING"]);
            expectedStates.push(["ERROR", "ERROR"]);
            client.on("sync", syncChecker(done));
            client.startClient();
        });
    });

    describe("inviteByEmail", function() {
        var roomId = "!foo:bar";

        it("should send an invite HTTP POST", function() {
            httpLookups = [{
                method: "POST",
                path: "/rooms/!foo%3Abar/invite",
                data: {},
                expectBody: {
                    id_server: identityServerUrl,
                    medium: "email",
                    address: "alice@gmail.com"
                }
            }];
            client.inviteByEmail(roomId, "alice@gmail.com");
            expect(httpLookups.length).toEqual(0);
        });

    });

    describe("guest rooms", function() {
        var roomIds = [
            "!foo:bar", "!baz:bar"
        ];

        it("should be set via setGuestRooms and used in /events calls", function(done) {
            httpLookups.push({
                method: "GET",
                path: "/events",
                data: eventData,
                expectQueryParams: {
                    room_id: roomIds
                },
                thenCall: function() {
                    done();
                }
            });
            client.setGuestRooms(roomIds);
            client.startClient();
        });
    });
});
<|endoftext|>


<commit_before>/*
 * TODO:
 * - disable all sections except current OR disable page scroll
 * - jumpto function from websockets to jump to next page
 * -
 */

//change LOCALHOST to your IP to enable connecting from other devices

var socket = io.connect('http://localhost:8080');

//var socket = io.connect('http://192.168.0.33:80');

var thisUser = {
	name: "phone" + Math.floor(Math.random()*10000000000)
};

(function() {

	var currentPage = 1; // first section
	var voteSlider = null;
	var chosenImages = [-1,-1,-1];

	function preventEvent ( event ){
		//console.log('prevented');
		event.preventDefault();
	}

	// initialize fullpage scrolling plugin
	$(document).ready(function() {
		voteSlider = new Dragdealer('vote-slider');

		var section5Rows = 6;

        $('#section5 .row').css('height', ($(window).height()/section5Rows) + 'px');

		$('#fullpage').fullpage({
			sectionsColor: ['#000', '#200', '#000', '#002', '#000', '#022', '#000','#202'],
			afterLoad: function(anchorLink, index) {
				if (index == 5)
				{
					//console.log('section 5');
					var sec5Imgs = $('#section5 .row img');
					if (sec5Imgs.length > 0)
					{
						var h = sec5Imgs[0].height;
						var w = sec5Imgs[0].width;

						$('.replaceme').height( h );
						$('.replaceme').width( w );
						$('li').height( h );
					}
				}
			},

			afterResize: function()
            {
                var windowsHeight = $(window).height();

                $('#section5 .row').css('height', (windowsHeight/section5Rows) + 'px');

                // TODO: consolide with above code
                var sec5Imgs = $('#section5 .row img');
					if (sec5Imgs.length > 0)
					{
						var h = sec5Imgs[0].height;
						var w = sec5Imgs[0].width;

						$('.replaceme').height( h );
						$('.replaceme').width( w );
						$('li').height( h );
					}
            }
		});
		// turn of scrolling - this is done by the 'conductor' only
		$.fn.fullpage.setAllowScrolling(false);
		$.fn.fullpage.setKeyboardScrolling(false);

		//
		// image dragging/voting section
		//

		$( ".draggable" ).draggable({
	      revert: "invalid", // when not dropped, the item will revert back to its initial position
	      containment: "document",
	      //helper: "clone",
	      cursor: "move",
	      start: function(){
     	   //get the start position
        	var start = {left: $(this).position().left, top:$(this).position().top};
        	//store the start position on this element
        	$(this).data('start', start);
    	  }
		});

	    var i=3;

	    while (i--)
	    {
	    	$( ".targetx-"+i ).data('targetIndex', i);

		    $( ".targetx-"+i ).droppable({
		      //accept: ".choice-"+i,
		      accept: ".draggable",
		      activeClass: "target-active",
		      hoverClass: "target-hover",
		      drop: function( event, ui ) {
		      	var me = $( this );

		      	if ( me.hasClass("target-dropped") )
		      	{
		      		// TODO - something
		      	}
		      	else
		      	{
		      		var src = ui.draggable.find('img').attr( "src" );
		      		//console.log('src=' + src);

			        me.addClass( "target-dropped" )
			          .find( ".replaceme")
			           	// TODO: make this work!
			          	//.replaceWith('

')
			          	.replaceWith('

')
			          	.end();

			        var sec5Imgs = $('#section5 .row img');
					if (sec5Imgs.length > 0)
					{
						var h = sec5Imgs[0].height;
						var w = sec5Imgs[0].width;

						$('.replaceme').height( h );
						$('.replaceme').width( w );
					}

			        // check class to keep track...
			        // TODO: find a better way... regex match of class would be better
			        if (ui.draggable.hasClass('choice-0'))
			        {
			        	chosenImages[0] = me.data('targetIndex');
			        }
			        else if (ui.draggable.hasClass('choice-1'))
			        {
			        	chosenImages[1] = me.data('targetIndex');
			        }
			        else if (ui.draggable.hasClass('choice-2'))
			        {
			        	chosenImages[2] = me.data('targetIndex');
			        }

			        ui.draggable.fadeOut(function() {
			        	//ui.draggable.remove();

			        	//determine the start/end positions

				        //var end = {left: $(this).position().left, top: $(this).position().top } ;
				        var start = $(this).data('start');

				        $(this).css({top: start.top, left: start.left});
				        $(this).find('img').css({border: 'none', opacity:0.3});
				        ui.draggable.draggable("disable", 1);

				        $(this).fadeIn();

			        });

			  	}

			      // check if all 3 images have been dropped and finish button can be activated
			      var totalDropped = $('.target-dropped').length;

			      if (totalDropped == 3)
			      {
					$('#finish-button').removeClass('disabled').html('send vote!');

					// this should broadcast image results back to server...
					$('#finish-button').click( function() {

						socket.emit('images', chosenImages);

						//console.log( chosenImages);

						$('#finish-button').addClass('disabled')
							.off()
							.html('sent!');
					});

			      }
			  }
		    });
		}

		$('#email').on('click', function()
		{
			$(this).val("");
		});

		$('#email-button').on('click', function()
		{

			var email = $('#email').val();
			console.log('sending email: ' + email);
			socket.emit('e', email);
			$(this).addClass('disabled')
							.off()
							.html('sent!');
		});

	});
	//
	// end document onready
	//

	//
	// voting buttons for slide 3
	//
	function voteUp()
	{
		//console.log(thisUser)
		socket.emit('vote', 1);
	}

	function voteDown()
	{
		//console.log(thisUser)
		socket.emit('vote', -1);
	}

	// TODO - CSS animation add/remove

	$('#vote-left').click( voteDown );
	$('#vote-right').click( voteUp );

	//
	// websockets
	//

	// on connection to server
	socket.on('connect', function() {
		/*
		thisUser.gui = new Array()

		for (var i=0;i<nx.nxObjects.length;i++) {
			thisUser.gui.push({
				type: nx.nxObjects[i].getName(),
				x: nx.nxObjects[i].offset.left,
				y: nx.nxObjects[i].offset.top,
				width: nx.nxObjects[i].width,
				height: nx.nxObjects[i].height,
				oscName: nx.nxObjects[i].oscName
			})
			thisUser.gui[i].oscName = thisUser.gui[i].oscName.replace("/","")
		}
*/
		//console.log(thisUser)
		socket.emit('adduser', thisUser);

		// Whenever the server emits 'new message', update the chat body
		socket.on('new user', function (data) {
		   // console.log(data);
		});

		socket.on('jumpto', function (index) {
			// jump to section data using fullpage...
			if (currentPage != index)
			{
				$.fn.fullpage.moveTo( index );
				currentPage = index;
				console.log('jumped to ' + index);
			}
		});

		socket.on('scrollingState', function (state) {
			$.fn.fullpage.setAllowScrolling(state);
		});

		socket.on('voteData', function (voteData) {
			// do some sanity checks on vote data
			//
			var ave = voteData.average;
			var val = (!ave || isNaN(ave)) ? 0 : ave;

			val = Math.max(ave,-1);
			val = Math.min(ave,1);
			val = (val + 1) * 0.5;
			//console.log(val);
			voteSlider.setValue(val);
			//slider1.set({ value: val });
		});

	});

/*
	nx.onload = function() {
		nx.sendsTo("node")
	};
*/
})();<commit_msg>removed AfterResize function based on prev css fix<commit_after>/*
 * TODO:
 * - disable all sections except current OR disable page scroll
 * - jumpto function from websockets to jump to next page
 * -
 */

//change LOCALHOST to your IP to enable connecting from other devices

var socket = io.connect('http://localhost:8080');

//var socket = io.connect('http://192.168.0.33:80');

var thisUser = {
	name: "phone" + Math.floor(Math.random()*10000000000)
};

(function() {

	var currentPage = 1; // first section
	var voteSlider = null;
	var chosenImages = [-1,-1,-1];

	function preventEvent ( event ){
		//console.log('prevented');
		event.preventDefault();
	}

	// initialize fullpage scrolling plugin
	$(document).ready(function() {
		voteSlider = new Dragdealer('vote-slider');

		var section5Rows = 6;

        $('#section5 .row').css('height', ($(window).height()/section5Rows) + 'px');

		$('#fullpage').fullpage({
			sectionsColor: ['#000', '#200', '#000', '#002', '#000', '#022', '#000','#202'],
			afterLoad: function(anchorLink, index) {
				if (index == 5)
				{
					//console.log('section 5');
					var sec5Imgs = $('#section5 .row img');
					if (sec5Imgs.length > 0)
					{
						var h = sec5Imgs[0].height;
						var w = sec5Imgs[0].width;

						$('.replaceme').height( h );
						$('.replaceme').width( w );
						$('li').height( h );
					}
				}
			},
			/*
			afterResize:
			function()
            {
                var windowsHeight = $(window).height();

                $('#section5 .row').css('height', (windowsHeight/section5Rows) + 'px');

                // TODO: consolide with above code
                var sec5Imgs = $('#section5 .row img');
					if (sec5Imgs.length > 0)
					{
						var h = sec5Imgs[0].height;
						var w = sec5Imgs[0].width;

						$('.replaceme').height( h );
						$('.replaceme').width( w );
						$('li').height( h );
					}
            }
            */
		});
		// turn of scrolling - this is done by the 'conductor' only
		$.fn.fullpage.setAllowScrolling(false);
		$.fn.fullpage.setKeyboardScrolling(false);

		//
		// image dragging/voting section
		//

		$( ".draggable" ).draggable({
	      revert: "invalid", // when not dropped, the item will revert back to its initial position
	      containment: "document",
	      //helper: "clone",
	      cursor: "move",
	      start: function(){
     	   //get the start position
        	var start = {left: $(this).position().left, top:$(this).position().top};
        	//store the start position on this element
        	$(this).data('start', start);
    	  }
		});

	    var i=3;

	    while (i--)
	    {
	    	$( ".targetx-"+i ).data('targetIndex', i);

		    $( ".targetx-"+i ).droppable({
		      //accept: ".choice-"+i,
		      accept: ".draggable",
		      activeClass: "target-active",
		      hoverClass: "target-hover",
		      drop: function( event, ui ) {
		      	var me = $( this );

		      	if ( me.hasClass("target-dropped") )
		      	{
		      		// TODO - something
		      	}
		      	else
		      	{
		      		var src = ui.draggable.find('img').attr( "src" );
		      		//console.log('src=' + src);

			        me.addClass( "target-dropped" )
			          .find( ".replaceme")
			           	// TODO: make this work!
			          	//.replaceWith('

')
			          	.replaceWith('

')
			          	.end();

			        var sec5Imgs = $('#section5 .row img');
					if (sec5Imgs.length > 0)
					{
						var h = sec5Imgs[0].height;
						var w = sec5Imgs[0].width;

						$('.replaceme').height( h );
						$('.replaceme').width( w );
					}

			        // check class to keep track...
			        // TODO: find a better way... regex match of class would be better
			        if (ui.draggable.hasClass('choice-0'))
			        {
			        	chosenImages[0] = me.data('targetIndex');
			        }
			        else if (ui.draggable.hasClass('choice-1'))
			        {
			        	chosenImages[1] = me.data('targetIndex');
			        }
			        else if (ui.draggable.hasClass('choice-2'))
			        {
			        	chosenImages[2] = me.data('targetIndex');
			        }

			        ui.draggable.fadeOut(function() {
			        	//ui.draggable.remove();

			        	//determine the start/end positions

				        //var end = {left: $(this).position().left, top: $(this).position().top } ;
				        var start = $(this).data('start');

				        $(this).css({top: start.top, left: start.left});
				        $(this).find('img').css({border: 'none', opacity:0.3});
				        ui.draggable.draggable("disable", 1);

				        $(this).fadeIn();

			        });

			  	}

			      // check if all 3 images have been dropped and finish button can be activated
			      var totalDropped = $('.target-dropped').length;

			      if (totalDropped == 3)
			      {
					$('#finish-button').removeClass('disabled').html('send vote!');

					// this should broadcast image results back to server...
					$('#finish-button').click( function() {

						socket.emit('images', chosenImages);

						//console.log( chosenImages);

						$('#finish-button').addClass('disabled')
							.off()
							.html('sent!');
					});

			      }
			  }
		    });
		}

		$('#email').on('click', function()
		{
			$(this).val("");
		});

		$('#email-button').on('click', function()
		{

			var email = $('#email').val();
			console.log('sending email: ' + email);
			socket.emit('e', email);
			$(this).addClass('disabled')
							.off()
							.html('sent!');
		});

	});
	//
	// end document onready
	//

	//
	// voting buttons for slide 3
	//
	function voteUp()
	{
		//console.log(thisUser)
		socket.emit('vote', 1);
	}

	function voteDown()
	{
		//console.log(thisUser)
		socket.emit('vote', -1);
	}

	// TODO - CSS animation add/remove

	$('#vote-left').click( voteDown );
	$('#vote-right').click( voteUp );

	//
	// websockets
	//

	// on connection to server
	socket.on('connect', function() {
		/*
		thisUser.gui = new Array()

		for (var i=0;i<nx.nxObjects.length;i++) {
			thisUser.gui.push({
				type: nx.nxObjects[i].getName(),
				x: nx.nxObjects[i].offset.left,
				y: nx.nxObjects[i].offset.top,
				width: nx.nxObjects[i].width,
				height: nx.nxObjects[i].height,
				oscName: nx.nxObjects[i].oscName
			})
			thisUser.gui[i].oscName = thisUser.gui[i].oscName.replace("/","")
		}
*/
		//console.log(thisUser)
		socket.emit('adduser', thisUser);

		// Whenever the server emits 'new message', update the chat body
		socket.on('new user', function (data) {
		   // console.log(data);
		});

		socket.on('jumpto', function (index) {
			// jump to section data using fullpage...
			if (currentPage != index)
			{
				$.fn.fullpage.moveTo( index );
				currentPage = index;
				console.log('jumped to ' + index);
			}
		});

		socket.on('scrollingState', function (state) {
			$.fn.fullpage.setAllowScrolling(state);
		});

		socket.on('voteData', function (voteData) {
			// do some sanity checks on vote data
			//
			var ave = voteData.average;
			var val = (!ave || isNaN(ave)) ? 0 : ave;

			val = Math.max(ave,-1);
			val = Math.min(ave,1);
			val = (val + 1) * 0.5;
			//console.log(val);
			voteSlider.setValue(val);
			//slider1.set({ value: val });
		});

	});

/*
	nx.onload = function() {
		nx.sendsTo("node")
	};
*/
})();
<|endoftext|>


<commit_before>import PIXI from 'pixi.js/bin/pixi';
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';

import { animate, reportParser } from 'javascript/utils';
import {
  updateMapPositionAction, selectHexAction, zoomInAction, zoomOutAction
} from 'javascript/actions/map.actions';
import ZoomComponent from 'javascript/components/map-zoom';

let HEX_MAP = {},
    HEX_SELECTION = null;

class MapContainer extends Component {
  constructor(props) {
    super(props);
    this.onZoomIn = this.onZoomIn.bind(this);
    this.onZoomOut = this.onZoomOut.bind(this);
  }

  shouldComponentUpdate() {
    return false;
  }

  componentWillUnmount() {
    if (this.mapRenderer) {
      this.mapRenderer.destroy(true);
      HEX_MAP = {};
    }
  }

  componentDidMount() {
    this.mapRenderer = new PIXI.CanvasRenderer(
      this.refs.map.offsetWidth-50, this.refs.map.offsetHeight-10, {backgroundColor : 0x808080}
    );

    //Initialize root stage container and bind map actions mouse events
    this.rootStage = new PIXI.Container();
    this.rootStage.interactive = true;
    this.rootStage.buttonMode = true;
    this.rootStage.hitArea = new PIXI.Rectangle(0, 0, this.refs.map.offsetWidth, this.refs.map.offsetHeight);
    this.rootStage
      .on('mousedown', this.onMouseDown.bind(this))
      .on('mouseup', this.onMouseUp.bind(this))
      .on('mousemove', this.onMouseMove.bind(this));

    //Initialize map container and set base x,y position
    this.mapContainer = new PIXI.Container();
    this.mapContainer.x = this.props.map.posX;
    this.mapContainer.y = this.props.map.posY;
    this.mapContainer.scale.set(this.props.map.zoomLevel/100);

    //Render available to user map from report
    this.renderHexes();

    //Attach maps to DOM
    this.rootStage.addChild(this.mapContainer);
    this.refs.map.appendChild(this.mapRenderer.view);

    //Start animation
    animate(this.mapRenderer, this.rootStage);
  }

  componentWillReceiveProps(nextProps) {
    //Set x,y panning position to map
    this.mapContainer.x = nextProps.map.posX;
    this.mapContainer.y = nextProps.map.posY;

    //Select / unselect hex if something changed
    if (this.props.map.selectedHexId !== nextProps.map.selectedHexId) {
      this.selectHex(nextProps.map.selectedHexId);
    }

    //Change zoom and center to selected hex if something changed
    if (this.props.map.zoomLevel !== nextProps.map.zoomLevel ||
      this.props.map.selectedHexId !== nextProps.map.selectedHexId
    ) {
      this.zoomAndCenterHex(nextProps.map.selectedHexId, nextProps.map.zoomLevel);
    }
  }

  selectHex(selectedHexId) {
    //Unselect previous selection
    if (this.props.map.selectedHexId) {
      HEX_MAP[this.props.map.selectedHexId].removeChild(HEX_SELECTION);
    }

    HEX_SELECTION = new PIXI.Sprite(PIXI.loader.resources.hex_selected.texture);
    //Add selection border sprite ontop of hex
    HEX_MAP[selectedHexId].addChild(HEX_SELECTION);
  }

  zoomAndCenterHex(selectedHexId, zoomLevel) {
    if (!selectedHexId) {
      selectedHexId = this.props.map.selectedHexId;
    }
    const hex = HEX_MAP[selectedHexId];

    zoomLevel = zoomLevel / 100;
    this.mapContainer.scale.set(zoomLevel);

    this.mapContainer.x = -1 * hex.position.x * zoomLevel + this.refs.map.offsetWidth / 2;
    this.mapContainer.y = -1 * hex.position.y * zoomLevel + this.refs.map.offsetHeight / 2;
  }

  onMouseDown() {
    this.dragStart = true;
    this.startX = this.mapRenderer.plugins.interaction.mouse.global.x;
    this.startY = this.mapRenderer.plugins.interaction.mouse.global.y;
  }

  onMouseMove() {
    if (!this.dragStart) {
      return;
    }

    //Calculate offset from prev click / move
    const offsetX = this.mapRenderer.plugins.interaction.mouse.global.x - this.startX;
    const offsetY = this.mapRenderer.plugins.interaction.mouse.global.y - this.startY;

    //Set up new start position for next offset calculation
    this.startX = this.mapRenderer.plugins.interaction.mouse.global.x;
    this.startY = this.mapRenderer.plugins.interaction.mouse.global.y;

    //Move map
    this.mapContainer.x = this.mapContainer.x + offsetX;
    this.mapContainer.y = this.mapContainer.y + offsetY;
  }

  onMouseUp() {
    this.dragStart = false;
    this.props.dispatch(updateMapPositionAction(this.mapContainer.x, this.mapContainer.y));
  }

  onHexClick(hex) {
    this.props.dispatch(selectHexAction(hex.hexId));
  }

  onZoomIn() {
    this.props.dispatch(zoomInAction());
  }

  onZoomOut() {
    this.props.dispatch(zoomOutAction());
  }

  renderHexes() {
    let selectedHexId;

    Object.keys(this.props.map.userMap.regions).forEach((regionKey, i) => {
      let region = reportParser.getState().regions[regionKey];
      if (region.isUnderworld) {
        return;
      }

      let hex = new PIXI.Sprite(PIXI.loader.resources['hex_' + region.type].texture);
      hex.interactive = true;
      hex.buttonMode = true;
      hex.hexId = region.x + ',' + region.y;
      //Set tile x/y position on canvas map
      hex.x = region.x / 2 * 100 + region.x / 2 * 50;
      hex.y = region.y / 2 * 87;

      HEX_MAP[hex.hexId] = hex;
      selectedHexId = hex.hexId;
      this.mapContainer.addChild(hex);
      hex.on('mousedown', this.onHexClick.bind(this, hex));
    });

    //Automatically select random hex
    this.props.dispatch(selectHexAction(selectedHexId));
  }

  render() {
    return (

        <ZoomComponent onZoomIn={this.onZoomIn} onZoomOut={this.onZoomOut} />

    );
  }
}

function mapStateToProps(state) {
  const { map } = state;
  return { map };
}

export default connect(mapStateToProps)(MapContainer);
<commit_msg>Zoom & todo<commit_after>import PIXI from 'pixi.js/bin/pixi';
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';

import { animate, reportParser } from 'javascript/utils';
import {
  updateMapPositionAction, selectHexAction, zoomInAction, zoomOutAction
} from 'javascript/actions/map.actions';
import ZoomComponent from 'javascript/components/map-zoom';

let HEX_MAP = {},
    HEX_SELECTION = null;

class MapContainer extends Component {
  constructor(props) {
    super(props);
    this.onZoomIn = this.onZoomIn.bind(this);
    this.onZoomOut = this.onZoomOut.bind(this);
  }

  shouldComponentUpdate() {
    return false;
  }

  componentWillUnmount() {
    if (this.mapRenderer) {
      this.mapRenderer.destroy(true);
      HEX_MAP = {};
    }
  }

  componentDidMount() {
    this.mapRenderer = new PIXI.CanvasRenderer(
      this.refs.map.offsetWidth-50, this.refs.map.offsetHeight-10, {backgroundColor : 0x808080}
    );

    //Initialize root stage container and bind map actions mouse events
    this.rootStage = new PIXI.Container();
    this.rootStage.interactive = true;
    this.rootStage.buttonMode = true;
    this.rootStage.hitArea = new PIXI.Rectangle(0, 0, this.refs.map.offsetWidth, this.refs.map.offsetHeight);
    this.rootStage
      .on('mousedown', this.onMouseDown.bind(this))
      .on('mouseup', this.onMouseUp.bind(this))
      .on('mousemove', this.onMouseMove.bind(this));

    //Initialize map container and set base x,y position
    this.mapContainer = new PIXI.Container();
    this.mapContainer.x = this.props.map.posX;
    this.mapContainer.y = this.props.map.posY;
    this.mapContainer.scale.set(this.props.map.zoomLevel/100);

    //Render available to user map from report
    this.renderHexes();

    //Attach maps to DOM
    this.rootStage.addChild(this.mapContainer);
    this.refs.map.appendChild(this.mapRenderer.view);

    //Start animation
    animate(this.mapRenderer, this.rootStage);
  }

  componentWillReceiveProps(nextProps) {
    //Set x,y panning position to map
    this.mapContainer.x = nextProps.map.posX;
    this.mapContainer.y = nextProps.map.posY;

    //Select / unselect hex if selectedHexId changed
    if (this.props.map.selectedHexId !== nextProps.map.selectedHexId) {
      this.selectHex(nextProps.map.selectedHexId);
    }

    //Change zoom and center to selected hex if zoom changed or this is first rendering
    if (this.props.map.zoomLevel !== nextProps.map.zoomLevel || this.props.map.selectedHexId === null) {
      this.zoomAndCenterHex(nextProps.map.selectedHexId, nextProps.map.zoomLevel);
    }
  }

  selectHex(selectedHexId) {
    //Unselect previous selection
    if (this.props.map.selectedHexId) {
      HEX_MAP[this.props.map.selectedHexId].removeChild(HEX_SELECTION);
    }

    HEX_SELECTION = new PIXI.Sprite(PIXI.loader.resources.hex_selected.texture);
    //Add selection border sprite ontop of hex
    HEX_MAP[selectedHexId].addChild(HEX_SELECTION);
  }

  zoomAndCenterHex(selectedHexId, zoomLevel) {
    if (!selectedHexId) {
      selectedHexId = this.props.map.selectedHexId;
    }
    const hex = HEX_MAP[selectedHexId];

    zoomLevel = zoomLevel / 100;
    this.mapContainer.scale.set(zoomLevel);

    this.mapContainer.x = -1 * hex.position.x * zoomLevel + this.refs.map.offsetWidth / 2 - 50;
    this.mapContainer.y = -1 * hex.position.y * zoomLevel + this.refs.map.offsetHeight / 2 - 50;
  }

  onMouseDown() {
    this.dragStart = true;
    this.startX = this.mapRenderer.plugins.interaction.mouse.global.x;
    this.startY = this.mapRenderer.plugins.interaction.mouse.global.y;
  }

  onMouseMove() {
    if (!this.dragStart) {
      return;
    }

    //Calculate offset from prev click / move
    const offsetX = this.mapRenderer.plugins.interaction.mouse.global.x - this.startX;
    const offsetY = this.mapRenderer.plugins.interaction.mouse.global.y - this.startY;

    //Set up new start position for next offset calculation
    this.startX = this.mapRenderer.plugins.interaction.mouse.global.x;
    this.startY = this.mapRenderer.plugins.interaction.mouse.global.y;

    //Move map
    this.mapContainer.x = this.mapContainer.x + offsetX;
    this.mapContainer.y = this.mapContainer.y + offsetY;
  }

  onMouseUp() {
    this.dragStart = false;
    this.props.dispatch(updateMapPositionAction(this.mapContainer.x, this.mapContainer.y));
  }

  onHexClick(hexId) {
    this.props.dispatch(selectHexAction(hexId));
  }

  onZoomIn() {
    this.props.dispatch(zoomInAction());
  }

  onZoomOut() {
    this.props.dispatch(zoomOutAction());
  }

  renderHexes() {
    let selectedHexId;

    Object.keys(this.props.map.userMap.regions).forEach((regionKey, i) => {
      let region = reportParser.getState().regions[regionKey];
      if (region.isUnderworld) {
        return;
      }

      let hex = new PIXI.Sprite(PIXI.loader.resources['hex_' + region.type].texture);
      hex.interactive = true;
      hex.buttonMode = true;
      hex.hexId = region.x + ',' + region.y;
      //Set tile x/y position on canvas map
      hex.x = region.x / 2 * 100 + region.x / 2 * 50;
      hex.y = region.y / 2 * 87;

      HEX_MAP[hex.hexId] = hex;
      selectedHexId = hex.hexId;
      this.mapContainer.addChild(hex);
      hex.on('mousedown', this.onHexClick.bind(this, selectedHexId));
    });

    //Automatically select random hex
    this.props.dispatch(selectHexAction(selectedHexId));

    //TODO: connect map edges?
  }

  render() {
    return (

        <ZoomComponent onZoomIn={this.onZoomIn} onZoomOut={this.onZoomOut} />

    );
  }
}

function mapStateToProps(state) {
  const { map } = state;
  return { map };
}

export default connect(mapStateToProps)(MapContainer);
<|endoftext|>


<commit_before>// This patch is used for auto-upgrading when DOM is changed by blaze.
// Well, maybe not just blaze.
// But when you are manipulating the DOM by yourself, you should remember to upgrade.
//
// Browser compatibility: check https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
// also http://caniuse.com/#search=MutationObserver

/*global MDl:true*/

if (Meteor.isClient) {
  const MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
  const ObjectHasOwnProperty = Object.prototype.hasOwnProperty;

  class AutoUpgrade {
    static handleMutation(mutation) {
      switch (mutation.type) {
        case 'attributes':
          //! Try to upgrade this element.
          break;
        case 'characterData':
          // Ignore character changes.
          break;
        case 'childList':
          // Upgrade the new children.
          if (mutation.addedNodes.length > 0 && mutation.target instanceof Element) {
            MDl.componentHandler.upgradeElements(mutation.target);
          }
          break;
        default:
          throw new Error('Invalid type of mutation.');
          break;
      }
    }
    constructor(MutationObserver) {
      this._upgradeStyle = false;
      this._upgradeBehavior = null;
      this._observer = new MutationObserver(this.onMutationObserved.bind(this));
    }
    onMutationObserved(mutations, observer) {
      if (this._upgradeBehavior) {
        this._upgradeBehavior(mutations, observer);
      }
    }
    setUpgradeStyle(style) {
      if (ObjectHasOwnProperty.call(AutoUpgrade.upgradeBehaviors, style)) {
        this._upgradeStyle = style;
        this._upgradeBehavior = AutoUpgrade.upgradeBehaviors[style];

        if (style === 'none') {
          this._observer.disconnect();
        } else {
          this._observer.observe(document.body, AutoUpgrade.observeConfig);
        }
      } else {
        throw new Error("Invalid upgrade style.");
      }
    }
    getUpgradeStyle() {
      return this._upgradeStyle;
    }
  }
  AutoUpgrade.upgradeBehaviors = {
    "fullUpgrade": function (mutations, observer) {
      MDl.componentHandler.upgradeAllRegistered();
    },
    "mutationOnly": function (mutations, observer) {
      for (let i = 0, n = mutations.length; i < n; i++) {
        AutoUpgrade.handleMutation(mutations[i]);
      }
    },
    "none": function (mutations, observer) {}
  };
  AutoUpgrade.observeConfig = {
    childList: true,
    attributes: true,
    characterData: false,
    subtree: true
    //attributeOldValue: false,
    //characterDataOldValue: false
    //attributeFilter: []
  };

  Meteor.startup(function () {
    // Read settings.
    let upgradeStyle = this.settings.patches.autoUpgrade;
    // If upgradeStyle is `false`, disable everything.
    if (upgradeStyle === false) {
      this.autoUpgrade = null;
    } else {
      // If MutationObserver is not available on this platform, there's little we can do.
      if (!MutationObserver) {
        throw new Error("MDl AutoUpgrade doesn't support your current client environment. Please disable it.");
      } else {
        this.autoUpgrade = new AutoUpgrade(MutationObserver);
        this.autoUpgrade.setUpgradeStyle(upgradeStyle);
      }
    }
  }.bind(MDl));
}
<commit_msg>Fix the error message when the package is not enabled (.settings missing).<commit_after>// This patch is used for auto-upgrading when DOM is changed by blaze.
// Well, maybe not just blaze.
// But when you are manipulating the DOM by yourself, you should remember to upgrade.
//
// Browser compatibility: check https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
// also http://caniuse.com/#search=MutationObserver

/*global MDl:true*/

if (Meteor.isClient) {
  const MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
  const ObjectHasOwnProperty = Object.prototype.hasOwnProperty;

  class AutoUpgrade {
    static handleMutation(mutation) {
      switch (mutation.type) {
        case 'attributes':
          //! Try to upgrade this element.
          break;
        case 'characterData':
          // Ignore character changes.
          break;
        case 'childList':
          // Upgrade the new children.
          if (mutation.addedNodes.length > 0 && mutation.target instanceof Element) {
            MDl.componentHandler.upgradeElements(mutation.target);
          }
          break;
        default:
          throw new Error('Invalid type of mutation.');
          break;
      }
    }
    constructor(MutationObserver) {
      this._upgradeStyle = false;
      this._upgradeBehavior = null;
      this._observer = new MutationObserver(this.onMutationObserved.bind(this));
    }
    onMutationObserved(mutations, observer) {
      if (this._upgradeBehavior) {
        this._upgradeBehavior(mutations, observer);
      }
    }
    setUpgradeStyle(style) {
      if (ObjectHasOwnProperty.call(AutoUpgrade.upgradeBehaviors, style)) {
        this._upgradeStyle = style;
        this._upgradeBehavior = AutoUpgrade.upgradeBehaviors[style];

        if (style === 'none') {
          this._observer.disconnect();
        } else {
          this._observer.observe(document.body, AutoUpgrade.observeConfig);
        }
      } else {
        throw new Error("Invalid upgrade style.");
      }
    }
    getUpgradeStyle() {
      return this._upgradeStyle;
    }
  }
  AutoUpgrade.upgradeBehaviors = {
    "fullUpgrade": function (mutations, observer) {
      MDl.componentHandler.upgradeAllRegistered();
    },
    "mutationOnly": function (mutations, observer) {
      for (let i = 0, n = mutations.length; i < n; i++) {
        AutoUpgrade.handleMutation(mutations[i]);
      }
    },
    "none": function (mutations, observer) {}
  };
  AutoUpgrade.observeConfig = {
    childList: true,
    attributes: true,
    characterData: false,
    subtree: true
    //attributeOldValue: false,
    //characterDataOldValue: false
    //attributeFilter: []
  };

  Meteor.startup(function () {
    // Check if settings is loaded.
    if (typeof this.settings === 'undefined') {
      return;
    }
    //else

    // Read settings.
    let upgradeStyle = this.settings.patches.autoUpgrade;
    // If upgradeStyle is `false`, disable everything.
    if (upgradeStyle === false) {
      this.autoUpgrade = null;
    } else {
      // If MutationObserver is not available on this platform, there's little we can do.
      if (!MutationObserver) {
        throw new Error("MDl AutoUpgrade doesn't support your current client environment. Please disable it.");
      } else {
        this.autoUpgrade = new AutoUpgrade(MutationObserver);
        this.autoUpgrade.setUpgradeStyle(upgradeStyle);
      }
    }
  }.bind(MDl));
}
<|endoftext|>


<commit_before>module.exports = {
    afterInstall: function() {
        const self = this;

        return this.addBowerPackagesToProject([
            {
                name: 'bootstrap-datepicker',
                target: '~1.3.0'
            }, {
                name: 'fontawesome',
                target: '~4.3.0'
            }, {
                name: 'highcharts',
                target: '~4.1.5'
            }, {
                name: 'moment',
                target: '~2.10.3'
            }, {
                name: 'moment-timezone',
                target: '~0.4.0'
            }, {
                name: 'select2',
                target: '~3.5.2'
            }, {
                name: 'typeahead.js',
                target: '~0.11.1'
            }, {
                name: 'softlayer/sl-bootstrap',
                target: '1.1.0'
            }
        ]);
    },

    normalizeEntityName: function() {}
};<commit_msg>Remove unneeded self variable<commit_after>module.exports = {
    afterInstall: function() {
        return this.addBowerPackagesToProject([
            {
                name: 'bootstrap-datepicker',
                target: '~1.3.0'
            }, {
                name: 'fontawesome',
                target: '~4.3.0'
            }, {
                name: 'highcharts',
                target: '~4.1.5'
            }, {
                name: 'moment',
                target: '~2.10.3'
            }, {
                name: 'moment-timezone',
                target: '~0.4.0'
            }, {
                name: 'select2',
                target: '~3.5.2'
            }, {
                name: 'typeahead.js',
                target: '~0.11.1'
            }, {
                name: 'softlayer/sl-bootstrap',
                target: '1.1.0'
            }
        ]);
    },

    normalizeEntityName: function() {}
};
<|endoftext|>


<commit_before>const { BatchRecorder, ConsoleRecorder } = require('zipkin')
const { HttpLogger } = require('zipkin-transport-http')
const config = require('../secret').tracing.zipkin

let recorder
if (config !== null) {
    recorder = new BatchRecorder({
        logger: new HttpLogger({
            endpoint: `${config.url}/api/v1/spans`
        })
    })
} else {
    recorder = new ConsoleRecorder()
}

module.exports = recorder
<commit_msg>Fix Zipkin issues<commit_after>const { BatchRecorder, ConsoleRecorder } = require('zipkin')
const { HttpLogger } = require('zipkin-transport-http')
const config = require('../secret').tracing.zipkin
const debug = require('../config').debug

let recorder
if (config !== null) {
    recorder = new BatchRecorder({
        logger: new HttpLogger({
            endpoint: `${config.url}/api/v1/spans`
        })
    })
} else if (debug) {
    recorder = new ConsoleRecorder()
} else {
    recorder = {
        record: function record () {},
        toString: function toString () {
            return 'NullRecorder'
        },
    }
}

module.exports = recorder
<|endoftext|>


<commit_before>angular.module('materialscommons', []);

var app = angular.module('materialscommons',
    [
        'ngSanitize',
        'ngMessages',
        'ui',
        'ngCookies',
        'ui.router',
        'restangular',
        'jmdobry.angular-cache',
        'textAngular', 'angularGrid',
        'ngDragDrop', 'ngTagsInput',
        'angular.filter', 'ui.calendar',
        '$strap.directives', 'ui.bootstrap', 'toastr',
        "hljs", "RecursionHelper", 'googlechart',
        'materialscommons']);

app.config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {

    mcglobals = {};
    doConfig();
    $stateProvider
        // Navbar
        .state('home', {
            url: '/home',
            templateUrl: 'application/core/splash.html'
        })
        .state('login', {
            url: '/login',
            templateUrl: 'application/core/login/login.html'
        })
        .state('logout', {
            url: '/logout',
            controller: 'LogoutController'
        })
        .state('reviews', {
            url: '/reviews',
            templateUrl: 'application/core/reviews/reviews.html'
        })
        .state('machines', {
            url: '/machines',
            templateUrl: 'application/core/machines/machines.html'
        })

        /*
         ########################################################################
         ####################### Account ##################################
         ########################################################################
         */
        .state('account', {
            url: '/account',
            templateUrl: 'application/core/account/account.html'
        })
        .state('account.password', {
            url: '/password',
            templateUrl: 'application/core/account/password/password.html'
        })
        .state('account.apikey', {
            url: '/apikey',
            templateUrl: 'application/core/account/apikey/apikey.html'
        })
        .state('account.settings', {
            url: '/settings',
            templateUrl: 'application/core/account/settings/settings.html'
        })
        .state('account.templates', {
            url: '/templates',
            templateUrl: 'application/core/account/templates/templates.html'
        })

        /*
         ########################################################################
         ########################### Projects ###################################
         ########################################################################
         */
        .state('projects', {
            url: '/projects',
            abstract: true,
            template: '

',
            resolve: {
                Projects: "model.projects",
                projects: function (Projects) {
                    return Projects.getList();
                }
            }
        })
        .state('projects.create', {
            url: '/create',
            templateUrl: 'application/core/projects/create.html',
            controller: 'CreateProjectController',
            controllerAs: 'project'
        })
        .state('projects.project', {
            url: '/project/:id',
            templateUrl: 'application/core/projects/project/project.html',
            resolve: {
                project: ["$stateParams", "model.projects", "projects",
                    function ($stateParams, Projects) {
                        // We use templates as a dependency so that they are all loaded
                        // before getting to this step. Otherwise the order of items
                        // being resolved isn't in the order we need them.
                        return Projects.get($stateParams.id);
                    }]
            },
            onEnter: ["pubsub", "project", function (pubsub) {
                pubsub.send("reviews.change");
            }],
            controller: "ProjectController",
            controllerAs: 'project'
        })
        .state('projects.project.home', {
            url: '/home',
            templateUrl: 'application/core/projects/project/home/home.html',
            controller: "ProjectHomeController",
            controllerAs: "ctrl"
        })
        .state('projects.project.search', {
            url: '/search/:query',
            templateUrl: 'application/core/projects/project/search.html',
            controller: 'SearchController',
            controllerAs: 'search'
        })
        .state("projects.project.files", {
            url: "/files",
            abstract: true,
            template: '

'
        })
        .state("projects.project.files.all", {
            url: "/all",
            templateUrl: "application/core/projects/project/files/all.html",
            controller: "FilesAllController",
            controllerAs: 'files'

        })
        .state("projects.project.files.all.edit", {
            url: "/edit/:file_id",
            templateUrl: "application/core/projects/project/files/edit.html",
            controller: "FileEditController",
            controllerAs: 'ctrl',
            resolve: {
                file: ["$stateParams", "Restangular",
                    function ($stateParams, Restangular) {
                        return Restangular.one('v2').one('projects', $stateParams.id).
                            one('files', $stateParams.file_id).get();
                    }]
            }
        })
        .state("projects.project.files.all.dir", {
            url: "/dir/:dir_id",
            templateUrl: "application/core/projects/project/files/dir.html",
            controller: "DirController",
            controllerAs: "ctrl"
        })
        .state("projects.project.files.edit", {
            url: "/edit/:file_id",
            templateUrl: "application/core/projects/project/files/edit.html",
            controller: "FileEditController",
            controllerAs: "ctrl",
            resolve: {
                file: ["$stateParams", "Restangular",
                function ($stateParams, Restangular) {
                    return Restangular.one('v2').one('projects', $stateParams.id).
                        one('files', $stateParams.file_id).get();
                }]
            }
        })
        .state("projects.project.files.search", {
            url: "/search",
            templateUrl: "application/core/projects/project/files/search.html",
            controller: "FilesSearchController",
            controllerAs: "search"
        })
        .state("projects.project.access", {
            url: "/access",
            templateUrl: "application/core/projects/project/access/access.html",
            controller: "ProjectAccessController",
            controllerAs: 'access'
        })
        .state("projects.project.reviews", {
            url: "/reviews/:category",
            templateUrl: "application/core/projects/project/reviews/reviews.html",
            controller: "projectReviews"
        })
        .state("projects.project.reviews.edit", {
            url: "/edit/:review_id",
            templateUrl: "application/core/projects/project/reviews/edit.html",
            controller: "projectEditReview"
        })
        .state("projects.project.reviews.create", {
            url: "/reviews/create",
            templateUrl: "application/core/projects/project/reviews/create.html",
            controller: "projectCreateReview"
        })
        .state("projects.project.notes", {
            url: "/notes",
            templateUrl: "application/core/projects/project/notes/notes.html",
            controller: "projectNotes",
            controllerAs: 'notes'
        })
        .state("projects.project.sideboard", {
            url: "/sideboard",
            templateUrl: "application/core/projects/project/sideboard/sideboard.html",
            controller: "projectSideboard"
        })
        .state("projects.project.processes", {
            url: "/processes",
            abstract: true,
            template: '

'
        })
        .state("projects.project.processes.create", {
            url: "/create",
            templateUrl: "application/core/projects/project/processes/create/create.html",
            controller: "CreateProcessController",
            controllerAs: 'ctrl',
            resolve: {
                template: ["processList", "processTemplates", "$filter", "measurements",
                    function (processList, processTemplates, $filter, measurements) {
                        var template = processTemplates.getActiveTemplate();
                        template.name = template.name + ' - ' + $filter('date')(new Date(), 'MM/dd/yyyy @ h:mma');
                        measurements.templates();
                        return template;
                    }
                ]
                //,
                //process: ["$q", "$timeout", function($q, $timeout) {
                //    //return selectProcessTemplate.open();
                //    var deferred = $q.defer();
                //    $timeout(function () {
                //        //deferred.resolve("successful");
                //        console.log('rejecting');
                //        deferred.reject("fail");   // resolve fails here
                //    }, 2000);
                //    return deferred.promise;
                //}]
            }
        })
        //.state("projects.project.processes.prefill", {
        //    url: "/prefill",
        //    templateUrl: "application/core/projects/project/processes/prefill.html",
        //    controller: "projectPreFillProcess",
        //    controllerAs: "ctrl",
        //    resolve: {
        //        template: ["processList", "processTemplates", "$filter",
        //            function (processList, processTemplates, $filter) {
        //                var template = processTemplates.getActiveTemplate();
        //                template.name = template.name + ' - ' + $filter('date')(new Date(), 'MM/dd/yyyy @ h:mma');
        //                return template;
        //            }
        //        ]
        //    }
        //})
        .state("projects.project.processes.edit", {
            url: "/edit/:process_id",
            templateUrl: "application/core/projects/project/processes/edit.html",
            controller: "projectEditProcess",
            controllerAs: 'edit'
        })
        .state("projects.project.processes.list", {
            url: "/list",
            templateUrl: "application/core/projects/project/processes/list.html",
            controller: "projectListProcess",
            controllerAs: "ctrl",
            resolve: {
                processes: ["project",
                    function (project) {
                        return project.processes;
                    }]
            }
        })
        .state("projects.project.processes.list.view", {
            url: "/view/:process_id",
            templateUrl: "application/core/projects/project/processes/view.html",
            controller: "projectViewProcess",
            controllerAs: 'view',
            resolve: {
                process: ["$stateParams", "Restangular", "processes",
                    function ($stateParams, Restangular, processes) {
                        var process_id = '';
                        if ($stateParams.process_id) {
                            process_id = $stateParams.process_id;
                        } else {
                            if (processes.length > 0) {
                                process_id = processes[0].id;
                            }
                        }
                        return Restangular.one('process').one('details', process_id).get();
                    }
                ]
            }
        })
        .state("projects.project.samples", {
            url: "/samples",
            templateUrl: "application/core/projects/project/samples/samples.html",
            controller: "SamplesController",
            controllerAs: "ctrl",
            resolve: {
                samples: ["project",
                    function (project) {
                        return project.samples;
                    }]
            }
        })
        .state("projects.project.samples.edit", {
            url: "/edit/:sample_id",
            templateUrl: "application/core/projects/project/samples/edit.html",
            controller: "SamplesEditController",
            controllerAs: "ctrl",
            resolve: {
                //At this point we have a sample object with properties and best measure.
                // So, to get other measures Restangular call is made
                sample: ["$stateParams", "Restangular", "samples",
                    function ($stateParams, Restangular, samples) {
                        if ($stateParams.sample_id) {
                            var sample_id = $stateParams.sample_id;
                        } else {
                            if (samples.length > 0) {
                                sample_id = samples[0].id;
                            }
                        }
                        return Restangular.one('sample').one('details', sample_id).get();
                    }
                ]
            }
        });

    $urlRouterProvider.otherwise('/home');
}]);

app.run(["$rootScope", "User", "Restangular", appRun]);

function appRun($rootScope, User, Restangular) {
    Restangular.setBaseUrl(mcglobals.apihost);
    if (User.isAuthenticated()) {
        Restangular.setDefaultRequestParams({apikey: User.apikey()});
    }

    // appRun will run when the application starts up and before any controllers have run.
    // This means it will run on a refresh. We check if the user is already authenticated
    // during the run. If they are then the browser has been refreshed and we need to
    // set the apikey param for Restangular. This param is set in the login-controller.
    // However on a refresh the login-controller isn't run so we need to explicitly set
    // the apikey param in Restangular.
    if (User.isAuthenticated()) {
        Restangular.setDefaultRequestParams({apikey: User.apikey()});
    }

    $rootScope.$on('$stateChangeStart', function () {
        if (User.isAuthenticated()) {
            $rootScope.email_address = User.u();
        }
    });
}
<commit_msg>Remove machines route.<commit_after>angular.module('materialscommons', []);

var app = angular.module('materialscommons',
    [
        'ngSanitize',
        'ngMessages',
        'ui',
        'ngCookies',
        'ui.router',
        'restangular',
        'jmdobry.angular-cache',
        'textAngular', 'angularGrid',
        'ngDragDrop', 'ngTagsInput',
        'angular.filter', 'ui.calendar',
        '$strap.directives', 'ui.bootstrap', 'toastr',
        "hljs", "RecursionHelper", 'googlechart',
        'materialscommons']);

app.config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {

    mcglobals = {};
    doConfig();
    $stateProvider
        // Navbar
        .state('home', {
            url: '/home',
            templateUrl: 'application/core/splash.html'
        })
        .state('login', {
            url: '/login',
            templateUrl: 'application/core/login/login.html'
        })
        .state('logout', {
            url: '/logout',
            controller: 'LogoutController'
        })
        .state('reviews', {
            url: '/reviews',
            templateUrl: 'application/core/reviews/reviews.html'
        })

        /*
         ########################################################################
         ####################### Account ##################################
         ########################################################################
         */
        .state('account', {
            url: '/account',
            templateUrl: 'application/core/account/account.html'
        })
        .state('account.password', {
            url: '/password',
            templateUrl: 'application/core/account/password/password.html'
        })
        .state('account.apikey', {
            url: '/apikey',
            templateUrl: 'application/core/account/apikey/apikey.html'
        })
        .state('account.settings', {
            url: '/settings',
            templateUrl: 'application/core/account/settings/settings.html'
        })
        .state('account.templates', {
            url: '/templates',
            templateUrl: 'application/core/account/templates/templates.html'
        })

        /*
         ########################################################################
         ########################### Projects ###################################
         ########################################################################
         */
        .state('projects', {
            url: '/projects',
            abstract: true,
            template: '

',
            resolve: {
                Projects: "model.projects",
                projects: function (Projects) {
                    return Projects.getList();
                }
            }
        })
        .state('projects.create', {
            url: '/create',
            templateUrl: 'application/core/projects/create.html',
            controller: 'CreateProjectController',
            controllerAs: 'project'
        })
        .state('projects.project', {
            url: '/project/:id',
            templateUrl: 'application/core/projects/project/project.html',
            resolve: {
                project: ["$stateParams", "model.projects", "projects",
                    function ($stateParams, Projects) {
                        // We use templates as a dependency so that they are all loaded
                        // before getting to this step. Otherwise the order of items
                        // being resolved isn't in the order we need them.
                        return Projects.get($stateParams.id);
                    }]
            },
            onEnter: ["pubsub", "project", function (pubsub) {
                pubsub.send("reviews.change");
            }],
            controller: "ProjectController",
            controllerAs: 'project'
        })
        .state('projects.project.home', {
            url: '/home',
            templateUrl: 'application/core/projects/project/home/home.html',
            controller: "ProjectHomeController",
            controllerAs: "ctrl"
        })
        .state('projects.project.search', {
            url: '/search/:query',
            templateUrl: 'application/core/projects/project/search.html',
            controller: 'SearchController',
            controllerAs: 'search'
        })
        .state("projects.project.files", {
            url: "/files",
            abstract: true,
            template: '

'
        })
        .state("projects.project.files.all", {
            url: "/all",
            templateUrl: "application/core/projects/project/files/all.html",
            controller: "FilesAllController",
            controllerAs: 'files'

        })
        .state("projects.project.files.all.edit", {
            url: "/edit/:file_id",
            templateUrl: "application/core/projects/project/files/edit.html",
            controller: "FileEditController",
            controllerAs: 'ctrl',
            resolve: {
                file: ["$stateParams", "Restangular",
                    function ($stateParams, Restangular) {
                        return Restangular.one('v2').one('projects', $stateParams.id).
                            one('files', $stateParams.file_id).get();
                    }]
            }
        })
        .state("projects.project.files.all.dir", {
            url: "/dir/:dir_id",
            templateUrl: "application/core/projects/project/files/dir.html",
            controller: "DirController",
            controllerAs: "ctrl"
        })
        .state("projects.project.files.edit", {
            url: "/edit/:file_id",
            templateUrl: "application/core/projects/project/files/edit.html",
            controller: "FileEditController",
            controllerAs: "ctrl",
            resolve: {
                file: ["$stateParams", "Restangular",
                function ($stateParams, Restangular) {
                    return Restangular.one('v2').one('projects', $stateParams.id).
                        one('files', $stateParams.file_id).get();
                }]
            }
        })
        .state("projects.project.files.search", {
            url: "/search",
            templateUrl: "application/core/projects/project/files/search.html",
            controller: "FilesSearchController",
            controllerAs: "search"
        })
        .state("projects.project.access", {
            url: "/access",
            templateUrl: "application/core/projects/project/access/access.html",
            controller: "ProjectAccessController",
            controllerAs: 'access'
        })
        .state("projects.project.reviews", {
            url: "/reviews/:category",
            templateUrl: "application/core/projects/project/reviews/reviews.html",
            controller: "projectReviews"
        })
        .state("projects.project.reviews.edit", {
            url: "/edit/:review_id",
            templateUrl: "application/core/projects/project/reviews/edit.html",
            controller: "projectEditReview"
        })
        .state("projects.project.reviews.create", {
            url: "/reviews/create",
            templateUrl: "application/core/projects/project/reviews/create.html",
            controller: "projectCreateReview"
        })
        .state("projects.project.notes", {
            url: "/notes",
            templateUrl: "application/core/projects/project/notes/notes.html",
            controller: "projectNotes",
            controllerAs: 'notes'
        })
        .state("projects.project.sideboard", {
            url: "/sideboard",
            templateUrl: "application/core/projects/project/sideboard/sideboard.html",
            controller: "projectSideboard"
        })
        .state("projects.project.processes", {
            url: "/processes",
            abstract: true,
            template: '

'
        })
        .state("projects.project.processes.create", {
            url: "/create",
            templateUrl: "application/core/projects/project/processes/create/create.html",
            controller: "CreateProcessController",
            controllerAs: 'ctrl',
            resolve: {
                template: ["processList", "processTemplates", "$filter", "measurements",
                    function (processList, processTemplates, $filter, measurements) {
                        var template = processTemplates.getActiveTemplate();
                        template.name = template.name + ' - ' + $filter('date')(new Date(), 'MM/dd/yyyy @ h:mma');
                        measurements.templates();
                        return template;
                    }
                ]
                //,
                //process: ["$q", "$timeout", function($q, $timeout) {
                //    //return selectProcessTemplate.open();
                //    var deferred = $q.defer();
                //    $timeout(function () {
                //        //deferred.resolve("successful");
                //        console.log('rejecting');
                //        deferred.reject("fail");   // resolve fails here
                //    }, 2000);
                //    return deferred.promise;
                //}]
            }
        })
        //.state("projects.project.processes.prefill", {
        //    url: "/prefill",
        //    templateUrl: "application/core/projects/project/processes/prefill.html",
        //    controller: "projectPreFillProcess",
        //    controllerAs: "ctrl",
        //    resolve: {
        //        template: ["processList", "processTemplates", "$filter",
        //            function (processList, processTemplates, $filter) {
        //                var template = processTemplates.getActiveTemplate();
        //                template.name = template.name + ' - ' + $filter('date')(new Date(), 'MM/dd/yyyy @ h:mma');
        //                return template;
        //            }
        //        ]
        //    }
        //})
        .state("projects.project.processes.edit", {
            url: "/edit/:process_id",
            templateUrl: "application/core/projects/project/processes/edit.html",
            controller: "projectEditProcess",
            controllerAs: 'edit'
        })
        .state("projects.project.processes.list", {
            url: "/list",
            templateUrl: "application/core/projects/project/processes/list.html",
            controller: "projectListProcess",
            controllerAs: "ctrl",
            resolve: {
                processes: ["project",
                    function (project) {
                        return project.processes;
                    }]
            }
        })
        .state("projects.project.processes.list.view", {
            url: "/view/:process_id",
            templateUrl: "application/core/projects/project/processes/view.html",
            controller: "projectViewProcess",
            controllerAs: 'view',
            resolve: {
                process: ["$stateParams", "Restangular", "processes",
                    function ($stateParams, Restangular, processes) {
                        var process_id = '';
                        if ($stateParams.process_id) {
                            process_id = $stateParams.process_id;
                        } else {
                            if (processes.length > 0) {
                                process_id = processes[0].id;
                            }
                        }
                        return Restangular.one('process').one('details', process_id).get();
                    }
                ]
            }
        })
        .state("projects.project.samples", {
            url: "/samples",
            templateUrl: "application/core/projects/project/samples/samples.html",
            controller: "SamplesController",
            controllerAs: "ctrl",
            resolve: {
                samples: ["project",
                    function (project) {
                        return project.samples;
                    }]
            }
        })
        .state("projects.project.samples.edit", {
            url: "/edit/:sample_id",
            templateUrl: "application/core/projects/project/samples/edit.html",
            controller: "SamplesEditController",
            controllerAs: "ctrl",
            resolve: {
                //At this point we have a sample object with properties and best measure.
                // So, to get other measures Restangular call is made
                sample: ["$stateParams", "Restangular", "samples",
                    function ($stateParams, Restangular, samples) {
                        if ($stateParams.sample_id) {
                            var sample_id = $stateParams.sample_id;
                        } else {
                            if (samples.length > 0) {
                                sample_id = samples[0].id;
                            }
                        }
                        return Restangular.one('sample').one('details', sample_id).get();
                    }
                ]
            }
        });

    $urlRouterProvider.otherwise('/home');
}]);

app.run(["$rootScope", "User", "Restangular", appRun]);

function appRun($rootScope, User, Restangular) {
    Restangular.setBaseUrl(mcglobals.apihost);
    if (User.isAuthenticated()) {
        Restangular.setDefaultRequestParams({apikey: User.apikey()});
    }

    // appRun will run when the application starts up and before any controllers have run.
    // This means it will run on a refresh. We check if the user is already authenticated
    // during the run. If they are then the browser has been refreshed and we need to
    // set the apikey param for Restangular. This param is set in the login-controller.
    // However on a refresh the login-controller isn't run so we need to explicitly set
    // the apikey param in Restangular.
    if (User.isAuthenticated()) {
        Restangular.setDefaultRequestParams({apikey: User.apikey()});
    }

    $rootScope.$on('$stateChangeStart', function () {
        if (User.isAuthenticated()) {
            $rootScope.email_address = User.u();
        }
    });
}
<|endoftext|>