<commit_before>var path = require('path');
var alias = require('../util/alias');
var Command = require('cli-define').Command;
var ErrorDefinition = require('cli-error').ErrorDefinition;

function getModulePath(cmd) {
  if(cmd.parent() === this) {
    return cmd.key();
  }else{
    // build name from all parent commands
    var p = cmd.parent();
    var list = [];
    while(p !== this) {
      list.push(p.key());
      p = p.parent();
    }
    list.reverse();
    list.push(cmd.key());
    return path.join.apply(path, list);
  }
}

// lazily load a command action definition from a module
function lazy(arg) {
  var conf = this.configure();
  var action = arg.action();
  if(!conf.command.dir || action !== undefined) return false;
  var file = path.join(conf.command.dir, getModulePath.call(this, arg))
  try{
    action = require(file);
    if(typeof action !== 'function') {
      return this.raise(this.errors.ECMD_TYPE, [file]);
    }
    arg.action(action);
  }catch(e) {
    return this.raise(this.errors.ECMD_REQUIRE, [file, e.message], e);
  }
}

function invoke(obj, req, next) {
  var keys = Object.keys(obj);
  if(!keys.length) return next();
  var i, key, arg, names;
  for(i = 0;i < keys.length;i++) {
    key = keys[i];
    arg = obj[key];
    names = arg.names();
    //console.log('invoke subcommand %s, %s', key, arg.toString(null));
    if(~names.indexOf(key)) {
      req.command.parents = req.command.parents || [];
      req.command.parents.push(req.command.name);
      req.command.name = key;
      req.command.args.shift();
      if(typeof arg === 'function') {
        return arg.call(this, req.command, req, next);
      }else if(arg instanceof Command) {
        lazy.call(this, arg);
        var action = arg.action();
        if(typeof action === 'function') {
          return action.call(this, req.command, req, next);
        }
      }
    }
  }
  return next();
}

/**
 *  Searches the raw arguments looking for the first argument
 *  that matches a known command and invokes an action associated
 *  with the command.
 */
module.exports = function() {
  return function command(req, next) {
    if(!arguments.length) return;
    var scope = this, conf = this.configure();
    function callback(obj) {
      //console.dir('callback');
      //console.dir(arguments);

      // proceed to next middleware
      if(!arguments.length) {
        return next();
      // stop middleware execution
      }else if((obj instanceof Error)
        || (obj instanceof ErrorDefinition)
        || typeof obj === 'string') {
        // error raised
        return next.apply(null, arguments);
      }else if(obj === null || typeof obj === 'boolean') {
        return next(obj);
      // execute subcommand
      }else if(obj
        && typeof obj === 'object' && !Array.isArray(obj)) {
        // TODO: allow passing of subcommand object map
        // TODO: and subcommands associated with the command
        return invoke.call(scope, obj, req, callback);
      }else if(Array.isArray(obj)) {
        return next(scope.errors.ECMD_ARRAY);
      }
      // unknown response
      next.apply(null, arguments);
    }
    var i, raw = req.unparsed.slice(0), action, cmd, arg, ind, file;
    for(i = 0;i < raw.length;i++) {
      cmd = raw[i]; arg = alias(cmd, this._commands);
      //console.log('testing for command with %s', cmd);
      if(arg) {
        raw.splice(i, 1);
        lazy.call(this, arg);
        action = arg.action();
        if(typeof action == 'function') {
          ind = req.args.indexOf(cmd);
          //req.args.splice(ind, 1);
          req.command = {name: cmd, cmd: arg, args: raw};
          req.command.validate = function(cb) {
            var subcommands = this.commands();
            var sub = raw[0], k, names;
            for(k in subcommands) {
              names = subcommands[k].names();
              if(~names.indexOf(sub)) return cb();
            }
            cb(scope.errors.EUNKNOWN_SUBCOMMAND, [sub, cmd]);
          }.bind(arg);
          //console.dir(req.command);
          action.call(this, req.command, req, callback);
          return false;
        }
      }
    }
    if(conf && conf.command.required && raw.length) {
      return next(scope.errors.EUNKNOWN_COMMAND, [raw[0]]);
    }
    next();
  }
}
<commit_msg>Fix command middleware invoke().<commit_after>var path = require('path');
var alias = require('../util/alias');
var Command = require('cli-define').Command;
var ErrorDefinition = require('cli-error').ErrorDefinition;

function getModulePath(cmd) {
  if(cmd.parent() === this) {
    return cmd.key();
  }else{
    // build name from all parent commands
    var p = cmd.parent();
    var list = [];
    while(p !== this) {
      list.push(p.key());
      p = p.parent();
    }
    list.reverse();
    list.push(cmd.key());
    return path.join.apply(path, list);
  }
}

// lazily load a command action definition from a module
function lazy(arg) {
  var conf = this.configure();
  var action = arg.action();
  if(!conf.command.dir || action !== undefined) return false;
  var file = path.join(conf.command.dir, getModulePath.call(this, arg))
  try{
    action = require(file);
    if(typeof action !== 'function') {
      return this.raise(this.errors.ECMD_TYPE, [file]);
    }
    arg.action(action);
  }catch(e) {
    return this.raise(this.errors.ECMD_REQUIRE, [file, e.message], e);
  }
}

function invoke(obj, req, next) {
  var keys = Object.keys(obj);
  if(!keys.length) return next();
  var i, key, arg, names;
  for(i = 0;i < keys.length;i++) {
    key = keys[i];
    arg = obj[key];
    names = arg.names();
    //console.log('invoke subcommand %s, %s', key, arg.toString(null));
    if(~names.indexOf(req.command.args[0])) {
      req.command.parents = req.command.parents || [];
      req.command.parents.push(req.command.name);
      req.command.name = key;
      req.command.args.shift();
      if(typeof arg === 'function') {
        return arg.call(this, req.command, req, next);
      }else if(arg instanceof Command) {
        lazy.call(this, arg);
        var action = arg.action();
        if(typeof action === 'function') {
          return action.call(this, req.command, req, next);
        }
      }
    }
  }
  return next();
}

/**
 *  Searches the raw arguments looking for the first argument
 *  that matches a known command and invokes an action associated
 *  with the command.
 */
module.exports = function() {
  return function command(req, next) {
    if(!arguments.length) return;
    var scope = this, conf = this.configure();
    function callback(obj) {
      //console.dir('callback');
      //console.dir(arguments);

      // proceed to next middleware
      if(!arguments.length) {
        return next();
      // stop middleware execution
      }else if((obj instanceof Error)
        || (obj instanceof ErrorDefinition)
        || typeof obj === 'string') {
        // error raised
        return next.apply(null, arguments);
      }else if(obj === null || typeof obj === 'boolean') {
        return next(obj);
      // execute subcommand
      }else if(obj
        && typeof obj === 'object' && !Array.isArray(obj)) {
        // TODO: allow passing of subcommand object map
        // TODO: and subcommands associated with the command
        return invoke.call(scope, obj, req, callback);
      }else if(Array.isArray(obj)) {
        return next(scope.errors.ECMD_ARRAY);
      }
      // unknown response
      next.apply(null, arguments);
    }
    var i, raw = req.unparsed.slice(0), action, cmd, arg, ind, file;
    for(i = 0;i < raw.length;i++) {
      cmd = raw[i]; arg = alias(cmd, this._commands);
      //console.log('testing for command with %s', cmd);
      if(arg) {
        raw.splice(i, 1);
        lazy.call(this, arg);
        action = arg.action();
        if(typeof action == 'function') {
          ind = req.args.indexOf(cmd);
          //req.args.splice(ind, 1);
          req.command = {name: cmd, cmd: arg, args: raw};
          req.command.validate = function(cb) {
            var subcommands = this.commands();
            var sub = raw[0], k, names;
            for(k in subcommands) {
              names = subcommands[k].names();
              if(~names.indexOf(sub)) return cb();
            }
            cb(scope.errors.EUNKNOWN_SUBCOMMAND, [sub, cmd]);
          }.bind(arg);
          //console.dir(req.command);
          action.call(this, req.command, req, callback);
          return false;
        }
      }
    }
    if(conf && conf.command.required && raw.length) {
      return next(scope.errors.EUNKNOWN_COMMAND, [raw[0]]);
    }
    next();
  }
}
<|endoftext|>


<commit_before>// TODO build an session store api
var env = process.env;
var EventEmitter = require('events').EventEmitter;
var cookie = require('cookie');
var clone = require(env.Z_PATH_UTILS + 'clone');
var Model = require(env.Z_PATH_MODELS + 'factory');

var randomStringBase = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var publicSid = uid();
var sessionCookieKey = 'sid';
var roleKey = env.Z_SESSION_ROLE_KEY;
var userKey = env.Z_SESSION_USER_KEY;
var localeKey = env.Z_SESSION_LOCALE_KEY;
var sessionModel;

module.exports = setup;

// session class
var Session = {};

// create a new session
Session.create = function (role, locale, user, callback) {

    var session = clone(Session);
    session.sid = uid();
    session[roleKey] = role;
    session[userKey] = user;
    session[localeKey] = locale || 'en_US';
    session.store = sessionModel;

    // save session
    session.save(callback);
};

Session.regenerate = function () {
    // renew session with a new sid
};

Session.destroy = function (callback) {
    var self = this;

    // remove from store
    self.store.request({m: 'remove', q: {sid: self.sid}}, function (err) {
        callback(err);
    });

    // remove sid
    delete self.sid;
    // set public role
    self[roleKey] = '';
};
Session.reload = function () {
    // reload session data
};

// save session in store
Session.save = function (callback) {
    var self = this;
    var doc = {sid: self.sid};
    doc[localeKey] = self[localeKey];
    doc[roleKey] = self[roleKey];
    doc[userKey] = self[userKey];

    // save session
    self.store.request({m: 'update', q: {sid: self.sid}, d: {$set: doc}, o: {upsert: true}}, function (err) {
        callback(err, self);
    });
};
Session.touch = function () {
    // update expire
};
Session.maxAge = function () {
    // expire info
};

// setup session middleware
function setup (callback) {

    Model.factory(env.Z_SESSION_MODEL, env.Z_SESSION_ROLE, function (err, model) {

        if (err) {
            return callback(err);
        }

        // save session model (mongodb-native collection)
        sessionModel = model;

        // return handler
        callback(null, factory);

    });
}

// get or create session
function factory (callback) {

    return function (connection, response) {

        // make it compatible with ws connections
        var con = connection.upgradeReq ? connection.upgradeReq : connection;

        // parse cookies, get session id
        if (con.headers.cookie) {
            var parsedCookie = cookie.parse(con.headers.cookie);

            if (parsedCookie && parsedCookie[sessionCookieKey]) {

                // pause connection
                connection.pause();

                var sessionId = parsedCookie[sessionCookieKey];

                // TODO update expire
                return sessionModel.request({m: 'findOne', q: {sid: sessionId/*TODO expire, exp: {$lt: now}*/}}, function (err, item) {

                    if (err) {
                        return callback(err);
                    }

                    // set public session if no session is found.. or error?
                    if (!item) {
                        connection.session = {
                            create: Session.create
                        };

                    // create session for current connection
                    } else {

                        var session = clone(Session);
                        session.sid = sessionId;
                        session[roleKey] = item[roleKey];
                        session[localeKey] = item[localeKey];
                        session[userKey] = item[userKey].toString();
                        session.store = sessionModel;

                        // append session to connection
                        connection.session = session;
                    }

                    callback(null, connection, response);
                    connection.resume();
                });
            } else {

                // set public session to connection
                connection.session = {
                    create: Session.create
                };
            }
        } else {

            // set public session to connection
            connection.session = {
                create: Session.create
            };
        }

        callback(null, connection, response);
    };
}

// random string generator
function uid (len, string) {
    len = len || 23;
    string = string || '';

    for (var i = 0; i < len; ++i) {
        string += randomStringBase[0 | Math.random() * 62];
    }
    return string;
}
<commit_msg>use models new query api<commit_after>// TODO build an session store api
var env = process.env;
var EventEmitter = require('events').EventEmitter;
var cookie = require('cookie');
var clone = require(env.Z_PATH_UTILS + 'clone');
var Model = require(env.Z_PATH_MODELS + 'factory');

var randomStringBase = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var publicSid = uid();
var sessionCookieKey = 'sid';
var roleKey = env.Z_SESSION_ROLE_KEY;
var userKey = env.Z_SESSION_USER_KEY;
var localeKey = env.Z_SESSION_LOCALE_KEY;
var sessionModel;

module.exports = setup;

// session class
var Session = {};

// create a new session
Session.create = function (role, locale, user, callback) {

    var session = clone(Session);
    session.sid = uid();
    session[roleKey] = role;
    session[userKey] = user;
    session[localeKey] = locale || 'en_US';
    session.store = sessionModel;

    // save session
    session.save(callback);
};

Session.regenerate = function () {
    // renew session with a new sid
};

Session.destroy = function (callback) {
    var self = this;

    // remove from store
    self.store.queries.remove({sid: self.sid}, function (err) {
        callback(err);
    });

    // remove sid
    delete self.sid;
    // set public role
    self[roleKey] = '';
};
Session.reload = function () {
    // reload session data
};

// save session in store
Session.save = function (callback) {
    var self = this;
    var doc = {sid: self.sid};
    doc[localeKey] = self[localeKey];
    doc[roleKey] = self[roleKey];
    doc[userKey] = self[userKey];

    // save session
    self.store.queries.renew({sid: self.sid, doc: doc}, function (err) {
        callback(err, self);
    });
};
Session.touch = function () {
    // update expire
};
Session.maxAge = function () {
    // expire info
};

// setup session middleware
function setup (callback) {

    Model.factory(env.Z_SESSION_MODEL, env.Z_SESSION_ROLE, function (err, model) {

        if (err) {
            return callback(err);
        }

        // save session model (mongodb-native collection)
        sessionModel = model;

        // return handler
        callback(null, factory);

    });
}

// get or create session
function factory (callback) {

    return function (connection, response) {

        // make it compatible with ws connections
        var con = connection.upgradeReq ? connection.upgradeReq : connection;

        // parse cookies, get session id
        if (con.headers.cookie) {
            var parsedCookie = cookie.parse(con.headers.cookie);

            if (parsedCookie && parsedCookie[sessionCookieKey]) {

                // pause connection
                connection.pause();

                var sessionId = parsedCookie[sessionCookieKey];

                // TODO update expire
                return sessionModel.queries.get({sid: sessionId/*, now: new Date().getTime() / 1000*/}, function (err, item) {

                    if (err) {
                        return callback(err);
                    }

                    // set public session if no session is found.. or error?
                    if (!item) {
                        connection.session = {
                            create: Session.create
                        };

                    // create session for current connection
                    } else {

                        var session = clone(Session);
                        session.sid = sessionId;
                        session[roleKey] = item[roleKey];
                        session[localeKey] = item[localeKey];
                        session[userKey] = item[userKey].toString();
                        session.store = sessionModel;

                        // append session to connection
                        connection.session = session;
                    }

                    callback(null, connection, response);
                    connection.resume();
                });
            } else {

                // set public session to connection
                connection.session = {
                    create: Session.create
                };
            }
        } else {

            // set public session to connection
            connection.session = {
                create: Session.create
            };
        }

        callback(null, connection, response);
    };
}

// random string generator
function uid (len, string) {
    len = len || 23;
    string = string || '';

    for (var i = 0; i < len; ++i) {
        string += randomStringBase[0 | Math.random() * 62];
    }
    return string;
}
<|endoftext|>


<commit_before>"use strict";

const cache = require("../cache");
const request = require("request");
const urlencode = require("urlencode");
const mustache = require("mustache");
const postProcessor = require("../post-processor");
mustache.escape = v => v;

module.exports = (superclass) => class extends superclass {
    getUrl(options) {
        if (this.pr.processor == "bikeshed") {
            return this.getBikeshedUrl(options);
        }

        if (this.pr.processor == "respec") {
            return this.getRespecUrl(options);
        }

        throw new Error(`Unknown processor ${ pr.processor }`);
    }

    getBikeshedUrl(data) {
        let query = this.getQuery(data, urlencode);
        query = query ? "&" + query : ""
        return `https://api.csswg.org/bikeshed/?url=${ urlencode(this.github_url) }${ query }`;
    }

    getRespecUrl(data) {
        let query = this.getQuery(data);
        query = query ? "?" + query : ""
        return `https://labs.w3.org/spec-generator/?type=respec&url=${urlencode(this.rawgit_url + query)}`
    }

    get file_path() {
        return `${ this.owner }/${ this.repo }/${ this.sha }/${ this.pr.config.src_file }`;
    }

    get github_url() {
        return `https://raw.githubusercontent.com/${ this.file_path }`;
    }

    get rawgit_url() {
        return `https://cdn.rawgit.com/${ this.file_path }`;
    }

    getQuery(data, encode) {
        let params = this.pr.config.params || {};
        return Object.keys(params).map(k => {
            let tmpl = String(params[k]);
            let v = mustache.render(tmpl, data);
            return `${ k }=${ encode ? urlencode(v) : v }`;
        }).join("&");
    }

    urlOptions() {
        return {
            config:       this.pr.config,
            pull_request: this.pr.payload,
            owner:        this.owner,
            repo:         this.repo,
            branch:       this.ref,
            sha:          this.sha,
            short_sha:    this.short_sha,
            url:          this.cache_url
        };
    }

    fetchUrl(url) {
        return new Promise((resolve, reject) => {
            request(url, function (error, response, body) {
                if (error) {
                    error.data = { request_url: url };
                    reject(error);
                } else if (response.statusCode != 200) {
                    var err = new Error(`${ response.statusCode } ${ response.statusMessage }`);
                    try { err.data = JSON.parse(body); } catch (e) { err.data = {}; }
                    err.data.request_url = url;
                    reject(err);
                } else {
                    resolve(body);
                }
            });
        });
    }

    fetch() {
        var url = this.getUrl(this.urlOptions());
        var postProcess = postProcessor(this.pr.postProcessingConfig) || postProcessor.noop;
        return this.fetchUrl(url).then(postProcess);
    }
};<commit_msg>Remove unused mixin<commit_after><|endoftext|>


<commit_before>/**
 * Core constructor function.
 * @private
 */
(function init() {
	// unmark the no-js flag on html tag
	$html.removeClass('no-js');

    ch.instances = instances;

	ch.shortcuts.init();

    // Exposse private $ (jQuery) into ch.$
    ch.$ = $;
}());<commit_msg>GH-973 identation changed<commit_after>/**
 * Core constructor function.
 * @private
 */
(function init() {
    // unmark the no-js flag on html tag
    $html.removeClass('no-js');

    ch.instances = instances;

    ch.shortcuts.init();

    // Exposse private $ (jQuery) into ch.$
    ch.$ = $;
}());<|endoftext|>


<commit_before>import qrcode from 'qrcode-terminal';
import chalk from 'chalk';
import log from './log';
import promisifyEvent from 'promisify-event';

export default async function (testCafe, remoteCount, showQRCode) {
    var connections = [];

    if (remoteCount) {
        log.hideSpinner();

        for (var i = 0; i < remoteCount; i++) {
            var browserConnection = testCafe.createBrowserConnection();

            log.write(`To connect a remote browser #${i + 1}, use it to open ${chalk.underline.blue(browserConnection.url)}`);

            if (showQRCode) {
                log.write('or scan this QR-code:\n');
                qrcode.generate(browserConnection.url);
            }

            await promisifyEvent(browserConnection, 'ready');

            connections.push(browserConnection);
            log.write(`${chalk.green('CONNECTED')} ${browserConnection.userAgent}\n`);
        }

        log.showSpinner();
    }

    return connections;
}
<commit_msg>Wizard text changed<commit_after>import qrcode from 'qrcode-terminal';
import chalk from 'chalk';
import log from './log';
import promisifyEvent from 'promisify-event';
import dedent from 'dedent';

export default async function (testCafe, remoteCount, showQRCode) {
    var connections = [];

    if (remoteCount) {
        log.hideSpinner();

        var description = dedent(`
            Connecting ${remoteCount} remote browser(s)...
            Navigate to the appropriate URL from each of the remote browsers.
        `);

        log.write(description);

        if (showQRCode)
            log.write('You can either enter the URL or scan the QR-code.');

        for (var i = 0; i < remoteCount; i++) {
            var browserConnection = testCafe.createBrowserConnection();

            log.write(`Browser #${i + 1}: ${chalk.underline.blue(browserConnection.url)}`);

            if (showQRCode)
                qrcode.generate(browserConnection.url);

            await promisifyEvent(browserConnection, 'ready');

            connections.push(browserConnection);
            log.write(`${chalk.green('CONNECTED')} ${browserConnection.userAgent}\n`);
        }

        log.showSpinner();
    }

    return connections;
}
<|endoftext|>


<commit_before>import OAuth2Client from "../common/OAuth2Client"

export default class Oauth2Handler {

  /**
   * Create an OAuth2.0 handler.
   *
   * @param {Object} settings The settings
   * @param {SessionHandler} session The session
   * @param {Function} fetch The fetch function
   */
  constructor(settings, session, fetch) {
    this.settings = settings
    this.session = session
    this.fetch = fetch
    this.oauth2Client = new OAuth2Client(settings.oauthUrl, settings.oauthClientId, fetch)
  }

  /**
   * @param {FetchEvent} event The intercepted event
   * @returns {void}
   */
  handle(event) {
    console.log(`proauth.js Oauth2Handler::handle for ${event.request.url}`)

    const {oauthUrl} = this.settings
    const request = event.request
    const url = request.url
    const isAuthRequest = url === oauthUrl || `${url}/` === oauthUrl
    const oauth = this.oauth2Client
    const unauthorizedHttpCode = 401
    let tokens = this.session.content || {}

    const updateSession = (grantPromise) => {
      return grantPromise.then((oA2Response) => {
        console.log("proauth.js: authentication successful, updating session", oA2Response)
        tokens = this.session.content = oA2Response.toObject()
        return true
      }, (oA2Error) => {
        console.log("proauth.js: cannot authenticate, clearing session", oA2Error)
        this.session.clear()
        return false
      })
    }

    // If it is not trying to authenticate then attach the access token
    if (!isAuthRequest && tokens.accessToken) {
      request.headers.set("Authorization", `${tokens.tokenType} ${tokens.accessToken}`)
    }

    // Fetch and handle the response
    const fetch = this.fetch
    event.respondWith(fetch(request).then((response) => {

      if (response.ok) {
        // Is it an authentication response?
        if (isAuthRequest) {
          return updateSession(
            oauth.handleAuthenticationResponse(response.clone())
          ).then(() => response)
        }
      } else if (response.status === unauthorizedHttpCode && tokens.refreshToken) {
        // Got 401, but we have a refresh token, so try to get a new access token
        return oauth.refreshToken(tokens.refreshToken).then((authResponse) => {
          return updateSession(
            oauth.handleAuthenticationResponse(authResponse)
          ).then((newSession) => {
            // We got a new token?
            // Then try to re-fetch the original request...
            if (newSession) {
              request.headers.set("Authorization", `${tokens.tokenType} ${tokens.accessToken}`)
              return fetch(request)
            } //...else passthrough the 401 response
            return newSession ? fetch(request) : response
          })
        })
      }

      return response // Passthrough any others
    }))
  }

}
<commit_msg>Fix: Cannot re-use request when bodyUsed<commit_after>import OAuth2Client from "../common/OAuth2Client"

export default class Oauth2Handler {

  /**
   * Create an OAuth2.0 handler.
   *
   * @param {Object} settings The settings
   * @param {SessionHandler} session The session
   * @param {Function} fetch The fetch function
   */
  constructor(settings, session, fetch) {
    this.settings = settings
    this.session = session
    this.fetch = fetch
    this.oauth2Client = new OAuth2Client(settings.oauthUrl, settings.oauthClientId, fetch)
  }

  /**
   * @param {FetchEvent} event The intercepted event
   * @returns {void}
   */
  handle(event) {
    console.log(`proauth.js Oauth2Handler::handle for ${event.request.url}`)

    const {oauthUrl} = this.settings
    const request = event.request
    const url = request.url
    const isAuthRequest = url === oauthUrl || `${url}/` === oauthUrl
    const oauth = this.oauth2Client
    const unauthorizedHttpCode = 401
    let tokens = this.session.content || {}

    const updateSession = (grantPromise) => {
      return grantPromise.then((oA2Response) => {
        console.log("proauth.js: authentication successful, updating session", oA2Response)
        tokens = this.session.content = oA2Response.toObject()
        return true
      }, (oA2Error) => {
        console.log("proauth.js: cannot authenticate, clearing session", oA2Error)
        this.session.clear()
        return false
      })
    }

    // If it is not trying to authenticate then attach the access token
    if (!isAuthRequest && tokens.accessToken) {
      request.headers.set("Authorization", `${tokens.tokenType} ${tokens.accessToken}`)
    }

    const requestCopy = request.clone()
    // Fetch and handle the response
    const fetch = this.fetch
    event.respondWith(fetch(request).then((response) => {

      if (response.ok) {
        // Is it an authentication response?
        if (isAuthRequest) {
          return updateSession(
            oauth.handleAuthenticationResponse(response.clone())
          ).then(() => response)
        }
      } else if (response.status === unauthorizedHttpCode && tokens.refreshToken) {
        // Got 401, but we have a refresh token, so try to get a new access token
        return oauth.refreshToken(tokens.refreshToken).then((authResponse) => {
          return updateSession(
            oauth.handleAuthenticationResponse(authResponse)
          ).then((newSession) => {
            // We got a new token?
            // Then try to re-fetch the original request...
            if (newSession) {
              requestCopy.headers.set("Authorization", `${tokens.tokenType} ${tokens.accessToken}`)
              return fetch(requestCopy)
            } //...else passthrough the 401 response
            return response
          })
        })
      }

      return response // Passthrough any others
    }))
  }

}
<|endoftext|>


<commit_before>goog.provide('ngeo.StateManager');

goog.require('goog.asserts');
goog.require('ngeo');
goog.require('ngeo.Location');

ngeo.module.value('ngeoUsedKeyRegexp', [new RegExp('.*')]);

/**
 * Provides a service for managing the application state.
 * The application state is written to both the URL and the local storage.
 * @constructor
 * @struct
 * @param {!ngeo.Location} ngeoLocation ngeo location service.
 * @param {!Array.<!RegExp>} ngeoUsedKeyRegexp regexp used to identify the used keys.
 * @ngInject
 */
ngeo.StateManager = function(ngeoLocation, ngeoUsedKeyRegexp) {

  /**
   * Object representing the application's initial state.
   * @type {!Object.<string, string>}
   */
  this.initialState = {};

  /**
   * @type {!ngeo.Location}
   */
  this.ngeoLocation = ngeoLocation;

  /**
   * @type {!Array.<!RegExp>}
   */
  this.usedKeyRegexp = ngeoUsedKeyRegexp;

  /**
   * @type {boolean}
   */
  this.useLocalStorage = true;

  try {
    if ('localStorage' in window) {
      window.localStorage['test'] = '';
      delete window.localStorage['test'];
    } else {
      this.useLocalStorage = false;
    }
  } catch (err) {
    console.error(err);
    this.useLocalStorage = false;
  }

  // Populate initialState with the application's initial state. The initial
  // state is read from the location URL, or from the local storage if there
  // is no state in the location URL.

  const paramKeys = ngeoLocation.getParamKeys().filter(key => key != 'debug' && key != 'no_redirect');

  if (paramKeys.length === 0) {
    if (this.useLocalStorage) {
      for (const key in window.localStorage) {
        goog.asserts.assert(key);

        this.usedKeyRegexp.some((keyRegexp) => {
          if (key.match(keyRegexp)) {
            const value = window.localStorage[key];
            if (value !== undefined || value !== null) {
              this.initialState[key] = value;
            } else {
              this.initialState[key] = '';
            }
            return true;
          }
        });
      }
    }
  } else {
    paramKeys.forEach((key) => {
      this.usedKeyRegexp.some((keyRegexp) => {
        if (key.match(keyRegexp)) {
          const value = this.ngeoLocation.getParam(key);
          if (value !== undefined) {
            this.initialState[key] = value;
            return true;
          }
        }
      });
    });
  }
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {string|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialValue = function(key) {
  return this.initialState[key];
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {string|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialStringValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return value;
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {number|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialNumberValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return parseFloat(value);
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {boolean|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialBooleanValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return value === 'true';
};

/**
 * Update the application state with the values in `object`.
 * @param {!Object.<string, string>} object Object.
 */
ngeo.StateManager.prototype.updateState = function(object) {
  this.ngeoLocation.updateParams(object);
  if (this.useLocalStorage) {
    for (const key in object) {
      goog.asserts.assert(key);
      const value = object[key];
      goog.asserts.assert(value !== undefined);
      window.localStorage[key] = value;
    }
  }
};

/**
 * Delete a parameter
 * @param {string} key Key.
 */
ngeo.StateManager.prototype.deleteParam = function(key) {
  this.ngeoLocation.deleteParam(key);
  if (this.useLocalStorage) {
    delete window.localStorage[key];
  }
};

ngeo.module.service('ngeoStateManager', ngeo.StateManager);
<commit_msg>Disable the localstorage by default<commit_after>goog.provide('ngeo.StateManager');

goog.require('goog.asserts');
goog.require('ngeo');
goog.require('ngeo.Location');

ngeo.module.value('ngeoUsedKeyRegexp', [new RegExp('.*')]);

/**
 * Provides a service for managing the application state.
 * The application state is written to both the URL and the local storage.
 * @constructor
 * @struct
 * @param {!ngeo.Location} ngeoLocation ngeo location service.
 * @param {!Array.<!RegExp>} ngeoUsedKeyRegexp regexp used to identify the used keys.
 * @ngInject
 */
ngeo.StateManager = function(ngeoLocation, ngeoUsedKeyRegexp) {

  /**
   * Object representing the application's initial state.
   * @type {!Object.<string, string>}
   */
  this.initialState = {};

  /**
   * @type {!ngeo.Location}
   */
  this.ngeoLocation = ngeoLocation;

  /**
   * @type {!Array.<!RegExp>}
   */
  this.usedKeyRegexp = ngeoUsedKeyRegexp;

  /**
   * @type {boolean}
   */
  this.useLocalStorage = false;

  try {
    if ('localStorage' in window) {
      window.localStorage['test'] = '';
      delete window.localStorage['test'];
    } else {
      this.useLocalStorage = false;
    }
  } catch (err) {
    console.error(err);
    this.useLocalStorage = false;
  }

  // Populate initialState with the application's initial state. The initial
  // state is read from the location URL, or from the local storage if there
  // is no state in the location URL.

  const paramKeys = ngeoLocation.getParamKeys().filter(key => key != 'debug' && key != 'no_redirect');

  if (paramKeys.length === 0) {
    if (this.useLocalStorage) {
      for (const key in window.localStorage) {
        goog.asserts.assert(key);

        this.usedKeyRegexp.some((keyRegexp) => {
          if (key.match(keyRegexp)) {
            const value = window.localStorage[key];
            if (value !== undefined || value !== null) {
              this.initialState[key] = value;
            } else {
              this.initialState[key] = '';
            }
            return true;
          }
        });
      }
    }
  } else {
    paramKeys.forEach((key) => {
      this.usedKeyRegexp.some((keyRegexp) => {
        if (key.match(keyRegexp)) {
          const value = this.ngeoLocation.getParam(key);
          if (value !== undefined) {
            this.initialState[key] = value;
            return true;
          }
        }
      });
    });
  }
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {string|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialValue = function(key) {
  return this.initialState[key];
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {string|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialStringValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return value;
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {number|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialNumberValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return parseFloat(value);
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {boolean|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialBooleanValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return value === 'true';
};

/**
 * Update the application state with the values in `object`.
 * @param {!Object.<string, string>} object Object.
 */
ngeo.StateManager.prototype.updateState = function(object) {
  this.ngeoLocation.updateParams(object);
  if (this.useLocalStorage) {
    for (const key in object) {
      goog.asserts.assert(key);
      const value = object[key];
      goog.asserts.assert(value !== undefined);
      window.localStorage[key] = value;
    }
  }
};

/**
 * Delete a parameter
 * @param {string} key Key.
 */
ngeo.StateManager.prototype.deleteParam = function(key) {
  this.ngeoLocation.deleteParam(key);
  if (this.useLocalStorage) {
    delete window.localStorage[key];
  }
};

ngeo.module.service('ngeoStateManager', ngeo.StateManager);
<|endoftext|>


<commit_before>import { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

import { fetchSubscribers, deleteSubscriber } from 'modules/crud/subscriber';
import { select } from 'modules/crud/selectors';

import {
  Layout,
  Subscriber,
  Spinner,
  FloatingButton,
  Blank,
  Dimmed
} from 'components';

import Document from './Document';

class Collection extends Component {
  state = {
    search: '',
    document: {
      action: '',
      visible: false,
      dimmed: false
    }
  };

  componentWillMount() {
    const { subscribers, dispatch } = this.props

    if (subscribers.needsFetch) {
      dispatch(subscribers.fetch)
    }
  }

  componentWillReceiveProps(nextProps) {
    const { subscribers } = nextProps
    const { dispatch } = this.props
    if (subscribers.needsFetch) {
      dispatch(subscribers.fetch)
    }
  }

  handleSearchChange = (e) => {
    this.setState({
      search: e.target.value
    });
  }

  handleSearchClear = (e) => {
    this.setState({
      search: ''
    });
  }

  documentHandler = {
    show: (action, payload) => {
      this.setState({
        document: {
          action,
          visible: true,
          dimmed: true,
          ...payload
        }
      })
    },
    hide: () => {
      this.setState({
        document: {
          ...this.state.document,
          visible: false,
          dimmed: false
        }
      })
    },
    actions: {
      add: () => {
        this.documentHandler.show('add');
      },
      browser: (imsi) => {
      },
      change: (imsi) => {
        this.documentHandler.show('change', { imsi });
      },
      delete: (imsi) => {
        const { dispatch } = this.props
        dispatch(deleteSubscriber(imsi));
      }
    }
  }

  render() {
    const {
      handleSearchChange,
      handleSearchClear,
      documentHandler
    } = this;

    const {
      search,
      document
    } = this.state;

    const {
      subscribers
    } = this.props

    const {
      isLoading,
      data
    } = subscribers;

    return (
      <Layout.Content>
        {data.length !== 0 && <Subscriber.Search
          onChange={handleSearchChange}
          value={search}
          onClear={handleSearchClear} />}
        <Subscriber.List
          subscribers={data}
          onShow={documentHandler.actions.browser}
          onEdit={documentHandler.actions.change}
          onDelete={documentHandler.actions.delete}
          search={search}
        />
        {isLoading && <Spinner md />}
        <Blank
          visible={!isLoading && !data.length}
          title="ADD A SUBSCRIBER"
          body="You have no subscribers... yet!"
          onTitle={documentHandler.actions.add}
          />
        <FloatingButton onClick={documentHandler.actions.add}/>
        <Document
          { ...document }
          onHide={documentHandler.hide} />
        <Dimmed visible={document.dimmed} />
      </Layout.Content>
    )
  }
}

function mapStateToProps(state) {
  return { subscribers: select(fetchSubscribers(), state.crud) }
}

Collection = connect(
  (state) => ({
    subscribers: select(fetchSubscribers(), state.crud)
  })
)(Collection);

export default Collection;<commit_msg>update it<commit_after>import { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

import { fetchSubscribers, deleteSubscriber } from 'modules/crud/subscriber';
import { select } from 'modules/crud/selectors';

import {
  Layout,
  Subscriber,
  Spinner,
  FloatingButton,
  Blank,
  Dimmed
} from 'components';

import Document from './Document';

class Collection extends Component {
  state = {
    search: '',
    document: {
      action: '',
      visible: false,
      dimmed: false
    }
  };

  componentWillMount() {
    const { subscribers, dispatch } = this.props

    if (subscribers.needsFetch) {
      dispatch(subscribers.fetch)
    }
  }

  componentWillReceiveProps(nextProps) {
    const { subscribers } = nextProps
    const { dispatch } = this.props
    if (subscribers.needsFetch) {
      dispatch(subscribers.fetch)
    }
  }

  handleSearchChange = (e) => {
    this.setState({
      search: e.target.value
    });
  }

  handleSearchClear = (e) => {
    this.setState({
      search: ''
    });
  }

  documentHandler = {
    show: (action, payload) => {
      this.setState({
        document: {
          action,
          visible: true,
          dimmed: true,
          ...payload
        }
      })
    },
    hide: () => {
      this.setState({
        document: {
          ...this.state.document,
          visible: false,
          dimmed: false
        }
      })
    },
    actions: {
      add: () => {
        this.documentHandler.show('add');
      },
      browser: (imsi) => {
      },
      change: (imsi) => {
        this.documentHandler.show('change', { imsi });
      },
      delete: (imsi) => {
        const { dispatch } = this.props
        dispatch(deleteSubscriber(imsi));
      }
    }
  }

  render() {
    const {
      handleSearchChange,
      handleSearchClear,
      documentHandler
    } = this;

    const {
      search,
      document
    } = this.state;

    const {
      subscribers
    } = this.props

    const {
      isLoading,
      data
    } = subscribers;

    return (
      <Layout.Content>
        {data.length !== 0 && <Subscriber.Search
          onChange={handleSearchChange}
          value={search}
          onClear={handleSearchClear} />}
        <Subscriber.List
          subscribers={data}
          onShow={documentHandler.actions.browser}
          onEdit={documentHandler.actions.change}
          onDelete={documentHandler.actions.delete}
          search={search}
        />
        {isLoading && <Spinner md />}
        <Blank
          visible={!isLoading && !data.length}
          title="ADD A SUBSCRIBER"
          body="You have no subscribers... yet!"
          onTitle={documentHandler.actions.add}
          />
        <FloatingButton onClick={documentHandler.actions.add}/>
        <Document
          { ...document }
          onHide={documentHandler.hide} />
        <Dimmed visible={document.dimmed} />
      </Layout.Content>
    )
  }
}

Collection = connect(
  (state) => ({
    subscribers: select(fetchSubscribers(), state.crud)
  })
)(Collection);

export default Collection;<|endoftext|>


<commit_before>// ==========================================================================
// Project:   Tp5.sourceController
// Copyright: ©2010 My Company, Inc.
// ==========================================================================
/*globals Tp5 */

/** @class

  (Document Your Controller Here)

  @extends SC.Object
*/

Tp5.sourceController = SC.ArrayController.create(
/** @scope Tp5.sourceController.prototype */ {

	projector: null,
	switcher: null,

	attempts: 0,
	attempt_source: null,

	contextView: null,

	setSource: function(name){
		var source = this.get('states')[name];
		if(source)this.set('source', source);
		else return NO;
	},

	sourceChanged: function(){
		//this code is to make sure that we don't just keep trying in vain to set the source,
		//as our feedback may not be working properly
		if(!this.get('source'))return;
		if(this.get('projector') && this.attempts < 3 || !this.attempt_source || this.attempt_source != this.get('source').name)
		{
			Tp5.log("Attempt #%d", this.attempts);
			this.projector.set_var("input", this.get('source').projector);
			this.attempts = this.attempts+1;
			if(this.attempts_source != this.get('source').name)this.attempts = 0;
			this.attempt_source = this.get('source').name;
		}

		if(this.get('switcher'))this.switcher.set_var("input", this.get('source').switcher);

		this.runCommands(this.get('source'));

		this.switchContext(this.get('source'));

	}.observes("source"),

	switcherChanged: function(){
		if(this.get('content').get('length') === 0)return;
		this.set("source", this.get('states')[this.switcher_map[this.switcher.get('states').input]]);
	}.observes("switcher", "states", ".switcher.states"),

	projectorPowerChanged: function(){
		if(this.get('content').get('length') === 0)return;
		if(this.projector.get('states').power == YES && this.get('source') && this.projector.get('states').power != this.old_projector_power)
		{
			var input = this.get('source').projector;
			if(input && this.projector.get('states').input != input)
			{
				this.projector.set_var("input", input);
			}
		}
		this.old_projector_power = this.projector.get('states').power;
	}.observes("projector", "states", ".projector.states"),

	contentChanged: function() {
		var states = {};
		var switcher_map = {};
		this.get('content').forEach(function(source){
			states[source.get('name')] = {
				guid: source.get('guid'),
				name: source.get('name'),
				projector: source.get('input').projector,
				switcher: source.get('input').switcher,
				commands: source.get('input').commands,
				context: source.get('input').context,
				image: source.get('icon')
			};
			switcher_map[source.get('input').switcher] = source.get('name');
		});
		this.set('switcher_map', switcher_map);
		this.set('states', states);
	}.observes("content"),

	runCommands: function(source){
		if(source && source.commands){
			source.commands.forEach(function(command){
				try {
					var device = Tp5.store.find(Tp5.Device, command.device);
					device.send_command(command.command, command.arg);
				}
				catch(e) {
					Tp5.log("Failed to run command %s: %s", command, e.message);
				}
			});
		}
	},

	switchContext: function(source){
		Tp5.log("Switching contexts to %s", source.context);
		if(source.context && Tp5[source.context])
		{
			this.set('contextView', Tp5[source.context].create({
				layout: {left: 0, right: 0, top: 0, bottom: 0}
			}));

		}
		else
		{
			this.set('contextView', null);
		}
	},

	projectorBinding: "Tp5.roomController.projector",
	switcherBinding: "Tp5.roomController.switcher"

}) ;
<commit_msg>Fixed initial source selection issue for projector-only rooms (#13)<commit_after>// ==========================================================================
// Project:   Tp5.sourceController
// Copyright: ©2010 My Company, Inc.
// ==========================================================================
/*globals Tp5 */

/** @class

  (Document Your Controller Here)

  @extends SC.Object
*/

Tp5.sourceController = SC.ArrayController.create(
/** @scope Tp5.sourceController.prototype */ {

	projector: null,
	switcher: null,

	attempts: 0,
	attempt_source: null,

	contextView: null,

	setSource: function(name){
		var source = this.get('states')[name];
		if(source)this.set('source', source);
		else return NO;
	},

	sourceChanged: function(){
		//this code is to make sure that we don't just keep trying in vain to set the source,
		//as our feedback may not be working properly
		if(!this.get('source'))return;
		if(this.get('projector') && this.attempts < 3 || !this.attempt_source || this.attempt_source != this.get('source').name)
		{
			Tp5.log("Attempt #%d", this.attempts);
			this.projector.set_var("input", this.get('source').projector);
			this.attempts = this.attempts+1;
			if(this.attempts_source != this.get('source').name)this.attempts = 0;
			this.attempt_source = this.get('source').name;
		}

		if(this.get('switcher'))this.switcher.set_var("input", this.get('source').switcher);
		this.runCommands(this.get('source'));

		this.switchContext(this.get('source'));

	}.observes("source"),

	switcherChanged: function(){
		if(this.get('content').get('length') === 0 || !this.get('switcher'))return;
		this.set("source", this.get('states')[this.switcher_map[this.switcher.get('states').input]]);
	}.observes("switcher", "states", ".switcher.states"),

	projectorChanged: function(){
		if(this.get('content').get('length') === 0 || this.get('switcher'))return;
		this.set("source",this.get('states')[this.projector_map[this.projector.get('states').input]]);
	}.observes("projector", "states", ".projector.states"),

	projectorPowerChanged: function(){
		if(this.get('content').get('length') === 0)return;
		if(this.projector.get('states').power == YES && this.get('source') && this.projector.get('states').power != this.old_projector_power)
		{
			var input = this.get('source').projector;
			if(input && this.projector.get('states').input != input)
			{
				this.projector.set_var("input", input);
			}
		}
		this.old_projector_power = this.projector.get('states').power;
	}.observes("projector", "states", ".projector.states"),

	contentChanged: function() {
		var states = {};
		var switcher_map = {};
		var projector_map = {};
		this.get('content').forEach(function(source){
			states[source.get('name')] = {
				guid: source.get('guid'),
				name: source.get('name'),
				projector: source.get('input').projector,
				switcher: source.get('input').switcher,
				commands: source.get('input').commands,
				context: source.get('input').context,
				image: source.get('icon')
			};
			switcher_map[source.get('input').switcher] = source.get('name');
			projector_map[source.get('input').projector] = source.get('name');
		});
		this.set('switcher_map', switcher_map);
		this.set('projector_map', projector_map);
		this.set('states', states);

		if(!Tp5.roomController.switcher) //we're in a projector-only room
		{
			//hopefully we have a 1-1 mapping from projector inputs to sources
		}
	}.observes("content"),

	runCommands: function(source){
		if(source && source.commands){
			source.commands.forEach(function(command){
				try {
					var device = Tp5.store.find(Tp5.Device, command.device);
					device.send_command(command.command, command.arg);
				}
				catch(e) {
					Tp5.log("Failed to run command %s: %s", command, e.message);
				}
			});
		}
	},

	switchContext: function(source){
		Tp5.log("Switching contexts to %s", source.context);
		if(source.context && Tp5[source.context])
		{
			this.set('contextView', Tp5[source.context].create({
				layout: {left: 0, right: 0, top: 0, bottom: 0}
			}));

		}
		else
		{
			this.set('contextView', null);
		}
	},

	projectorBinding: "Tp5.roomController.projector",
	switcherBinding: "Tp5.roomController.switcher"

}) ;
<|endoftext|>


<commit_before>/**
 * generators.js
 * http://github.com/sjkaliski/numbers.js
 *
 * Copyright 2012 Stephen Kaliski, Kartik Talwar
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var generate = exports;

/**
 * Fast Fibonacci Implementation
 *
 * @param {Number} number to calculate
 * @return {Number} nth fibonacci number
 */
generate.fibonacci = function (n) {
  // Adapted from
  // http://bosker.wordpress.com/2011/04/29/the-worst-algorithm-in-the-world/

  var bitSystem = function (n) {
    var bit, bits = [];

    while (n > 0) {
      bit = (n < 2) ? n : n % 2;
      n = Math.floor(n / 2);
      bits.push(bit);
    }

    return bits.reverse();
  };

  var a = 1;
  var b = 0;
  var c = 1;
  var system = bitSystem(n);
  var temp;

  for (var i = 0; i < system.length; i++) {
    var bit = system[i];
    if (bit) {
      temp = [(a + c) * b, (b * b) + (c * c)];
      a = temp[0];
      b = temp[1];
    } else {
      temp = [(a * a) + (b * b), (a + c) * b];
      a = temp[0];
      b = temp[1];
    }

    c = a + b;
  }

  return b;
};

/**
 * Build an array of numbers in a Collatz sequence
 *
 * @param {number} The number for which to build a Collatz sequence
 * @return {Array} An array of numbers in a Collatz sequence
 */
generate.collatz = function (n) {
  var sequence = [];

  sequence.push(n);

  (function makeSequence(n) {
    if (n !== 1) {
      if (n % 2 === 0) {
        sequence.push(n / 2);
      } else {
        sequence.push(3 * n + 1);
      }
      makeSequence(sequence[sequence.length - 1]);
    }
  })(n);

  return sequence;
};
<commit_msg>Return undefined if the numbers.generate.collatz argument is not a number<commit_after>/**
 * generators.js
 * http://github.com/sjkaliski/numbers.js
 *
 * Copyright 2012 Stephen Kaliski, Kartik Talwar
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var generate = exports;

/**
 * Fast Fibonacci Implementation
 *
 * @param {Number} number to calculate
 * @return {Number} nth fibonacci number
 */
generate.fibonacci = function (n) {
  // Adapted from
  // http://bosker.wordpress.com/2011/04/29/the-worst-algorithm-in-the-world/

  var bitSystem = function (n) {
    var bit, bits = [];

    while (n > 0) {
      bit = (n < 2) ? n : n % 2;
      n = Math.floor(n / 2);
      bits.push(bit);
    }

    return bits.reverse();
  };

  var a = 1;
  var b = 0;
  var c = 1;
  var system = bitSystem(n);
  var temp;

  for (var i = 0; i < system.length; i++) {
    var bit = system[i];
    if (bit) {
      temp = [(a + c) * b, (b * b) + (c * c)];
      a = temp[0];
      b = temp[1];
    } else {
      temp = [(a * a) + (b * b), (a + c) * b];
      a = temp[0];
      b = temp[1];
    }

    c = a + b;
  }

  return b;
};

/**
 * Build an array of numbers in a Collatz sequence
 *
 * @param {number} The number for which to build a Collatz sequence
 * @return {Array|undefined} An array of numbers in a Collatz sequence
 */
generate.collatz = function (n) {
  if (!isNaN(n)){
    var sequence = [];

    sequence.push(n);

    (function makeSequence(n) {
      if (n !== 1) {
        if (n % 2 === 0) {
          sequence.push(n / 2);
        } else {
          sequence.push(3 * n + 1);
        }
        makeSequence(sequence[sequence.length - 1]);
      }
    })(n);

    return sequence;
  }
};
<|endoftext|>


<commit_before>'use strict';

// Nunjucks specific functions. This module is currently not in use.

function createForBuild(build) {
  var exports = {};

  function bundles(name, sourceType) {
    /*jshint validthis: true */
    var ml = build.bundles(name, sourceType);
    return this.markSafe(ml);
  }
  exports.bundle = bundle;

  function link(srcPath) {
    /*jshint validthis: true */
    var ml = build.link(srcPath);
    return this.markSafe(ml);
  }
  exports.link = link;

  function script(srcPath) {
    /*jshint validthis: true */
    var ml = build.script(srcPath);
    return this.markSafe(ml);
  }
  exports.script = script;

  function scriptCode(js) {
    /*jshint validthis: true */
    var ml = '<script type="text/javascript">' + js + '</script>';
    return this.markSafe(ml);
  }
  exports.scriptCode = scriptCode;

  exports.t = build.translate.bind(build);
  exports.tn = build.translateNumeric.bind(build);

  return exports;
}
exports.createForBuild = createForBuild;
<commit_msg>Minor correction.<commit_after>'use strict';

// Nunjucks specific functions. This module is currently not in use.

function createForBuild(build) {
  var exports = {};

  function bundles(name, sourceType) {
    /*jshint validthis: true */
    var ml = build.bundles(name, sourceType);
    return this.markSafe(ml);
  }
  exports.bundles = bundles;

  function link(srcPath) {
    /*jshint validthis: true */
    var ml = build.link(srcPath);
    return this.markSafe(ml);
  }
  exports.link = link;

  function script(srcPath) {
    /*jshint validthis: true */
    var ml = build.script(srcPath);
    return this.markSafe(ml);
  }
  exports.script = script;

  function scriptCode(js) {
    /*jshint validthis: true */
    var ml = '<script type="text/javascript">' + js + '</script>';
    return this.markSafe(ml);
  }
  exports.scriptCode = scriptCode;

  exports.t = build.translate.bind(build);
  exports.tn = build.translateNumeric.bind(build);

  return exports;
}
exports.createForBuild = createForBuild;
<|endoftext|>


<commit_before>(function (angular, window) {
    angular
        .module('mediaCenterWidget')
        .controller('WidgetMediaCtrl', ['$scope', '$window', 'Messaging', 'Buildfire', 'COLLECTIONS', 'media', 'EVENTS', '$timeout', "$sce", "DB", 'PATHS', '$rootScope','Location',
            function ($scope, $window, Messaging, Buildfire, COLLECTIONS, media, EVENTS, $timeout, $sce, DB, PATHS, $rootScope,Location) {

                var WidgetMedia = this;
                WidgetMedia.API = null;
                WidgetMedia.mediaType = null;
                WidgetMedia.showVideo = false;
                WidgetMedia.showSource = false;
                WidgetMedia.loadingVideo = false;
                var MediaCenter = new DB(COLLECTIONS.MediaCenter);

                WidgetMedia.onPlayerReady = function ($API) {
                    WidgetMedia.API = $API;
                    WidgetMedia.loadingVideo = true;
                    if(WidgetMedia.media.data.design.skipMediaPage&&WidgetMedia.item.data.videoUrl && !$rootScope.deepLinkNavigate)
                        WidgetMedia.toggleShowVideo();
                    };

                WidgetMedia.videoPlayerConfig = {
                    autoHide: false,
                    preload: "none",
                    sources: undefined,
                    tracks: undefined,
                    theme: {
                        url: "./assets/css/videogular.css"
                    }
                };
                WidgetMedia.changeVideoSrc = function () {
                    if (WidgetMedia.item.data.videoUrl){
                        var myType;
                        var videoUrlToSend=WidgetMedia.item.data.videoUrl;
                        if(videoUrlToSend.includes("www.dropbox")||videoUrlToSend.includes("dl.dropbox.com")){
                            videoUrlToSend=videoUrlToSend.replace("www.dropbox","dl.dropboxusercontent").split("?dl=")[0];
                            videoUrlToSend=videoUrlToSend.replace("dl.dropbox.com","dl.dropboxusercontent.com");
                            myType=videoUrlToSend.split('.').pop();
                        }else if(videoUrlToSend.includes("drive.google.com")){
                            //var urlArray=videoUrlToSend.replace("/view","").replace("/preview","").split("/");
                            //var urlId=urlArray[urlArray.length-1].split("?")[0];
                            //videoUrlToSend="https://drive.google.com/uc?id="+urlId;
                            videoUrlToSend=WidgetMedia.item.data.videoUrl.replace("/view","/preview").split("?")[0];
                            WidgetMedia.item.data.videoUrl=videoUrlToSend;
                            //var frame=document.getElementsByTagName("iframe")[0];
                            //frame.setAttribute("src",WidgetMedia.item.data.videoUrl);
                            myType="mp4";
                        }
                        else{
                            myType=videoUrlToSend.split('.').pop();
                        }
                        WidgetMedia.videoPlayerConfig.sources = [{
                            src: $sce.trustAsResourceUrl(videoUrlToSend),
                            type: 'video/' + myType //"video/mp4"
                        }];
                    }
                };
                MediaCenter.get().then(function (data) {
                    WidgetMedia.media = {
                        data: data.data
                    };
                    $rootScope.backgroundImage = WidgetMedia.media && WidgetMedia.media.data && WidgetMedia.media.data.design && WidgetMedia.media.data.design.backgroundImage;
                }, function (err) {
                    WidgetMedia.media = {
                        data: {}
                    };
                });

                WidgetMedia.sourceChanged = function ($source) {
                    WidgetMedia.API.stop();
                };

                WidgetMedia.item = {
                    data: {
                        audioUrl: "",
                        body: "",
                        bodyHTML: "",
                        deepLinkUrl: "",
                        image: "",
                        links: [],
                        srcUrl: "",
                        summary: "",
                        title: "",
                        topImage: "",
                        videoUrl: ""
                    }
                };
                if (media) {
                    WidgetMedia.item = media;
                    WidgetMedia.mediaType = media.data.audioUrl ? 'AUDIO' : (media.data.videoUrl ?  'VIDEO' : null);
                  //  WidgetMedia.item.title.length > 27 ? WidgetMedia.item.title = WidgetMedia.item.title.substring(0, 24) + "..." : WidgetMedia.item.title;
                    WidgetMedia.item.srcUrl = media.data.audioUrl ? media.data.audioUrl : media.data.videoUrl;
                    bookmarks.sync($scope);
                    WidgetMedia.changeVideoSrc();
                    WidgetMedia.iframeSrcUrl = $sce.trustAsUrl(WidgetMedia.item.data.srcUrl);
                    if($rootScope.deepLinkNavigate && $rootScope.seekTime) {
                        if(WidgetMedia.mediaType == 'VIDEO') {
                            var retry = setInterval(function () {
                                if (!WidgetMedia.API || !WidgetMedia.API.isReady || WidgetMedia.API.totalTime === 0) {
                                    return;
                                } else {
                                    clearInterval(retry);
                                    WidgetMedia.API.seekTime($rootScope.seekTime);
                                    WidgetMedia.toggleShowVideo();
                                    $rootScope.deepLinkNavigate = null;
                                    $rootScope.seekTime = null;
                                    setTimeout(function () {
                                            WidgetMedia.API.play();
                                    }, 500);
                                }
                            }, 500);
                        }
                    }
                }
                else {
                    WidgetMedia.iframeSrcUrl = '';
                }

                /*declare the device width heights*/
                $rootScope.deviceHeight = WidgetMedia.deviceHeight = window.innerHeight;
                $rootScope.deviceWidth = WidgetMedia.deviceWidth = window.innerWidth;

                /*initialize the device width heights*/
                var initDeviceSize = function (callback) {
                    WidgetMedia.deviceHeight = window.innerHeight;
                    WidgetMedia.deviceWidth = window.innerWidth;
                    if (callback) {
                        if (WidgetMedia.deviceWidth == 0 || WidgetMedia.deviceHeight == 0) {
                            setTimeout(function () {
                                initDeviceSize(callback);
                            }, 500);
                        } else {
                            callback();
                            if (!$scope.$$phase && !$scope.$root.$$phase) {
                                $scope.$apply();
                            }
                        }
                    }
                };

                Messaging.onReceivedMessage(function (event) {
                    if (event) {
                        switch (event.name) {
                            case EVENTS.ROUTE_CHANGE:
                                var path = event.message.path,
                                    id = event.message.id;
                                var url = "#/";
                                switch (path) {
                                    case PATHS.MEDIA:
                                        url = url + "media";
                                        if (id) {
                                            url = url + "/" + id;
                                        }
                                        break;
                                    default :

                                        break
                                }
                                Location.go(url);
                                break;
                        }
                    }
                });
                WidgetMedia.onUpdateFn = Buildfire.datastore.onUpdate(function (event) {
                    switch (event.tag) {
                        case COLLECTIONS.MediaContent:
                            if (event.data) {
                                WidgetMedia.item = event;
                                $scope.$digest();
                            }
                            break;
                        case COLLECTIONS.MediaCenter:
                            var old=WidgetMedia.media.data.design.itemLayout;
                            WidgetMedia.media = event;
                            $rootScope.backgroundImage = WidgetMedia.media.data.design.backgroundImage;
                            $rootScope.allowShare = WidgetMedia.media.data.content.allowShare;
                            $rootScope.allowSource = WidgetMedia.media.data.content.allowSource;
                            WidgetMedia.media.data.design.itemLayout = event.data.design.itemLayout;
                            if(old == WidgetMedia.media.data.design.itemLayout)WidgetMedia.ApplayUpdates();
                            $scope.$apply();
                            if(old != WidgetMedia.media.data.design.itemLayout)
                            $scope.$$postDigest(function () {
                                WidgetMedia.ApplayUpdates();
                              })
                            break;
                    }
                });
                WidgetMedia.playAudio = function () {
                    Location.go('#/nowplaying/' + WidgetMedia.item.id, true);
                }
                WidgetMedia.ApplayUpdates = function () {
                    if(WidgetMedia.media.data.design.skipMediaPage&&!WidgetMedia.item.data.videoUrl&&WidgetMedia.item.data.audioUrl)
                    {
                        if(WidgetMedia.showVideo){
                            WidgetMedia.showVideo=false;
                            WidgetMedia.API.pause();
                        }
                        Location.go('#/nowplaying/' + WidgetMedia.item.id, true);
                    }
                    else if(WidgetMedia.media.data.design.skipMediaPage&&WidgetMedia.item.data.videoUrl){
                        WidgetMedia.showVideo=true;
                        WidgetMedia.API.play();
                    }else{
                        WidgetMedia.showVideo=false;
                        WidgetMedia.API.pause();
                    }
                };

                WidgetMedia.toggleShowVideo = function () {
                    WidgetMedia.showVideo = !WidgetMedia.showVideo;
                    if (WidgetMedia.showVideo)
                        WidgetMedia.API.play();
                    else
                        WidgetMedia.API.pause();
                };

                WidgetMedia.showSourceIframe = function () {
                    var link = WidgetMedia.item.data.srcUrl;
                    if (!/^(?:f|ht)tps?\:\/\//.test(link)) {
                        link = "http://" + link;
                    }
                    Buildfire.navigation.openWindow(link, '_system');
                    /* WidgetMedia.showSource = !WidgetMedia.showSource;
                     if (WidgetMedia.showSource) {
                     $timeout(function () {
                     angular.element('#sourceIframe').attr('src', WidgetMedia.item.data.srcUrl);
                     }, 1000);
                     }*/
                };

                WidgetMedia.openLinks = function (actionItems) {
                    if (actionItems && actionItems.length) {
                        var options = {};
                        var callback = function (error, result) {
                            if (error) {
                                console.error('Error:', error);
                            }
                        };
                        Buildfire.actionItems.list(actionItems, options, callback);
                    }
                };

                WidgetMedia.executeAction = function (actionItem) {
                    Buildfire.actionItems.execute(actionItem);
                };

                WidgetMedia.videoLoaded = function () {
                    WidgetMedia.loadingVideo = false;
                };

                buildfire.auth.onLogin(function () {
                    bookmarks.sync($scope);
                });

                buildfire.auth.onLogout(function () {
                    bookmarks.sync($scope);
                });

                WidgetMedia.bookmark = function ($event) {
                    $event.stopImmediatePropagation();
                    var isBookmarked = WidgetMedia.item.data.bookmarked ? true : false;
                    if (isBookmarked) {
                        bookmarks.delete($scope, WidgetMedia.item);
                    } else {
                        bookmarks.add($scope, WidgetMedia.item);
                    }
                };

                WidgetMedia.share = function ($event) {
                    $event.stopImmediatePropagation();

                    var link = {};
                    link.title = WidgetMedia.item.data.title;
                    link.type = "website";
                    link.description = WidgetMedia.item.data.summary ? WidgetMedia.item.data.summary : null;
                    link.data = {
                        "mediaId": WidgetMedia.item.id
                    };

                    buildfire.deeplink.generateUrl(link, function (err, result) {
                        if (err) {
                            console.error(err)
                        } else {
                            buildfire.device.share({
                                subject: link.title,
                                text: link.description,
                                image: link.imageUrl,
                                link: result.url
                            }, function(err, result) {});

                        }
                    });
                };

                WidgetMedia.addNote = function () {
                    var options = {
                        itemId: WidgetMedia.item.id,
                        title: WidgetMedia.item.data.title,
                        imageUrl: WidgetMedia.item.data.topImage
                    };
                    if (WidgetMedia.mediaType === 'VIDEO' && WidgetMedia.API) {
                        options.timeIndex = WidgetMedia.API.currentTime / 1000;
                    }

                    var callback = function (err, data) {
                        if (err) throw err;
                        console.log(data);
                    };

                    buildfire.notes.openDialog(options, callback);
                };

                WidgetMedia.openLink = function (link) {
                    Buildfire.navigation.openWindow(link, '_system');
                };

              var initializing = true;
                $scope.$watch(function () {
                    return WidgetMedia.item.data.videoUrl;
                }, function () {
                    if (initializing) {
                        $timeout(function () {
                            initializing = false;
                        });
                    } else {
                        WidgetMedia.changeVideoSrc();
                    }
                });
                $scope.$on("$destroy", function () {
                    WidgetMedia.onUpdateFn.clear();
                });

                //Sync with Control section
                Messaging.sendMessageToControl({
                    name: EVENTS.ROUTE_CHANGE,
                    message: {
                        path: PATHS.MEDIA,
                        id: WidgetMedia.item.id || null
                    }
                });

                /**
                 * Implementation of pull down to refresh
                 */
                var onRefresh=Buildfire.datastore.onRefresh(function(){
                });

                /**
                 * Unbind the onRefresh
                 */
                $scope.$on('$destroy', function () {
                    onRefresh.clear();
                    Buildfire.datastore.onRefresh(function(){
                        Location.goToHome();
                    });
                });

                $rootScope.$on('deviceLocked', function () {
                    // pause videogular video (if any)
                    if(WidgetMedia.API)
                    WidgetMedia.API.pause();

                    // pause Youtube video (no need to check if there is any yt video playing)
                    callPlayer('ytPlayer', 'pauseVideo');

                    // pause Vimeo video (no need to check if there is any vimeo video playing)
                    callVimeoPlayer('ytPlayer');
                });

            }]);
})(window.angular, window);<commit_msg>support src url for showing source icon (#130)<commit_after>(function (angular, window) {
    angular
        .module('mediaCenterWidget')
        .controller('WidgetMediaCtrl', ['$scope', '$window', 'Messaging', 'Buildfire', 'COLLECTIONS', 'media', 'EVENTS', '$timeout', "$sce", "DB", 'PATHS', '$rootScope','Location',
            function ($scope, $window, Messaging, Buildfire, COLLECTIONS, media, EVENTS, $timeout, $sce, DB, PATHS, $rootScope,Location) {

                var WidgetMedia = this;
                WidgetMedia.API = null;
                WidgetMedia.mediaType = null;
                WidgetMedia.showVideo = false;
                WidgetMedia.showSource = false;
                WidgetMedia.loadingVideo = false;
                var MediaCenter = new DB(COLLECTIONS.MediaCenter);

                WidgetMedia.onPlayerReady = function ($API) {
                    WidgetMedia.API = $API;
                    WidgetMedia.loadingVideo = true;
                    if(WidgetMedia.media.data.design.skipMediaPage&&WidgetMedia.item.data.videoUrl && !$rootScope.deepLinkNavigate)
                        WidgetMedia.toggleShowVideo();
                    };

                WidgetMedia.videoPlayerConfig = {
                    autoHide: false,
                    preload: "none",
                    sources: undefined,
                    tracks: undefined,
                    theme: {
                        url: "./assets/css/videogular.css"
                    }
                };
                WidgetMedia.changeVideoSrc = function () {
                    if (WidgetMedia.item.data.videoUrl){
                        var myType;
                        var videoUrlToSend=WidgetMedia.item.data.videoUrl;
                        if(videoUrlToSend.includes("www.dropbox")||videoUrlToSend.includes("dl.dropbox.com")){
                            videoUrlToSend=videoUrlToSend.replace("www.dropbox","dl.dropboxusercontent").split("?dl=")[0];
                            videoUrlToSend=videoUrlToSend.replace("dl.dropbox.com","dl.dropboxusercontent.com");
                            myType=videoUrlToSend.split('.').pop();
                        }else if(videoUrlToSend.includes("drive.google.com")){
                            //var urlArray=videoUrlToSend.replace("/view","").replace("/preview","").split("/");
                            //var urlId=urlArray[urlArray.length-1].split("?")[0];
                            //videoUrlToSend="https://drive.google.com/uc?id="+urlId;
                            videoUrlToSend=WidgetMedia.item.data.videoUrl.replace("/view","/preview").split("?")[0];
                            WidgetMedia.item.data.videoUrl=videoUrlToSend;
                            //var frame=document.getElementsByTagName("iframe")[0];
                            //frame.setAttribute("src",WidgetMedia.item.data.videoUrl);
                            myType="mp4";
                        }
                        else{
                            myType=videoUrlToSend.split('.').pop();
                        }
                        WidgetMedia.videoPlayerConfig.sources = [{
                            src: $sce.trustAsResourceUrl(videoUrlToSend),
                            type: 'video/' + myType //"video/mp4"
                        }];
                    }
                };
                MediaCenter.get().then(function (data) {
                    WidgetMedia.media = {
                        data: data.data
                    };
                    $rootScope.backgroundImage = WidgetMedia.media && WidgetMedia.media.data && WidgetMedia.media.data.design && WidgetMedia.media.data.design.backgroundImage;
                }, function (err) {
                    WidgetMedia.media = {
                        data: {}
                    };
                });

                WidgetMedia.sourceChanged = function ($source) {
                    WidgetMedia.API.stop();
                };

                WidgetMedia.item = {
                    data: {
                        audioUrl: "",
                        body: "",
                        bodyHTML: "",
                        deepLinkUrl: "",
                        image: "",
                        links: [],
                        srcUrl: "",
                        summary: "",
                        title: "",
                        topImage: "",
                        videoUrl: ""
                    }
                };
                if (media) {
                    WidgetMedia.item = media;
                    WidgetMedia.mediaType = media.data.audioUrl ? 'AUDIO' : (media.data.videoUrl ?  'VIDEO' : null);
                    WidgetMedia.item.srcUrl = media.data.srcUrl ? media.data.srcUrl
                    : (media.data.audioUrl ? media.data.audioUrl : media.data.videoUrl);
                    bookmarks.sync($scope);
                    WidgetMedia.changeVideoSrc();
                    WidgetMedia.iframeSrcUrl = $sce.trustAsUrl(WidgetMedia.item.data.srcUrl);
                    if($rootScope.deepLinkNavigate && $rootScope.seekTime) {
                        if(WidgetMedia.mediaType == 'VIDEO') {
                            var retry = setInterval(function () {
                                if (!WidgetMedia.API || !WidgetMedia.API.isReady || WidgetMedia.API.totalTime === 0) {
                                    return;
                                } else {
                                    clearInterval(retry);
                                    WidgetMedia.API.seekTime($rootScope.seekTime);
                                    WidgetMedia.toggleShowVideo();
                                    $rootScope.deepLinkNavigate = null;
                                    $rootScope.seekTime = null;
                                    setTimeout(function () {
                                            WidgetMedia.API.play();
                                    }, 500);
                                }
                            }, 500);
                        }
                    }
                }
                else {
                    WidgetMedia.iframeSrcUrl = '';
                }

                /*declare the device width heights*/
                $rootScope.deviceHeight = WidgetMedia.deviceHeight = window.innerHeight;
                $rootScope.deviceWidth = WidgetMedia.deviceWidth = window.innerWidth;

                /*initialize the device width heights*/
                var initDeviceSize = function (callback) {
                    WidgetMedia.deviceHeight = window.innerHeight;
                    WidgetMedia.deviceWidth = window.innerWidth;
                    if (callback) {
                        if (WidgetMedia.deviceWidth == 0 || WidgetMedia.deviceHeight == 0) {
                            setTimeout(function () {
                                initDeviceSize(callback);
                            }, 500);
                        } else {
                            callback();
                            if (!$scope.$$phase && !$scope.$root.$$phase) {
                                $scope.$apply();
                            }
                        }
                    }
                };

                Messaging.onReceivedMessage(function (event) {
                    if (event) {
                        switch (event.name) {
                            case EVENTS.ROUTE_CHANGE:
                                var path = event.message.path,
                                    id = event.message.id;
                                var url = "#/";
                                switch (path) {
                                    case PATHS.MEDIA:
                                        url = url + "media";
                                        if (id) {
                                            url = url + "/" + id;
                                        }
                                        break;
                                    default :

                                        break
                                }
                                Location.go(url);
                                break;
                        }
                    }
                });
                WidgetMedia.onUpdateFn = Buildfire.datastore.onUpdate(function (event) {
                    switch (event.tag) {
                        case COLLECTIONS.MediaContent:
                            if (event.data) {
                                WidgetMedia.item = event;
                                $scope.$digest();
                            }
                            break;
                        case COLLECTIONS.MediaCenter:
                            var old=WidgetMedia.media.data.design.itemLayout;
                            WidgetMedia.media = event;
                            $rootScope.backgroundImage = WidgetMedia.media.data.design.backgroundImage;
                            $rootScope.allowShare = WidgetMedia.media.data.content.allowShare;
                            $rootScope.allowSource = WidgetMedia.media.data.content.allowSource;
                            WidgetMedia.media.data.design.itemLayout = event.data.design.itemLayout;
                            if(old == WidgetMedia.media.data.design.itemLayout)WidgetMedia.ApplayUpdates();
                            $scope.$apply();
                            if(old != WidgetMedia.media.data.design.itemLayout)
                            $scope.$$postDigest(function () {
                                WidgetMedia.ApplayUpdates();
                              })
                            break;
                    }
                });
                WidgetMedia.playAudio = function () {
                    Location.go('#/nowplaying/' + WidgetMedia.item.id, true);
                }
                WidgetMedia.ApplayUpdates = function () {
                    if(WidgetMedia.media.data.design.skipMediaPage&&!WidgetMedia.item.data.videoUrl&&WidgetMedia.item.data.audioUrl)
                    {
                        if(WidgetMedia.showVideo){
                            WidgetMedia.showVideo=false;
                            WidgetMedia.API.pause();
                        }
                        Location.go('#/nowplaying/' + WidgetMedia.item.id, true);
                    }
                    else if(WidgetMedia.media.data.design.skipMediaPage&&WidgetMedia.item.data.videoUrl){
                        WidgetMedia.showVideo=true;
                        WidgetMedia.API.play();
                    }else{
                        WidgetMedia.showVideo=false;
                        WidgetMedia.API.pause();
                    }
                };

                WidgetMedia.toggleShowVideo = function () {
                    WidgetMedia.showVideo = !WidgetMedia.showVideo;
                    if (WidgetMedia.showVideo)
                        WidgetMedia.API.play();
                    else
                        WidgetMedia.API.pause();
                };

                WidgetMedia.showSourceIframe = function () {
                    var link = WidgetMedia.item.data.srcUrl;
                    if (!/^(?:f|ht)tps?\:\/\//.test(link)) {
                        link = "http://" + link;
                    }
                    Buildfire.navigation.openWindow(link, '_system');
                    /* WidgetMedia.showSource = !WidgetMedia.showSource;
                     if (WidgetMedia.showSource) {
                     $timeout(function () {
                     angular.element('#sourceIframe').attr('src', WidgetMedia.item.data.srcUrl);
                     }, 1000);
                     }*/
                };

                WidgetMedia.openLinks = function (actionItems) {
                    if (actionItems && actionItems.length) {
                        var options = {};
                        var callback = function (error, result) {
                            if (error) {
                                console.error('Error:', error);
                            }
                        };
                        Buildfire.actionItems.list(actionItems, options, callback);
                    }
                };

                WidgetMedia.executeAction = function (actionItem) {
                    Buildfire.actionItems.execute(actionItem);
                };

                WidgetMedia.videoLoaded = function () {
                    WidgetMedia.loadingVideo = false;
                };

                buildfire.auth.onLogin(function () {
                    bookmarks.sync($scope);
                });

                buildfire.auth.onLogout(function () {
                    bookmarks.sync($scope);
                });

                WidgetMedia.bookmark = function ($event) {
                    $event.stopImmediatePropagation();
                    var isBookmarked = WidgetMedia.item.data.bookmarked ? true : false;
                    if (isBookmarked) {
                        bookmarks.delete($scope, WidgetMedia.item);
                    } else {
                        bookmarks.add($scope, WidgetMedia.item);
                    }
                };

                WidgetMedia.share = function ($event) {
                    $event.stopImmediatePropagation();

                    var link = {};
                    link.title = WidgetMedia.item.data.title;
                    link.type = "website";
                    link.description = WidgetMedia.item.data.summary ? WidgetMedia.item.data.summary : null;
                    link.data = {
                        "mediaId": WidgetMedia.item.id
                    };

                    buildfire.deeplink.generateUrl(link, function (err, result) {
                        if (err) {
                            console.error(err)
                        } else {
                            buildfire.device.share({
                                subject: link.title,
                                text: link.description,
                                image: link.imageUrl,
                                link: result.url
                            }, function(err, result) {});

                        }
                    });
                };

                WidgetMedia.addNote = function () {
                    var options = {
                        itemId: WidgetMedia.item.id,
                        title: WidgetMedia.item.data.title,
                        imageUrl: WidgetMedia.item.data.topImage
                    };
                    if (WidgetMedia.mediaType === 'VIDEO' && WidgetMedia.API) {
                        options.timeIndex = WidgetMedia.API.currentTime / 1000;
                    }

                    var callback = function (err, data) {
                        if (err) throw err;
                        console.log(data);
                    };

                    buildfire.notes.openDialog(options, callback);
                };

                WidgetMedia.openLink = function (link) {
                    Buildfire.navigation.openWindow(link, '_system');
                };

              var initializing = true;
                $scope.$watch(function () {
                    return WidgetMedia.item.data.videoUrl;
                }, function () {
                    if (initializing) {
                        $timeout(function () {
                            initializing = false;
                        });
                    } else {
                        WidgetMedia.changeVideoSrc();
                    }
                });
                $scope.$on("$destroy", function () {
                    WidgetMedia.onUpdateFn.clear();
                });

                //Sync with Control section
                Messaging.sendMessageToControl({
                    name: EVENTS.ROUTE_CHANGE,
                    message: {
                        path: PATHS.MEDIA,
                        id: WidgetMedia.item.id || null
                    }
                });

                /**
                 * Implementation of pull down to refresh
                 */
                var onRefresh=Buildfire.datastore.onRefresh(function(){
                });

                /**
                 * Unbind the onRefresh
                 */
                $scope.$on('$destroy', function () {
                    onRefresh.clear();
                    Buildfire.datastore.onRefresh(function(){
                        Location.goToHome();
                    });
                });

                $rootScope.$on('deviceLocked', function () {
                    // pause videogular video (if any)
                    if(WidgetMedia.API)
                    WidgetMedia.API.pause();

                    // pause Youtube video (no need to check if there is any yt video playing)
                    callPlayer('ytPlayer', 'pauseVideo');

                    // pause Vimeo video (no need to check if there is any vimeo video playing)
                    callVimeoPlayer('ytPlayer');
                });

            }]);
})(window.angular, window);<|endoftext|>