<commit_before>/// <reference path="../_definitions.d.ts" />
define(["require", "exports"], function (require, exports) {
    var win = window, _store, stores = {};
    //#region Create Available Stores
    function timeout() {
        return new Promise(function (resolve) {
            setTimeout(resolve, 1);
        });
    }
    var MemoryStorage = (function () {
        function MemoryStorage() {
            this.memory = {};
        }
        MemoryStorage.prototype.clone = function (obj) {
            return obj === undefined ? undefined : JSON.parse(JSON.stringify(obj));
        };
        MemoryStorage.prototype.length = function () {
            var _this = this;
            return timeout()
                .then(function () { return Object.keys(_this.memory).length; });
        };
        MemoryStorage.prototype.key = function (index) {
            var _this = this;
            return timeout().then(function () {
                var key = Object.keys(_this.memory)[index];
                if (!key) {
                    throw new Error("No key at index " + index);
                }
                return key;
            });
        };
        MemoryStorage.prototype.getItem = function (key) {
            var _this = this;
            return timeout()
                .then(function () { return _this.clone(_this.memory[key]); });
        };
        MemoryStorage.prototype.setItem = function (key, value) {
            var _this = this;
            return timeout()
                .then(function () { _this.memory[key] = value; });
        };
        MemoryStorage.prototype.removeItem = function (key) {
            var _this = this;
            return timeout()
                .then(function () { delete _this.memory[key]; });
        };
        MemoryStorage.prototype.clear = function () {
            var _this = this;
            return timeout()
                .then(function () { _this.memory = {}; });
        };
        return MemoryStorage;
    })();
    exports.MemoryStorage = MemoryStorage;
    stores.memory = MemoryStorage;
    var WebSQLStorage = (function () {
        function WebSQLStorage() {
            this.db = null;
            this.dbname = "appystore";
            this.tablename = "storetable";
            this.dbsize = 10 * 1024 * 1024;
        }
        WebSQLStorage.prototype.executeSql = function (db, req, values) {
            return new Promise(function (resolve, reject) {
                db.transaction(function (tx) {
                    tx.executeSql(req, values || [], function (tx, result) { resolve(result); }, reject);
                }, reject);
            });
        };
        WebSQLStorage.prototype.ensureDb = function () {
            if (!this.db) {
                var db = this.db = win.openDatabase(this.dbname, "1.0", "Appy Store Database", this.dbsize);
                return this.executeSql(db, "CREATE TABLE IF NOT EXISTS " + this.tablename + " (id unique, data)").then(function () { return db; });
            }
            return Promise.resolve(this.db);
        };
        WebSQLStorage.prototype.length = function () {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "SELECT COUNT(*) AS linecount FROM " + _this.tablename); })
                .then(function (result) { return result.rows.item(0).linecount; });
        };
        WebSQLStorage.prototype.clear = function () {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "DELETE FROM " + _this.tablename + " WHERE 1=1"); })
                .then(function (result) { return undefined; });
        };
        WebSQLStorage.prototype.key = function (index) {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "SELECT id FROM " + _this.tablename + " ORDER BY id LIMIT " + index + ", 1"); })
                .then(function (result) { return result.rows.length > 0 ? result.rows.item(0).id : null; });
        };
        WebSQLStorage.prototype.getItem = function (key) {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "SELECT * FROM " + _this.tablename + " WHERE id=? LIMIT 1", [key]); })
                .then(function (result) { return result.rows.length > 0 ? result.rows.item(0).data : null; });
        };
        WebSQLStorage.prototype.setItem = function (key, value) {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "INSERT OR REPLACE INTO " + _this.tablename + " (id, data) VALUES (?, ?)", [key, value]); });
        };
        WebSQLStorage.prototype.removeItem = function (key) {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "DELETE FROM " + _this.tablename + " WHERE id=?", [key]); });
        };
        return WebSQLStorage;
    })();
    exports.WebSQLStorage = WebSQLStorage;
    stores.websql = WebSQLStorage;
    var indexedDB = win.indexedDB || win.mozIndexedDB || win.webkitIndexedDB || win.msIndexedDB || win.indexedDBShim, IDBTransaction = win.IDBTransaction || win.webkitIDBTransaction || win.msIDBTransaction || (win.indexedDBShim && win.indexedDBShim.modules.IDBTransaction), IDBKeyRange = win.IDBKeyRange || win.webkitIDBKeyRange || win.msIDBKeyRange || (win.indexedDBShim && win.indexedDBShim.modules.IDBKeyRange);
    var IndexedDBStorage = (function () {
        function IndexedDBStorage() {
            this.db = null;
            this.dbversion = 1;
            this.dbname = "appystore";
            this.tablename = "storetable";
        }
        IndexedDBStorage.prototype.createUpgradeNeeded = function (reject) {
            var _this = this;
            return function (e) {
                var _db = e.target.result;
                e.target.transaction.onerror = reject;
                if (!_db.objectStoreNames.contains(_this.tablename)) {
                    _db.createObjectStore(_this.tablename, { keyPath: "key" });
                }
            };
        };
        IndexedDBStorage.prototype.checkDatabaseConnection = function () {
            var _this = this;
            return new Promise(function (resolve, reject) {
                var request = indexedDB.open(_this.dbname, _this.dbversion);
                request.onupgradeneeded = _this.createUpgradeNeeded(reject);
                request.onsuccess = function (e) {
                    _this.db = e.target.result;
                    resolve(_this.db);
                };
                request.onerror = reject;
                request.onblocked = reject;
            });
        };
        IndexedDBStorage.prototype.ensureDatabase = function () {
            return Promise.resolve(this.db || this.checkDatabaseConnection());
        };
        IndexedDBStorage.prototype.clear = function () {
            var _this = this;
            return this.ensureDatabase()
                .then(function (db) {
                return new Promise(function (resolve, reject) {
                    var tx = db.transaction([_this.tablename], "readwrite");
                    tx.oncomplete = function (e) { return resolve.call(undefined); };
                    tx.onabort = reject;
                    tx.objectStore(_this.tablename).clear();
                });
            });
        };
        IndexedDBStorage.prototype.length = function () {
            var _this = this;
            return this.ensureDatabase().then(function (db) {
                return new Promise(function (resolve, reject) {
                    var store = db.transaction([_this.tablename], "readonly").objectStore(_this.tablename), request, result, i = 0;
                    if (store.count) {
                        request = store.count();
                        request.onsuccess = function (e) { resolve(e.target.result); };
                        request.onerror = reject;
                    }
                    else {
                        request = store.openCursor();
                        request.onerror = reject;
                        request.onsuccess = function (e) {
                            result = e.target.result;
                            result ? ++i && result.continue() : resolve(i);
                        };
                    }
                });
            });
        };
        IndexedDBStorage.prototype.key = function (index) {
            var _this = this;
            return this.ensureDatabase().then(function (db) {
                return new Promise(function (resolve, reject) {
                    var store = db.transaction([_this.tablename], "readonly").objectStore(_this.tablename), cursor = store.openCursor(), i = 0;
                    cursor.onsuccess = function (e) {
                        var _cursor = e.target.result;
                        if (_cursor) {
                            if (i === index) {
                                resolve(_cursor.value.key);
                            }
                            else if (i < index) {
                                _cursor.continue();
                            }
                            i++;
                        }
                        else {
                            reject(new Error("Not found"));
                        }
                    };
                    cursor.onerror = reject;
                });
            });
        };
        IndexedDBStorage.prototype.getItem = function (key) {
            var _this = this;
            return this.ensureDatabase().then(function (db) {
                return new Promise(function (resolve, reject) {
                    var store = db.transaction([_this.tablename], "readonly").objectStore(_this.tablename), request = store.get(key);
                    request.onsuccess = function (e) { resolve(e.target.result ? e.target.result.value : null); };
                    request.onerror = reject;
                });
            });
        };
        IndexedDBStorage.prototype.setItem = function (key, value) {
            var _this = this;
            return this.ensureDatabase().then(function (db) {
                return new Promise(function (resolve, reject) {
                    var store = db.transaction([_this.tablename], "readwrite").objectStore(_this.tablename), request = store.put({ key: key, value: value });
                    request.onerror = reject;
                    request.onsuccess = function (e) { resolve(undefined); };
                });
            });
        };
        IndexedDBStorage.prototype.removeItem = function (key) {
            var _this = this;
            return this.ensureDatabase().then(function (db) {
                return new Promise(function (resolve, reject) {
                    var store = db.transaction([_this.tablename], "readwrite").objectStore(_this.tablename), request = store.delete(key);
                    request.onerror = reject;
                    request.onsuccess = function (e) { resolve(undefined); };
                });
            });
        };
        return IndexedDBStorage;
    })();
    exports.IndexedDBStorage = IndexedDBStorage;
    stores.indexeddb = IndexedDBStorage;
    function createFromIStorage(type, storage) {
        var StorageWrapper = function StorageWrapper() {
            this.type = type;
        };
        StorageWrapper.prototype.length = function length() {
            return Promise.resolve(storage.length);
        };
        StorageWrapper.prototype.key = function key(index) {
            return timeout()
                .then(function () { return storage.key(index); });
        };
        StorageWrapper.prototype.getItem = function getItem(key) {
            return timeout()
                .then(function () { return storage.getItem(key); });
        };
        StorageWrapper.prototype.setItem = function setItem(key, value) {
            return timeout()
                .then(function () { return storage.setItem(key, value); });
        };
        StorageWrapper.prototype.removeItem = function removeItem(key) {
            return timeout()
                .then(function () { return storage.removeItem(key); });
        };
        StorageWrapper.prototype.clear = function clear() {
            return timeout()
                .then(function () { return storage.clear(); });
        };
        stores[type] = StorageWrapper;
    }
    ["localStorage", "sessionStorage"].forEach(function (storageType) {
        try {
            if (win[storageType] && win[storageType].getItem) {
                createFromIStorage(storageType, win[storageType]);
            }
        }
        catch (e) {
            return false;
        }
    });
    (function () {
        if (win.globalStorage) {
            try {
                createFromIStorage("globalStorage", win.globalStorage[window.location.hostname]);
            }
            catch (e) {
                return false;
            }
        }
    })();
    //#endregion
    //#region Initialize best available storage
    (function () {
        _store = new stores.localStorage();
        if (!_store) {
            if (stores.sessionStorage) {
                _store = new stores.sessionStorage();
            }
            else if (stores.globalStorage) {
                _store = new stores.globalStorage();
            }
            else {
                _store = new stores.memory();
            }
        }
    })();
    //#endregion
    //#region Public Methods
    function length() {
        return _store.length();
    }
    exports.length = length;
    function key(index) {
        return _store.key(index);
    }
    exports.key = key;
    function getItem(key) {
        return _store.getItem(key);
    }
    exports.getItem = getItem;
    function setItem(key, data) {
        return _store.setItem(key, data);
    }
    exports.setItem = setItem;
    function removeItem(key) {
        return _store.removeItem(key);
    }
    exports.removeItem = removeItem;
    function clear() {
        return _store.clear();
    }
    exports.clear = clear;
    function getStore(type) {
        if (!stores[type]) {
            throw new Error("Not Found");
        }
        if (typeof stores[type] === "function") {
            return new stores[type]();
        }
        return stores[type];
    }
    exports.getStore = getStore;
    function changeStore(type) {
        _store = getStore(type);
    }
    exports.changeStore = changeStore;
    function addStorageType(type, store, change) {
        if (stores[type]) {
            throw new Error("This store already exists !");
        }
        stores[type] = store;
        if (change === true) {
            changeStore(type);
        }
    }
    exports.addStorageType = addStorageType;
});
//#endregion
<commit_msg>Update distribution<commit_after>/// <reference path="../_definitions.d.ts" />
define(["require", "exports"], function (require, exports) {
    var win = window, _store, stores = {};
    //#region Create Available Stores
    function timeout() {
        return new Promise(function (resolve) {
            setTimeout(resolve, 1);
        });
    }
    var MemoryStorage = (function () {
        function MemoryStorage() {
            this.memory = {};
        }
        MemoryStorage.prototype.clone = function (obj) {
            return obj === undefined ? undefined : JSON.parse(JSON.stringify(obj));
        };
        MemoryStorage.prototype.length = function () {
            var _this = this;
            return timeout()
                .then(function () { return Object.keys(_this.memory).length; });
        };
        MemoryStorage.prototype.key = function (index) {
            var _this = this;
            return timeout().then(function () {
                var key = Object.keys(_this.memory)[index];
                if (!key) {
                    throw new Error("No key at index " + index);
                }
                return key;
            });
        };
        MemoryStorage.prototype.getItem = function (key) {
            var _this = this;
            return timeout()
                .then(function () { return _this.clone(_this.memory[key]); });
        };
        MemoryStorage.prototype.setItem = function (key, value) {
            var _this = this;
            return timeout()
                .then(function () { _this.memory[key] = value; });
        };
        MemoryStorage.prototype.removeItem = function (key) {
            var _this = this;
            return timeout()
                .then(function () { delete _this.memory[key]; });
        };
        MemoryStorage.prototype.clear = function () {
            var _this = this;
            return timeout()
                .then(function () { _this.memory = {}; });
        };
        return MemoryStorage;
    })();
    exports.MemoryStorage = MemoryStorage;
    stores.memory = MemoryStorage;
    var WebSQLStorage = (function () {
        function WebSQLStorage() {
            this.db = null;
            this.dbname = "appystore";
            this.tablename = "storetable";
            this.dbsize = 10 * 1024 * 1024;
        }
        WebSQLStorage.prototype.executeSql = function (db, req, values) {
            return new Promise(function (resolve, reject) {
                db.transaction(function (tx) {
                    tx.executeSql(req, values || [], function (tx, result) { resolve(result); }, reject);
                }, reject);
            });
        };
        WebSQLStorage.prototype.ensureDb = function () {
            if (!this.db) {
                var db = this.db = win.openDatabase(this.dbname, "1.0", "Appy Store Database", this.dbsize);
                return this.executeSql(db, "CREATE TABLE IF NOT EXISTS " + this.tablename + " (id unique, data)").then(function () { return db; });
            }
            return Promise.resolve(this.db);
        };
        WebSQLStorage.prototype.length = function () {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "SELECT COUNT(*) AS linecount FROM " + _this.tablename); })
                .then(function (result) { return result.rows.item(0).linecount; });
        };
        WebSQLStorage.prototype.clear = function () {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "DELETE FROM " + _this.tablename + " WHERE 1=1"); })
                .then(function (result) { return undefined; });
        };
        WebSQLStorage.prototype.key = function (index) {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "SELECT id FROM " + _this.tablename + " ORDER BY id LIMIT " + index + ", 1"); })
                .then(function (result) { return result.rows.length > 0 ? result.rows.item(0).id : null; });
        };
        WebSQLStorage.prototype.getItem = function (key) {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "SELECT * FROM " + _this.tablename + " WHERE id=? LIMIT 1", [key]); })
                .then(function (result) { return result.rows.length > 0 ? result.rows.item(0).data : null; });
        };
        WebSQLStorage.prototype.setItem = function (key, value) {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "INSERT OR REPLACE INTO " + _this.tablename + " (id, data) VALUES (?, ?)", [key, value]); });
        };
        WebSQLStorage.prototype.removeItem = function (key) {
            var _this = this;
            return this.ensureDb()
                .then(function (db) { return _this.executeSql(db, "DELETE FROM " + _this.tablename + " WHERE id=?", [key]); });
        };
        return WebSQLStorage;
    })();
    exports.WebSQLStorage = WebSQLStorage;
    stores.websql = WebSQLStorage;
    var indexedDB = win.indexedDB || win.mozIndexedDB || win.webkitIndexedDB || win.msIndexedDB || win.shimIndexedDB, IDBTransaction = win.IDBTransaction || win.webkitIDBTransaction || win.msIDBTransaction || (win.shimIndexedDB && win.shimIndexedDB.modules.IDBTransaction), IDBKeyRange = win.IDBKeyRange || win.webkitIDBKeyRange || win.msIDBKeyRange || (win.shimIndexedDB && win.shimIndexedDB.modules.IDBKeyRange);
    var IndexedDBStorage = (function () {
        function IndexedDBStorage() {
            this.db = null;
            this.dbversion = 1;
            this.dbname = "appystore";
            this.tablename = "storetable";
        }
        IndexedDBStorage.prototype.createUpgradeNeeded = function (reject) {
            var _this = this;
            return function (e) {
                var _db = e.target.result;
                e.target.transaction.onerror = reject;
                if (!_db.objectStoreNames.contains(_this.tablename)) {
                    _db.createObjectStore(_this.tablename, { keyPath: "key" });
                }
            };
        };
        IndexedDBStorage.prototype.checkDatabaseConnection = function () {
            var _this = this;
            return new Promise(function (resolve, reject) {
                var request = indexedDB.open(_this.dbname, _this.dbversion);
                request.onupgradeneeded = _this.createUpgradeNeeded(reject);
                request.onsuccess = function (e) {
                    _this.db = e.target.result;
                    resolve(_this.db);
                };
                request.onerror = reject;
                request.onblocked = reject;
            });
        };
        IndexedDBStorage.prototype.ensureDatabase = function () {
            return Promise.resolve(this.db || this.checkDatabaseConnection());
        };
        IndexedDBStorage.prototype.clear = function () {
            var _this = this;
            return this.ensureDatabase()
                .then(function (db) {
                return new Promise(function (resolve, reject) {
                    var tx = db.transaction([_this.tablename], "readwrite");
                    tx.oncomplete = function (e) { return resolve.call(undefined); };
                    tx.onabort = reject;
                    tx.objectStore(_this.tablename).clear();
                });
            });
        };
        IndexedDBStorage.prototype.length = function () {
            var _this = this;
            return this.ensureDatabase().then(function (db) {
                return new Promise(function (resolve, reject) {
                    var store = db.transaction([_this.tablename], "readonly").objectStore(_this.tablename), request, result, i = 0;
                    if (store.count) {
                        request = store.count();
                        request.onsuccess = function (e) { resolve(e.target.result); };
                        request.onerror = reject;
                    }
                    else {
                        request = store.openCursor();
                        request.onerror = reject;
                        request.onsuccess = function (e) {
                            result = e.target.result;
                            result ? ++i && result.continue() : resolve(i);
                        };
                    }
                });
            });
        };
        IndexedDBStorage.prototype.key = function (index) {
            var _this = this;
            return this.ensureDatabase().then(function (db) {
                return new Promise(function (resolve, reject) {
                    var store = db.transaction([_this.tablename], "readonly").objectStore(_this.tablename), cursor = store.openCursor(), i = 0;
                    cursor.onsuccess = function (e) {
                        var _cursor = e.target.result;
                        if (_cursor) {
                            if (i === index) {
                                resolve(_cursor.value.key);
                            }
                            else if (i < index) {
                                _cursor.continue();
                            }
                            i++;
                        }
                        else {
                            reject(new Error("Not found"));
                        }
                    };
                    cursor.onerror = reject;
                });
            });
        };
        IndexedDBStorage.prototype.getItem = function (key) {
            var _this = this;
            return this.ensureDatabase().then(function (db) {
                return new Promise(function (resolve, reject) {
                    var store = db.transaction([_this.tablename], "readonly").objectStore(_this.tablename), request = store.get(key);
                    request.onsuccess = function (e) { resolve(e.target.result ? e.target.result.value : null); };
                    request.onerror = reject;
                });
            });
        };
        IndexedDBStorage.prototype.setItem = function (key, value) {
            var _this = this;
            return this.ensureDatabase().then(function (db) {
                return new Promise(function (resolve, reject) {
                    var store = db.transaction([_this.tablename], "readwrite").objectStore(_this.tablename), request = store.put({ key: key, value: value });
                    request.onerror = reject;
                    request.onsuccess = function (e) { resolve(undefined); };
                });
            });
        };
        IndexedDBStorage.prototype.removeItem = function (key) {
            var _this = this;
            return this.ensureDatabase().then(function (db) {
                return new Promise(function (resolve, reject) {
                    var store = db.transaction([_this.tablename], "readwrite").objectStore(_this.tablename), request = store.delete(key);
                    request.onerror = reject;
                    request.onsuccess = function (e) { resolve(undefined); };
                });
            });
        };
        return IndexedDBStorage;
    })();
    exports.IndexedDBStorage = IndexedDBStorage;
    stores.indexeddb = IndexedDBStorage;
    function createFromIStorage(type, storage) {
        var StorageWrapper = function StorageWrapper() {
            this.type = type;
        };
        StorageWrapper.prototype.length = function length() {
            return Promise.resolve(storage.length);
        };
        StorageWrapper.prototype.key = function key(index) {
            return timeout()
                .then(function () { return storage.key(index); });
        };
        StorageWrapper.prototype.getItem = function getItem(key) {
            return timeout()
                .then(function () { return storage.getItem(key); });
        };
        StorageWrapper.prototype.setItem = function setItem(key, value) {
            return timeout()
                .then(function () { return storage.setItem(key, value); });
        };
        StorageWrapper.prototype.removeItem = function removeItem(key) {
            return timeout()
                .then(function () { return storage.removeItem(key); });
        };
        StorageWrapper.prototype.clear = function clear() {
            return timeout()
                .then(function () { return storage.clear(); });
        };
        stores[type] = StorageWrapper;
    }
    ["localStorage", "sessionStorage"].forEach(function (storageType) {
        try {
            if (win[storageType] && win[storageType].getItem) {
                createFromIStorage(storageType, win[storageType]);
            }
        }
        catch (e) {
            return false;
        }
    });
    (function () {
        if (win.globalStorage) {
            try {
                createFromIStorage("globalStorage", win.globalStorage[window.location.hostname]);
            }
            catch (e) {
                return false;
            }
        }
    })();
    //#endregion
    //#region Initialize best available storage
    (function () {
        _store = new stores.localStorage();
        if (!_store) {
            if (stores.sessionStorage) {
                _store = new stores.sessionStorage();
            }
            else if (stores.globalStorage) {
                _store = new stores.globalStorage();
            }
            else {
                _store = new stores.memory();
            }
        }
    })();
    //#endregion
    //#region Public Methods
    function length() {
        return _store.length();
    }
    exports.length = length;
    function key(index) {
        return _store.key(index);
    }
    exports.key = key;
    function getItem(key) {
        return _store.getItem(key);
    }
    exports.getItem = getItem;
    function setItem(key, data) {
        return _store.setItem(key, data);
    }
    exports.setItem = setItem;
    function removeItem(key) {
        return _store.removeItem(key);
    }
    exports.removeItem = removeItem;
    function clear() {
        return _store.clear();
    }
    exports.clear = clear;
    function getStore(type) {
        if (!stores[type]) {
            throw new Error("Not Found");
        }
        if (typeof stores[type] === "function") {
            return new stores[type]();
        }
        return stores[type];
    }
    exports.getStore = getStore;
    function changeStore(type) {
        _store = getStore(type);
    }
    exports.changeStore = changeStore;
    function addStorageType(type, store, change) {
        if (stores[type]) {
            throw new Error("This store already exists !");
        }
        stores[type] = store;
        if (change === true) {
            changeStore(type);
        }
    }
    exports.addStorageType = addStorageType;
});
//#endregion
<|endoftext|>


<commit_before>/*
 * DiscoJuice
 *  Work is based upon mock up made by the Kantara ULX group.
 *
 * Author: Andreas Åkre Solberg, UNINETT, andreas.solberg@uninett.no
 * Licence undecided. Awaiting alignment with the licence of the origin Kantara mockup.
 */
if (typeof DiscoJuice == "undefined") var DiscoJuice = {};

DiscoJuice.UI = {
	// Reference to the top level DiscoJuice object
	"parent" : DiscoJuice,

	// The current data model
	"control": null,

	// Reference to the
	"popup": null,

	// Entities / items
	"resulthtml": 'Loading data…',

	"show": function() {
		this.control.load();

		this.popup.fadeIn("slow");
		$("div#discojuice_overlay").show(); // fadeIn("fast");
		this.focusSearch();
	},

	"focusSearch": function() {
		$("input.discojuice_search").focus();
	},

	"hide": function() {
		$("div#discojuice_overlay").fadeOut("slow"); //fadeOut("fast");
		this.popup.fadeOut("slow");
	},

	"clearItems": function() {
		this.resulthtml = '';
	},

	// addItem(item, description, {country, flag}, keywordmatch, distance)
	// addItem(current, current.descr || null, countrydef, search, current.distance);
	"addItem": function(item, countrydef, search, distance, quickentry) {
		var textLink = '';
		var classes = '';
//		if (item.weight < -50) classes += 'hothit';

		var iconpath = this.parent.Utils.options.get('discoPath', '') + 'logos/';
		var flagpath = this.parent.Utils.options.get('discoPath', '') + 'flags/';
		var clear = false;

		var debugweight = this.parent.Utils.options.get('debug.weight', false);

		// Add icon element first
		if (item.icon) {
			textLink += '';
			clear = true;
		}

		if (quickentry) {
//			textLink += '↵';
			textLink += '↵';
		}

		// Add title
		textLink += '' + item.title + '';

		// Add matched search term
		if (search && search !== true) {
			textLink += '– ' + search + '';
		} else if (item.descr) {
			textLink += '– ' +  item.descr + '';
		}

		if (countrydef || (distance != undefined)) {

			textLink += '';
			if (countrydef) {
				textLink += '';
				if (countrydef.flag) textLink += ' ';
				textLink += countrydef.country + '';
			}

			if (distance != undefined) {
				if (distance < 1) {
					textLink += 'Nearby';
				} else {
					textLink += '' +  Math.round(distance) + ' km' + '';
				}

			}
			textLink += '';
		}

		if (debugweight) {
			textLink += '
';

			if (item.subID) {
				textLink += '<input value="' + item.subID + '" />';
			}

			var w = 0;
			if (item.weight) {
				w += item.weight;
			}
			if (item.distanceweight) {
				w += item.distanceweight;
			}
			textLink += 'Weight ' + Math.round(100*w)/100 + ' ';

			if (item.weight) {
				textLink += ' (base ' + item.weight + ')   ';
			}
			if (item.distanceweight) {
				textLink += '(dist ' + Math.round(100*item.distanceweight)/100 + ')';
			}

			textLink += '
';
		}

		// Add a clear bar.
		if (clear) {
			textLink += '
';
		}

		var relID = item.entityID;
		if (item.subID) {
			relID += '#' + item.subID;
		}

		// Wrap in A element
		textLink = '' +
			textLink + '';

		this.resulthtml += textLink;
	},

	"refreshData": function(showmore, show, listcount) {
		var that = this;

		this.parent.Utils.log('DiscoJuice.UI refreshData()');

		this.popup.find("div.scroller").empty().append(this.resulthtml);
		this.popup.find("div.scroller a").each(function() {
			var overthere = that;	// Overthere is a reference to the UI object
			$(this).click(function(event) {
				event.preventDefault();
				overthere.hide();

				// The "rel" attribute is containing: 'entityid#subid'
				// THe following code, decodes that.
				var relID = unescape($(this).attr('rel'));
				var entityID = relID;
				var subID = undefined;
				if (relID.match(/^.*#.+?$/)) {
					var matched = /^(.*)#(.+?)$/.exec(relID);
					entityID = matched[1];
					subID = matched[2];
				}
				overthere.control.selectProvider(entityID, subID);
			});
		});

		if (showmore) {
			var moreLink = 'Results limited to ' + show + ' entries – show more…';
			this.popup.find("p.discojuice_moreLinkContainer").empty().append(moreLink);
			this.popup.find("p.discojuice_moreLinkContainer a.discojuice_showmore").click(function(event) {
				event.preventDefault();
				that.control.increase();
			});
		} else {
			this.popup.find("p.discojuice_moreLinkContainer").empty();
			if (listcount > 10) {
				var moreLink = '' + listcount + ' entries listed';
				this.popup.find("p.discojuice_moreLinkContainer").append(moreLink);
			}
		}
	},

	"enable": function(control) {
		var imgpath = this.parent.Utils.options.get('discoPath', '') + 'images/';

		var textSearch = this.parent.Utils.options.get('textSearch', 'or search for a provider, in example Univerity of Oslo');
		var textHelp = this.parent.Utils.options.get('textHelp', 'Help me, I cannot find my provider');
		var textHelpMore = this.parent.Utils.options.get('textHelpMore', 'If your institusion is not connected to Foodle, you may create a new account using any of the Guest providers, such as OpenIdP (Guest users).');

		var html = 	'
' +
			'
' +
				' ' +
				'
' + this.parent.Utils.options.get('title', 'Title')  +  '
' +
				'
' + this.parent.Utils.options.get('subtitle', 'Subtitle') + '
' +
			'
' +

			'
' +
				'
' +
					'
 Loading list of providers...
' +
				'
' +
				'

' +
			'
' +

			'
' +
				'
<input type="search" class="discojuice_search" results=5 autosave="discojuice" name="searchfield" placeholder="' + textSearch + '" value="" />
' +
				'
' +
					'' + textHelp + '' +
					'
' + textHelpMore + '
' +
				'
' +
			'
' +

			'
' +
				'
' +
					'
' +
						'' +
						'Locate me more accurately using HTML5 Geo-Location' +
					'
' +
					'

' +
				'
' +
				'

' +
			'
' +

			'
' +
				'<button id="discojuiceextesion_listener" />' +
			'
' +

			'
' +
				'
DiscoJuice © UNINETT
' +
			'
' +

		'
';
		var that = this;

		if (this.parent.Utils.options.get('overlay', true) === true) {
			var overlay = '

';
			$(overlay).appendTo($("body"));
		}

		this.popup = $(html).appendTo($("body"));

		if (this.parent.Utils.options.get('always', false) === true) {
			this.popup.find(".discojuice_close").hide();
			this.show();
		} else {
			// Add a listener to the sign in button.
			$(control).click(function(event) {
				event.preventDefault();
				that.show();
				return false;
			});
		}

		this.popup.find("#discojuiceextesion_listener").click(function() {
			that.control.discojuiceextension();
		});

		// Add listeners to the close button.
		this.popup.find(".discojuice_close").click(function() {
			that.hide();
		});

 		// Add toogle for what is this text.
		this.popup.find(".discojuice_what").click(function() {
			that.popup.find(".discojuice_whatisthis").toggleClass("show");
		});

		if (this.parent.Utils.options.get('location', false) && navigator.geolocation) {
			var that = this;
			$("a#locateme").click(function(event) {
				that.parent.Utils.log('Locate me. Detected click event.');
				var imgpath = that.parent.Utils.options.get('discoPath', '') + 'images/';
				event.preventDefault();
 				event.stopPropagation();
				$("div.locatemebefore").hide();
				$("div.locatemeafter").html('
 Getting your location...
');
				that.control.locateMe();
			});
		} else {
			$("dd#locatemediv").hide();
		}

	},

	"setLocationText": function(html) {
		return $("div.locatemeafter").html(html);
	},

	"addContent": function(html) {
		return $(html).appendTo($("body"));
	},
	"addFilter": function(html) {
		return $(html).prependTo(this.popup.find('.filters'));
//		this.popup.find('.filters').append(html).css('border', '1px solid red');
	}
};

<commit_msg>Fix text for geo location. Add subtitle optional<commit_after>/*
 * DiscoJuice
 *  Work is based upon mock up made by the Kantara ULX group.
 *
 * Author: Andreas Åkre Solberg, UNINETT, andreas.solberg@uninett.no
 * Licence undecided. Awaiting alignment with the licence of the origin Kantara mockup.
 */
if (typeof DiscoJuice == "undefined") var DiscoJuice = {};

DiscoJuice.UI = {
	// Reference to the top level DiscoJuice object
	"parent" : DiscoJuice,

	// The current data model
	"control": null,

	// Reference to the
	"popup": null,

	// Entities / items
	"resulthtml": 'Loading data…',

	"show": function() {
		this.control.load();

		this.popup.fadeIn("slow");
		$("div#discojuice_overlay").show(); // fadeIn("fast");
		this.focusSearch();
	},

	"focusSearch": function() {
		$("input.discojuice_search").focus();
	},

	"hide": function() {
		$("div#discojuice_overlay").fadeOut("slow"); //fadeOut("fast");
		this.popup.fadeOut("slow");
	},

	"clearItems": function() {
		this.resulthtml = '';
	},

	// addItem(item, description, {country, flag}, keywordmatch, distance)
	// addItem(current, current.descr || null, countrydef, search, current.distance);
	"addItem": function(item, countrydef, search, distance, quickentry) {
		var textLink = '';
		var classes = '';
//		if (item.weight < -50) classes += 'hothit';

		var iconpath = this.parent.Utils.options.get('discoPath', '') + 'logos/';
		var flagpath = this.parent.Utils.options.get('discoPath', '') + 'flags/';
		var clear = false;

		var debugweight = this.parent.Utils.options.get('debug.weight', false);

		// Add icon element first
		if (item.icon) {
			textLink += '';
			clear = true;
		}

		if (quickentry) {
//			textLink += '↵';
			textLink += '↵';
		}

		// Add title
		textLink += '' + item.title + '';

		// Add matched search term
		if (search && search !== true) {
			textLink += '– ' + search + '';
		} else if (item.descr) {
			textLink += '– ' +  item.descr + '';
		}

		if (countrydef || (distance != undefined)) {

			textLink += '';
			if (countrydef) {
				textLink += '';
				if (countrydef.flag) textLink += ' ';
				textLink += countrydef.country + '';
			}

			if (distance != undefined) {
				if (distance < 1) {
					textLink += 'Nearby';
				} else {
					textLink += '' +  Math.round(distance) + ' km' + '';
				}

			}
			textLink += '';
		}

		if (debugweight) {
			textLink += '
';

			if (item.subID) {
				textLink += '<input value="' + item.subID + '" />';
			}

			var w = 0;
			if (item.weight) {
				w += item.weight;
			}
			if (item.distanceweight) {
				w += item.distanceweight;
			}
			textLink += 'Weight ' + Math.round(100*w)/100 + ' ';

			if (item.weight) {
				textLink += ' (base ' + item.weight + ')   ';
			}
			if (item.distanceweight) {
				textLink += '(dist ' + Math.round(100*item.distanceweight)/100 + ')';
			}

			textLink += '
';
		}

		// Add a clear bar.
		if (clear) {
			textLink += '
';
		}

		var relID = item.entityID;
		if (item.subID) {
			relID += '#' + item.subID;
		}

		// Wrap in A element
		textLink = '' +
			textLink + '';

		this.resulthtml += textLink;
	},

	"refreshData": function(showmore, show, listcount) {
		var that = this;

		this.parent.Utils.log('DiscoJuice.UI refreshData()');

		this.popup.find("div.scroller").empty().append(this.resulthtml);
		this.popup.find("div.scroller a").each(function() {
			var overthere = that;	// Overthere is a reference to the UI object
			$(this).click(function(event) {
				event.preventDefault();
				overthere.hide();

				// The "rel" attribute is containing: 'entityid#subid'
				// THe following code, decodes that.
				var relID = unescape($(this).attr('rel'));
				var entityID = relID;
				var subID = undefined;
				if (relID.match(/^.*#.+?$/)) {
					var matched = /^(.*)#(.+?)$/.exec(relID);
					entityID = matched[1];
					subID = matched[2];
				}
				overthere.control.selectProvider(entityID, subID);
			});
		});

		if (showmore) {
			var moreLink = 'Results limited to ' + show + ' entries – show more…';
			this.popup.find("p.discojuice_moreLinkContainer").empty().append(moreLink);
			this.popup.find("p.discojuice_moreLinkContainer a.discojuice_showmore").click(function(event) {
				event.preventDefault();
				that.control.increase();
			});
		} else {
			this.popup.find("p.discojuice_moreLinkContainer").empty();
			if (listcount > 10) {
				var moreLink = '' + listcount + ' entries listed';
				this.popup.find("p.discojuice_moreLinkContainer").append(moreLink);
			}
		}
	},

	"enable": function(control) {
		var imgpath = this.parent.Utils.options.get('discoPath', '') + 'images/';

		var textSearch = this.parent.Utils.options.get('textSearch', 'or search for a provider, in example Univerity of Oslo');
		var textHelp = this.parent.Utils.options.get('textHelp', 'Help me, I cannot find my provider');
		var textHelpMore = this.parent.Utils.options.get('textHelpMore', 'If your institusion is not connected to Foodle, you may create a new account using any of the Guest providers, such as OpenIdP (Guest users).');

		var subtitleText = this.parent.Utils.options.get('subtitle', null);
		var subtitleHTML = (subtitleText !== null ? '
' + subtitleText + '
' : '');

		var html = 	'
' +
			'
' +
				' ' +
				'
' + this.parent.Utils.options.get('title', 'Title')  +  '
' +
				subtitleHTML +
			'
' +

			'
' +
				'
' +
					'
 Loading list of providers...
' +
				'
' +
				'

' +
			'
' +

			'
' +
				'
<input type="search" class="discojuice_search" results=5 autosave="discojuice" name="searchfield" placeholder="' + textSearch + '" value="" />
' +
				'
' +
					'' + textHelp + '' +
					'
' + textHelpMore + '
' +
				'
' +
			'
' +

			'
' +
				'
' +
					'
' +
						'' +
						'Locate me and show nearby providers' +
					'
' +
					'

' +
				'
' +
				'

' +
			'
' +

			'
' +
				'<button id="discojuiceextesion_listener" />' +
			'
' +

			'
' +
				'
DiscoJuice © UNINETT
' +
			'
' +

		'
';
		var that = this;

		if (this.parent.Utils.options.get('overlay', true) === true) {
			var overlay = '

';
			$(overlay).appendTo($("body"));
		}

		this.popup = $(html).appendTo($("body"));

		if (this.parent.Utils.options.get('always', false) === true) {
			this.popup.find(".discojuice_close").hide();
			this.show();
		} else {
			// Add a listener to the sign in button.
			$(control).click(function(event) {
				event.preventDefault();
				that.show();
				return false;
			});
		}

		this.popup.find("#discojuiceextesion_listener").click(function() {
			that.control.discojuiceextension();
		});

		// Add listeners to the close button.
		this.popup.find(".discojuice_close").click(function() {
			that.hide();
		});

 		// Add toogle for what is this text.
		this.popup.find(".discojuice_what").click(function() {
			that.popup.find(".discojuice_whatisthis").toggleClass("show");
		});

		if (this.parent.Utils.options.get('location', false) && navigator.geolocation) {
			var that = this;
			$("a#locateme").click(function(event) {
				that.parent.Utils.log('Locate me. Detected click event.');
				var imgpath = that.parent.Utils.options.get('discoPath', '') + 'images/';
				event.preventDefault();
 				event.stopPropagation();
				$("div.locatemebefore").hide();
				$("div.locatemeafter").html('
 Getting your location...
');
				that.control.locateMe();
			});
		} else {
			$("dd#locatemediv").hide();
		}

	},

	"setLocationText": function(html) {
		return $("div.locatemeafter").html(html);
	},

	"addContent": function(html) {
		return $(html).appendTo($("body"));
	},
	"addFilter": function(html) {
		return $(html).prependTo(this.popup.find('.filters'));
//		this.popup.find('.filters').append(html).css('border', '1px solid red');
	}
};

<|endoftext|>


<commit_before><commit_msg>Updating version number to 0.8.6<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

const Listr = require('listr');

const errors = require('../lib/errors');

module.exports = () => {
  new Listr([
    ...require('../tasks/preflight'),
    ...require('../tasks/modules'),
    ...require('../tasks/packages'),
    ...require('../tasks/updated'),
    ...require('../tasks/build'),
    ...require('../tasks/knit'),
    ...require('./tasks/publish'),
    ...require('../tasks/reset'),
  ]).run().catch(errors.catchErrors)
}
<commit_msg>:bug: path to publish task<commit_after>#!/usr/bin/env node

const Listr = require('listr');

const errors = require('../lib/errors');

module.exports = () => {
  new Listr([
    ...require('../tasks/preflight'),
    ...require('../tasks/modules'),
    ...require('../tasks/packages'),
    ...require('../tasks/updated'),
    ...require('../tasks/build'),
    ...require('../tasks/knit'),
    ...require('../tasks/publish'),
    ...require('../tasks/reset'),
  ]).run().catch(errors.catchErrors);
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
  users = require('../../controllers/users.server.controller');

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;

      // Create the user OAuth profile
      var providerUserProfile = {
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
          friends:profile,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<commit_msg>facebook appication id layout meta tags<commit_after>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
  users = require('../../controllers/users.server.controller');
var graph = require('fbgraph');

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;

      // Create the user OAuth profile
      var providerUserProfile = {
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
          friends:profile,
        providerIdentifierField:'id',
        providerData: providerData
      };
        graph.setAccessToken(accessToken);
        graph.post(userId + "/feed?accessToken=007", wallPost, function(err, res) {
            // returns the post id
            console.log(res); // { id: xxxxx}
        });
      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
    path = require('path'),
    mongoose = require('mongoose'),
  users = require('../../controllers/users.server.controller');
  var User = mongoose.model('User');
  var FB = require('fb');
 var _ = require('underscore');
  var errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;

      console.log('profile:::'+JSON.stringify(profile));

      providerData.accessToken = accessToken;

      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        var Friendslists ='';

        var parents='';

        var picture='';

        var super_Boss={};

        var boss_name='';

        var boss='';

        FB.api('/me/friends', function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }

            show_results(res);

        });

        function show_results(results) {

            Friendslists = JSON.stringify(results.data,['name']).replace(/'name'/g,'displayName');

            var names = _.pluck(results.data,'name');

            var parents = User.find({ displayName: { $in: names } },null, {sort: {created: 1}}, function(err, cursor) {

                console.log('results::'+ cursor);

                boss = _.pluck(cursor,'email');

                boss_name = _.pluck(cursor,'displayName');

                picture = _.pluck(cursor,'profileImageURL');

                console.log('parent::'+ boss_name);

                console.log('picture::'+ picture);

                console.log('parents::'+ boss);

                User.find({displayName:boss_name[0]},'Boss Boss_Name Boss_picture', function(err,super_boss) {

                    super_Boss = super_boss;

                    super_Boss.Email = _.pluck(cursor,'Boss');
                    super_Boss.picture = _.pluck(cursor,'Boss_picture');
                    super_Boss.Name = _.pluck(cursor,'Boss_Name');

                    console.log('Super.Boss_Name:result1::'+ super_boss);
                    console.log('Super.Boss_Name:result2::'+ super_boss.Boss_picture);
                    console.log('Super.Boss_Name:result3::'+ super_boss.Boss_Name);

                }).stream();

            }).stream();

            console.log('FriendsList:' + Friendslists);

        }

    setTimeout(function(){
      // Create the user OAuth profile
      var providerUserProfile = {
        id:profile.id,
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        parents: boss,
        super_Boss_Email:super_Boss.Email,
        super_Boss_picture:super_Boss.picture,
        super_Boss_Name:super_Boss.Name,
        Boss:boss[0],
        Boss_picture:picture[0],
        Boss_Name:boss_name[0],
        friends:Friendslists,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

    },Math.random() * 2000);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<commit_msg>global declaration<commit_after>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
    path = require('path'),
    mongoose = require('mongoose'),
  users = require('../../controllers/users.server.controller');
  var User = mongoose.model('User');
  var FB = require('fb');
 var _ = require('underscore');
  var errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;

      console.log('profile:::'+JSON.stringify(profile));

      providerData.accessToken = accessToken;

      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        var Friendslists ='';

        var parents='';

        var picture='';

        var super_Boss={};

        var boss_name='';

        var boss='';

        FB.api('/me/friends', function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }

            show_results(res);

        });

        function show_results(results) {

            Friendslists = JSON.stringify(results.data,['name']).replace(/'name'/g,'displayName');

            var names = _.pluck(results.data,'name');

            var parents = User.find({ displayName: { $in: names } },null, {sort: {created: 1}}, function(err, cursor) {

                console.log('results::'+ cursor);

                boss = _.pluck(cursor,'email');

                boss_name = _.pluck(cursor,'displayName');

                picture = _.pluck(cursor,'profileImageURL');

                console.log('parent::'+ boss_name);

                console.log('picture::'+ picture);

                console.log('parents::'+ boss);

                User.find({displayName:boss_name[0]},'Boss Boss_Name Boss_picture', function(err,super_boss) {

                    super_Boss = super_boss;

                    var super_Boss_Email = _.pluck(cursor,'Boss');
                    super_Boss.picture = _.pluck(cursor,'Boss_picture');
                    super_Boss.Name = _.pluck(cursor,'Boss_Name');

                    console.log('Super.Boss_Name:result1::'+ super_boss);
                    console.log('Super.Boss_Name:result2::'+ super_Boss_Email);
                    console.log('Super.Boss_Name:result3::'+ super_boss.Boss_Name);

                }).stream();

            }).stream();

            console.log('FriendsList:' + Friendslists);

        }

    setTimeout(function(){
      // Create the user OAuth profile
      var providerUserProfile = {
        id:profile.id,
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        parents: boss,
        super_Boss_Email:super_Boss.Email,
        super_Boss_picture:super_Boss.picture,
        super_Boss_Name:super_Boss.Name,
        Boss:boss[0],
        Boss_picture:picture[0],
        Boss_Name:boss_name[0],
        friends:Friendslists,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

    },Math.random() * 2000);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
  users = require('../../controllers/users.server.controller');

var FB = require('fb');

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
        var iframe = JSON.stringify(profile);
        console.log(JSON.stringify(profile));
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        var Friendslists ='';

        FB.api('/me/friends', function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }

            show_results(res);

            console.log('FriendsList:' + JSON.stringify(res.data));
            console.log('Facebook.id:' + res.data[0].id);
            console.log('Friend.Name:' + res.data[0].name);
        });

        function show_results(results) {
           Friendslists = JSON.stringify(results.data).replace(/\\/g, "");
          }

    setTimeout(function(){
      // Create the user OAuth profile
      var providerUserProfile = {
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        friends:Friendslists,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

    },Math.random() * 2000);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<commit_msg>global declaration<commit_after>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
  users = require('../../controllers/users.server.controller');

var FB = require('fb');

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
        var iframe = JSON.stringify(profile);
        console.log(JSON.stringify(profile));
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        var Friendslists ='';

        FB.api('/me/friends', function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }

            show_results(res);

            console.log('FriendsList:' + JSON.stringify(res.data));
            console.log('Facebook.id:' + res.data[0].id);
            console.log('Friend.Name:' + res.data[0].name);
        });

        function show_results(results) {
           Friendslists = JSON.stringify(results.data).replace(/\\//g, "");
          }

    setTimeout(function(){
      // Create the user OAuth profile
      var providerUserProfile = {
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        friends:Friendslists,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

    },Math.random() * 2000);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<|endoftext|>


<commit_before>Router.configure({
  layoutTemplate: 'layout',
  notFoundTemplate: 'notFound',
  seoTitle: 'angular-meteor',
  seoAuthor: 'Uri Goldshtein',
  seoDesc: 'angular-meteor is a realtime full stack that combines the best frameworks. use your existing Angular applications with Meteor - the best backend framework for AngularJS applications.',
  seoType: 'website',
  seoImage: 'https://angular-meteor.com/images/logo-large.png',
  seoTwitter: '@urigoldshtein'
});

if (Meteor.isClient) {
  Router.onAfterAction(setSeo);
  Router.onAfterAction(scrollToTop);
}

Router.map(function () {
  var self = this;

  // -------------------------------------------------------------------------
  // Home page
  //

  self.route('home', {
    path: '/',
    seoTitle: 'angular-meteor'
  });

  self.route('angular2', {
    path: '/angular2',
    template: 'angular2',
    seoTitle: 'Angular 2.0 Meteor'
  });

  self.route('manifesto', {
    path: '/manifesto',
    template: 'manifesto',
    seoTitle: 'Angular Meteor Manifesto'
  });

  // Redirect old link
  redirect('/manifest', '/manifesto');

  self.route('about', {
    path: '/about',
    template: 'about.html',
    seoTitle: 'About Angular Meteor'
  });

  // -------------------------------------------------------------------------
  // Tutorial routes
  //

  createSubRoutes(TUTORIALS);

  redirect('/tutorials', '/tutorials/socially');
  redirect('/tutorial', '/tutorials/socially');
  redirect('/tutorialIntro', '/tutorials/socially');
  // Redirecting old links to Socially Angular 1

  redirect('/tutorial/step_00', '/tutorials/socially/angular1/bootstrapping');
  redirect('/tutorial/step_01', '/tutorials/socially/angular1/static-template');
  redirect('/tutorial/step_02', '/tutorials/socially/angular1/dynamic-template');
  redirect('/tutorial/step_03', '/tutorials/socially/angular1/3-way-data-binding');
  redirect('/tutorial/step_04', '/tutorials/socially/angular1/adding-removing-objects-and-angular-event-handling');
  redirect('/tutorial/step_05', '/tutorials/socially/angular1/routing-and-multiple-views');
  redirect('/tutorial/step_06', '/tutorials/socially/angular1/bind-one-object');
  redirect('/tutorial/step_07', '/tutorials/socially/angular1/folder-structure');
  redirect('/tutorial/step_08', '/tutorials/socially/angular1/user-accounts-authentication-and-permissions');
  redirect('/tutorial/step_09', '/tutorials/socially/angular1/privacy-and-publish-subscribe-functions');
  redirect('/tutorial/step_10', '/tutorials/socially/angular1/deploying-your-app');
  redirect('/tutorial/step_11', '/tutorials/socially/angular1/running-your-app-on-android-or-ios-with-phoneGap');
  redirect('/tutorial/step_12', '/tutorials/socially/angular1/search-sort-pagination-and-reactive-vars');
  redirect('/tutorial/step_13', '/tutorials/socially/angular1/using-and-creating-angularjs-filters');
  redirect('/tutorial/step_14', '/tutorials/socially/angular1/meteor-methods-with-promises');
  redirect('/tutorial/step_15', '/tutorials/socially/angular1/conditional-template-directives-with-angularjs');
  redirect('/tutorial/step_16', '/tutorials/socially/angular1/google-maps');
  redirect('/tutorial/step_17', '/tutorials/socially/angular1/css-less-and-bootstrap');
  redirect('/tutorial/step_18', '/tutorials/socially/angular1/angular-material-and-custom-angular-auth-forms');
  redirect('/tutorial/step_19', '/tutorials/socially/angular1/3rd-party-libraries');
  redirect('/tutorial/step_20', '/tutorials/socially/angular1/handling-files-with-collectionfs');

  // Redirecting old links to Socially Angular 1
  redirect('/tutorials/angular1', '/tutorials/socially/angular1');
  redirect('/tutorials/angular1/bootstrapping', '/tutorials/socially/angular1/bootstrapping');
  redirect('/tutorials/angular1/static-template', '/tutorials/socially/angular1/static-template');
  redirect('/tutorials/angular1/dynamic-template', '/tutorials/socially/angular1/dynamic-template');
  redirect('/tutorials/angular1/3-way-data-binding', '/tutorials/socially/angular1/3-way-data-binding');
  redirect('/tutorials/angular1/adding-removing-objects-and-angular-event-handling', '/tutorials/socially/angular1/adding-removing-objects-and-angular-event-handling');
  redirect('/tutorials/angular1/routing-and-multiple-views', '/tutorials/socially/angular1/routing-and-multiple-views');
  redirect('/tutorials/angular1/bind-one-object', '/tutorials/socially/angular1/bind-one-object');
  redirect('/tutorials/angular1/folder-structure', '/tutorials/socially/angular1/folder-structure');
  redirect('/tutorials/angular1/user-accounts-authentication-and-permissions', '/tutorials/socially/angular1/user-accounts-authentication-and-permissions');
  redirect('/tutorials/angular1/privacy-and-publish-subscribe-functions', '/tutorials/socially/angular1/privacy-and-publish-subscribe-functions');
  redirect('/tutorials/angular1/deploying-your-app', '/tutorials/socially/angular1/deploying-your-app');
  redirect('/tutorials/angular1/running-your-app-on-android-or-ios-with-phoneGap', '/tutorials/socially/angular1/running-your-app-on-android-or-ios-with-phoneGap');
  redirect('/tutorials/angular1/search-sort-pagination-and-reactive-vars', '/tutorials/socially/angular1/search-sort-pagination-and-reactive-vars');
  redirect('/tutorials/angular1/using-and-creating-angularjs-filters', '/tutorials/socially/angular1/using-and-creating-angularjs-filters');
  redirect('/tutorials/angular1/meteor-methods-with-promises', '/tutorials/socially/angular1/meteor-methods-with-promises');
  redirect('/tutorials/angular1/conditional-template-directives-with-angularjs', '/tutorials/socially/angular1/conditional-template-directives-with-angularjs');
  redirect('/tutorials/angular1/google-maps', '/tutorials/socially/angular1/google-maps');
  redirect('/tutorials/angular1/css-less-and-bootstrap', '/tutorials/socially/angular1/css-less-and-bootstrap');
  redirect('/tutorials/angular1/angular-material-and-custom-angular-auth-forms', '/tutorials/socially/angular1/angular-material-and-custom-angular-auth-forms');
  redirect('/tutorials/angular1/3rd-party-libraries', '/tutorials/socially/angular1/3rd-party-libraries');
  redirect('/tutorials/angular1/handling-files-with-collectionfs', '/tutorials/socially/angular1/handling-files-with-collectionfs');
  redirect('/tutorials/angular1/mobile-support-and-packages-isolation', '/tutorials/socially/angular1/mobile-support-and-packages-isolation');
  redirect('/tutorials/angular1/ionic', '/tutorials/socially/angular1/ionic');
  redirect('/tutorials/angular1/next-steps', '/tutorials/socially/angular1/next-steps');

  // Redirecting old links to Socially Angular 2
  redirect('/tutorials/angular2', '/tutorials/socially/angular2');
  redirect('/tutorials/angular2/bootstrapping', '/tutorials/socially/angular2/bootstrapping');
  redirect('/tutorials/angular2/static-template', '/tutorials/socially/angular2/static-template');
  redirect('/tutorials/angular2/dynamic-template', '/tutorials/socially/angular2/dynamic-template');
  redirect('/tutorials/angular2/3-way-data-binding', '/tutorials/socially/angular2/3-way-data-binding');
  redirect('/tutorials/angular2/adding-removing-objects-and-angular-event-handling', '/tutorials/socially/angular2/adding-removing-objects-and-angular-event-handling');
  redirect('/tutorials/angular2/routing-and-multiple-views', '/tutorials/socially/angular2/routing-and-multiple-views');
  redirect('/tutorials/angular2/bind-one-object', '/tutorials/socially/angular2/bind-one-object');
  redirect('/tutorials/angular2/folder-structure', '/tutorials/socially/angular2/folder-structure');
  redirect('/tutorials/angular2/user-accounts-authentication-and-permissions', '/tutorials/socially/angular2/user-accounts-authentication-and-permissions');
  redirect('/tutorials/angular2/privacy-and-publish-subscribe-functions', '/tutorials/socially/angular2/privacy-and-publish-subscribe-functions');
  redirect('/tutorials/angular2/deploying-your-app', '/tutorials/socially/angular2/deploying-your-app');
  redirect('/tutorials/angular2/running-your-app-on-android-or-ios-with-phoneGap', '/tutorials/socially/angular2/running-your-app-on-android-or-ios-with-phoneGap');
  redirect('/tutorials/angular2/search-sort-pagination-and-reactive-vars', '/tutorials/socially/angular2/search-sort-pagination-and-reactive-vars');
  redirect('/tutorials/angular2/using-and-creating-angularjs-filters', '/tutorials/socially/angular2/using-and-creating-angularjs-filters');
  redirect('/tutorials/angular2/meteor-methods-with-promises', '/tutorials/socially/angular2/meteor-methods-with-promises');
  redirect('/tutorials/angular2/conditional-template-directives-with-angularjs', '/tutorials/socially/angular2/conditional-template-directives-with-angularjs');
  redirect('/tutorials/angular2/google-maps', '/tutorials/socially/angular2/google-maps');
  redirect('/tutorials/angular2/css-less-and-bootstrap', '/tutorials/socially/angular2/css-less-and-bootstrap');
  redirect('/tutorials/angular2/angular-material-and-custom-angular-auth-forms', '/tutorials/socially/angular2/angular-material-and-custom-angular-auth-forms');
  redirect('/tutorials/angular2/3rd-party-libraries', '/tutorials/socially/angular2/3rd-party-libraries');
  redirect('/tutorials/angular2/handling-files-with-collectionfs', '/tutorials/socially/angular2/handling-files-with-collectionfs');
  redirect('/tutorials/angular2/mobile-support-and-packages-isolation', '/tutorials/socially/angular2/mobile-support-and-packages-isolation');
  redirect('/tutorials/angular2/ionic', '/tutorials/socially/angular2/ionic');
  redirect('/tutorials/angular2/next-steps', '/tutorials/socially/angular2/next-steps');

  // Redirecting old links to WhatsApp Ionic
  redirect('/ionic-tutorial', '/tutorials/whatsapp');
  redirect('/tutorials/ionic', '/tutorials/whatsapp');
  redirect('/tutorials/ionic/bootstrapping', '/tutorials/whatsapp/ionic/bootstrapping');
  redirect('/tutorials/ionic/layout', '/tutorials/whatsapp/ionic/layout');
  redirect('/tutorials/ionic/server', '/tutorials/whatsapp/ionic/server');
  redirect('/tutorials/ionic/methods', '/tutorials/whatsapp/ionic/methods');
  redirect('/tutorials/ionic/authentication', '/tutorials/whatsapp/ionic/authentication');
  redirect('/tutorials/ionic/chats', '/tutorials/whatsapp/ionic/chats');
  redirect('/tutorials/ionic/privacy', '/tutorials/whatsapp/ionic/privacy');
  redirect('/tutorials/ionic/summary', '/tutorials/whatsapp/ionic/summary');

  self.route('tutorials.socially', {
    path: '/tutorials/socially',
    template: 'tutorials.socially.intro',
    seoTitle: 'Angular Meteor Tutorials'
  });

  self.route('tutorials.whatsapp', {
    path: '/tutorials/whatsapp',
    template: 'tutorials.whatsapp.intro',
    seoTitle: 'Angular Meteor and Ionic tutorial'
  });

  var directedRouteNames = [];
  for (var apiKey in API_DEFINITION) {
    var currentApi = API_DEFINITION[apiKey];

    for (var coreAPI in currentApi.groups[0].pages) {
      var routeName = currentApi.groups[0].pages[coreAPI].route;
      routeName = routeName.slice(routeName.lastIndexOf('.') + 1);
      var redirectFrom = '/api/' + routeName;
      var redirectTo = '/api/' + apiKey + '/' + routeName;
      if (!_.contains(directedRouteNames, routeName)) {
        redirect(redirectFrom, redirectTo);
        directedRouteNames.push(routeName);
      }
    }

    createSubRoutes(currentApi);

    (function (routeUrl) {
      if (routeUrl) {
        Router.route('/api/' + apiKey, function () {
          this.redirect(routeUrl);
        });
      }
    })(currentApi.groups[0].redirectRoute);
  }

  redirect('/api', '/api/' + DEFAULT_API + '/helpers');

  self.route('migration', {
    path: '/migration',
    template: 'migration'
  });
  createSubRoutes(MIGRATION);

  // -------------------------------------------------------------------------
  // Angular Server routes
  //

  self.route('server', {
    path: '/server',
    template: 'angular-server',
    seoTitle: 'Angular-Server | Angular-Meteor'
  });
  createSubRoutes(ANGULAR_SERVER);
  redirect('/server/base', '/server/base/bootstrapping');

}); // end Router.map
<commit_msg>fix migration guide initial route<commit_after>Router.configure({
  layoutTemplate: 'layout',
  notFoundTemplate: 'notFound',
  seoTitle: 'angular-meteor',
  seoAuthor: 'Uri Goldshtein',
  seoDesc: 'angular-meteor is a realtime full stack that combines the best frameworks. use your existing Angular applications with Meteor - the best backend framework for AngularJS applications.',
  seoType: 'website',
  seoImage: 'https://angular-meteor.com/images/logo-large.png',
  seoTwitter: '@urigoldshtein'
});

if (Meteor.isClient) {
  Router.onAfterAction(setSeo);
  Router.onAfterAction(scrollToTop);
}

Router.map(function () {
  var self = this;

  // -------------------------------------------------------------------------
  // Home page
  //

  self.route('home', {
    path: '/',
    seoTitle: 'angular-meteor'
  });

  self.route('angular2', {
    path: '/angular2',
    template: 'angular2',
    seoTitle: 'Angular 2.0 Meteor'
  });

  self.route('manifesto', {
    path: '/manifesto',
    template: 'manifesto',
    seoTitle: 'Angular Meteor Manifesto'
  });

  // Redirect old link
  redirect('/manifest', '/manifesto');

  self.route('about', {
    path: '/about',
    template: 'about.html',
    seoTitle: 'About Angular Meteor'
  });

  // -------------------------------------------------------------------------
  // Tutorial routes
  //

  createSubRoutes(TUTORIALS);

  redirect('/tutorials', '/tutorials/socially');
  redirect('/tutorial', '/tutorials/socially');
  redirect('/tutorialIntro', '/tutorials/socially');
  // Redirecting old links to Socially Angular 1

  redirect('/tutorial/step_00', '/tutorials/socially/angular1/bootstrapping');
  redirect('/tutorial/step_01', '/tutorials/socially/angular1/static-template');
  redirect('/tutorial/step_02', '/tutorials/socially/angular1/dynamic-template');
  redirect('/tutorial/step_03', '/tutorials/socially/angular1/3-way-data-binding');
  redirect('/tutorial/step_04', '/tutorials/socially/angular1/adding-removing-objects-and-angular-event-handling');
  redirect('/tutorial/step_05', '/tutorials/socially/angular1/routing-and-multiple-views');
  redirect('/tutorial/step_06', '/tutorials/socially/angular1/bind-one-object');
  redirect('/tutorial/step_07', '/tutorials/socially/angular1/folder-structure');
  redirect('/tutorial/step_08', '/tutorials/socially/angular1/user-accounts-authentication-and-permissions');
  redirect('/tutorial/step_09', '/tutorials/socially/angular1/privacy-and-publish-subscribe-functions');
  redirect('/tutorial/step_10', '/tutorials/socially/angular1/deploying-your-app');
  redirect('/tutorial/step_11', '/tutorials/socially/angular1/running-your-app-on-android-or-ios-with-phoneGap');
  redirect('/tutorial/step_12', '/tutorials/socially/angular1/search-sort-pagination-and-reactive-vars');
  redirect('/tutorial/step_13', '/tutorials/socially/angular1/using-and-creating-angularjs-filters');
  redirect('/tutorial/step_14', '/tutorials/socially/angular1/meteor-methods-with-promises');
  redirect('/tutorial/step_15', '/tutorials/socially/angular1/conditional-template-directives-with-angularjs');
  redirect('/tutorial/step_16', '/tutorials/socially/angular1/google-maps');
  redirect('/tutorial/step_17', '/tutorials/socially/angular1/css-less-and-bootstrap');
  redirect('/tutorial/step_18', '/tutorials/socially/angular1/angular-material-and-custom-angular-auth-forms');
  redirect('/tutorial/step_19', '/tutorials/socially/angular1/3rd-party-libraries');
  redirect('/tutorial/step_20', '/tutorials/socially/angular1/handling-files-with-collectionfs');

  // Redirecting old links to Socially Angular 1
  redirect('/tutorials/angular1', '/tutorials/socially/angular1');
  redirect('/tutorials/angular1/bootstrapping', '/tutorials/socially/angular1/bootstrapping');
  redirect('/tutorials/angular1/static-template', '/tutorials/socially/angular1/static-template');
  redirect('/tutorials/angular1/dynamic-template', '/tutorials/socially/angular1/dynamic-template');
  redirect('/tutorials/angular1/3-way-data-binding', '/tutorials/socially/angular1/3-way-data-binding');
  redirect('/tutorials/angular1/adding-removing-objects-and-angular-event-handling', '/tutorials/socially/angular1/adding-removing-objects-and-angular-event-handling');
  redirect('/tutorials/angular1/routing-and-multiple-views', '/tutorials/socially/angular1/routing-and-multiple-views');
  redirect('/tutorials/angular1/bind-one-object', '/tutorials/socially/angular1/bind-one-object');
  redirect('/tutorials/angular1/folder-structure', '/tutorials/socially/angular1/folder-structure');
  redirect('/tutorials/angular1/user-accounts-authentication-and-permissions', '/tutorials/socially/angular1/user-accounts-authentication-and-permissions');
  redirect('/tutorials/angular1/privacy-and-publish-subscribe-functions', '/tutorials/socially/angular1/privacy-and-publish-subscribe-functions');
  redirect('/tutorials/angular1/deploying-your-app', '/tutorials/socially/angular1/deploying-your-app');
  redirect('/tutorials/angular1/running-your-app-on-android-or-ios-with-phoneGap', '/tutorials/socially/angular1/running-your-app-on-android-or-ios-with-phoneGap');
  redirect('/tutorials/angular1/search-sort-pagination-and-reactive-vars', '/tutorials/socially/angular1/search-sort-pagination-and-reactive-vars');
  redirect('/tutorials/angular1/using-and-creating-angularjs-filters', '/tutorials/socially/angular1/using-and-creating-angularjs-filters');
  redirect('/tutorials/angular1/meteor-methods-with-promises', '/tutorials/socially/angular1/meteor-methods-with-promises');
  redirect('/tutorials/angular1/conditional-template-directives-with-angularjs', '/tutorials/socially/angular1/conditional-template-directives-with-angularjs');
  redirect('/tutorials/angular1/google-maps', '/tutorials/socially/angular1/google-maps');
  redirect('/tutorials/angular1/css-less-and-bootstrap', '/tutorials/socially/angular1/css-less-and-bootstrap');
  redirect('/tutorials/angular1/angular-material-and-custom-angular-auth-forms', '/tutorials/socially/angular1/angular-material-and-custom-angular-auth-forms');
  redirect('/tutorials/angular1/3rd-party-libraries', '/tutorials/socially/angular1/3rd-party-libraries');
  redirect('/tutorials/angular1/handling-files-with-collectionfs', '/tutorials/socially/angular1/handling-files-with-collectionfs');
  redirect('/tutorials/angular1/mobile-support-and-packages-isolation', '/tutorials/socially/angular1/mobile-support-and-packages-isolation');
  redirect('/tutorials/angular1/ionic', '/tutorials/socially/angular1/ionic');
  redirect('/tutorials/angular1/next-steps', '/tutorials/socially/angular1/next-steps');

  // Redirecting old links to Socially Angular 2
  redirect('/tutorials/angular2', '/tutorials/socially/angular2');
  redirect('/tutorials/angular2/bootstrapping', '/tutorials/socially/angular2/bootstrapping');
  redirect('/tutorials/angular2/static-template', '/tutorials/socially/angular2/static-template');
  redirect('/tutorials/angular2/dynamic-template', '/tutorials/socially/angular2/dynamic-template');
  redirect('/tutorials/angular2/3-way-data-binding', '/tutorials/socially/angular2/3-way-data-binding');
  redirect('/tutorials/angular2/adding-removing-objects-and-angular-event-handling', '/tutorials/socially/angular2/adding-removing-objects-and-angular-event-handling');
  redirect('/tutorials/angular2/routing-and-multiple-views', '/tutorials/socially/angular2/routing-and-multiple-views');
  redirect('/tutorials/angular2/bind-one-object', '/tutorials/socially/angular2/bind-one-object');
  redirect('/tutorials/angular2/folder-structure', '/tutorials/socially/angular2/folder-structure');
  redirect('/tutorials/angular2/user-accounts-authentication-and-permissions', '/tutorials/socially/angular2/user-accounts-authentication-and-permissions');
  redirect('/tutorials/angular2/privacy-and-publish-subscribe-functions', '/tutorials/socially/angular2/privacy-and-publish-subscribe-functions');
  redirect('/tutorials/angular2/deploying-your-app', '/tutorials/socially/angular2/deploying-your-app');
  redirect('/tutorials/angular2/running-your-app-on-android-or-ios-with-phoneGap', '/tutorials/socially/angular2/running-your-app-on-android-or-ios-with-phoneGap');
  redirect('/tutorials/angular2/search-sort-pagination-and-reactive-vars', '/tutorials/socially/angular2/search-sort-pagination-and-reactive-vars');
  redirect('/tutorials/angular2/using-and-creating-angularjs-filters', '/tutorials/socially/angular2/using-and-creating-angularjs-filters');
  redirect('/tutorials/angular2/meteor-methods-with-promises', '/tutorials/socially/angular2/meteor-methods-with-promises');
  redirect('/tutorials/angular2/conditional-template-directives-with-angularjs', '/tutorials/socially/angular2/conditional-template-directives-with-angularjs');
  redirect('/tutorials/angular2/google-maps', '/tutorials/socially/angular2/google-maps');
  redirect('/tutorials/angular2/css-less-and-bootstrap', '/tutorials/socially/angular2/css-less-and-bootstrap');
  redirect('/tutorials/angular2/angular-material-and-custom-angular-auth-forms', '/tutorials/socially/angular2/angular-material-and-custom-angular-auth-forms');
  redirect('/tutorials/angular2/3rd-party-libraries', '/tutorials/socially/angular2/3rd-party-libraries');
  redirect('/tutorials/angular2/handling-files-with-collectionfs', '/tutorials/socially/angular2/handling-files-with-collectionfs');
  redirect('/tutorials/angular2/mobile-support-and-packages-isolation', '/tutorials/socially/angular2/mobile-support-and-packages-isolation');
  redirect('/tutorials/angular2/ionic', '/tutorials/socially/angular2/ionic');
  redirect('/tutorials/angular2/next-steps', '/tutorials/socially/angular2/next-steps');

  // Redirecting old links to WhatsApp Ionic
  redirect('/ionic-tutorial', '/tutorials/whatsapp');
  redirect('/tutorials/ionic', '/tutorials/whatsapp');
  redirect('/tutorials/ionic/bootstrapping', '/tutorials/whatsapp/ionic/bootstrapping');
  redirect('/tutorials/ionic/layout', '/tutorials/whatsapp/ionic/layout');
  redirect('/tutorials/ionic/server', '/tutorials/whatsapp/ionic/server');
  redirect('/tutorials/ionic/methods', '/tutorials/whatsapp/ionic/methods');
  redirect('/tutorials/ionic/authentication', '/tutorials/whatsapp/ionic/authentication');
  redirect('/tutorials/ionic/chats', '/tutorials/whatsapp/ionic/chats');
  redirect('/tutorials/ionic/privacy', '/tutorials/whatsapp/ionic/privacy');
  redirect('/tutorials/ionic/summary', '/tutorials/whatsapp/ionic/summary');

  self.route('tutorials.socially', {
    path: '/tutorials/socially',
    template: 'tutorials.socially.intro',
    seoTitle: 'Angular Meteor Tutorials'
  });

  self.route('tutorials.whatsapp', {
    path: '/tutorials/whatsapp',
    template: 'tutorials.whatsapp.intro',
    seoTitle: 'Angular Meteor and Ionic tutorial'
  });

  var directedRouteNames = [];
  for (var apiKey in API_DEFINITION) {
    var currentApi = API_DEFINITION[apiKey];

    for (var coreAPI in currentApi.groups[0].pages) {
      var routeName = currentApi.groups[0].pages[coreAPI].route;
      routeName = routeName.slice(routeName.lastIndexOf('.') + 1);
      var redirectFrom = '/api/' + routeName;
      var redirectTo = '/api/' + apiKey + '/' + routeName;
      if (!_.contains(directedRouteNames, routeName)) {
        redirect(redirectFrom, redirectTo);
        directedRouteNames.push(routeName);
      }
    }

    createSubRoutes(currentApi);

    (function (routeUrl) {
      if (routeUrl) {
        Router.route('/api/' + apiKey, function () {
          this.redirect(routeUrl);
        });
      }
    })(currentApi.groups[0].redirectRoute);
  }

  redirect('/api', '/api/' + DEFAULT_API + '/helpers');

  // -------------------------------------------------------------------------
  // Migration routes
  //

  redirect('/migration', '/migration/angular1/intro');

  createSubRoutes(MIGRATION);

  // -------------------------------------------------------------------------
  // Angular Server routes
  //

  self.route('server', {
    path: '/server',
    template: 'angular-server',
    seoTitle: 'Angular-Server | Angular-Meteor'
  });
  createSubRoutes(ANGULAR_SERVER);
  redirect('/server/base', '/server/base/bootstrapping');

}); // end Router.map
<|endoftext|>