<commit_before>var OAuth = require('oauth');

module.exports = {

    /*
     * Attributes
     */

    manager: null,
    oauth: null,

    /*
     * Initialization
     */

    init: function(config, manager) {
        this.manager = manager;
        this.oauth = new OAuth(
            'https://api.twitter.com/oauth/request_token',
            'https://api.twitter.com/oauth/access_token',
            config.application.consumer_key,
            config.application.consumer_secret,
            '1.0',
            config.application.callback_url,
            'HMAC-SHA1'
        );
    },

    /*
     * Controllers
     */

    controllers: {

        auth: function(req, res, next) {
            oa.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret) {
                if(!error) {
                    req.session.token = oauth_token;
                    req.session.token_secret = oauth_token_secret;
                    res.redirect('https://twitter.com/oauth/authenticate?oauth_token=' + oauth_token);
                }
                else {
                    console.log('Request token failure');
                    next(); // Sends to the route displaying the issue to the client
                }
            });
        },

        callback: function(req, res, next) {
            if (req.session.token) {

                var oauth = req.session;
                req.session.verifier = req.query.oauth_verifier;

                oa.getOAuthAccessToken(oauth.token, oauth.token_secret, oauth.verifier,

                    function(error, oauth_access_token, oauth_access_token_secret, results){
                        if(!error){
                            // Works!
                        } else {
                            // Needs a status to inform the next route callback
                            next();
                        }
                    }

                );

            } else {
                // Needs a status to inform the next route callback
                next();
            }
        }
    },

};<commit_msg>Controllers inside the "auth" module can now access the "oauth" object<commit_after>var OAuth = require('oauth').OAuth;

module.exports = {

    /*
     * Attributes
     */

    manager: null,
    oauth: null,

    /*
     * Initialization
     */

    init: function(config, manager) {
        this.manager = manager;
        this.oauth = new OAuth(
            'https://api.twitter.com/oauth/request_token',
            'https://api.twitter.com/oauth/access_token',
            config.application.consumer_key,
            config.application.consumer_secret,
            '1.0',
            config.application.callback_url,
            'HMAC-SHA1'
        );

        // We need to redefine the "this" reference or the controllers won't find the "oauth" object
        for(var i in this.controllers) {
            this.controllers[i] = this.controllers[i](this);
        }
    },

    /*
     * Controllers : each controller needs to be inside a closure so the "this" keyword could be avoided
     * and the "_this" reference will be used instead
     */

    controllers: {

        auth: function(_this) {
            return function(req, res, next) {
                _this.oauth.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret) {
                    if(!error) {
                        req.session.token = oauth_token;
                        req.session.token_secret = oauth_token_secret;
                        res.redirect('https://twitter.com/oauth/authenticate?oauth_token=' + oauth_token);
                    }
                    else {
                        console.log('Request token failure');
                        next(); // Sends to the route displaying the issue to the client
                    }
                });
            };
        },

        callback: function(_this) {
            return function(req, res, next) {
                if(req.session.token) {

                    var oauth = req.session;
                    req.session.verifier = req.query.oauth_verifier;

                    _this.oauth.getOAuthAccessToken(oauth.token, oauth.token_secret, oauth.verifier,

                        function(error, oauth_access_token, oauth_access_token_secret, results){
                            if(!error){
                                // Works!
                            } else {
                                // Needs a status to inform the next route callback
                                next();
                            }
                        }

                    );

                } else {
                    // Needs a status to inform the next route callback
                    next();
                }
            };
        }
    }

};<|endoftext|>


<commit_before>/** Authentication for AWS services.
 */

/*
 *  Generate a HMAC-SHA signature for AWS
 */
exports.sign = function (request, secretKey) {
    return "";
}

/*
 * Request a AWS security token.
 */

exports.getSecurityToken = function (credentials, callback) {

    var querystring = require('querystring');

    var timestamp = querystring.stringify({"Timestamp" : new Date().toISOString()});

    var stringToSign =  "GET\n" +
                        "sts.amazonaws.com\n" +
                        "/\n" +
                        "AWSAccessKeyId=" + credentials.keyid +
                        "&Action=GetSessionToken" +
                        "&DurationSeconds=3600" +
                        "&SignatureMethod=HmacSHA256" +
                        "&SignatureVersion=2" +
                        "&" + timestamp +
                        "&Version=2011-06-15";

    var hmac = require('crypto').createHmac('sha256', credentials.secret);
    hmac.update(stringToSign);
    var signature = querystring.stringify({"Signature" : hmac.digest('base64')});

    var https = require('https');
    var options = {
        host    : 'sts.amazonaws.com',
        method  : 'GET',
        path    : '/?Action=GetSessionToken' +
                  '&DurationSeconds=3600' +
                  '&AWSAccessKeyId=' + credentials.keyid +
                  '&Version=2011-06-15' +
                  '&' + timestamp +
                  '&' + signature +
                  '&SignatureVersion=2&SignatureMethod=HmacSHA256'
    }

    var token = new Object();

    https.get(options, function (res) {

        var sax    = require("sax"),
            strict = true,
            parser = sax.parser(strict);

        parser.onerror = function (e) {
            throw e;
        };

        parser.onopentag = function (node) {
            switch (node.name) {
                case "SessionToken" :
                    parser.ontext = function (t) {
                        if (!token.SessionToken) token.SessionToken = t;
                    }
                    break;
                case "SecretAccessKey" :
                    parser.ontext = function (t) {
                        if (!token.SecretAccessKey) token.SecretAccessKey = t;
                    }
                    break;
                case "Expiration" :
                    parser.ontext = function (t) {
                        if (!token.Expiration) token.Expiration = t;
                    }
                    break;
                case "AccessKeyId" :
                    parser.ontext = function (t) {
                        if (!token.AccessKeyId) token.AccessKeyId = t;
                    }
                    break;
            }
        }

        if (res.statusCode !== 200) {
            console.log("Error accessing dynamoDB. Failed to get session token.");
        } else {
            // callback(token, secretKey);
        }
        res.on('data', function (chunk) {
            parser.write(chunk.toString());
        });

        res.on('end', function () {
            parser.close();
            if (callback) callback(token);
        });
    });
}
<commit_msg>Added auth module that creates a temporary security token.<commit_after>/*
 * Request a AWS security token.
 */

exports.getSecurityToken = function (credentials, callback) {

    var querystring = require('querystring');

    var timestamp = querystring.stringify({"Timestamp" : new Date().toISOString()});

    var stringToSign =  "GET\n" +
                        "sts.amazonaws.com\n" +
                        "/\n" +
                        "AWSAccessKeyId=" + credentials.keyid +
                        "&Action=GetSessionToken" +
                        "&DurationSeconds=3600" +
                        "&SignatureMethod=HmacSHA256" +
                        "&SignatureVersion=2" +
                        "&" + timestamp +
                        "&Version=2011-06-15";

    var hmac = require('crypto').createHmac('sha256', credentials.secret);
    hmac.update(stringToSign);
    var signature = querystring.stringify({"Signature" : hmac.digest('base64')});

    var https = require('https');
    var options = {
        host    : 'sts.amazonaws.com',
        method  : 'GET',
        path    : '/?Action=GetSessionToken' +
                  '&DurationSeconds=3600' +
                  '&AWSAccessKeyId=' + credentials.keyid +
                  '&Version=2011-06-15' +
                  '&' + timestamp +
                  '&' + signature +
                  '&SignatureVersion=2&SignatureMethod=HmacSHA256'
    }

    var token = new Object();

    https.get(options, function (res) {

        var sax    = require("sax"),
            strict = true,
            parser = sax.parser(strict);

        parser.onerror = function (e) {
            throw e;
        };

        parser.onopentag = function (node) {
            switch (node.name) {
                case "SessionToken" :
                    parser.ontext = function (t) {
                        if (!token.SessionToken) token.SessionToken = t;
                    }
                    break;
                case "SecretAccessKey" :
                    parser.ontext = function (t) {
                        if (!token.SecretAccessKey) token.SecretAccessKey = t;
                    }
                    break;
                case "Expiration" :
                    parser.ontext = function (t) {
                        if (!token.Expiration) token.Expiration = t;
                    }
                    break;
                case "AccessKeyId" :
                    parser.ontext = function (t) {
                        if (!token.AccessKeyId) token.AccessKeyId = t;
                    }
                    break;
            }
        }

        if (res.statusCode !== 200) {
            console.log("Error accessing dynamoDB. Failed to get session token.");
        } else {
            // callback(token, secretKey);
        }
        res.on('data', function (chunk) {
            parser.write(chunk.toString());
        });

        res.on('end', function () {
            parser.close();
            if (callback) callback(token);
        });
    });
}
<|endoftext|>


<commit_before>var Model = require('base/model')
var debug = require('debug')('holodex:role:model')

module.exports = Model.extend({
  typeName: 'Role',
  collectionName: 'roles',

  props: {
    type: 'link',
    agent: 'link',
    relationship: 'link'
  },

  derived: {
    label: {
      deps: ['type', 'agent', 'relationship'],
      fn: function () {
        var agentsByRole = {}
        if (this.relationship) {
          this.relationship.roles.forEach(function (role) {
            agentsByRole[role.type.name] = role.agent.getId()
          })
        } else {
          agentsByRole[this.type.name] = this.agent
        }
        return this.type.generateLabel(agentsByRole)
      }
    },
    linkTypeId: {
      deps: ['type'],
      fn: function () {
        return this.type.getId() + '/link'
      }
    },
    linkTargetId: { //potentially superfluos given 'pair' below
      cache: false,
      deps: ['relationship', 'agent'],
      fn: function () {
        return this.relationship.roles.reduce(function (memo, role) {
          if (role.agent.getId() !== this.agent.getId()) {
            memo = role.agent.getId()
          }
          return memo
        }.bind(this))
      }
    },
    pair: {
      cache: false,
      deps: ['relationship', 'agent'],
      fn: function () {
        return this.relationship.roles.reduce(function (memo, role) {
          if (role.agent.getId() !== this.agent.getId()) {
            memo = role
          }
          return memo
        }.bind(this))
      }
    },
  }
})
<commit_msg>simpler role.pair property<commit_after>var Model = require('base/model')
var debug = require('debug')('holodex:role:model')

module.exports = Model.extend({
  typeName: 'Role',
  collectionName: 'roles',

  props: {
    type: 'link',
    agent: 'link',
    relationship: 'link'
  },

  derived: {
    label: {
      deps: ['type', 'agent', 'relationship'],
      fn: function () {
        var agentsByRole = {}
        if (this.relationship) {
          this.relationship.roles.forEach(function (role) {
            agentsByRole[role.type.name] = role.agent.getId()
          })
        } else {
          agentsByRole[this.type.name] = this.agent
        }
        return this.type.generateLabel(agentsByRole)
      }
    },
    linkTypeId: {
      deps: ['type'],
      fn: function () {
        return this.type.getId() + '/link'
      }
    },
    linkTargetId: { //potentially superfluos given 'pair' below
      cache: false,
      deps: ['relationship', 'agent'],
      fn: function () {
        return this.relationship.roles.reduce(function (memo, role) {
          if (role.agent.getId() !== this.agent.getId()) {
            memo = role.agent.getId()
          }
          return memo
        }.bind(this))
      }
    },
    pair: {
      cache: false,
      deps: ['relationship', 'agent'],
      fn: function () {
        var roleId = this.getId()
        var pair
        this.relationship.roles.forEach(function (role) {
          if (role.getId() !== roleId) pair = role
        })
        return pair
      }
    },
  }
})
<|endoftext|>


<commit_before>'use strict';

module.exports = {

  controller: function (args) {
    this.servico = args.servico;
  },

  view: function (ctrl) {
    return m('fieldset#gratuidade', [
      m('h3', [
        'Gratuidade deste serviço',
        m.component(require('tooltips').gratuidade)
      ]),

      m('label',
        m('input[type=checkbox]', {
          onchange: m.withAttr('checked', ctrl.servico().gratuidade),
          checked: ctrl.servico().gratuidade()
        }),
        'Este serviço é gratuito para o solicitante'
      )
    ]);
  }

};
<commit_msg>ajusta opção de checkbox para radio button #140<commit_after>'use strict';

module.exports = {

  controller: function (args) {
    this.servico = args.servico;
  },

  view: function (ctrl) {
    return m('fieldset#gratuidade', [
      m('h3', [
        'Gratuidade deste serviço',
        m.component(require('tooltips').gratuidade)
      ]),

      m('label',
        m('input[type=radio][name=gratuidade]', {
          onchange: function() {
            ctrl.servico().gratuidade(true);
          },
          checked: ctrl.servico().gratuidade() !== undefined && ctrl.servico().gratuidade()
        }),
        'Este serviço é gratuito para o solicitante'
      ),

      m('label',
        m('input[type=radio][name=gratuidade]', {
          onchange: function () {
            ctrl.servico().gratuidade(false);
          },
          checked: ctrl.servico().gratuidade() !== undefined && !ctrl.servico().gratuidade()
        }),
        'Este serviço não é gratuito para o solicitante'
      )

    ]);
  }

};
<|endoftext|>


<commit_before>/*global cordova: true */
define(
  ['uuid'],
  function (uuid) {
    "use strict";
    var API = {
      getAnswerSpaceMap: function (user) {
        return new Promise(function (resolve, reject) {
          var userString = '';
          if (user) {
            userString = '&_username=' + user;
          }
          cordova.offline.retrieveContent(
            function (data) {
              resolve(JSON.parse(data));
            },
            reject,
            '/_R_/common/3/xhr/GetConfig.php?_asn=' + window.BMP.BIC.siteVars.answerSpace + userString
          );
        });
      },

      getInteractionResult: function (iact, args) {
        var getargs = '';
        if (args && typeof args === "object") {
          _.each(args, function (value, key) {
            if (value) {
              getargs += '&' + key + '=' + value;
            }
          });
        }
        return new Promise(function (resolve, reject) {
          cordova.offline.retrieveContent(
            resolve,
            reject,
            '/_R_/common/3/xhr/GetAnswer.php?asn=' + window.BMP.BIC.siteVars.answerSpace + '&iact=' + iact + '&ajax=false' + getargs
          );
        });
      },

      getForm: function () {
        return new Promise(function (resolve, reject) {
          cordova.offline.retrieveContent(
            function (data) {
              resolve(JSON.parse(data));
            },
            reject,
            '/_R_/common/3/xhr/GetForm.php?_v=3&_aid=' + window.BMP.BIC.siteVars.answerSpaceId
          );
        });
      },

      getDataSuitcase: function (suitcase, time) {
        return new Promise(function (resolve, reject) {
          cordova.offline.retrieveContent(
            resolve,
            reject,
            '/_R_/common/3/xhr/GetMoJO.php?_id=' + window.BMP.BIC.siteVars.answerSpaceId + '&_m=' + suitcase + '&_lc=' + time
          );
        });
      },

      setPendingItem: function (formname, formaction, formdata) {
        formdata._uuid = uuid.v4();
        return $.post('/_R_/common/3/xhr/SaveFormRecord.php?_asid=' + window.BMP.BIC.siteVars.answerSpaceId + '&_fn=' + formname + '&_action=' + formaction, formdata);
      },

      getLoginStatus: function () {
        return $.ajax('/_R_/common/3/xhr/GetLogin.php');
      },

      getFormList: function (formName) {
        return new Promise(function (resolve, reject) {
          cordova.offline.retrieveContent(
            function (data) {
              resolve($.parseXML(data));
            },
            reject,
            '/_R_/common/3/xhr/GetFormList.php?_asid=' + window.BMP.BIC.siteVars.answerSpaceId + '&_fn=' + formName
          );
        });
      },

      getFormRecord: function (formName, formAction, recordID) {
        return new Promise(function (resolve, reject) {
          cordova.offline.retrieveContent(
            function (data) {
              resolve($.parseXML(data));
            },
            reject,
            '/_R_/common/3/xhr/GetFormRecord.php?_asid=' + window.BMP.BIC.siteVars.answerSpaceId + '&_fn=' + formName + '&_tid=' + recordID + '&action=' + formAction
          );
        });
      }
    };

    return API;
  }
);
<commit_msg>Native API's were incorrectly invoked<commit_after>/*global cordova: true */
define(
  ['uuid'],
  function (uuid) {
    "use strict";
    var API = {
      getAnswerSpaceMap: function (user) {
        return new Promise(function (resolve, reject) {
          var userString = '';
          if (user) {
            userString = '&_username=' + user;
          }
          cordova.offline.retrieveContent(
            function (data) {
              resolve(JSON.parse(data));
            },
            reject,
            {
              url: '/_R_/common/3/xhr/GetConfig.php?_asn=' + window.BMP.BIC.siteVars.answerSpace + userString
            }
          );
        });
      },

      getInteractionResult: function (iact, args) {
        var getargs = '';
        if (args && typeof args === "object") {
          _.each(args, function (value, key) {
            if (value) {
              getargs += '&' + key + '=' + value;
            }
          });
        }
        return new Promise(function (resolve, reject) {
          cordova.offline.retrieveContent(
            resolve,
            reject,
            {
              url: '/_R_/common/3/xhr/GetAnswer.php?asn=' + window.BMP.BIC.siteVars.answerSpace + '&iact=' + iact + '&ajax=false' + getargs
            }
          );
        });
      },

      getForm: function () {
        return new Promise(function (resolve, reject) {
          cordova.offline.retrieveContent(
            function (data) {
              resolve(JSON.parse(data));
            },
            reject,
            {
              url: '/_R_/common/3/xhr/GetForm.php?_v=3&_aid=' + window.BMP.BIC.siteVars.answerSpaceId
            }
          );
        });
      },

      getDataSuitcase: function (suitcase, time) {
        return new Promise(function (resolve, reject) {
          cordova.offline.retrieveContent(
            resolve,
            reject,
            {
              url: '/_R_/common/3/xhr/GetMoJO.php?_id=' + window.BMP.BIC.siteVars.answerSpaceId + '&_m=' + suitcase + '&_lc=' + time
            }
          );
        });
      },

      setPendingItem: function (formname, formaction, formdata) {
        formdata._uuid = uuid.v4();
        return $.post('/_R_/common/3/xhr/SaveFormRecord.php?_asid=' + window.BMP.BIC.siteVars.answerSpaceId + '&_fn=' + formname + '&_action=' + formaction, formdata);
      },

      getLoginStatus: function () {
        return $.ajax('/_R_/common/3/xhr/GetLogin.php');
      },

      getFormList: function (formName) {
        return new Promise(function (resolve, reject) {
          cordova.offline.retrieveContent(
            function (data) {
              resolve($.parseXML(data));
            },
            reject,
            {
              url: '/_R_/common/3/xhr/GetFormList.php?_asid=' + window.BMP.BIC.siteVars.answerSpaceId + '&_fn=' + formName
            }
          );
        });
      },

      getFormRecord: function (formName, formAction, recordID) {
        return new Promise(function (resolve, reject) {
          cordova.offline.retrieveContent(
            function (data) {
              resolve($.parseXML(data));
            },
            reject,
            {
              url: '/_R_/common/3/xhr/GetFormRecord.php?_asid=' + window.BMP.BIC.siteVars.answerSpaceId + '&_fn=' + formName + '&_tid=' + recordID + '&action=' + formAction
            }
          );
        });
      }
    };

    return API;
  }
);
<|endoftext|>


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

// Native
const {resolve} = require('path')

// Packages
const nodeVersion = require('node-version')
const updateNotifier = require('update-notifier')

// Ours
const {error} = require('../lib/error')
const pkg = require('../package')

// Support for keywords "async" and "await"
require('async-to-gen/register')({
  excludes: null
})

// Throw an error if node version is too low
if (nodeVersion.major < 6) {
  error('Now requires at least version 6 of Node. Please upgrade!')
  process.exit(1)
}

// Only check for updates in the npm version
if (!process.pkg) {
  updateNotifier({pkg}).notify()
}

// This command will be run if no other sub command is specified
const defaultCommand = 'deploy'

const commands = new Set([
  defaultCommand,
  'help',
  'list',
  'ls',
  'rm',
  'remove',
  'alias',
  'aliases',
  'ln',
  'domain',
  'domains',
  'dns',
  'cert',
  'certs',
  'secret',
  'secrets'
])

const aliases = new Map([
  ['ls', 'list'],
  ['rm', 'remove'],
  ['ln', 'alias'],
  ['aliases', 'alias'],
  ['domain', 'domains'],
  ['cert', 'certs'],
  ['secret', 'secrets']
])

let cmd = defaultCommand
const args = process.argv.slice(2)
const index = args.findIndex(a => commands.has(a))

if (index > -1) {
  cmd = args[index]
  args.splice(index, 1)

  if (cmd === 'help') {
    if (index < args.length && commands.has(args[index])) {
      cmd = args[index]
      args.splice(index, 1)
    } else {
      cmd = defaultCommand
    }

    args.unshift('--help')
  }

  cmd = aliases.get(cmd) || cmd
}

const bin = resolve(__dirname, 'now-' + cmd + '.js')

// Prepare process.argv for subcommand
process.argv = process.argv.slice(0, 2).concat(args)

// Load sub command
// With custom parameter to make "pkg" happy
require(bin, 'may-exclude')
<commit_msg>Only transform our code with `async-to-gen/register` (#254)<commit_after>#!/usr/bin/env node

// Native
const {resolve} = require('path')

// Packages
const nodeVersion = require('node-version')
const updateNotifier = require('update-notifier')

// Ours
const {error} = require('../lib/error')
const pkg = require('../package')

// Support for keywords "async" and "await"
require('async-to-gen/register')({
  includes: /.*now(-cli)?\/(lib|bin).*/,
  excludes: null
})

// Throw an error if node version is too low
if (nodeVersion.major < 6) {
  error('Now requires at least version 6 of Node. Please upgrade!')
  process.exit(1)
}

// Only check for updates in the npm version
if (!process.pkg) {
  updateNotifier({pkg}).notify()
}

// This command will be run if no other sub command is specified
const defaultCommand = 'deploy'

const commands = new Set([
  defaultCommand,
  'help',
  'list',
  'ls',
  'rm',
  'remove',
  'alias',
  'aliases',
  'ln',
  'domain',
  'domains',
  'dns',
  'cert',
  'certs',
  'secret',
  'secrets'
])

const aliases = new Map([
  ['ls', 'list'],
  ['rm', 'remove'],
  ['ln', 'alias'],
  ['aliases', 'alias'],
  ['domain', 'domains'],
  ['cert', 'certs'],
  ['secret', 'secrets']
])

let cmd = defaultCommand
const args = process.argv.slice(2)
const index = args.findIndex(a => commands.has(a))

if (index > -1) {
  cmd = args[index]
  args.splice(index, 1)

  if (cmd === 'help') {
    if (index < args.length && commands.has(args[index])) {
      cmd = args[index]
      args.splice(index, 1)
    } else {
      cmd = defaultCommand
    }

    args.unshift('--help')
  }

  cmd = aliases.get(cmd) || cmd
}

const bin = resolve(__dirname, 'now-' + cmd + '.js')

// Prepare process.argv for subcommand
process.argv = process.argv.slice(0, 2).concat(args)

// Load sub command
// With custom parameter to make "pkg" happy
require(bin, 'may-exclude')
<|endoftext|>


<commit_before>'use strict';

(function (angular, buildfire) {
  angular
    .module('loyaltyPluginWidget')
    .controller('WidgetHomeCtrl', ['$scope', 'ViewStack', 'LoyaltyAPI', 'STATUS_CODE', 'TAG_NAMES', 'LAYOUTS', 'DataStore', 'RewardCache', '$rootScope', '$sce', 'Context',
      function ($scope, ViewStack, LoyaltyAPI, STATUS_CODE, TAG_NAMES, LAYOUTS, DataStore, RewardCache, $rootScope, $sce, Context) {
        console.error('Loyalty----------WidgetHomeCtrl--------------------------Loaded----------------------------');

        var WidgetHome = this;

        $rootScope.deviceHeight = window.innerHeight;
        $rootScope.deviceWidth = window.innerWidth;
        $rootScope.itemListbackgroundImage = "";
        $rootScope.itemDetailsBackgroundImage = "";

        //create new instance of buildfire carousel viewer
        WidgetHome.view = null;

        WidgetHome.listeners = {};

        /**
         * Initialize current logged in user as null. This field is re-initialized if user is already logged in or user login user auth api.
         */
        WidgetHome.currentLoggedInUser = null;

        /**
         * Method to open a reward details page.
         */
        WidgetHome.openReward = function (reward) {
          RewardCache.setReward(reward);
          ViewStack.push({
            template: 'Item_Details',
            totalPoints: $rootScope.loyaltyPoints
          });
          buildfire.messaging.sendMessageToControl({
            type: 'OpenItem',
            data: reward
          });
        };

        /**
         * Method to fetch logged in user's loyalty points
         */
        WidgetHome.getLoyaltyPoints = function (userId) {
          var success = function (result) {
              console.error('Points>>>>>>>>>>>>>>>.---------------------------------------------------', result);
              $rootScope.loyaltyPoints = result.totalPoints;
            }
            , error = function (err) {
              if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                console.error('Error while getting points data----------------------------------------', err);
              }
            };
          LoyaltyAPI.getLoyaltyPoints(userId, WidgetHome.currentLoggedInUser.userToken, WidgetHome.context.instanceId).then(success, error);
        };

        /**
         * Method to fetch loyalty application and list of rewards
         */
        WidgetHome.getApplicationAndRewards = function () {
          var successLoyaltyRewards = function (result) {
              WidgetHome.loyaltyRewards = result;
              if (!WidgetHome.loyaltyRewards)
                WidgetHome.loyaltyRewards = [];
              console.error('Rewards> got successfully>>>>>>>>>>>>>.:--------------------------------------', result);
            }
            , errorLoyaltyRewards = function (err) {
                console.error('Error while getting data loyaltyRewards--------------------------------------', err);
                if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                console.error('Error while getting data loyaltyRewards--------------------------------------', err);
              }
            };
          var successApplication = function (result) {
            console.error('Successfully got application----------------------------------------------------------------------',result);
            if (result.image)
              WidgetHome.carouselImages = result.image;
            if (result.content && result.content.description)
              WidgetHome.description = result.content.description;
            RewardCache.setApplication(result);
          };

          var errorApplication = function (error) {
            console.error('Error fetching loyalty application---------------------------------------------------',error);
          };

          console.error("$$$$$$$$$$$$$$$$$$$$$$$---------------context----------------------------------------------", WidgetHome.context);
          LoyaltyAPI.getApplication(WidgetHome.context.instanceId).then(successApplication, errorApplication);
          LoyaltyAPI.getRewards(WidgetHome.context.instanceId).then(successLoyaltyRewards, errorLoyaltyRewards);
        };

        /**
         * Method to show amount page where user can fill in the amount they have made purchase of.
         */
        WidgetHome.openGetPoints = function () {
          console.log(">>>>>>>>>>>>>>-----------------------");
          if (WidgetHome.currentLoggedInUser) {
            ViewStack.push({
              template: 'Amount',
              loyaltyPoints: $rootScope.loyaltyPoints

            });
          }
          else {
            WidgetHome.openLogin();
          }
        };

        /**
         * Method to open buildfire auth login pop up and allow user to login using credentials.
         */
        WidgetHome.openLogin = function () {
          buildfire.auth.login({}, function () {

          });
        };

        /**
         * This event listener is bound for "POINTS_REDEEMED" event broadcast
         */
        WidgetHome.listeners['POINTS_REDEEMED'] = $rootScope.$on('POINTS_REDEEMED', function (e, points) {
          if (points)
            $rootScope.loyaltyPoints = $rootScope.loyaltyPoints - points;
        });

        /**
         * This event listener is bound for "POINTS_ADDED" event broadcast
         */
        WidgetHome.listeners['POINTS_ADDED'] = $rootScope.$on('POINTS_ADDED', function (e, points) {
          if (points)
            $rootScope.loyaltyPoints = $rootScope.loyaltyPoints + points;
        });

        /**
         * This event listener is bound for "REWARD_DELETED" event broadcast
         */
        WidgetHome.listeners['REWARD_DELETED'] = $rootScope.$on('REWARD_DELETED', function (e, index) {
          if (index != -1)
            WidgetHome.loyaltyRewards.splice(index, 1);
        });

        /**
         * This event listener is bound for "REWARDS_SORTED" event broadcast
         */
        WidgetHome.listeners['REWARDS_SORTED'] = $rootScope.$on('REWARDS_SORTED', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        /**
         * This event listener is bound for "Carousel:LOADED" event broadcast
         */
        WidgetHome.listeners['Carousel:LOADED'] = $rootScope.$on("Carousel:LOADED", function () {
          WidgetHome.view = null;
          if (!WidgetHome.view) {
            WidgetHome.view = new buildfire.components.carousel.view("#carousel", [], "WideScreen");
          }
          if (WidgetHome.carouselImages) {
            WidgetHome.view.loadItems(WidgetHome.carouselImages, null, "WideScreen");
          } else {
            WidgetHome.view.loadItems([]);
          }
        });

        /**
         * This event listener is bound for "REWARD_ADDED" event broadcast
         */
        WidgetHome.listeners['REWARD_ADDED'] = $rootScope.$on('REWARD_ADDED', function (e, item) {
          WidgetHome.loyaltyRewards.unshift(item);
        });

        /**
         * This event listener is bound for "GOTO_HOME" event broadcast
         */
        WidgetHome.listeners['GOTO_HOME'] = $rootScope.$on('GOTO_HOME', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        /**
         * This event listener is bound for "APPLICATION_UPDATED" event broadcast
         */
        WidgetHome.listeners['APPLICATION_UPDATED'] = $rootScope.$on('APPLICATION_UPDATED', function (e, app) {
          if (app.image) {
            WidgetHome.carouselImages = app.image;
            if (WidgetHome.view) {
              WidgetHome.view.loadItems(WidgetHome.carouselImages);
            }
          }
          if (app.content && app.content.description)
            WidgetHome.description = app.content.description;
          RewardCache.setApplication(app);
        });

        /**
         * This event listener is bound for "REFRESH_APP" event broadcast
         */
        WidgetHome.listeners['REFRESH_APP'] = $rootScope.$on('REFRESH_APP', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        WidgetHome.showDescription = function (description) {
          return !((description == '

') || (description == '

'));
        };

        /**
         * Method to parse and show description in html format
         */
        WidgetHome.safeHtml = function (html) {
          if (html)
            return $sce.trustAsHtml(html);
        };

        /*
         * Fetch user's data from datastore
         */

        var init = function () {
          var success = function (result) {
                console.error('Get Loyalty info -----from datastore--------------------------success---------------------------------------',result);
                if(result && result.data){
                  console.log('BUILDFIRE GET--------------------------LOYALTY---------RESULT',result);
                  WidgetHome.data = result.data;
                }
                else{
                  WidgetHome.data={
                    design:{
                      listLayout:LAYOUTS.listLayout[0].name
                    }
                  };
                }
              if (!WidgetHome.data.design)
                WidgetHome.data.design = {};
              if (!WidgetHome.data.settings)
                WidgetHome.data.settings = {};
              if (!WidgetHome.data.design.listLayout) {
                WidgetHome.data.design.listLayout = LAYOUTS.listLayout[0].name;
              }
              if (!WidgetHome.data.design.itemListbackgroundImage) {
                $rootScope.itemListbackgroundImage = "";
              } else {
                $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListbackgroundImage;
              }
              if (!WidgetHome.data.design.itemDetailsBackgroundImage) {
                $rootScope.itemDetailsBackgroundImage = "";
              } else {
                $rootScope.itemDetailsBackgroundImage = WidgetHome.data.design.itemDetailsBackgroundImage;
              }
            }
            , error = function (err) {
                WidgetHome.data={design:{listLayout:LAYOUTS.listLayout[0].name}};
              console.error('Error while getting data', err);
                console.error('Get Loyalty info -----from datastore---------Error-----------------------------------------------------------------------------------',err);
              };
          DataStore.get(TAG_NAMES.LOYALTY_INFO).then(success, error);
          WidgetHome.getApplicationAndRewards();
        };

        var loginCallback = function () {
          buildfire.auth.getCurrentUser(function (err, user) {
            console.log("_______________________", user);
            if (user) {
              WidgetHome.currentLoggedInUser = user;
              WidgetHome.getLoyaltyPoints(user._id);
              $scope.$digest();
            }
          });
        };

        var onUpdateCallback = function (event) {
          console.log("++++++++++++++++++++++++++", event);
          setTimeout(function () {
            if (event && event.tag) {
              switch (event.tag) {
                case TAG_NAMES.LOYALTY_INFO:
                  WidgetHome.data = event.data;
                  if (!WidgetHome.data.design)
                    WidgetHome.data.design = {};
                  if (!WidgetHome.data.design.listLayout) {
                    WidgetHome.data.design.listLayout = LAYOUTS.listLayout[0].name;
                  }
                  if (!WidgetHome.data.design.itemListbackgroundImage) {
                    $rootScope.itemListbackgroundImage = "";
                  } else {
                    $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListbackgroundImage;
                  }
                  if (!WidgetHome.data.design.itemDetailsBackgroundImage) {
                    $rootScope.itemDetailsBackgroundImage = "";
                  } else {
                    $rootScope.itemDetailsBackgroundImage = WidgetHome.data.design.itemDetailsBackgroundImage;
                  }
                  break;
              }
              $scope.$digest();
              $rootScope.$digest();
            }
          }, 0);
        };

        /**
         * DataStore.onUpdate() is bound to listen any changes in datastore
         */
        DataStore.onUpdate().then(null, null, onUpdateCallback);

        /**
         * onLogin() listens when user logins using buildfire.auth api.
         */
        buildfire.auth.onLogin(loginCallback);

        /**
         * Check for current logged in user, if yes fetch its loyalty points
         */
        buildfire.auth.getCurrentUser(function (err, user) {
          console.log("_______________________", user);
          if (user) {
            WidgetHome.currentLoggedInUser = user;
            if (!WidgetHome.context) {
              Context.getContext(function (ctx) {
                console.log('Context     ==============================================================',ctx);
                WidgetHome.context = ctx;
                WidgetHome.getLoyaltyPoints(WidgetHome.currentLoggedInUser._id);
                $scope.$digest();
              });
            } else {
              WidgetHome.getLoyaltyPoints(WidgetHome.currentLoggedInUser._id);
              $scope.$digest();
            }
          }
        });

        $scope.$on("$destroy", function () {
          console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>destroyed");
          for (var i in WidgetHome.listeners) {
            if (WidgetHome.listeners.hasOwnProperty(i)) {
              WidgetHome.listeners[i]();
            }
          }
        });

        Context.getContext(function (ctx) {
          WidgetHome.context = ctx;
          init();
        });

      }]);
})(window.angular, window.buildfire);

<commit_msg>init calling changed<commit_after>'use strict';

(function (angular, buildfire) {
  angular
    .module('loyaltyPluginWidget')
    .controller('WidgetHomeCtrl', ['$scope', 'ViewStack', 'LoyaltyAPI', 'STATUS_CODE', 'TAG_NAMES', 'LAYOUTS', 'DataStore', 'RewardCache', '$rootScope', '$sce', 'Context',
      function ($scope, ViewStack, LoyaltyAPI, STATUS_CODE, TAG_NAMES, LAYOUTS, DataStore, RewardCache, $rootScope, $sce, Context) {
        console.error('Loyalty----------WidgetHomeCtrl--------------------------Loaded----------------------------');

        var WidgetHome = this;

        $rootScope.deviceHeight = window.innerHeight;
        $rootScope.deviceWidth = window.innerWidth;
        $rootScope.itemListbackgroundImage = "";
        $rootScope.itemDetailsBackgroundImage = "";

        //create new instance of buildfire carousel viewer
        WidgetHome.view = null;

        WidgetHome.listeners = {};

        /**
         * Initialize current logged in user as null. This field is re-initialized if user is already logged in or user login user auth api.
         */
        WidgetHome.currentLoggedInUser = null;

        /**
         * Method to open a reward details page.
         */
        WidgetHome.openReward = function (reward) {
          RewardCache.setReward(reward);
          ViewStack.push({
            template: 'Item_Details',
            totalPoints: $rootScope.loyaltyPoints
          });
          buildfire.messaging.sendMessageToControl({
            type: 'OpenItem',
            data: reward
          });
        };

        /**
         * Method to fetch logged in user's loyalty points
         */
        WidgetHome.getLoyaltyPoints = function (userId) {
          var success = function (result) {
              console.error('Points>>>>>>>>>>>>>>>.---------------------------------------------------', result);
              $rootScope.loyaltyPoints = result.totalPoints;
            }
            , error = function (err) {
              if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                console.error('Error while getting points data----------------------------------------', err);
              }
            };
          LoyaltyAPI.getLoyaltyPoints(userId, WidgetHome.currentLoggedInUser.userToken, WidgetHome.context.instanceId).then(success, error);
        };

        /**
         * Method to fetch loyalty application and list of rewards
         */
        WidgetHome.getApplicationAndRewards = function () {
          var successLoyaltyRewards = function (result) {
              WidgetHome.loyaltyRewards = result;
              if (!WidgetHome.loyaltyRewards)
                WidgetHome.loyaltyRewards = [];
              console.error('Rewards> got successfully>>>>>>>>>>>>>.:--------------------------------------', result);
            }
            , errorLoyaltyRewards = function (err) {
                console.error('Error while getting data loyaltyRewards--------------------------------------', err);
                if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                console.error('Error while getting data loyaltyRewards--------------------------------------', err);
              }
            };
          var successApplication = function (result) {
            console.error('Successfully got application----------------------------------------------------------------------',result);
            if (result.image)
              WidgetHome.carouselImages = result.image;
            if (result.content && result.content.description)
              WidgetHome.description = result.content.description;
            RewardCache.setApplication(result);
          };

          var errorApplication = function (error) {
            console.error('Error fetching loyalty application---------------------------------------------------',error);
          };

          console.error("$$$$$$$$$$$$$$$$$$$$$$$---------------context----------------------------------------------", WidgetHome.context);
          if(WidgetHome.context && WidgetHome.context.instanceId){
            LoyaltyAPI.getApplication(WidgetHome.context.instanceId).then(successApplication, errorApplication);
            LoyaltyAPI.getRewards(WidgetHome.context.instanceId).then(successLoyaltyRewards, errorLoyaltyRewards);
          }
          else{
            Context.getContext(function (ctx) {
              console.log('COntext got successfully-----------------' +
                  '');
              WidgetHome.context = ctx;
              LoyaltyAPI.getApplication(WidgetHome.context.instanceId).then(successApplication, errorApplication);
              LoyaltyAPI.getRewards(WidgetHome.context.instanceId).then(successLoyaltyRewards, errorLoyaltyRewards);
            });
          }
        };

        /**
         * Method to show amount page where user can fill in the amount they have made purchase of.
         */
        WidgetHome.openGetPoints = function () {
          console.log(">>>>>>>>>>>>>>-----------------------");
          if (WidgetHome.currentLoggedInUser) {
            ViewStack.push({
              template: 'Amount',
              loyaltyPoints: $rootScope.loyaltyPoints

            });
          }
          else {
            WidgetHome.openLogin();
          }
        };

        /**
         * Method to open buildfire auth login pop up and allow user to login using credentials.
         */
        WidgetHome.openLogin = function () {
          buildfire.auth.login({}, function () {

          });
        };

        /**
         * This event listener is bound for "POINTS_REDEEMED" event broadcast
         */
        WidgetHome.listeners['POINTS_REDEEMED'] = $rootScope.$on('POINTS_REDEEMED', function (e, points) {
          if (points)
            $rootScope.loyaltyPoints = $rootScope.loyaltyPoints - points;
        });

        /**
         * This event listener is bound for "POINTS_ADDED" event broadcast
         */
        WidgetHome.listeners['POINTS_ADDED'] = $rootScope.$on('POINTS_ADDED', function (e, points) {
          if (points)
            $rootScope.loyaltyPoints = $rootScope.loyaltyPoints + points;
        });

        /**
         * This event listener is bound for "REWARD_DELETED" event broadcast
         */
        WidgetHome.listeners['REWARD_DELETED'] = $rootScope.$on('REWARD_DELETED', function (e, index) {
          if (index != -1)
            WidgetHome.loyaltyRewards.splice(index, 1);
        });

        /**
         * This event listener is bound for "REWARDS_SORTED" event broadcast
         */
        WidgetHome.listeners['REWARDS_SORTED'] = $rootScope.$on('REWARDS_SORTED', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        /**
         * This event listener is bound for "Carousel:LOADED" event broadcast
         */
        WidgetHome.listeners['Carousel:LOADED'] = $rootScope.$on("Carousel:LOADED", function () {
          WidgetHome.view = null;
          if (!WidgetHome.view) {
            WidgetHome.view = new buildfire.components.carousel.view("#carousel", [], "WideScreen");
          }
          if (WidgetHome.carouselImages) {
            WidgetHome.view.loadItems(WidgetHome.carouselImages, null, "WideScreen");
          } else {
            WidgetHome.view.loadItems([]);
          }
        });

        /**
         * This event listener is bound for "REWARD_ADDED" event broadcast
         */
        WidgetHome.listeners['REWARD_ADDED'] = $rootScope.$on('REWARD_ADDED', function (e, item) {
          WidgetHome.loyaltyRewards.unshift(item);
        });

        /**
         * This event listener is bound for "GOTO_HOME" event broadcast
         */
        WidgetHome.listeners['GOTO_HOME'] = $rootScope.$on('GOTO_HOME', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        /**
         * This event listener is bound for "APPLICATION_UPDATED" event broadcast
         */
        WidgetHome.listeners['APPLICATION_UPDATED'] = $rootScope.$on('APPLICATION_UPDATED', function (e, app) {
          if (app.image) {
            WidgetHome.carouselImages = app.image;
            if (WidgetHome.view) {
              WidgetHome.view.loadItems(WidgetHome.carouselImages);
            }
          }
          if (app.content && app.content.description)
            WidgetHome.description = app.content.description;
          RewardCache.setApplication(app);
        });

        /**
         * This event listener is bound for "REFRESH_APP" event broadcast
         */
        WidgetHome.listeners['REFRESH_APP'] = $rootScope.$on('REFRESH_APP', function (e) {
          WidgetHome.getApplicationAndRewards();
        });

        WidgetHome.showDescription = function (description) {
          return !((description == '

') || (description == '

'));
        };

        /**
         * Method to parse and show description in html format
         */
        WidgetHome.safeHtml = function (html) {
          if (html)
            return $sce.trustAsHtml(html);
        };

        /*
         * Fetch user's data from datastore
         */

        var init = function () {
          var success = function (result) {
                console.error('Get Loyalty info -----from datastore--------------------------success---------------------------------------',result);
                if(result && result.data){
                  console.log('BUILDFIRE GET--------------------------LOYALTY---------RESULT',result);
                  WidgetHome.data = result.data;
                }
                else{
                  WidgetHome.data={
                    design:{
                      listLayout:LAYOUTS.listLayout[0].name
                    }
                  };
                }
              if (!WidgetHome.data.design)
                WidgetHome.data.design = {};
              if (!WidgetHome.data.settings)
                WidgetHome.data.settings = {};
              if (!WidgetHome.data.design.listLayout) {
                WidgetHome.data.design.listLayout = LAYOUTS.listLayout[0].name;
              }
              if (!WidgetHome.data.design.itemListbackgroundImage) {
                $rootScope.itemListbackgroundImage = "";
              } else {
                $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListbackgroundImage;
              }
              if (!WidgetHome.data.design.itemDetailsBackgroundImage) {
                $rootScope.itemDetailsBackgroundImage = "";
              } else {
                $rootScope.itemDetailsBackgroundImage = WidgetHome.data.design.itemDetailsBackgroundImage;
              }
            }
            , error = function (err) {
                WidgetHome.data={design:{listLayout:LAYOUTS.listLayout[0].name}};
              console.error('Error while getting data', err);
                console.error('Get Loyalty info -----from datastore---------Error-----------------------------------------------------------------------------------',err);
              };
          DataStore.get(TAG_NAMES.LOYALTY_INFO).then(success, error);
          WidgetHome.getApplicationAndRewards();
        };

        var loginCallback = function () {
          buildfire.auth.getCurrentUser(function (err, user) {
            console.log("_______________________", user);
            if (user) {
              WidgetHome.currentLoggedInUser = user;
              WidgetHome.getLoyaltyPoints(user._id);
              $scope.$digest();
            }
          });
        };

        var onUpdateCallback = function (event) {
          console.log("++++++++++++++++++++++++++", event);
          setTimeout(function () {
            if (event && event.tag) {
              switch (event.tag) {
                case TAG_NAMES.LOYALTY_INFO:
                  WidgetHome.data = event.data;
                  if (!WidgetHome.data.design)
                    WidgetHome.data.design = {};
                  if (!WidgetHome.data.design.listLayout) {
                    WidgetHome.data.design.listLayout = LAYOUTS.listLayout[0].name;
                  }
                  if (!WidgetHome.data.design.itemListbackgroundImage) {
                    $rootScope.itemListbackgroundImage = "";
                  } else {
                    $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListbackgroundImage;
                  }
                  if (!WidgetHome.data.design.itemDetailsBackgroundImage) {
                    $rootScope.itemDetailsBackgroundImage = "";
                  } else {
                    $rootScope.itemDetailsBackgroundImage = WidgetHome.data.design.itemDetailsBackgroundImage;
                  }
                  break;
              }
              $scope.$digest();
              $rootScope.$digest();
            }
          }, 0);
        };

        /**
         * DataStore.onUpdate() is bound to listen any changes in datastore
         */
        DataStore.onUpdate().then(null, null, onUpdateCallback);

        /**
         * onLogin() listens when user logins using buildfire.auth api.
         */
        buildfire.auth.onLogin(loginCallback);

        /**
         * Check for current logged in user, if yes fetch its loyalty points
         */
        buildfire.auth.getCurrentUser(function (err, user) {
          console.log("_______________________", user);
          if (user) {
            WidgetHome.currentLoggedInUser = user;
            if (!WidgetHome.context) {
              Context.getContext(function (ctx) {
                console.log('Context     ==============================================================',ctx);
                WidgetHome.context = ctx;
                WidgetHome.getLoyaltyPoints(WidgetHome.currentLoggedInUser._id);
                $scope.$digest();
              });
            } else {
              WidgetHome.getLoyaltyPoints(WidgetHome.currentLoggedInUser._id);
              $scope.$digest();
            }
          }
        });

        $scope.$on("$destroy", function () {
          console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>destroyed");
          for (var i in WidgetHome.listeners) {
            if (WidgetHome.listeners.hasOwnProperty(i)) {
              WidgetHome.listeners[i]();
            }
          }
        });

        Context.getContext(function (ctx) {
          console.log('COntext got successfully-----------------' +
              '');
          WidgetHome.context = ctx;
        });
        init();

      }]);
})(window.angular, window.buildfire);

<|endoftext|>


<commit_before>import departments_directory from '../../api/departments-directory'
import * as mutation_types from '../mutation-types'
import * as action_types from '../action-types'

const state = {
  all: [],
  old_all: [],
  can_edit: false,
  department_types: []
}

const getters = {
  allDepartments: state => state.all,
  oldDepartments: state => state.old_all,
  diff_departments: state => {
    console.log(state.all, state.old_all)
    let diff = []
    let departments = state.all
    for (let row of departments) {
      for (let in_row of state.old_all) {
        if (in_row.pk === row.pk) {
          if (in_row.title !== row.title || in_row.type !== row.type) {
            diff.push(row)
          }
          break
        }
      }
    }
    return diff
  },
  canEditDepartments: state => state.can_edit,
  allTypes: state => state.department_types,
}

const actions = {
  async [action_types.GET_ALL_DEPARTMENTS]({commit}) {
    const answer = await departments_directory.getDepartments()
    let departments = answer.departments
    commit(mutation_types.UPDATE_DEPARTMENTS, {departments})
    commit(mutation_types.UPDATE_OLD_DEPARTMENTS, {departments})
    commit(mutation_types.SET_CAN_EDIT, {can_edit: answer.can_edit})
    commit(mutation_types.SET_TYPES, {department_types: answer.types})
  },

  async [action_types.UPDATE_DEPARTMENTS]({commit, getters}, type_update, to_update) {
    to_update = to_update || getters.diff_departments
    type_update = type_update || 'update'
    if (to_update.length === 0)
      return []
    try {
      const answer = await departments_directory.sendDepartments(type_update, to_update)
      commit(mutation_types.UPDATE_OLD_DEPARTMENTS, {departments: getters.allDepartments})
      if (answer.ok) {
        return to_update
      }
    } catch (e) {
      console.log(e)
    }
    return []
  }
}

const mutations = {
  [mutation_types.UPDATE_DEPARTMENTS](state, {departments}) {
    state.all = departments
  },
  [mutation_types.UPDATE_OLD_DEPARTMENTS](state, {departments}) {
    console.log(departments)
    state.old_all = JSON.parse(JSON.stringify(departments))
  },
  [mutation_types.SET_CAN_EDIT](state, {can_edit}) {
    state.can_edit = can_edit
  },
  [mutation_types.SET_TYPES](state, {department_types}) {
    state.department_types = department_types
  },
  [mutation_types.SET_UPDATED_DEPARTMENT](state, data) {
    for (let i = 0; i < state.all.length; i++) {
      if (state.all[i].pk === data.pk) {
        state.all[i].updated = data.value
        break
      }
    }
  },
}

export default {
  state,
  getters,
  actions,
  mutations,
}
<commit_msg>Debug fix<commit_after>import departments_directory from '../../api/departments-directory'
import * as mutation_types from '../mutation-types'
import * as action_types from '../action-types'

const state = {
  all: [],
  old_all: [],
  can_edit: false,
  department_types: []
}

const getters = {
  allDepartments: state => state.all,
  oldDepartments: state => state.old_all,
  diff_departments: state => {
    // console.log(state.all, state.old_all)
    let diff = []
    let departments = state.all
    for (let row of departments) {
      for (let in_row of state.old_all) {
        if (in_row.pk === row.pk) {
          if (in_row.title !== row.title || in_row.type !== row.type) {
            diff.push(row)
          }
          break
        }
      }
    }
    return diff
  },
  canEditDepartments: state => state.can_edit,
  allTypes: state => state.department_types,
}

const actions = {
  async [action_types.GET_ALL_DEPARTMENTS]({commit}) {
    const answer = await departments_directory.getDepartments()
    let departments = answer.departments
    commit(mutation_types.UPDATE_DEPARTMENTS, {departments})
    commit(mutation_types.UPDATE_OLD_DEPARTMENTS, {departments})
    commit(mutation_types.SET_CAN_EDIT, {can_edit: answer.can_edit})
    commit(mutation_types.SET_TYPES, {department_types: answer.types})
  },

  async [action_types.UPDATE_DEPARTMENTS]({commit, getters}, type_update, to_update) {
    to_update = to_update || getters.diff_departments
    type_update = type_update || 'update'
    if (to_update.length === 0)
      return []
    try {
      const answer = await departments_directory.sendDepartments(type_update, to_update)
      commit(mutation_types.UPDATE_OLD_DEPARTMENTS, {departments: getters.allDepartments})
      if (answer.ok) {
        return to_update
      }
    } catch (e) {
      // console.log(e)
    }
    return []
  }
}

const mutations = {
  [mutation_types.UPDATE_DEPARTMENTS](state, {departments}) {
    state.all = departments
  },
  [mutation_types.UPDATE_OLD_DEPARTMENTS](state, {departments}) {
    // console.log(departments)
    state.old_all = JSON.parse(JSON.stringify(departments))
  },
  [mutation_types.SET_CAN_EDIT](state, {can_edit}) {
    state.can_edit = can_edit
  },
  [mutation_types.SET_TYPES](state, {department_types}) {
    state.department_types = department_types
  },
  [mutation_types.SET_UPDATED_DEPARTMENT](state, data) {
    for (let i = 0; i < state.all.length; i++) {
      if (state.all[i].pk === data.pk) {
        state.all[i].updated = data.value
        break
      }
    }
  },
}

export default {
  state,
  getters,
  actions,
  mutations,
}
<|endoftext|>


<commit_before>const Story = require('../models/Story');
const User = require('../models/User');

const UpdateUtil = {};
UpdateUtil.updateStoryPrice = function(){
  Story.find(function(err, stories){
    stories.forEach(function(story){
      console.log(story.price)
    })
  })
};

UpdateUtil.authorName = function(){

}
UpdateUtil.updateUser = function(){
  const updateVersion = 1;
  const updateObject = { $set: { __v: updateVersion }};

  User.find(function(err, users){
    let updateCount = 0;
    let successCount = 0;
    let totalCount  = users.length;
    users.forEach(function(user){
      if(!user.__v || user.__v !== updateVersion){
        updateCount++;
        User.update(
          {_id: user._id},
          updateObject,
          (err, res) => {
            if(err){console.error(err)}
            else{ successCount++ }
          }
        );
      }
    })
    console.log(`${updateCount}/${totalCount} users updated with ${successCount/updateCount || 100}% success`)
  })
};

module.exports = UpdateUtil;
<commit_msg>adds update utility for authorName<commit_after>const Story = require('../models/Story');
const User = require('../models/User');

const UpdateUtil = {};
UpdateUtil.updateStoryPrice = function(){
  Story.find(function(err, stories){
    stories.forEach(function(story){
      console.log(story.price)
    })
  })
};

UpdateUtil.authorName = function(){
  const updateObject = { $set: { authorName: 'Doctor Dogood' }};
  let updateCount = 0;
  let errorCount = 0;
  Story.find(function(err, stories){
    let totalCount  = stories.length;
    stories.forEach(function(story){
      if(story.authorName === 'Guest Author'){
        updateCount++;
        Story.update(
          {_id: story._id},
          updateObject,
          (err, res) => {
            if(err){errorCount++; console.error(err)}
          }
        );
      }
    })
    console.log(`${updateCount}/${totalCount} stories updated with ${errorCount} errors`)
  })
};

UpdateUtil.updateUser = function(){
  const updateVersion = 1;
  const updateObject = { $set: { __v: updateVersion }};

  User.find(function(err, users){
    let updateCount = 0;
    let errorCount = 0;
    let totalCount  = users.length;
    users.forEach(function(user){
      if(!user.__v || user.__v !== updateVersion){
        updateCount++;
        User.update(
          {_id: user._id},
          updateObject,
          (err, res) => {
            if(err){errorCount++; console.error(err)}
          }
        );
      }
    })
    console.log(`${updateCount}/${totalCount} users updated with ${errorCount} errors`)
  })
};

module.exports = UpdateUtil;
<|endoftext|>


<commit_before>// Miscellaneous geo functions

var Geo;
export default Geo = {};

// Projection constants
Geo.tile_size = 256;
Geo.half_circumference_meters = 20037508.342789244;
Geo.circumference_meters = Geo.half_circumference_meters * 2;
Geo.min_zoom_meters_per_pixel = Geo.circumference_meters / Geo.tile_size; // min zoom draws world as 2 tiles wide
Geo.meters_per_pixel = [];
Geo.meters_per_tile = [];
Geo.max_zoom = 18;
for (var z=0; z <= Geo.max_zoom; z++) {
    Geo.meters_per_pixel[z] = Geo.min_zoom_meters_per_pixel / Math.pow(2, z);
    Geo.meters_per_tile[z] = Geo.circumference_meters / Math.pow(2, z);
}

Geo.metersPerPixel = function (zoom) {
    return Geo.min_zoom_meters_per_pixel / Math.pow(2, zoom);
};

// Conversion functions based on an defined tile scale
Geo.units_per_meter = [];
Geo.tile_scale = 4096; // coordinates are locally scaled to the range [0, tile_scale]
Geo.units_per_pixel = Geo.tile_scale / Geo.tile_size;

for (let z=0; z <= Geo.max_zoom; z++) {
    Geo.units_per_meter[z] = Geo.tile_scale / (Geo.tile_size * Geo.meters_per_pixel[z]);
}

// Convert tile location to mercator meters - multiply by pixels per tile, then by meters per pixel, adjust for map origin
Geo.metersForTile = function (tile) {
    return {
        x: tile.x * Geo.circumference_meters / Math.pow(2, tile.z) - Geo.half_circumference_meters,
        y: -(tile.y * Geo.circumference_meters / Math.pow(2, tile.z) - Geo.half_circumference_meters)
    };
};

/**
   Given a point in mercator meters and a zoom level, return the tile X/Y/Z that the point lies in
*/
Geo.tileForMeters = function ([x, y], zoom) {
    return {
        x: Math.floor((x + Geo.half_circumference_meters) / (Geo.circumference_meters / Math.pow(2, zoom))),
        y: Math.floor((-y + Geo.half_circumference_meters) / (Geo.circumference_meters / Math.pow(2, zoom))),
        z: zoom
    };
};

// Wrap a tile to positive #s for zoom
// Optionally specify the axes to wrap
Geo.wrapTile = function({ x, y, z }, mask = { x: true, y: false }) {
    var m = (1 << z) - 1;
    if (mask.x) {
        x = x & m;
    }
    if (mask.y) {
        y = y & m;
    }
    return { x, y, z };
};

/**
   Convert mercator meters to lat-lng
*/
Geo.metersToLatLng = function ([x, y]) {

    x /= Geo.half_circumference_meters;
    y /= Geo.half_circumference_meters;

    y = (2 * Math.atan(Math.exp(y * Math.PI)) - (Math.PI / 2)) / Math.PI;

    x *= 180;
    y *= 180;

    return [x, y];
};

/**
  Convert lat-lng to mercator meters
*/
Geo.latLngToMeters = function([x, y]) {

    // Latitude
    y = Math.log(Math.tan(y*Math.PI/360 + Math.PI/4)) / Math.PI;
    y *= Geo.half_circumference_meters;

    // Longitude
    x *= Geo.half_circumference_meters / 180;

    return [x, y];
};

Geo.wrapLng = function(x) {
    if (x > 180 || x < -180) {
        x = ((x + 180) % 360 + 360) % 360 - 180;
    }
    return x;
};

// Run an in-place transform function on each cooordinate in a GeoJSON geometry
Geo.transformGeometry = function (geometry, transform) {
    if (geometry == null) {
        return; // skip if missing geometry (valid GeoJSON)
    }

    if (geometry.type === 'Point') {
        transform(geometry.coordinates);
    }
    else if (geometry.type === 'LineString' || geometry.type === 'MultiPoint') {
        geometry.coordinates.forEach(transform);
    }
    else if (geometry.type === 'Polygon' || geometry.type === 'MultiLineString') {
        geometry.coordinates.forEach(coordinates => coordinates.forEach(transform));
    }
    else if (geometry.type === 'MultiPolygon') {
        geometry.coordinates.forEach(polygon => {
            polygon.forEach(coordinates => coordinates.forEach(transform));
        });
    }
    // TODO: support GeometryCollection
};

Geo.boxIntersect = function (b1, b2) {
    return !(
        b2.sw.x > b1.ne.x ||
        b2.ne.x < b1.sw.x ||
        b2.sw.y > b1.ne.y ||
        b2.ne.y < b1.sw.y
    );
};

// Finds the axis-aligned bounding box for a polygon
Geo.findBoundingBox = function (polygon) {
    var min_x = Infinity,
        max_x = -Infinity,
        min_y = Infinity,
        max_y = -Infinity;

    // Only need to examine outer ring (polygon[0])
    var num_coords = polygon[0].length;
    for (var c=0; c < num_coords; c++) {
        var coord = polygon[0][c];

        if (coord[0] < min_x) {
            min_x = coord[0];
        }
        if (coord[1] < min_y) {
            min_y = coord[1];
        }
        if (coord[0] > max_x) {
            max_x = coord[0];
        }
        if (coord[1] > max_y) {
            max_y = coord[1];
        }
    }

    return [min_x, min_y, max_x, max_y];
};

// Convert geometry type to one of: 'point', 'line', 'polygon'
Geo.geometryType = function(type) {
    if (type === 'Polygon' || type === 'MultiPolygon') {
        return 'polygon';
    }
    else if (type === 'LineString' || type === 'MultiLineString') {
        return 'line';
    }
    if (type === 'Point' || type === 'MultiPoint') {
        return 'point';
    }
};

Geo.centroid = function (polygon) {
    let n = polygon.length;
    let centroid = [0, 0];

    for (let p=0; p < polygon.length; p++) {
        centroid[0] += polygon[p][0];
        centroid[1] += polygon[p][1];
    }

    centroid[0] /= n;
    centroid[1] /= n;

    return centroid;
};

Geo.multiCentroid = function (polygons) {
    let n = polygons.length;
    let centroid = [0, 0];

    for (let p=0; p < polygons.length; p++) {
        let polygon = polygons[p][0];
        let c = Geo.centroid(polygon);
        centroid[0] += c[0];
        centroid[1] += c[1];
    }

    centroid[0] /= n;
    centroid[1] /= n;

    return centroid;
};

Geo.signedPolygonAreaSum = function (polygon) {
    let area = 0;
    let n = polygon.length;

    for (let i = 0; i < n - 1; i++) {
        let p0 = polygon[i];
        let p1 = polygon[i+1];

        area += p0[0] * p1[1] - p1[0] * p0[1];
    }

    area += polygon[n - 1][0] * polygon[0][1] - polygon[0][0] * polygon[n - 1][1];
    return area;
};

// TODO: subtract inner ring areas
Geo.polygonArea = function (polygon) {
    return Math.abs(Geo.signedPolygonAreaSum(polygon)) / 2;
};

Geo.multiPolygonArea = function (polygons) {
    let area = 0;

    for (let p=0; p < polygons.length; p++) {
        let polygon = polygons[p][0];
        area += Geo.polygonArea(polygon);
    }

    return area;
};

Geo.ringWinding = function (ring) {
    return Geo.signedPolygonAreaSum(ring) > 0 ? 'CW' : 'CCW';
};

// Enforce winding order on outer/inner rings
// winding: 'CW' or 'CCW'
Geo.enforceWinding = function (geom, winding) {
    let polys;
    if (geom.type === 'Polygon') {
        polys = [geom.coordinates];
    }
    else if (geom.type === 'MultiPolygon') {
        polys = geom.coordinates;
    }
    else {
        return geom;
    }

    for (let p=0; p < polys.length; p++) {
        let poly = polys[p];

        // If first ring winding doesn't match, reverse all rings
        // NOTE: assumes ring winding orders already alternate as expected
        if (Geo.ringWinding(poly[0]) !== winding) {
            for (let ring of poly) {
                ring.reverse();
            }
        }
    }
    return geom;
};
<commit_msg>memoize meters per pixel calc by zoom<commit_after>// Miscellaneous geo functions

var Geo;
export default Geo = {};

// Projection constants
Geo.max_zoom = 18;
Geo.tile_size = 256;
Geo.half_circumference_meters = 20037508.342789244;
Geo.circumference_meters = Geo.half_circumference_meters * 2;
Geo.min_zoom_meters_per_pixel = Geo.circumference_meters / Geo.tile_size; // min zoom draws world as 2 tiles wide
Geo.meters_per_tile = [];

for (var z=0; z <= Geo.max_zoom; z++) {
    Geo.meters_per_tile[z] = Geo.circumference_meters / Math.pow(2, z);
}

let meters_per_pixel = [];
Geo.metersPerPixel = function (z) {
    meters_per_pixel[z] = meters_per_pixel[z] || Geo.min_zoom_meters_per_pixel / Math.pow(2, z);
    return meters_per_pixel[z];
};

Geo.metersPerTile = function (z) {
    return Geo.circumference_meters / Math.pow(2, z);
};

// Conversion functions based on an defined tile scale
Geo.units_per_meter = [];
Geo.tile_scale = 4096; // coordinates are locally scaled to the range [0, tile_scale]
Geo.units_per_pixel = Geo.tile_scale / Geo.tile_size;

for (let z=0; z <= Geo.max_zoom; z++) {
    Geo.units_per_meter[z] = Geo.tile_scale / (Geo.tile_size * Geo.meters_per_pixel[z]);
}

// Convert tile location to mercator meters - multiply by pixels per tile, then by meters per pixel, adjust for map origin
Geo.metersForTile = function (tile) {
    return {
        x: tile.x * Geo.circumference_meters / Math.pow(2, tile.z) - Geo.half_circumference_meters,
        y: -(tile.y * Geo.circumference_meters / Math.pow(2, tile.z) - Geo.half_circumference_meters)
    };
};

/**
   Given a point in mercator meters and a zoom level, return the tile X/Y/Z that the point lies in
*/
Geo.tileForMeters = function ([x, y], zoom) {
    return {
        x: Math.floor((x + Geo.half_circumference_meters) / (Geo.circumference_meters / Math.pow(2, zoom))),
        y: Math.floor((-y + Geo.half_circumference_meters) / (Geo.circumference_meters / Math.pow(2, zoom))),
        z: zoom
    };
};

// Wrap a tile to positive #s for zoom
// Optionally specify the axes to wrap
Geo.wrapTile = function({ x, y, z }, mask = { x: true, y: false }) {
    var m = (1 << z) - 1;
    if (mask.x) {
        x = x & m;
    }
    if (mask.y) {
        y = y & m;
    }
    return { x, y, z };
};

/**
   Convert mercator meters to lat-lng
*/
Geo.metersToLatLng = function ([x, y]) {

    x /= Geo.half_circumference_meters;
    y /= Geo.half_circumference_meters;

    y = (2 * Math.atan(Math.exp(y * Math.PI)) - (Math.PI / 2)) / Math.PI;

    x *= 180;
    y *= 180;

    return [x, y];
};

/**
  Convert lat-lng to mercator meters
*/
Geo.latLngToMeters = function([x, y]) {

    // Latitude
    y = Math.log(Math.tan(y*Math.PI/360 + Math.PI/4)) / Math.PI;
    y *= Geo.half_circumference_meters;

    // Longitude
    x *= Geo.half_circumference_meters / 180;

    return [x, y];
};

Geo.wrapLng = function(x) {
    if (x > 180 || x < -180) {
        x = ((x + 180) % 360 + 360) % 360 - 180;
    }
    return x;
};

// Run an in-place transform function on each cooordinate in a GeoJSON geometry
Geo.transformGeometry = function (geometry, transform) {
    if (geometry == null) {
        return; // skip if missing geometry (valid GeoJSON)
    }

    if (geometry.type === 'Point') {
        transform(geometry.coordinates);
    }
    else if (geometry.type === 'LineString' || geometry.type === 'MultiPoint') {
        geometry.coordinates.forEach(transform);
    }
    else if (geometry.type === 'Polygon' || geometry.type === 'MultiLineString') {
        geometry.coordinates.forEach(coordinates => coordinates.forEach(transform));
    }
    else if (geometry.type === 'MultiPolygon') {
        geometry.coordinates.forEach(polygon => {
            polygon.forEach(coordinates => coordinates.forEach(transform));
        });
    }
    // TODO: support GeometryCollection
};

Geo.boxIntersect = function (b1, b2) {
    return !(
        b2.sw.x > b1.ne.x ||
        b2.ne.x < b1.sw.x ||
        b2.sw.y > b1.ne.y ||
        b2.ne.y < b1.sw.y
    );
};

// Finds the axis-aligned bounding box for a polygon
Geo.findBoundingBox = function (polygon) {
    var min_x = Infinity,
        max_x = -Infinity,
        min_y = Infinity,
        max_y = -Infinity;

    // Only need to examine outer ring (polygon[0])
    var num_coords = polygon[0].length;
    for (var c=0; c < num_coords; c++) {
        var coord = polygon[0][c];

        if (coord[0] < min_x) {
            min_x = coord[0];
        }
        if (coord[1] < min_y) {
            min_y = coord[1];
        }
        if (coord[0] > max_x) {
            max_x = coord[0];
        }
        if (coord[1] > max_y) {
            max_y = coord[1];
        }
    }

    return [min_x, min_y, max_x, max_y];
};

// Convert geometry type to one of: 'point', 'line', 'polygon'
Geo.geometryType = function(type) {
    if (type === 'Polygon' || type === 'MultiPolygon') {
        return 'polygon';
    }
    else if (type === 'LineString' || type === 'MultiLineString') {
        return 'line';
    }
    if (type === 'Point' || type === 'MultiPoint') {
        return 'point';
    }
};

Geo.centroid = function (polygon) {
    let n = polygon.length;
    let centroid = [0, 0];

    for (let p=0; p < polygon.length; p++) {
        centroid[0] += polygon[p][0];
        centroid[1] += polygon[p][1];
    }

    centroid[0] /= n;
    centroid[1] /= n;

    return centroid;
};

Geo.multiCentroid = function (polygons) {
    let n = polygons.length;
    let centroid = [0, 0];

    for (let p=0; p < polygons.length; p++) {
        let polygon = polygons[p][0];
        let c = Geo.centroid(polygon);
        centroid[0] += c[0];
        centroid[1] += c[1];
    }

    centroid[0] /= n;
    centroid[1] /= n;

    return centroid;
};

Geo.signedPolygonAreaSum = function (polygon) {
    let area = 0;
    let n = polygon.length;

    for (let i = 0; i < n - 1; i++) {
        let p0 = polygon[i];
        let p1 = polygon[i+1];

        area += p0[0] * p1[1] - p1[0] * p0[1];
    }

    area += polygon[n - 1][0] * polygon[0][1] - polygon[0][0] * polygon[n - 1][1];
    return area;
};

// TODO: subtract inner ring areas
Geo.polygonArea = function (polygon) {
    return Math.abs(Geo.signedPolygonAreaSum(polygon)) / 2;
};

Geo.multiPolygonArea = function (polygons) {
    let area = 0;

    for (let p=0; p < polygons.length; p++) {
        let polygon = polygons[p][0];
        area += Geo.polygonArea(polygon);
    }

    return area;
};

Geo.ringWinding = function (ring) {
    return Geo.signedPolygonAreaSum(ring) > 0 ? 'CW' : 'CCW';
};

// Enforce winding order on outer/inner rings
// winding: 'CW' or 'CCW'
Geo.enforceWinding = function (geom, winding) {
    let polys;
    if (geom.type === 'Polygon') {
        polys = [geom.coordinates];
    }
    else if (geom.type === 'MultiPolygon') {
        polys = geom.coordinates;
    }
    else {
        return geom;
    }

    for (let p=0; p < polys.length; p++) {
        let poly = polys[p];

        // If first ring winding doesn't match, reverse all rings
        // NOTE: assumes ring winding orders already alternate as expected
        if (Geo.ringWinding(poly[0]) !== winding) {
            for (let ring of poly) {
                ring.reverse();
            }
        }
    }
    return geom;
};
<|endoftext|>


<commit_before>/* eslint-env mocha */
import { expect } from 'chai';
import Vue from 'vue-test'; // eslint-disable-line
import { mount } from '@vue/test-utils';
import sinon from 'sinon';
import contentRenderer from '../src/views/content-renderer';

describe('contentRenderer Component', () => {
  const defaultFiles = [
    {
      available: true,
      extension: 'tst',
    },
  ];

  function defaultPropsDataFromFiles(files = defaultFiles) {
    return {
      id: 'testing',
      kind: 'test',
      files,
    };
  }

  describe('computed property', () => {
    describe('availableFiles', () => {
      function testAvailableFiles(files, expected) {
        const wrapper = mount(contentRenderer, {
          propsData: defaultPropsDataFromFiles(files),
        });
        expect(wrapper.vm.availableFiles.length).to.equal(expected);
      }

      it('should be 1 when there is one available file', () => {
        testAvailableFiles(defaultFiles, 1);
      });

      it('should be 1 when there is one available file and a supplementary file', () => {
        const newFiles = defaultFiles.concat({
          available: true,
          supplementary: true,
          extension: 'vtt',
        });
        testAvailableFiles(newFiles, 1);
      });

      it('should be 1 when there is one available file and a thumbnail file', () => {
        const newFiles = defaultFiles.concat({
          available: true,
          thumbnail: true,
          extension: 'vtt',
        });
        testAvailableFiles(newFiles, 1);
      });

      it('should be 2 when there are two available files', () => {
        const newFiles = defaultFiles.concat({
          available: true,
          extension: 'vtt',
        });
        testAvailableFiles(newFiles, 2);
      });
    });

    describe('defaultFile', () => {
      function testDefaultFile(files, expected) {
        const wrapper = mount(contentRenderer, {
          propsData: defaultPropsDataFromFiles(files),
        });
        expect(wrapper.vm.defaultFile).to.equal(expected);
      }

      it('should be the file when there is one available file', () => {
        testDefaultFile(defaultFiles, defaultFiles[0]);
      });

      it('should be undefined when there are no available files', () => {
        testDefaultFile([], undefined);
      });
    });

    describe('extension', () => {
      function testExtension(files, expected) {
        const wrapper = mount(contentRenderer, {
          propsData: defaultPropsDataFromFiles(files),
        });
        expect(wrapper.vm.extension).to.equal(expected);
      }

      it("should be the file's extension when there is one available file", () => {
        testExtension(defaultFiles, defaultFiles[0].extension);
      });

      it('should be undefined when there are no available files', () => {
        testExtension([], undefined);
      });
    });
  });

  describe('method', () => {
    describe('updateRendererComponent', () => {
      describe('when content is available', () => {
        describe('when renderer is available', () => {
          const dummyComponent = { test: 'testing' };
          before(() => {
            Vue.prototype.Kolibri = {
              retrieveContentRenderer: () => Promise.resolve(dummyComponent),
            };
          });

          after(() => {
            Vue.prototype.Kolibri = {};
          });

          it('should set currentViewClass to returned component', () => {
            const props = Object.assign(defaultPropsDataFromFiles(), {
              available: true,
            });
            const wrapper = mount(contentRenderer, {
              propsData: props,
            });
            return Vue.nextTick().then(() => {
              expect(wrapper.vm.currentViewClass).to.deep.equal(dummyComponent);
            });
          });

          it('should call initSession', () => {
            const props = Object.assign(defaultPropsDataFromFiles(), {
              available: true,
              initSession: sinon.stub().returns(Promise.resolve()),
            });
            const wrapper = mount(contentRenderer, {
              propsData: props,
            });
            return Vue.nextTick().then(() => {
              sinon.assert.calledOnce(wrapper.vm.initSession);
            });
          });
        });

        describe('when no renderer is available', () => {
          before(() => {
            Vue.prototype.Kolibri = {
              retrieveContentRenderer: () => Promise.reject({ message: 'oh no' }),
            };
          });

          after(() => {
            Vue.prototype.Kolibri = {};
          });

          it('calling updateRendererComponent should set noRendererAvailable to true', () => {
            const props = Object.assign(defaultPropsDataFromFiles(), {
              available: true,
            });
            const wrapper = mount(contentRenderer, {
              propsData: props,
            });
            // 'created' hook runs it once. Running it here again for testing.
            // TODO Look into how to do this without calling the method directly
            return wrapper.vm.updateRendererComponent().then(() => {
              expect(wrapper.vm.noRendererAvailable).to.be.true;
            });
          });
        });
      });

      describe('when content is not available', () => {
        it('should return null', () => {
          const props = Object.assign(defaultPropsDataFromFiles(), {
            available: false,
          });
          const wrapper = mount(contentRenderer, {
            propsData: props,
          });
          // 'created' hook runs it once. Running it here again for testing.
          return wrapper.vm.updateRendererComponent().then(component => {
            expect(component).to.equal(null);
          });
        });
      });
    });
  });
});
<commit_msg>Fixing existing tests for content renderer.<commit_after>/* eslint-env mocha */
import { expect } from 'chai';
import Vue from 'vue-test'; // eslint-disable-line
import { mount } from '@vue/test-utils';
import sinon from 'sinon';
import contentRenderer from '../src/views/content-renderer';

Vue.prototype.Kolibri = {
  canRenderContent: () => true,
};

describe('contentRenderer Component', () => {
  const defaultFiles = [
    {
      available: true,
      extension: 'tst',
    },
  ];

  function defaultPropsDataFromFiles(files = defaultFiles) {
    return {
      id: 'testing',
      kind: 'test',
      files,
    };
  }

  describe('computed property', () => {
    describe('availableFiles', () => {
      function testAvailableFiles(files, expected) {
        const wrapper = mount(contentRenderer, {
          propsData: defaultPropsDataFromFiles(files),
        });
        expect(wrapper.vm.availableFiles.length).to.equal(expected);
      }

      it('should be 1 when there is one available file', () => {
        testAvailableFiles(defaultFiles, 1);
      });

      it('should be 1 when there is one available file and a supplementary file', () => {
        const newFiles = defaultFiles.concat({
          available: true,
          supplementary: true,
          extension: 'vtt',
        });
        testAvailableFiles(newFiles, 1);
      });

      it('should be 1 when there is one available file and a thumbnail file', () => {
        const newFiles = defaultFiles.concat({
          available: true,
          thumbnail: true,
          extension: 'vtt',
        });
        testAvailableFiles(newFiles, 1);
      });

      it('should be 2 when there are two available files', () => {
        const newFiles = defaultFiles.concat({
          available: true,
          extension: 'vtt',
        });
        testAvailableFiles(newFiles, 2);
      });
    });

    describe('defaultFile', () => {
      function testDefaultFile(files, expected) {
        const wrapper = mount(contentRenderer, {
          propsData: defaultPropsDataFromFiles(files),
        });
        expect(wrapper.vm.defaultFile).to.equal(expected);
      }

      it('should be the file when there is one available file', () => {
        testDefaultFile(defaultFiles, defaultFiles[0]);
      });

      it('should be undefined when there are no available files', () => {
        testDefaultFile([], undefined);
      });
    });

    describe('extension', () => {
      function testExtension(files, expected) {
        const wrapper = mount(contentRenderer, {
          propsData: defaultPropsDataFromFiles(files),
        });
        expect(wrapper.vm.extension).to.equal(expected);
      }

      it("should be the file's extension when there is one available file", () => {
        testExtension(defaultFiles, defaultFiles[0].extension);
      });

      it('should be undefined when there are no available files', () => {
        testExtension([], undefined);
      });
    });
  });

  describe('method', () => {
    describe('updateRendererComponent', () => {
      describe('when content is available', () => {
        describe('when renderer is available', () => {
          const dummyComponent = { test: 'testing' };
          before(() => {
            Vue.prototype.Kolibri.retrieveContentRenderer = () => Promise.resolve(dummyComponent);
          });

          after(() => {
            delete Vue.prototype.Kolibri.retrieveContentRenderer;
          });

          it('should set currentViewClass to returned component', () => {
            const props = Object.assign(defaultPropsDataFromFiles(), {
              available: true,
            });
            const wrapper = mount(contentRenderer, {
              propsData: props,
            });
            return Vue.nextTick().then(() => {
              expect(wrapper.vm.currentViewClass).to.deep.equal(dummyComponent);
            });
          });

          it('should call initSession', () => {
            const props = Object.assign(defaultPropsDataFromFiles(), {
              available: true,
              initSession: sinon.stub().returns(Promise.resolve()),
            });
            const wrapper = mount(contentRenderer, {
              propsData: props,
            });
            return Vue.nextTick().then(() => {
              sinon.assert.calledOnce(wrapper.vm.initSession);
            });
          });
        });

        describe('when no renderer is available', () => {
          before(() => {
            Vue.prototype.Kolibri.retrieveContentRenderer = () =>
              Promise.reject({ message: 'oh no' });
          });

          after(() => {
            delete Vue.prototype.Kolibri.retrieveContentRenderer;
          });

          it('calling updateRendererComponent should set noRendererAvailable to true', () => {
            const props = Object.assign(defaultPropsDataFromFiles(), {
              available: true,
            });
            const wrapper = mount(contentRenderer, {
              propsData: props,
            });
            // 'created' hook runs it once. Running it here again for testing.
            // TODO Look into how to do this without calling the method directly
            return wrapper.vm.updateRendererComponent().then(() => {
              expect(wrapper.vm.noRendererAvailable).to.be.true;
            });
          });
        });
      });

      describe('when content is not available', () => {
        it('should return null', () => {
          const props = Object.assign(defaultPropsDataFromFiles(), {
            available: false,
          });
          const wrapper = mount(contentRenderer, {
            propsData: props,
          });
          // 'created' hook runs it once. Running it here again for testing.
          return wrapper.vm.updateRendererComponent().then(component => {
            expect(component).to.equal(null);
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>import proj4 from 'proj4';

export default function ProjectorFactory(options) {
    let {from, to, immutable = true} = options;
    let projections = immutable ? new WeakMap() : undefined;

    return function project(source) {
        let projection = projections && projections.get(source);

        if (!projection) {
            if (source instanceof Array) {
                if (source[0] instanceof Array) {
                    projection = source.map(project);
                } else {
                    projection = proj4(from, to, source.slice());
                }
            } else {
                let {type} = source;
                switch(type) {
                    case 'FeatureCollection': {
                        let {features} = source;
                        features = features.map(project);
                        projection = {...source, features};
                        break;
                    }
                    case 'Feature': {
                        let {geometry} = source;
                        geometry = project(geometry);
                        projection = {...source, geometry};
                        break;
                    }
                    case 'Point':
                    case 'Polygon':
                    case 'LineString': {
                        let {coordinates} = source;
                        coordinates = project(coordinates);
                        projection = {...source, coordinates};
                        break;
                    }
                    default: {
                        throw new Error(`Can not project ${type} of ${source}`);
                    }
                }
            }
            projections && projections.set(source, projection);
        }
        return projection;
    };
}
<commit_msg>geojson objects description list extended<commit_after>import proj4 from 'proj4';

const TRANSFORMED_PROPS = [
    'features',
    'geometry',
    'geometries',
    'bbox',
    'coordinates'
];

export default function ProjectorFactory(options) {
    let {from, to, immutable = true} = options;
    let projections = immutable ? new WeakMap() : undefined;

    return function project(source) {
        let projection = projections && projections.get(source);

        if (!projection) {
            if (source instanceof Array) {
                if (typeof source[0] === 'number') {
                    projection = proj4(from, to, source.slice());
                } else {
                    projection = source.map(project);
                }
            } else {
                let {type} = source;
                switch(type) {
                    case 'GeometryCollection':
                    case 'FeatureCollection':
                    case 'Feature':
                    case 'Point':
                    case 'MultiPoint':
                    case 'Polygon':
                    case 'MultiPolygon':
                    case 'LineString':
                    case 'MultiLineString': {
                        projection = {...source};
                        for(let prop of TRANSFORMED_PROPS) {
                            if (prop in projection) {
                                projection[prop] = project(projection[prop]);
                            }
                        }
                        break;
                    }
                    default: {
                        throw new Error(`Can not project ${type} of ${source}`);
                    }
                }
            }
            projections && projections.set(source, projection);
        }
        return projection;
    };
}
<|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-spam-filter@3ch01c
// @name           IITC plugin: spam-filter
// @category       Misc
// @version        0.0.2
// @namespace      https://github.com/3ch01c/ingress-intel-total-conversion
// @description    This is a spam filter plugin which filters out SPAM from Comm messages.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @include        https://www.ingress.com/mission/*
// @include        http://www.ingress.com/mission/*
// @match          https://www.ingress.com/mission/*
// @match          http://www.ingress.com/mission/*
// @grant          none
// @updateURL      https://github.com/Eccenux/iitc-plugin-spam-filter/raw/master/spamfilter.meta.js
// @downloadURL    https://github.com/Eccenux/iitc-plugin-spam-filter/raw/master/spamfilter.user.js
// ==/UserScript==

function wrapper(plugin_info) {
// ensure plugin framework is there, even if iitc is not yet loaded
if(typeof window.plugin !== 'function') window.plugin = function() {};

// setup plugin
var setup = function() {
	var renderData_orig = window.chat.renderData;

	// spam filter
	window.chat.renderData = function(data, element, likelyWereOldMsgs) {
		var filteredData = {};
		for (var key in data) {
			var user = data[key][3];
			if (user.search(/^(enl|res)[0-9]+$/)>=0) {
				continue;
			}
			var text = data[key][2];
			if (text.search(/xmps\.biz|ingress-shop|shop-ingress|ingressfarm\.com/i)>=0) {
				continue;
			}
			filteredData[key] = data[key];
		}
		renderData_orig(filteredData, element, likelyWereOldMsgs);
	}
}

//PLUGIN END //////////////////////////////////////////////////////////

setup.info = plugin_info; //add the script info data to the function as a property

if(!window.bootPlugins) window.bootPlugins = [];

window.bootPlugins.push(setup);

// if IITC has already booted, immediately run the 'setup' function
if(window.iitcLoaded && typeof setup === 'function') setup();

} // wrapper end

// inject code into site context
var script = document.createElement('script');
var info = {};
if (typeof GM_info !== 'undefined' && GM_info && GM_info.script) info.script = { version: GM_info.script.version, name: GM_info.script.name, description: GM_info.script.description };
script.appendChild(document.createTextNode('('+ wrapper +')('+JSON.stringify(info)+');'));
(document.body || document.head || document.documentElement).appendChild(script);

<commit_msg>version .3<commit_after>// ==UserScript==
// @id             iitc-plugin-spam-filter@3ch01c
// @name           IITC plugin: spam-filter
// @category       Misc
// @version        0.0.3
// @namespace      https://github.com/3ch01c/ingress-intel-total-conversion
// @description    This is a spam filter plugin which filters out SPAM from Comm messages.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @include        https://www.ingress.com/mission/*
// @include        http://www.ingress.com/mission/*
// @match          https://www.ingress.com/mission/*
// @match          http://www.ingress.com/mission/*
// @grant          none
// @updateURL      https://github.com/Eccenux/iitc-plugin-spam-filter/raw/master/spamfilter.meta.js
// @downloadURL    https://github.com/Eccenux/iitc-plugin-spam-filter/raw/master/spamfilter.user.js
// ==/UserScript==

function wrapper(plugin_info) {
// ensure plugin framework is there, even if iitc is not yet loaded
if(typeof window.plugin !== 'function') window.plugin = function() {};

// setup plugin
var setup = function() {
	var renderData_orig = window.chat.renderData;

	// spam filter
	window.chat.renderData = function(data, element, likelyWereOldMsgs) {
		var filteredData = {};
		for (var key in data) {
			var user = data[key][3];
			if (user.search(/^(enl|res)[0-9]+$/)>=0) {
				continue;
			}
			var text = data[key][2];
			if (text.search(/xmps\.biz|ingress-shop|shop-ingress|ingressfarm\.com/i)>=0) {
				continue;
			}
			filteredData[key] = data[key];
		}
		renderData_orig(filteredData, element, likelyWereOldMsgs);
	}
}

//PLUGIN END //////////////////////////////////////////////////////////

setup.info = plugin_info; //add the script info data to the function as a property

if(!window.bootPlugins) window.bootPlugins = [];

window.bootPlugins.push(setup);

// if IITC has already booted, immediately run the 'setup' function
if(window.iitcLoaded && typeof setup === 'function') setup();

} // wrapper end

// inject code into site context
var script = document.createElement('script');
var info = {};
if (typeof GM_info !== 'undefined' && GM_info && GM_info.script) info.script = { version: GM_info.script.version, name: GM_info.script.name, description: GM_info.script.description };
script.appendChild(document.createTextNode('('+ wrapper +')('+JSON.stringify(info)+');'));
(document.body || document.head || document.documentElement).appendChild(script);

<|endoftext|>