<commit_before>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4,
maxerr: 50, node: true */
/*global */

(function () {
    "use strict";

    /** @define{number} Number of ms to wait for the server to start */
    var SETUP_TIMEOUT = 5000; // wait up to 5 seconds for server to start

    /** @define{number} Number of ms between pings to parent process */
    var PING_DELAY = 1000; // send ping to parent process every 1 second

    var fs                = require("fs"),
        http              = require("http"),
        WebSocket         = require("./thirdparty/ws"),
        EventEmitter      = require("events").EventEmitter,
        Logger            = require("./Logger"),
        ConnectionManager = require("./ConnectionManager"),
        DomainManager     = require("./DomainManager");

    /**
     * @constructor
     * The Server module is a singleton object that manages both the
     * connection to the parent process (over stdin/stdout) and to clients
     * over WebSockets.
     *
     * Server inherits from the EventEmitter class and exports itself
     * as the module.
     */
    var Server = module.exports = new EventEmitter();

    /**
     * @private
     * @type{number} unique IDs for messages to parent process
     */
    var _commandCount = 1;

    /**
     * @private
     * @type{http.Server} the HTTP server
     */
    var _httpServer = null;

    /**
     * @private
     * @type{ws.WebSocketServer} the WebSocket server
     */
    var _wsServer = null;

    /**
     * Stops the server and does appropriate cleanup.
     * Emits an "end" event when shutdown is complete.
     */
    function stop() {
        Logger.info("[Server] stopping");
        if (_wsServer) {
            try {
                _wsServer.close();
            } catch (err1) { }
        }
        if (_httpServer) {
            try {
                _httpServer.close();
            } catch (err2) { }
        }
        ConnectionManager.closeAllConnections();
        Logger.info("[Server] stopped");
        Server.emit("end");
        Server.removeAllListeners();
    }

    /**
     * Starts the server.
     */
    function start() {
        function sendCommandToParentProcess() {
            var cmd = "\n\n" + (_commandCount++) + "|"
                + Array.prototype.join.call(arguments, "|") + "\n\n";
            process.stdout.write(cmd);
        }

        function httpRequestHandler(req, res) {
            if (req.method === "GET") {
                if (req.url === "/api" || req.url.indexOf("/api/") === 0) {
                    res.setHeader("Content-Type", "application/json");
                    res.end(
                        JSON.stringify(DomainManager.getDomainDescriptions(),
                                        null,
                                        4)
                    );
                } else {
                    res.setHeader("Content-Type", "text/plain");
                    res.end("Brackets-Shell Server\n");
                }
            } else { // Not a GET request
                res.statusCode = 501;
                res.end();
            }
        }

        function setupStdin() {
            // re-enable getting events from stdin
            try {
                process.stdin.resume();
                process.stdin.setEncoding("utf8");
            } catch (e) {
                // Couldn't resume stdin, so something is terribly wrong
                Logger.error("[Server] unable to resume stdin, stopping");
                stop();
            }

            // set up event handlers for stdin
            process.stdin.on("data", function (data) {
                // no-op, but make sure we read the data so the buffer
                // doesn't fill up
            });

            process.stdin.on("end", function receiveStdInClose() {
                Logger.info("[Server] stopping because stdin closed");
                stop();
            });
        }

        function setupStdout() {
            // Routinely check if stdout is closed. Stdout will close when our
            // parent process closes (either expectedly or unexpectedly) so this
            // is our signal to shutdown to prevent process abandonment.
            //
            // We need to continually ping because that's the only way to actually
            // check if the pipe is closed in a robust way (writable may only get
            // set to false after trying to write a ping to a closed pipe).
            setInterval(function () {
                if (!process.stdout.writable) {
                    // If stdout closes, our parent process has terminated or
                    // has explicitly closed it. Either way, we should exit.
                    Logger.info("[Server] stopping because stdout closed");
                    stop();
                } else {
                    try {
                        sendCommandToParentProcess("ping");
                    } catch (e) {
                        Logger.info("[Server] stopping because stdout was not writable");
                        stop();
                    }
                }
            }, PING_DELAY);
        }

        function setupHttpAndWebSocketServers(callback, timeout) {
            var timeoutTimer = null;
            var httpServer = null;

            if (timeout) {
                timeoutTimer = setTimeout(function () {
                    callback("ERR_TIMEOUT", null);
                }, timeout);
            }

            httpServer = http.createServer(httpRequestHandler);

            httpServer.on("error", function () {
                if (callback) {
                    callback("ERR_CREATE_SERVER", null);
                }
            });

            httpServer.listen(0, "127.0.0.1", function () {
                var wsServer = null;
                var address = httpServer.address();
                if (address !== null) {
                    httpServer.removeAllListeners("error");
                    httpServer.on("error", function () {
                        Logger.error("[Server] stopping due to HTTP error",
                                      arguments);
                        stop();
                    });

                    wsServer = new WebSocket.Server({server: httpServer});
                    wsServer.on("error", function () {
                        Logger.error(
                            "[Server] stopping due to WebSocket error",
                            arguments
                        );
                        stop();
                    });
                    wsServer.on("connection",
                                ConnectionManager.createConnection);

                    if (timeoutTimer) {
                        clearTimeout(timeoutTimer);
                    }

                    callback(null, {httpServer : httpServer,
                                    wsServer : wsServer,
                                    port : address.port
                                   });
                } else {
                    // address is null
                    // This shouldn't happen, because if we didn't get a socket
                    // we wouldn't have called this callback
                    if (timeoutTimer) {
                        clearTimeout(timeoutTimer);
                    }

                    if (callback) {
                        callback("ERR_UNKNOWN", null);
                    }
                }
            });
        }

        // Do initialization
        Logger.info("[Server] beginning startup");
        setupStdin();
        setupStdout();
        setupHttpAndWebSocketServers(function (err, servers) {
            if (err) {
                Logger.error(
                    "[Server] stopping due to error while starting http/ws servers: "
                        + err
                );
                stop();
            } else {
                Logger.info("[Server] serving on port", servers.port);
                _httpServer = servers.httpServer;
                _wsServer = servers._wsServer;
                // tell the parent process what port we're on
                sendCommandToParentProcess("port", servers.port);
            }
        }, SETUP_TIMEOUT);
        DomainManager.loadDomainModulesFromPaths(["./BaseDomain"]);
        Logger.info("[Server] startup complete");
    }

    // Public interface
    Server.start                    = start;
    Server.stop                     = stop;

}());
<commit_msg>Fix a typo that would prevent the Node WebSocket server from ever being properly closed.<commit_after>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4,
maxerr: 50, node: true */
/*global */

(function () {
    "use strict";

    /** @define{number} Number of ms to wait for the server to start */
    var SETUP_TIMEOUT = 5000; // wait up to 5 seconds for server to start

    /** @define{number} Number of ms between pings to parent process */
    var PING_DELAY = 1000; // send ping to parent process every 1 second

    var fs                = require("fs"),
        http              = require("http"),
        WebSocket         = require("./thirdparty/ws"),
        EventEmitter      = require("events").EventEmitter,
        Logger            = require("./Logger"),
        ConnectionManager = require("./ConnectionManager"),
        DomainManager     = require("./DomainManager");

    /**
     * @constructor
     * The Server module is a singleton object that manages both the
     * connection to the parent process (over stdin/stdout) and to clients
     * over WebSockets.
     *
     * Server inherits from the EventEmitter class and exports itself
     * as the module.
     */
    var Server = module.exports = new EventEmitter();

    /**
     * @private
     * @type{number} unique IDs for messages to parent process
     */
    var _commandCount = 1;

    /**
     * @private
     * @type{http.Server} the HTTP server
     */
    var _httpServer = null;

    /**
     * @private
     * @type{ws.WebSocketServer} the WebSocket server
     */
    var _wsServer = null;

    /**
     * Stops the server and does appropriate cleanup.
     * Emits an "end" event when shutdown is complete.
     */
    function stop() {
        Logger.info("[Server] stopping");
        if (_wsServer) {
            try {
                _wsServer.close();
            } catch (err1) { }
        }
        if (_httpServer) {
            try {
                _httpServer.close();
            } catch (err2) { }
        }
        ConnectionManager.closeAllConnections();
        Logger.info("[Server] stopped");
        Server.emit("end");
        Server.removeAllListeners();
    }

    /**
     * Starts the server.
     */
    function start() {
        function sendCommandToParentProcess() {
            var cmd = "\n\n" + (_commandCount++) + "|"
                + Array.prototype.join.call(arguments, "|") + "\n\n";
            process.stdout.write(cmd);
        }

        function httpRequestHandler(req, res) {
            if (req.method === "GET") {
                if (req.url === "/api" || req.url.indexOf("/api/") === 0) {
                    res.setHeader("Content-Type", "application/json");
                    res.end(
                        JSON.stringify(DomainManager.getDomainDescriptions(),
                                        null,
                                        4)
                    );
                } else {
                    res.setHeader("Content-Type", "text/plain");
                    res.end("Brackets-Shell Server\n");
                }
            } else { // Not a GET request
                res.statusCode = 501;
                res.end();
            }
        }

        function setupStdin() {
            // re-enable getting events from stdin
            try {
                process.stdin.resume();
                process.stdin.setEncoding("utf8");
            } catch (e) {
                // Couldn't resume stdin, so something is terribly wrong
                Logger.error("[Server] unable to resume stdin, stopping");
                stop();
            }

            // set up event handlers for stdin
            process.stdin.on("data", function (data) {
                // no-op, but make sure we read the data so the buffer
                // doesn't fill up
            });

            process.stdin.on("end", function receiveStdInClose() {
                Logger.info("[Server] stopping because stdin closed");
                stop();
            });
        }

        function setupStdout() {
            // Routinely check if stdout is closed. Stdout will close when our
            // parent process closes (either expectedly or unexpectedly) so this
            // is our signal to shutdown to prevent process abandonment.
            //
            // We need to continually ping because that's the only way to actually
            // check if the pipe is closed in a robust way (writable may only get
            // set to false after trying to write a ping to a closed pipe).
            setInterval(function () {
                if (!process.stdout.writable) {
                    // If stdout closes, our parent process has terminated or
                    // has explicitly closed it. Either way, we should exit.
                    Logger.info("[Server] stopping because stdout closed");
                    stop();
                } else {
                    try {
                        sendCommandToParentProcess("ping");
                    } catch (e) {
                        Logger.info("[Server] stopping because stdout was not writable");
                        stop();
                    }
                }
            }, PING_DELAY);
        }

        function setupHttpAndWebSocketServers(callback, timeout) {
            var timeoutTimer = null;
            var httpServer = null;

            if (timeout) {
                timeoutTimer = setTimeout(function () {
                    callback("ERR_TIMEOUT", null);
                }, timeout);
            }

            httpServer = http.createServer(httpRequestHandler);

            httpServer.on("error", function () {
                if (callback) {
                    callback("ERR_CREATE_SERVER", null);
                }
            });

            httpServer.listen(0, "127.0.0.1", function () {
                var wsServer = null;
                var address = httpServer.address();
                if (address !== null) {
                    httpServer.removeAllListeners("error");
                    httpServer.on("error", function () {
                        Logger.error("[Server] stopping due to HTTP error",
                                      arguments);
                        stop();
                    });

                    wsServer = new WebSocket.Server({server: httpServer});
                    wsServer.on("error", function () {
                        Logger.error(
                            "[Server] stopping due to WebSocket error",
                            arguments
                        );
                        stop();
                    });
                    wsServer.on("connection",
                                ConnectionManager.createConnection);

                    if (timeoutTimer) {
                        clearTimeout(timeoutTimer);
                    }

                    callback(null, {httpServer : httpServer,
                                    wsServer : wsServer,
                                    port : address.port
                                   });
                } else {
                    // address is null
                    // This shouldn't happen, because if we didn't get a socket
                    // we wouldn't have called this callback
                    if (timeoutTimer) {
                        clearTimeout(timeoutTimer);
                    }

                    if (callback) {
                        callback("ERR_UNKNOWN", null);
                    }
                }
            });
        }

        // Do initialization
        Logger.info("[Server] beginning startup");
        setupStdin();
        setupStdout();
        setupHttpAndWebSocketServers(function (err, servers) {
            if (err) {
                Logger.error(
                    "[Server] stopping due to error while starting http/ws servers: "
                        + err
                );
                stop();
            } else {
                Logger.info("[Server] serving on port", servers.port);
                _httpServer = servers.httpServer;
                _wsServer = servers.wsServer;
                // tell the parent process what port we're on
                sendCommandToParentProcess("port", servers.port);
            }
        }, SETUP_TIMEOUT);
        DomainManager.loadDomainModulesFromPaths(["./BaseDomain"]);
        Logger.info("[Server] startup complete");
    }

    // Public interface
    Server.start                    = start;
    Server.stop                     = stop;

}());
<|endoftext|>


<commit_before>module.exports = [
	{type: "getStorage", fn: _getStorage},
	{type: "gotStorage", fn: _gotStorage},

	{type: "checkFrom", fn: _checkFrom},
	{type: "checkTo", fn: _checkTo},

	{type: "calculate", fn: _calculate},
	{type: "calcStarted", fn: _calcStarted},
	{type: "calcProgress", fn: _calcProgress},
	{type: "calcFinished", fn: _calcFinished},
	// {type: "calcIsRunning", fn: _calcIsRunning},

	{type: "move", fn: _move},
	{type: "moveStarted", fn: _moveStarted},
	{type: "moveProgress", fn: _moveProgress},
	{type: "moveFinished", fn: _moveFinished},
]

function _getStorage({state, actions, dispatch}, {api, _}) {
	dispatch(actions.opInProgress, actions.getStorage)

	api.getStorage()
		.then(json => {
			dispatch(actions.gotStorage, json)
		})
	// here i can catch the error and show an appropriate message

	return state
}

function _gotStorage({state, actions, dispatch}, _, unraid) {
	// console.log('unraid: ', unraid)

	// let toDisk = {}
	// let fromDisk = {}
	// let maxFreeSize = 0
	// let maxFreePath = ""

	// unraid.disks.map( disk => {
	// 	toDisk[disk.path] = true
	// 	fromDisk[disk.path] = false

	// 	if (disk.free > maxFreeSize) {
	// 		maxFreeSize = disk.free
	// 		maxFreePath = disk.path
	// 	}

	// 	return disk
	// })

	// if (maxFreePath != "") {
	// 	toDisk[maxFreePath] = false
	// 	fromDisk[maxFreePath] = true
	// }

	let toDisk = {}
	let fromDisk = {}

	unraid.disks.forEach( disk => {
		fromDisk[disk.path] = disk.src
		toDisk[disk.path] = disk.dst
	})

	let newState = Object.assign({}, state)

	newState.opInProgress = null
	newState.moveDisabled = true
	newState.lines = []
	newState.unraid = unraid
	newState.fromDisk = fromDisk
	newState.toDisk = toDisk

	return newState
	// return {
	// 	...state,
	// 	opInProgress: null,
	// 	moveDisabled: true,
	// 	lines: [],
	// 	unraid,
	// 	fromDisk,
	// 	toDisk,
	// }
}

function _checkFrom({state, actions, dispatch}, _, path) {
	let newState = Object.assign({}, state)

	for (var key in newState.fromDisk) {
		if (key !== path) {
			newState.fromDisk[key] = false
		}
	}
	newState.fromDisk[path] = true

	for (var key in newState.toDisk) {
		newState.toDisk[key] = !(key === path)
	}

	return newState
}

function _checkTo({state, actions, dispatch}, _, path) {
	let newState = Object.assign({}, state)

	newState.toDisk[path] = !newState.toDisk[path]

	return newState
}

function _calculate({state, actions, dispatch}, {_, ws}) {
	dispatch(actions.opInProgress, actions.calculate)

	let srcDisk = ""

	for (var key in state.fromDisk) {
		if (state.fromDisk[key]) {
			srcDisk = key
			break
		}
	}

	ws.send({topic: actions.calculate, payload: {srcDisk, dstDisks: state.toDisk}})

	return state
}

function _calcStarted({state, actions, dispatch}, _, line) {
	let newState = Object.assign({}, state)

	// make sure we clean out the lines array
	newState.lines = [].concat('CALCULATE: ' + line)

	newState.unraid.disks.forEach( disk => {
		disk.newFree = disk.free
	})

	return newState

	// return {
	// 	...state,
	// 	lines: [].concat('CALCULATE: ' + payload),
	// }
}

function _calcProgress({state, actions, dispatch}, _, line) {
	let newState = Object.assign({}, state)

	// make sure we disable the interface, in case another browser is open
	// or even the initial browser is woken from sleep
	newState.opInProgress = actions.calculate
	newState.moveDisabled = true

	newState.lines.push('CALCULATE: ' + line)

	return newState

	// return {
	// 	...state,
	// 	lines: state.lines.concat('CALCULATE: ' + payload),
	// }
}

function _calcFinished({state, actions, dispatch}, _, unraid) {
	let newState = Object.assign({}, state)

	newState.unraid = unraid
	newState.opInProgress = null
	newState.moveDisabled = false

	return newState

	// return {
	// 	...state,
	// 	unraid,
	// 	opInProgress: null,
	// 	moveDisabled: false,
	// }
}

// // this message is received when the browser requests
// function _calcIsRunning({state, actions, dispatch}, _, unraid) {
// 	let newState = Object.assign({}, state)

// 	newState.opInProgress = actions.calculate
// 	newState.moveDisabled = true
// 	// newState.lines.push('CALCULATE: ' + line)

// 	return newState
// }

function _move({state, actions, dispatch}, {_, ws}) {
	dispatch(actions.opInProgress, actions.move)

	ws.send({topic: actions.move})

	return state
}

function _moveStarted({state, actions, dispatch}, _, line) {
	let newState = Object.assign({}, state)

	// make sure we clean out the lines array
	newState.lines = [].concat('MOVE: ' + line)

	return newState

	// return {
	// 	...state,
	// 	lines: [].concat('MOVE: ' + payload),
	// }
}

function _moveProgress({state, actions, dispatch}, _, line) {
	let newState = Object.assign({}, state)

	newState.lines.push('MOVE: ' + line)

	return newState
	// return {
	// 	...state,
	// 	lines: state.lines.concat('MOVE: ' + payload),
	// }
}

function _moveFinished({state, actions, dispatch}, _, unraid) {
	let newState = Object.assign({}, state)

	newState.unraid = unraid
	newState.opInProgress = null
	newState.moveDisabled = !state.config.dryRun

	return newState

	// let moveDisabled = !state.config.dryRun
	// console.log('moveDisabled: ', moveDisabled)
	// return {
	// 	...state,
	// 	unraid,
	// 	opInProgress: null,
	// 	moveDisabled,
	// }
}
<commit_msg>(front) Set feedback message when calculate returns 0 bytes to move<commit_after>module.exports = [
	{type: "getStorage", fn: _getStorage},
	{type: "gotStorage", fn: _gotStorage},

	{type: "checkFrom", fn: _checkFrom},
	{type: "checkTo", fn: _checkTo},

	{type: "calculate", fn: _calculate},
	{type: "calcStarted", fn: _calcStarted},
	{type: "calcProgress", fn: _calcProgress},
	{type: "calcFinished", fn: _calcFinished},
	// {type: "calcIsRunning", fn: _calcIsRunning},

	{type: "move", fn: _move},
	{type: "moveStarted", fn: _moveStarted},
	{type: "moveProgress", fn: _moveProgress},
	{type: "moveFinished", fn: _moveFinished},
]

function _getStorage({state, actions, dispatch}, {api, _}) {
	dispatch(actions.opInProgress, actions.getStorage)

	api.getStorage()
		.then(json => {
			dispatch(actions.gotStorage, json)
		})
	// here i can catch the error and show an appropriate message

	return state
}

function _gotStorage({state, actions, dispatch}, _, unraid) {
	// console.log('unraid: ', unraid)

	// let toDisk = {}
	// let fromDisk = {}
	// let maxFreeSize = 0
	// let maxFreePath = ""

	// unraid.disks.map( disk => {
	// 	toDisk[disk.path] = true
	// 	fromDisk[disk.path] = false

	// 	if (disk.free > maxFreeSize) {
	// 		maxFreeSize = disk.free
	// 		maxFreePath = disk.path
	// 	}

	// 	return disk
	// })

	// if (maxFreePath != "") {
	// 	toDisk[maxFreePath] = false
	// 	fromDisk[maxFreePath] = true
	// }

	let toDisk = {}
	let fromDisk = {}

	unraid.disks.forEach( disk => {
		fromDisk[disk.path] = disk.src
		toDisk[disk.path] = disk.dst
	})

	let newState = Object.assign({}, state)

	newState.opInProgress = null
	newState.moveDisabled = true
	newState.lines = []
	newState.unraid = unraid
	newState.fromDisk = fromDisk
	newState.toDisk = toDisk

	return newState
	// return {
	// 	...state,
	// 	opInProgress: null,
	// 	moveDisabled: true,
	// 	lines: [],
	// 	unraid,
	// 	fromDisk,
	// 	toDisk,
	// }
}

function _checkFrom({state, actions, dispatch}, _, path) {
	let newState = Object.assign({}, state)

	for (var key in newState.fromDisk) {
		if (key !== path) {
			newState.fromDisk[key] = false
		}
	}
	newState.fromDisk[path] = true

	for (var key in newState.toDisk) {
		newState.toDisk[key] = !(key === path)
	}

	return newState
}

function _checkTo({state, actions, dispatch}, _, path) {
	let newState = Object.assign({}, state)

	newState.toDisk[path] = !newState.toDisk[path]

	return newState
}

function _calculate({state, actions, dispatch}, {_, ws}) {
	dispatch(actions.opInProgress, actions.calculate)

	let srcDisk = ""

	for (var key in state.fromDisk) {
		if (state.fromDisk[key]) {
			srcDisk = key
			break
		}
	}

	ws.send({topic: actions.calculate, payload: {srcDisk, dstDisks: state.toDisk}})

	return state
}

function _calcStarted({state, actions, dispatch}, _, line) {
	let newState = Object.assign({}, state)

	// make sure we clean out the lines array
	newState.lines = [].concat('CALCULATE: ' + line)

	newState.unraid.disks.forEach( disk => {
		disk.newFree = disk.free
	})

	return newState

	// return {
	// 	...state,
	// 	lines: [].concat('CALCULATE: ' + payload),
	// }
}

function _calcProgress({state, actions, dispatch}, _, line) {
	let newState = Object.assign({}, state)

	// make sure we disable the interface, in case another browser is open
	// or even the initial browser is woken from sleep
	newState.opInProgress = actions.calculate
	newState.moveDisabled = true

	newState.lines.push('CALCULATE: ' + line)

	return newState

	// return {
	// 	...state,
	// 	lines: state.lines.concat('CALCULATE: ' + payload),
	// }
}

function _calcFinished({state, actions, dispatch}, _, unraid) {
	let newState = Object.assign({}, state)

	newState.unraid = unraid
	newState.opInProgress = null
	newState.moveDisabled = false

	if (newState.unraid.bytesToMove === 0) {
		newState.feedback.push("There's no space available to move any of the folders you selected.")
		newState.feedback.push("Check more disks in the TO column or go to the Settings page, to review the folders selected for moving.")
	}

	return newState

	// return {
	// 	...state,
	// 	unraid,
	// 	opInProgress: null,
	// 	moveDisabled: false,
	// }
}

// // this message is received when the browser requests
// function _calcIsRunning({state, actions, dispatch}, _, unraid) {
// 	let newState = Object.assign({}, state)

// 	newState.opInProgress = actions.calculate
// 	newState.moveDisabled = true
// 	// newState.lines.push('CALCULATE: ' + line)

// 	return newState
// }

function _move({state, actions, dispatch}, {_, ws}) {
	dispatch(actions.opInProgress, actions.move)

	ws.send({topic: actions.move})

	return state
}

function _moveStarted({state, actions, dispatch}, _, line) {
	let newState = Object.assign({}, state)

	// make sure we clean out the lines array
	newState.lines = [].concat('MOVE: ' + line)

	return newState

	// return {
	// 	...state,
	// 	lines: [].concat('MOVE: ' + payload),
	// }
}

function _moveProgress({state, actions, dispatch}, _, line) {
	let newState = Object.assign({}, state)

	newState.lines.push('MOVE: ' + line)

	return newState
	// return {
	// 	...state,
	// 	lines: state.lines.concat('MOVE: ' + payload),
	// }
}

function _moveFinished({state, actions, dispatch}, _, unraid) {
	let newState = Object.assign({}, state)

	newState.unraid = unraid
	newState.opInProgress = null
	newState.moveDisabled = !state.config.dryRun

	return newState

	// let moveDisabled = !state.config.dryRun
	// console.log('moveDisabled: ', moveDisabled)
	// return {
	// 	...state,
	// 	unraid,
	// 	opInProgress: null,
	// 	moveDisabled,
	// }
}
<|endoftext|>


<commit_before>Taskar.Sections.NewSection = function(container){
  container.on('click',     '.add_section',       show);
  container.on('click',     'input[type=button]', hide);
  container.on('key:esc',   'form',               hide);
  container.on('submit',    'form',               Taskar.Sections.validateForm);

  var form    = $('new_section'),
      appear  = new S2.FX.SlideDown(form, function(e){ form.down('input[type=text]').focus(); });

  function show(e, element){
    e && e.preventDefault();

    form.down('form').reset();
    form.down('input[name*=insert_before]').setValue(element.getAttribute('data-before'));

    if (element.previous() == form && form.visible()){
      return;
    }

    form.hide();

    element.hide()
    element.show.bind(element).defer();
    element.up('li').insert({before: form});

    appear.play();
  }

  function hide(){
    form.hide();
  }

  if (container.select('.section').length == 0){
    show(null, container.down('.add_section'));
  }
};<commit_msg>hide new section form with slide effect<commit_after>Taskar.Sections.NewSection = function(container){
  container.on('click',     '.add_section',       show);
  container.on('click',     'input[type=button]', hide);
  container.on('key:esc',   'form',               hide);
  container.on('submit',    'form',               Taskar.Sections.validateForm);

  var form    = $('new_section'),
      appear  = new S2.FX.SlideDown(form, function(e){ form.down('input[type=text]').focus(); });

  function show(e, element){
    e && e.preventDefault();

    form.down('form').reset();
    form.down('input[name*=insert_before]').setValue(element.getAttribute('data-before'));

    if (element.previous() == form && form.visible()){
      return;
    }

    form.hide();

    element.hide()
    element.show.bind(element).defer();
    element.up('li').insert({before: form});

    appear.play();
  }

  function hide(){
    form.slideUp();
  }

  if (container.select('.section').length == 0){
    show(null, container.down('.add_section'));
  }
};<|endoftext|>


<commit_before>// @flow
import Acl from '../src/classes/acl';
import Memory from '../src/stores/memory';

const store = new Memory();

describe('Constructor', () => {
  it('Should use default `buckets` names', () => {
    const acl = new Acl(store);

    expect(acl.options.buckets.meta).toEqual('meta');
    expect(acl.options.buckets.parents).toEqual('parents');
    expect(acl.options.buckets.permissions).toEqual('permissions');
    expect(acl.options.buckets.resources).toEqual('resources');
    expect(acl.options.buckets.roles).toEqual('roles');
    expect(acl.options.buckets.users).toEqual('users');
  });

  it('Should use given `buckets` names', () => {
    const acl = new Acl(store, null, {
      buckets: {
        meta: 'Meta',
        parents: 'Parents',
        permissions: 'Permissions',
        resources: 'Resources',
        roles: 'Roles',
        users: 'Users',
      }
    });

    expect(acl.options.buckets.meta).toEqual('Meta');
    expect(acl.options.buckets.parents).toEqual('Parents');
    expect(acl.options.buckets.permissions).toEqual('Permissions');
    expect(acl.options.buckets.resources).toEqual('Resources');
    expect(acl.options.buckets.roles).toEqual('Roles');
    expect(acl.options.buckets.users).toEqual('Users');
  });
});

describe(`Allows`, () => {
  it('guest to view blogs', () => {
    const acl = new Acl();
    acl.allow('guest', 'blogs', 'view', (err) => {
      expect(!err);
    });
  });

  it(`guest to view forums`, () => {
    const acl = new Acl(store);
    acl.allow('guest', 'forums', 'view', (err) => {
      expect(!err);
    });
  });

  it(`member to view/edit/delete blogs`, () => {
    const acl = new Acl(store);
    acl.allow('member', 'blogs', ['edit', 'view', 'delete'], (err) => {
      expect(!err);
    });
  });
});

describe(`Add user roles`, () => {
  it(`joed = guest, jsmith = member, harry = admin, test@test.com = member`, (done) => {
    const acl = new Acl(store);

    acl.addUserRoles('joed', 'guest', (err) => {
      expect(!err);

      acl.addUserRoles('jsmith', 'member', (err) => {
        expect(!err);

        acl.addUserRoles('harry', 'admin', (err) => {
          expect(!err);

          acl.addUserRoles('test@test.com', 'member', (err) => {
            expect(!err);
            done();
          });
        });
      });
    });
  });

  it(`0 = guest, 1 = member, 2 = admin`, (done) => {
    const acl = new Acl(store);

    acl.addUserRoles(0, 'guest', (err) => {
      expect(!err);

      acl.addUserRoles(1, 'member', (err) => {
        expect(!err);

        acl.addUserRoles(2, 'admin', (err) => {
          expect(!err);
          done();
        });
      });
    });
  });
});

describe(`Read user's roles`, () => {
  it(`Run userRoles function`, (done) => {
    const acl = new Acl(store);
    acl.addUserRoles('harry', 'admin', (err) => {
      if (err) return done(err);

      acl.userRoles('harry', (err, roles) => {
        if (err) return done(err);
        expect(roles).toEqual(['admin']);

        acl.hasRole('harry', 'admin', (err, is_in_role) => {
          if (err) return done(err);
          expect(is_in_role).toBeTruthy();

          acl.hasRole('harry', 'no role', (err, is_in_role) => {
            if (err) return done(err);
            expect(is_in_role).toBeFalsy();
            done();
          });
        });
      });
    });
  });
});
<commit_msg>chore(__tests__/index.test.js) read role's users tests created<commit_after>// @flow
import Acl from '../src/classes/acl';
import Memory from '../src/stores/memory';

const store = new Memory();

describe('Constructor', () => {
  it('Should use default `buckets` names', () => {
    const acl = new Acl(store);

    expect(acl.options.buckets.meta).toEqual('meta');
    expect(acl.options.buckets.parents).toEqual('parents');
    expect(acl.options.buckets.permissions).toEqual('permissions');
    expect(acl.options.buckets.resources).toEqual('resources');
    expect(acl.options.buckets.roles).toEqual('roles');
    expect(acl.options.buckets.users).toEqual('users');
  });

  it('Should use given `buckets` names', () => {
    const acl = new Acl(store, null, {
      buckets: {
        meta: 'Meta',
        parents: 'Parents',
        permissions: 'Permissions',
        resources: 'Resources',
        roles: 'Roles',
        users: 'Users',
      }
    });

    expect(acl.options.buckets.meta).toEqual('Meta');
    expect(acl.options.buckets.parents).toEqual('Parents');
    expect(acl.options.buckets.permissions).toEqual('Permissions');
    expect(acl.options.buckets.resources).toEqual('Resources');
    expect(acl.options.buckets.roles).toEqual('Roles');
    expect(acl.options.buckets.users).toEqual('Users');
  });
});

describe(`Allows`, () => {
  it('guest to view blogs', () => {
    const acl = new Acl();
    acl.allow('guest', 'blogs', 'view', (err) => {
      expect(!err);
    });
  });

  it(`guest to view forums`, () => {
    const acl = new Acl(store);
    acl.allow('guest', 'forums', 'view', (err) => {
      expect(!err);
    });
  });

  it(`member to view/edit/delete blogs`, () => {
    const acl = new Acl(store);
    acl.allow('member', 'blogs', ['edit', 'view', 'delete'], (err) => {
      expect(!err);
    });
  });
});

describe(`Add user roles`, () => {
  it(`joed = guest, jsmith = member, harry = admin, test@test.com = member`, (done) => {
    const acl = new Acl(store);

    acl.addUserRoles('joed', 'guest', (err) => {
      expect(!err);

      acl.addUserRoles('jsmith', 'member', (err) => {
        expect(!err);

        acl.addUserRoles('harry', 'admin', (err) => {
          expect(!err);

          acl.addUserRoles('test@test.com', 'member', (err) => {
            expect(!err);
            done();
          });
        });
      });
    });
  });

  it(`0 = guest, 1 = member, 2 = admin`, (done) => {
    const acl = new Acl(store);

    acl.addUserRoles(0, 'guest', (err) => {
      expect(!err);

      acl.addUserRoles(1, 'member', (err) => {
        expect(!err);

        acl.addUserRoles(2, 'admin', (err) => {
          expect(!err);
          done();
        });
      });
    });
  });
});

describe(`Read user's roles`, () => {
  it(`Run userRoles function`, (done) => {
    const acl = new Acl(store);
    acl.addUserRoles('harry', 'admin', (err) => {
      if (err) return done(err);

      acl.userRoles('harry', (err, roles) => {
        if (err) return done(err);
        expect(roles).toEqual(['admin']);

        acl.hasRole('harry', 'admin', (err, is_in_role) => {
          if (err) return done(err);
          expect(is_in_role).toBeTruthy();

          acl.hasRole('harry', 'no role', (err, is_in_role) => {
            if (err) return done(err);
            expect(is_in_role).toBeFalsy();
            done();
          });
        });
      });
    });
  });
});

describe(`Read role's users`, () => {
  it('Run roleUsers function', (done) => {
    const acl = new Acl(store);
    acl.addUserRoles('harry', 'admin', (err) => {
      if (err) return done(err);

      acl.roleUsers('admin', (err, users) => {
        if (err) return done(err);
        expect(users).toContain('harry');
        done();
      });
    });
  });
});

<|endoftext|>


<commit_before>import AlertService from './AlertService';
import controllerModule from '../common/ControllerModule';
import DeepStreamService from '../common/DeepStreamService';
import _ from 'underscore';

class AlertController {
    constructor(AlertService, CommonService, DeepStreamService, toaster) {
        this.toaster = toaster;
        this.alertService = AlertService;
        this.commonService = CommonService;
        this.deepStreamService = DeepStreamService;
        this.alertMessages = [];
        this.mappingIncidentIds = [];
        this.mapDetails = {};
        this.multiple = {
            incidents: []
        };
        this.connection = this.deepStreamService.getServerConnection();
        this.messagelist = this.connection.record.getList('safety/alerts');
        angular.extend(this, {
            center: {
                lat: 12.97,
                lng: 77.56,
                zoom: 10
            },
            markers: this.mapDetails,
            layers: {
                baselayers: {
                    googleTerrain: {
                        name: 'Google Terrain',
                        layerType: 'TERRAIN',
                        type: 'google'
                    },
                    googleHybrid: {
                        name: 'Google Hybrid',
                        layerType: 'HYBRID',
                        type: 'google'
                    },
                    googleRoadmap: {
                        name: 'Google Streets',
                        layerType: 'ROADMAP',
                        type: 'google'
                    }
                },
                overlays: {
                    Fire: {
                        name: 'Fire',
                        type: 'group',
                        visible: true
                    },
                    Police: {
                        name: 'Police',
                        type: 'group',
                        visible: true
                    },
                    Medical: {
                        name: 'Medical',
                        type: 'group',
                        visible: true
                    },
                    Hazard: {
                        name: 'Hazard',
                        type: 'group',
                        visible: true
                    },
                    Accident: {
                        name: 'Accident',
                        type: 'group',
                        visible: true
                    }
                }
            }
        });
        this.loadAlertsAsync();
        this.loadAsyncMobileVideos();
    };

    loadAlertsAsync() {
        this.mapDetails = {};
        this.messagelist.subscribe((entries)=> {
            this.alertMessages = entries.map((entry)=> {
                var list = this.connection.record.getRecord(entry);
                list.subscribe((data) => {
                    console.log(data.notificationType);
                    var incidentType = data.incidentType;
                    if (data.notificationType !== 'incident') {
                        if (this.mapDetails[incidentType] === undefined) {
                            this.mapDetails[incidentType] = {};
                        }
                        this.mapDetails[incidentType][data.incidentId] = {
                            lat: data.location.latitude,
                            lng: data.location.longitude,
                            message: data.location.latitude + "," + data.location.longitude,
                            draggable: false,
                            icon: {
                                iconUrl: '',
                            }
                        };
                        if (_.indexOf(this.mappingIncidentIds, data.incidentId) === -1) {
                            this.mappingIncidentIds.push(data.incidentId);
                        }
                        this.mapDetails[incidentType][data.incidentId].draggable = false;
                        this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/location-pointer.png';
                        this.mapDetails[incidentType][data.incidentId].icon.iconSize = [24, 24];
                        if (incidentType === 'Hazard') {
                            this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/hazard-location.png';
                        }
                        if (incidentType === 'Accident') {
                            this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/location-pointer.png';
                        }
                        if (incidentType === 'Fire') {
                            this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/fire-location.png';
                        }
                        if (incidentType === 'Police') {
                            this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/police-location.png';
                        }
                        if (incidentType === 'Medical') {
                            this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/medical-location.png';
                        }
                    }
                    else {
                        if (data.notificationType !== 'incident' && this.mapDetails[incidentType][data.incidentId] !== undefined) {
                            delete this.mapDetails[incidentType][data.incidentId];
                        }
                    }
                });
                return list;
            });

            angular.extend(this, {
                center: {
                    lat: 12.97,
                    lng: 77.56,
                    zoom: 10
                },
                markers: this.mapDetails,
                layers: {
                    baselayers: {
                        googleTerrain: {
                            name: 'Google Terrain',
                            layerType: 'TERRAIN',
                            type: 'google'
                        },
                        googleHybrid: {
                            name: 'Google Hybrid',
                            layerType: 'HYBRID',
                            type: 'google'
                        },
                        googleRoadmap: {
                            name: 'Google Streets',
                            layerType: 'ROADMAP',
                            type: 'google'
                        }
                    },
                    overlays: {
                        Fire: {
                            name: 'Fire',
                            type: 'group',
                            visible: true
                        },
                        Police: {
                            name: 'Police',
                            type: 'group',
                            visible: true
                        },
                        Medical: {
                            name: 'Medical',
                            type: 'group',
                            visible: true
                        },
                        Hazard: {
                            name: 'Hazard',
                            type: 'group',
                            visible: true
                        },
                        Accident: {
                            name: 'Accident',
                            type: 'group',
                            visible: true
                        }
                    }
                }
            });
        });
    };

    deleteRecordFromList(recordName, id, alertType) {
        var alertData = {};
        if (alertType === 'upload' || alertType === 'stream') {
            alertData = {
                notificationType: alertType,
                id: id,
                url: '',
                fileName: '',
                user: {
                    phoneNumber: '',
                    emailId: '',
                    userName: ''
                },
                location: {
                    latitude: '',
                    longitude: ''
                },
                status: 'read',
                mediaType: '',
                incidentType: '',
                time: '',
                incidentId: ''
            }
        }
        if (alertType === 'call') {
            alertData = {
                notificationType: alertType,
                id: id,
                caller: {
                    phoneNumber: '',
                    emailId: '',
                    userName: ''
                },
                callee: {
                    phoneNumber: '',
                    emailId: '',
                    userName: ''
                },
                location: {
                    latitude: '',
                    longitude: ''
                },
                status: "read",
                mediaType: '',
                incidentType: '',
                time: '',
                incidentId: ''
            }
        }
        console.log(id);
        this.alertService.deleteRecordFromDB(alertData).then((result)=> {
            console.log("result");
            console.log(result.data.message);
            if (result.data.message === "success") {
                delete this.mapDetails[id];
                console.log(this.mapDetails);
                console.log("recordName : " + recordName);
                this.connection.record.getRecord(recordName).delete();
                this.messagelist.removeEntry(recordName);
                this.toaster.pop("success", id + " deleted")
            } else {
                this.toaster.pop("error", "Error while delete")
            }

        });
    }

    setIncidentId(incidentId, id, notificationType) {
        this.selectIncidentId = incidentId;
        this.selectNotificationType = notificationType;
        console.log(this.selectIncidentId);
        console.log(this.selectNotificationType);
        this.mappingIncidentIdsWithoutParent = _.without(this.mappingIncidentIds, incidentId);
        this.multiple = {
            incidents: []
        };
    }

    saveMappedIncidents(recordName, incidentId, id, notificationType) {
        // console.log(id);
        // console.log(notificationType);
        var alert = {};
        if (notificationType === 'call') {
            alert = {
                id: '',
                time: '2017-06-19T22:40:02.486Z',
                name: '',
                parentAlert: [
                    {
                        alertType: notificationType,
                        alertId: id,
                        caller: {},
                        callee: {},
                        location: {},
                        status: '',
                        mediaType: '',
                        incidentType: '',
                        time: '',
                        incidentId: ''
                    }
                ],
                mappedAlerts: [],
                createdBy: '',
                description: '',
                status: '',
                assignedTo: [],
                alertUsers: []
            }
        } else {
            alert = {
                id: '',
                time: '2017-06-19T22:40:02.486Z',
                name: '',
                parentAlert: [
                    {
                        alertType: notificationType,
                        alertId: id,
                        user: {},
                        status: '',
                        mediaType: '',
                        incidentType: '',
                        time: '',
                        incidentId: ''
                    }
                ],
                mappedAlerts: [],
                createdBy: '',
                description: '',
                status: '',
                assignedTo: [],
                alertUsers: []
            }
        }
        console.log(alert);
        this.alertService.saveMappedIncidents(alert).then((result)=> {
            console.log(result);
            if (result.data.message === 'success') {
                console.log("recordName : " + recordName);
                this.connection.record.getRecord(recordName).delete();
                this.messagelist.removeEntry(recordName);
                this.toaster.pop("success", "Incident created")
            } else {
                this.toaster.pop("error", "Error while creating incident created");
            }
        })
    }

    loadAsyncMobileVideos() {
        this.url = "rtmp://192.168.1.101:1935/Sandeep-live-demo";
        this.file = "myStream";
        $("#flowplayer1").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        $("#flowplayer2").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        $("#flowplayer3").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        $("#flowplayer4").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        // Surv--Camera
        $("#surveillanceCamera1").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        $("#surveillanceCamera2").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        $("#surveillanceCamera3").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });
        $("#surveillanceCamera4").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });
    };
}

AlertController.$inject = ['AlertService', 'CommonService', 'DeepStreamService', 'toaster'];
export default controllerModule.controller('AlertController', AlertController).name;<commit_msg>updated incident mapping api and code<commit_after>import AlertService from './AlertService';
import controllerModule from '../common/ControllerModule';
import DeepStreamService from '../common/DeepStreamService';
import _ from 'underscore';

class AlertController {
    constructor(AlertService, CommonService, DeepStreamService, toaster) {
        this.toaster = toaster;
        this.alertService = AlertService;
        this.commonService = CommonService;
        this.deepStreamService = DeepStreamService;
        this.alertMessages = [];
        this.mappingIncidentIds = [];
        this.mapDetails = {};
        this.multiple = {
            incidents: []
        };
        this.connection = this.deepStreamService.getServerConnection();
        this.messagelist = this.connection.record.getList('safety/alerts');
        angular.extend(this, {
            center: {
                lat: 12.97,
                lng: 77.56,
                zoom: 10
            },
            markers: this.mapDetails,
            layers: {
                baselayers: {
                    googleTerrain: {
                        name: 'Google Terrain',
                        layerType: 'TERRAIN',
                        type: 'google'
                    },
                    googleHybrid: {
                        name: 'Google Hybrid',
                        layerType: 'HYBRID',
                        type: 'google'
                    },
                    googleRoadmap: {
                        name: 'Google Streets',
                        layerType: 'ROADMAP',
                        type: 'google'
                    }
                },
                overlays: {
                    Fire: {
                        name: 'Fire',
                        type: 'group',
                        visible: true
                    },
                    Police: {
                        name: 'Police',
                        type: 'group',
                        visible: true
                    },
                    Medical: {
                        name: 'Medical',
                        type: 'group',
                        visible: true
                    },
                    Hazard: {
                        name: 'Hazard',
                        type: 'group',
                        visible: true
                    },
                    Accident: {
                        name: 'Accident',
                        type: 'group',
                        visible: true
                    }
                }
            }
        });
        this.loadAlertsAsync();
        this.loadAsyncMobileVideos();
    };

    loadAlertsAsync() {
        this.mapDetails = {};
        this.messagelist.subscribe((entries)=> {
            this.alertMessages = entries.map((entry)=> {
                var list = this.connection.record.getRecord(entry);
                list.subscribe((data) => {
                    console.log(data.notificationType);
                    var incidentType = data.incidentType;
                    if (data.notificationType !== 'incident') {
                        if (this.mapDetails[incidentType] === undefined) {
                            this.mapDetails[incidentType] = {};
                        }
                        this.mapDetails[incidentType][data.incidentId] = {
                            lat: data.location.latitude,
                            lng: data.location.longitude,
                            message: data.location.latitude + "," + data.location.longitude,
                            draggable: false,
                            icon: {
                                iconUrl: '',
                            }
                        };
                        if (_.indexOf(this.mappingIncidentIds, data.incidentId) === -1) {
                            this.mappingIncidentIds.push(data.incidentId);
                        }
                        this.mapDetails[incidentType][data.incidentId].draggable = false;
                        this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/location-pointer.png';
                        this.mapDetails[incidentType][data.incidentId].icon.iconSize = [24, 24];
                        if (incidentType === 'Hazard') {
                            this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/hazard-location.png';
                        }
                        if (incidentType === 'Accident') {
                            this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/location-pointer.png';
                        }
                        if (incidentType === 'Fire') {
                            this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/fire-location.png';
                        }
                        if (incidentType === 'Police') {
                            this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/police-location.png';
                        }
                        if (incidentType === 'Medical') {
                            this.mapDetails[incidentType][data.incidentId].icon.iconUrl = 'img/medical-location.png';
                        }
                    }
                    else {
                        if (data.notificationType !== 'incident' && this.mapDetails[incidentType][data.incidentId] !== undefined) {
                            delete this.mapDetails[incidentType][data.incidentId];
                        }
                    }
                });
                return list;
            });

            angular.extend(this, {
                center: {
                    lat: 12.97,
                    lng: 77.56,
                    zoom: 10
                },
                markers: this.mapDetails,
                layers: {
                    baselayers: {
                        googleTerrain: {
                            name: 'Google Terrain',
                            layerType: 'TERRAIN',
                            type: 'google'
                        },
                        googleHybrid: {
                            name: 'Google Hybrid',
                            layerType: 'HYBRID',
                            type: 'google'
                        },
                        googleRoadmap: {
                            name: 'Google Streets',
                            layerType: 'ROADMAP',
                            type: 'google'
                        }
                    },
                    overlays: {
                        Fire: {
                            name: 'Fire',
                            type: 'group',
                            visible: true
                        },
                        Police: {
                            name: 'Police',
                            type: 'group',
                            visible: true
                        },
                        Medical: {
                            name: 'Medical',
                            type: 'group',
                            visible: true
                        },
                        Hazard: {
                            name: 'Hazard',
                            type: 'group',
                            visible: true
                        },
                        Accident: {
                            name: 'Accident',
                            type: 'group',
                            visible: true
                        }
                    }
                }
            });
        });
    };

    deleteRecordFromList(recordName, id, alertType) {
        var alertData = {};
        if (alertType === 'upload' || alertType === 'stream') {
            alertData = {
                notificationType: alertType,
                id: id,
                url: '',
                fileName: '',
                user: {
                    phoneNumber: '',
                    emailId: '',
                    userName: ''
                },
                location: {
                    latitude: '',
                    longitude: ''
                },
                status: 'read',
                mediaType: '',
                incidentType: '',
                time: '',
                incidentId: ''
            }
        }
        if (alertType === 'call') {
            alertData = {
                notificationType: alertType,
                id: id,
                caller: {
                    phoneNumber: '',
                    emailId: '',
                    userName: ''
                },
                callee: {
                    phoneNumber: '',
                    emailId: '',
                    userName: ''
                },
                location: {
                    latitude: '',
                    longitude: ''
                },
                status: "read",
                mediaType: '',
                incidentType: '',
                time: '',
                incidentId: ''
            }
        }
        console.log(id);
        this.alertService.deleteRecordFromDB(alertData).then((result)=> {
            console.log("result");
            console.log(result.data.message);
            if (result.data.message === "success") {
                delete this.mapDetails[id];
                console.log(this.mapDetails);
                console.log("recordName : " + recordName);
                this.connection.record.getRecord(recordName).delete();
                this.messagelist.removeEntry(recordName);
                this.toaster.pop("success", id + " deleted")
            } else {
                this.toaster.pop("error", "Error while delete")
            }

        });
    }

    setIncidentId(incidentId, id, notificationType) {
        this.selectIncidentId = incidentId;
        this.selectNotificationType = notificationType;
        console.log(this.selectIncidentId);
        console.log(this.selectNotificationType);
        this.mappingIncidentIdsWithoutParent = _.without(this.mappingIncidentIds, incidentId);
        this.multiple = {
            incidents: []
        };
    }

    saveMappedIncidents(recordName, incidentId, id, notificationType) {
        // console.log(id);
        // console.log(notificationType);
        var alert = {};
        if (notificationType === 'call') {
            alert = {
                id: '',
                time: '2017-06-19T22:40:02.486Z',
                name: '',
                parentAlert: [
                    {
                        alertType: 'call',
                        alertId: id,
                        caller: {},
                        callee: {},
                        location: {},
                        status: '',
                        mediaType: '',
                        incidentType: '',
                        time: '',
                        incidentId: ''
                    }
                ],
                mappedAlerts: [],
                createdBy: '',
                description: '',
                status: '',
                assignedTo: [],
                alertUsers: []
            }
        } else {
            alert = {
                id: '',
                time: '2017-06-19T22:40:02.486Z',
                name: '',
                parentAlert: [
                    {
                        alertType: 'file',
                        alertId: id,
                        user: {},
                        status: '',
                        mediaType: '',
                        incidentType: '',
                        time: '',
                        incidentId: ''
                    }
                ],
                mappedAlerts: [],
                createdBy: '',
                description: '',
                status: '',
                assignedTo: [],
                alertUsers: []
            }
        }
        console.log(alert);
        this.alertService.saveMappedIncidents(alert).then((result)=> {
            console.log(result);
            if (result.data.message === 'success') {
                console.log("recordName : " + recordName);
                this.connection.record.getRecord(recordName).delete();
                this.messagelist.removeEntry(recordName);
                this.toaster.pop("success", "Incident created")
            } else {
                this.toaster.pop("error", "Error while creating incident created");
            }
        })
    }

    loadAsyncMobileVideos() {
        this.url = "rtmp://192.168.1.101:1935/Sandeep-live-demo";
        this.file = "myStream";
        $("#flowplayer1").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        $("#flowplayer2").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        $("#flowplayer3").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        $("#flowplayer4").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        // Surv--Camera
        $("#surveillanceCamera1").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        $("#surveillanceCamera2").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });

        $("#surveillanceCamera3").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });
        $("#surveillanceCamera4").flowplayer({
            live: true,
            swf: "video/flowplayer.swf",
            rtmp: this.url,
            playlist: [[{
                flash: this.file
            }]]
        });
    };
}

AlertController.$inject = ['AlertService', 'CommonService', 'DeepStreamService', 'toaster'];
export default controllerModule.controller('AlertController', AlertController).name;<|endoftext|>