<commit_before>var
  // nodejs child_process object
  cp = require('child_process'),

  // The executor of system process
  exec = cp.exec,

  // The executor of system process
  execSync = cp.execSync,

  // Native event object
  events = require('events'),

  // Native node util class
  util = require('util'),

  ENV = process.env;

ENV.LANG = 'en_US';

/**
 * @class Git
 */
function Git() {
  this.whoiam = 'Git class that perform git operations';
}

util.inherits(Git, events.EventEmitter);

/**
 * @function getCurrentBranch - Return current branch of a git repository
 *
 * @param  {string} path - Path of the git repository
 * @param  {function} callback - Callback to be execute in error or success case
 */
Git.prototype.getCurrentBranch = function (path, callback) {
  exec('git branch -r && git symbolic-ref --short HEAD', { cwd: path, env: ENV }, function (error, stdout, stderr) {
    var err = null,
      localBranchs = stdout.split('\n'),
      currentBranch,
      remoteBranchs = [];

    if (error !== null) {
      err = error;
    } else {

      for (var i = 0; i < (localBranchs.length - 2); i++) {

        if (localBranchs[i].indexOf('HEAD') == -1) {
          localBranchs[i] = localBranchs[i].replace('origin/', '');

          if (localBranchs[i]) {
            remoteBranchs.push(localBranchs[i]);
          }
        }
      }

      currentBranch = localBranchs[localBranchs.length - 2];
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, currentBranch, remoteBranchs);
    }
  }.bind(this));
};

/**
 * @function getCommitHistory - Return a array with the commit history
 *
 * @param  {string} path - Path of the git repository
 * @param  {function} callback - Callback to be execute in error or success case
 */
Git.prototype.getCommitHistory = function (opts, callback) {

  exec(
    "git --no-pager log -n 50 --pretty=format:%an-gtseparator-%cr-gtseparator-%h-gtseparator-%s-gtseparator-%b-pieLineBreak-" + (opts.skip ? ' --skip '.concat(opts.skip) : '' ),

    { cwd: opts.path, env: ENV },

    function (error, stdout, stderr) {
    var lines = stdout.split('-pieLineBreak-'),
      historyList = [],
      err = null;

    if (error !== null) {
      err = error;
    } else {

      for (var i = 0; i < lines.length; i++) {

        if (lines[i] !== '') {
          var historyItem = lines[i].split('-gtseparator-');

          historyList.push({
            user: historyItem[0],
            date: historyItem[1],
            hash: historyItem[2],
            message: historyItem[3],
            body: historyItem[4]
          });
        }
      }
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, historyList);
    }
  });
};

/**
 * @function getStatus - Return the status of the repository
 *
 * @param  {string} path - Path of the git repository
 * @param  {function} callback - Callback to be execute in error or success case
 */
Git.prototype.getStatus = function (path, callback) {

  exec('git status -sb', {cwd: path, env: ENV}, function (error, stdout, stderr) {
    var err = null,
      syncStatus = {
        ahead: null,
        behind: null
      },
      files = [];

    if (error !== null) {
      err = error;
    }

    var lines = stdout.split('\n'),
      unsynChanges;

    // First line ever the sync numbers status
    unsynChanges = lines[0].substring(lines[0].lastIndexOf("[") + 1, lines[0].lastIndexOf("]"));

    var unsyncParts = unsynChanges.split(',');

    unsyncParts.forEach(function (i) {
      var item = i.trim();

      if (item.indexOf('ahead') > -1) {
        syncStatus.ahead = item.substring(item.lastIndexOf('ahead') + 5, item.length).trim();
      } else if (item.indexOf('behind') > -1) {
        syncStatus.behind = item.substring(item.lastIndexOf('behind ') + 6, item.length).trim();
      }
    });

    for (var i = 1; i < lines.length; i++) {

      if (lines[i].trim()[0] == 'M') {
        files.push({
          type: 'MODIFIED',
          path: lines[i].replace('M', '').trim()
        });
      } else if(lines[i].trim()[0] == '?') {
        files.push({
          type: 'NEW', //UNTRACKED
          path: lines[i].replace('??', '').trim()
        });
      } else if(lines[i].trim()[0] == 'D') {
        files.push({
          type: 'DELETED',
          path: lines[i].replace('D', '').trim()
        });
      }
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, syncStatus, files);
    }
  });
};

Git.prototype.fetch = function (path, callback) {

  exec('git fetch --prune', {cwd: path, env: ENV}, function (error, stdout, stderr) {
    var err = null;

    if (error) {
      err = error.message;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err);
    }
  });
};

Git.prototype.getDiff = function (opts, callback) {

  exec('git diff --numstat ' + opts.ancestorHash + ' ' + opts.hash, { cwd: opts.path, env: ENV}, function (error, stdout, stderr) {
    var err = null,
      files = [];

    if (error !== null) {
      err = error;
    } else {
      var lines = stdout.split('\n');

      lines.forEach(function (line) {

        if (line) {
          var props = line.split('\t');

          files.push({
            name: props[2],
            additions: parseInt(props[0]),
            deletions: parseInt(props[1]),
            isBinary: (props[0] == '-' || props[1] == '-') ? true : false
          });
        }
      });
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, files);
    }
  });
};

Git.prototype.getUnsyncFileDiff = function (opts, callback) {
  opts = opts || {};
  var path = opts.path,
    file = opts.file;

  exec('git diff HEAD ' + file, { cwd: path,  env: ENV}, function(error, stdout, stderr) {
    var err = null;

    if (error !== null) {
      err = error;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, stdout);
    }
  });
};

Git.prototype.getFileDiff = function (opts, callback) {

  exec('git log --format=\'%N\' -p -1 ' + opts.hash + ' -- ' + opts.file, { cwd: opts.path, env: ENV}, function (error, stdout, stderr) {
    var err = null;

    if (error !== null) {
      err = error;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, stdout);
    }
  });
};

Git.prototype.sync = function (opts, callback) {

  exec('git pull', { cwd: opts.path,  env: ENV}, function (error, stdout, stderr) {
    var err = null;

    if (error !== null) {
      err = error;
    } else {

      try {
        execSync('git push origin ' + opts.branch, { cwd: opts.path,  env: ENV});
      } catch (pushError) {
        err = pushError.message;
      }
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err);
    }
  });
};

Git.prototype.add = function (path, opts) {

  if (opts.forceSync) {
    return execSync('git add '.concat(opts.file), { cwd: path});
  } else {

    exec(
      'git add '.concat(opts.file),
      { cwd: path}, function (error, stdout, stderr) {
      var err = null;

      if (error !== null) {
        err = error;
      }

      if (opts.callback && typeof opts.callback == 'function') {
        opts.callback.call(this, err);
      }
    });
  }
};

Git.prototype.commit = function (path, opts) {
  var commad = 'git commit -m "'.concat(opts.message).concat('"');

  if (opts.description) {
    commad = commad.concat(' -m "').concat(opts.description).concat('"');
  }

  if (opts.forceSync) {
    return execSync(commad, { cwd: path});
  } else {

    exec(commad, { cwd: path}, function (error, stdout, stderr) {
      var err = null;

      if (error !== null) {
        err = error;
      }

      if (opts.callback && typeof opts.callback == 'function') {
        opts.callback.call(this, err);
      }
    });
  }
};

Git.prototype.switchBranch = function (opts, callback) {
  opts = opts || {};
  var path = opts.path,
    branch = opts.branch,
    forceCreateIfNotExists = opts.forceCreateIfNotExists;

  exec('git checkout ' + (forceCreateIfNotExists ? ' -b ': '') + branch, { cwd: path,  env: ENV}, function(error, stdout, stderr) {
    var err = null;

    if (error !== null) {
      err = error.message;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err);
    }
  });
};

Git.prototype.getCommitCount = function (path, callback) {

  exec('git rev-list HEAD --count', { cwd: path,  env: ENV}, function  (error, stdout, stderr){
    var err = null;

    if (error !== null) {
      err = error.message;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, stdout);
    }
  });
};

Git.prototype.listRemotes = function (path, callback) {

  exec('git remote -v', { cwd: path,  env: ENV}, function (error, stdout, stderr) {
    var err = null;

    if (error !== null) {
      err = error.message;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, stdout);
    }
  });
};

Git.prototype.discartChangesInFile = function (path, opts) {
  var command;

  opts = opts || {};

  if (opts.isUnknow) {
    command = 'git clean -df '.concat(opts.file);
  } else {
    command = 'git checkout -- '.concat(opts.file);
  }

  if (opts.forceSync) {
    return execSync(command, { cwd: path,  env: ENV });
  } else {

    exec(command, { cwd: path,  env: ENV}, function (error, stdout, stderr) {
      var err = null;

      if (error !== null) {
        err = error.message;
      }

      if (opts.callback && typeof opts.callback == 'function') {
        opts.callback.call(this, err, stdout);
      }
    });
  }
};

Git.prototype.getTag = function (path, callback) {

  exec('git tag', { cwd: path,  env: ENV}, function (error, stdout, stderr) {
    var err = null,
      tags = [];

    if (error !== null) {
      err = error.message;
    } else {
      var lines = stdout.split('\n');

      lines.forEach(function (tag) {

        if (tag !== '') {
          tags.push(tag);
        }
      });
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, tags);
    }
  });
};

module.exports = new Git();
<commit_msg>Added email in getCommitHistory method<commit_after>var
  // nodejs child_process object
  cp = require('child_process'),

  // The executor of system process
  exec = cp.exec,

  // The executor of system process
  execSync = cp.execSync,

  // Native event object
  events = require('events'),

  // Native node util class
  util = require('util'),

  ENV = process.env;

ENV.LANG = 'en_US';

/**
 * @class Git
 */
function Git() {
  this.whoiam = 'Git class that perform git operations';
}

util.inherits(Git, events.EventEmitter);

/**
 * @function getCurrentBranch - Return current branch of a git repository
 *
 * @param  {string} path - Path of the git repository
 * @param  {function} callback - Callback to be execute in error or success case
 */
Git.prototype.getCurrentBranch = function (path, callback) {
  exec('git branch -r && git symbolic-ref --short HEAD', { cwd: path, env: ENV }, function (error, stdout, stderr) {
    var err = null,
      localBranchs = stdout.split('\n'),
      currentBranch,
      remoteBranchs = [];

    if (error !== null) {
      err = error;
    } else {

      for (var i = 0; i < (localBranchs.length - 2); i++) {

        if (localBranchs[i].indexOf('HEAD') == -1) {
          localBranchs[i] = localBranchs[i].replace('origin/', '');

          if (localBranchs[i]) {
            remoteBranchs.push(localBranchs[i]);
          }
        }
      }

      currentBranch = localBranchs[localBranchs.length - 2];
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, currentBranch, remoteBranchs);
    }
  }.bind(this));
};

/**
 * @function getCommitHistory - Return a array with the commit history
 *
 * @param  {string} path - Path of the git repository
 * @param  {function} callback - Callback to be execute in error or success case
 */
Git.prototype.getCommitHistory = function (opts, callback) {

  exec(
    "git --no-pager log -n 50 --pretty=format:%an-gtseparator-%cr-gtseparator-%h-gtseparator-%s-gtseparator-%b-gtseparator-%ae-pieLineBreak-" + (opts.skip ? ' --skip '.concat(opts.skip) : '' ),

    { cwd: opts.path, env: ENV },

    function (error, stdout, stderr) {
    var lines = stdout.split('-pieLineBreak-'),
      historyList = [],
      err = null;

    if (error !== null) {
      err = error;
    } else {

      for (var i = 0; i < lines.length; i++) {

        if (lines[i] !== '') {
          var historyItem = lines[i].split('-gtseparator-');

          historyList.push({
            user: historyItem[0],
            date: historyItem[1],
            hash: historyItem[2],
            message: historyItem[3],
            body: historyItem[4],
            email: historyItem[5]
          });
        }
      }
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, historyList);
    }
  });
};

/**
 * @function getStatus - Return the status of the repository
 *
 * @param  {string} path - Path of the git repository
 * @param  {function} callback - Callback to be execute in error or success case
 */
Git.prototype.getStatus = function (path, callback) {

  exec('git status -sb', {cwd: path, env: ENV}, function (error, stdout, stderr) {
    var err = null,
      syncStatus = {
        ahead: null,
        behind: null
      },
      files = [];

    if (error !== null) {
      err = error;
    }

    var lines = stdout.split('\n'),
      unsynChanges;

    // First line ever the sync numbers status
    unsynChanges = lines[0].substring(lines[0].lastIndexOf("[") + 1, lines[0].lastIndexOf("]"));

    var unsyncParts = unsynChanges.split(',');

    unsyncParts.forEach(function (i) {
      var item = i.trim();

      if (item.indexOf('ahead') > -1) {
        syncStatus.ahead = item.substring(item.lastIndexOf('ahead') + 5, item.length).trim();
      } else if (item.indexOf('behind') > -1) {
        syncStatus.behind = item.substring(item.lastIndexOf('behind ') + 6, item.length).trim();
      }
    });

    for (var i = 1; i < lines.length; i++) {

      if (lines[i].trim()[0] == 'M') {
        files.push({
          type: 'MODIFIED',
          path: lines[i].replace('M', '').trim()
        });
      } else if(lines[i].trim()[0] == '?') {
        files.push({
          type: 'NEW', //UNTRACKED
          path: lines[i].replace('??', '').trim()
        });
      } else if(lines[i].trim()[0] == 'D') {
        files.push({
          type: 'DELETED',
          path: lines[i].replace('D', '').trim()
        });
      }
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, syncStatus, files);
    }
  });
};

Git.prototype.fetch = function (path, callback) {

  exec('git fetch --prune', {cwd: path, env: ENV}, function (error, stdout, stderr) {
    var err = null;

    if (error) {
      err = error.message;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err);
    }
  });
};

Git.prototype.getDiff = function (opts, callback) {

  exec('git diff --numstat ' + opts.ancestorHash + ' ' + opts.hash, { cwd: opts.path, env: ENV}, function (error, stdout, stderr) {
    var err = null,
      files = [];

    if (error !== null) {
      err = error;
    } else {
      var lines = stdout.split('\n');

      lines.forEach(function (line) {

        if (line) {
          var props = line.split('\t');

          files.push({
            name: props[2],
            additions: parseInt(props[0]),
            deletions: parseInt(props[1]),
            isBinary: (props[0] == '-' || props[1] == '-') ? true : false
          });
        }
      });
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, files);
    }
  });
};

Git.prototype.getUnsyncFileDiff = function (opts, callback) {
  opts = opts || {};
  var path = opts.path,
    file = opts.file;

  exec('git diff HEAD ' + file, { cwd: path,  env: ENV}, function(error, stdout, stderr) {
    var err = null;

    if (error !== null) {
      err = error;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, stdout);
    }
  });
};

Git.prototype.getFileDiff = function (opts, callback) {

  exec('git log --format=\'%N\' -p -1 ' + opts.hash + ' -- ' + opts.file, { cwd: opts.path, env: ENV}, function (error, stdout, stderr) {
    var err = null;

    if (error !== null) {
      err = error;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, stdout);
    }
  });
};

Git.prototype.sync = function (opts, callback) {

  exec('git pull', { cwd: opts.path,  env: ENV}, function (error, stdout, stderr) {
    var err = null;

    if (error !== null) {
      err = error;
    } else {

      try {
        execSync('git push origin ' + opts.branch, { cwd: opts.path,  env: ENV});
      } catch (pushError) {
        err = pushError.message;
      }
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err);
    }
  });
};

Git.prototype.add = function (path, opts) {

  if (opts.forceSync) {
    return execSync('git add '.concat(opts.file), { cwd: path});
  } else {

    exec(
      'git add '.concat(opts.file),
      { cwd: path}, function (error, stdout, stderr) {
      var err = null;

      if (error !== null) {
        err = error;
      }

      if (opts.callback && typeof opts.callback == 'function') {
        opts.callback.call(this, err);
      }
    });
  }
};

Git.prototype.commit = function (path, opts) {
  var commad = 'git commit -m "'.concat(opts.message).concat('"');

  if (opts.description) {
    commad = commad.concat(' -m "').concat(opts.description).concat('"');
  }

  if (opts.forceSync) {
    return execSync(commad, { cwd: path});
  } else {

    exec(commad, { cwd: path}, function (error, stdout, stderr) {
      var err = null;

      if (error !== null) {
        err = error;
      }

      if (opts.callback && typeof opts.callback == 'function') {
        opts.callback.call(this, err);
      }
    });
  }
};

Git.prototype.switchBranch = function (opts, callback) {
  opts = opts || {};
  var path = opts.path,
    branch = opts.branch,
    forceCreateIfNotExists = opts.forceCreateIfNotExists;

  exec('git checkout ' + (forceCreateIfNotExists ? ' -b ': '') + branch, { cwd: path,  env: ENV}, function(error, stdout, stderr) {
    var err = null;

    if (error !== null) {
      err = error.message;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err);
    }
  });
};

Git.prototype.getCommitCount = function (path, callback) {

  exec('git rev-list HEAD --count', { cwd: path,  env: ENV}, function  (error, stdout, stderr){
    var err = null;

    if (error !== null) {
      err = error.message;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, stdout);
    }
  });
};

Git.prototype.listRemotes = function (path, callback) {

  exec('git remote -v', { cwd: path,  env: ENV}, function (error, stdout, stderr) {
    var err = null;

    if (error !== null) {
      err = error.message;
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, stdout);
    }
  });
};

Git.prototype.discartChangesInFile = function (path, opts) {
  var command;

  opts = opts || {};

  if (opts.isUnknow) {
    command = 'git clean -df '.concat(opts.file);
  } else {
    command = 'git checkout -- '.concat(opts.file);
  }

  if (opts.forceSync) {
    return execSync(command, { cwd: path,  env: ENV });
  } else {

    exec(command, { cwd: path,  env: ENV}, function (error, stdout, stderr) {
      var err = null;

      if (error !== null) {
        err = error.message;
      }

      if (opts.callback && typeof opts.callback == 'function') {
        opts.callback.call(this, err, stdout);
      }
    });
  }
};

Git.prototype.getTag = function (path, callback) {

  exec('git tag', { cwd: path,  env: ENV}, function (error, stdout, stderr) {
    var err = null,
      tags = [];

    if (error !== null) {
      err = error.message;
    } else {
      var lines = stdout.split('\n');

      lines.forEach(function (tag) {

        if (tag !== '') {
          tags.push(tag);
        }
      });
    }

    if (callback && typeof callback == 'function') {
      callback.call(this, err, tags);
    }
  });
};

module.exports = new Git();
<|endoftext|>


<commit_before>// Provides an IpfsNode that can be started with .start() and exposes a working
// IPFS instance as .ipfs. Handles all of the startup and peer management stuff.
// Auto-finds its IPFS module dependency.
var IpfsNode = (function () {

  var ipfsnode = {}

  // If we decide to use the in-browser implementation, we call this.
  var startFallback = function(ipfsOnlineCallback) {
    console.log('Using ipfs-js fallback')

    // Find the IPFS implementation
    var IPFS
    if(!(typeof require === 'undefined')) {
      // Can load through Node
      IPFS = require('ipfs')
    } else if(!(typeof Ipfs === 'undefined')) {
      // Can load through browser global
      IPFS = Ipfs
    } else {
      return ipfsOnlineCallback(new Error('Cannot find IPFS implementation!'))
    }

    ipfsnode.ipfs = new IPFS()

    // Tell the node to fire the callback with an error or when it is ready.
    ipfsnode.ipfs.on('error', ipfsOnlineCallback)
    ipfsnode.ipfs.on('ready', ipfsOnlineCallback)

    // Find the buffer implementation for this mode
    ipfsnode.Buffer = ipfsnode.ipfs.types.Buffer
  }

  ipfsnode.ipfs = {}

  /**
   * Start the IPFS node.
   * After this calls back, the module will have an ipfs field holding the actual, running node.
   */
  ipfsnode.start = function(ipfsOnlineCallback) {
    if (window.ipfs) {
      // We maybe have a local IPFS. But we only want to use the go one; the JS one as part of an extension hangs the browser when we do anything hard.
      // So ask the node what it is.
      window.ipfs.id((err, id) => {
        if (err) {
          // Couldn't talk to the window node. Use the fallback
          return startFallback(ipfsOnlineCallback)
        }

        if (id.agentVersion && id.agentVersion.indexOf('js-ipfs') != -1) {
          // This is the JS implementation and we don't want to use it.
          // We have our own better JS implementation that doesn't hang the browser chrome.
          console.log('Rejecting blacklisted ' + id.agentVersion + ' via window.ipfs')
          return startFallback(ipfsOnlineCallback)
        }

        // Otherwise the browser node checks out.
        console.log('Using ' + id.agentVersion + ' via window.ipfs')
        ipfsnode.ipfs = window.ipfs

        // We don't need to start the node, since it is started.

        // Find the buffer implementation
        ipfsnode.Buffer = window.Buffer

        // Say we are started
        return ipfsOnlineCallback(null)
      })
    } else {
      // No window.ipfs at all. Use the fallback.
      return startFallback(ipfsOnlineCallback)
    }
  }

  // Return the completed module object, with start method and ipfs field
  return ipfsnode
}())
<commit_msg>Hook up to official websocket-star network<commit_after>// Provides an IpfsNode that can be started with .start() and exposes a working
// IPFS instance as .ipfs. Handles all of the startup and peer management stuff.
// Auto-finds its IPFS module dependency.
var IpfsNode = (function () {

  var ipfsnode = {}

  // If we decide to use the in-browser implementation, we call this.
  var startFallback = function(ipfsOnlineCallback) {
    console.log('Using ipfs-js fallback')

    // Find the IPFS implementation
    var IPFS
    if(!(typeof require === 'undefined')) {
      // Can load through Node
      IPFS = require('ipfs')
    } else if(!(typeof Ipfs === 'undefined')) {
      // Can load through browser global
      IPFS = Ipfs
    } else {
      return ipfsOnlineCallback(new Error('Cannot find IPFS implementation!'))
    }

    // Make the IPFS node, using websockets and webrtc as transports.
    ipfsnode.ipfs = new IPFS({
      config: {
        Addresses: {
          Swarm: [
            // Disable webrtc-star because it's still not good.
            // It interferes with peers being found over websocket-star
            //'/dns4/wrtc-star.discovery.libp2p.io/tcp/443/wss/p2p-webrtc-star',
            '/dns4/ws-star.discovery.libp2p.io/tcp/443/wss/p2p-websocket-star'
          ]
        }
      }
    })

    // Tell the node to fire the callback with an error or when it is ready.
    ipfsnode.ipfs.on('error', ipfsOnlineCallback)
    ipfsnode.ipfs.on('ready', ipfsOnlineCallback)

    // Find the buffer implementation for this mode
    ipfsnode.Buffer = ipfsnode.ipfs.types.Buffer

    // Periodically dump peers
    setInterval(() => {
      ipfsnode.ipfs.id((err, id) => {
        if (err) {
          throw err
        }
        ipfsnode.ipfs.swarm.peers({}, function(err, peers) {
          if (err) {
            throw err
          }
          console.log('We are IPFS node ' + id.id + ' with ' + peers.length + ' peers')
        })
      })
    }, 60000)
  }

  ipfsnode.ipfs = {}

  /**
   * Start the IPFS node.
   * After this calls back, the module will have an ipfs field holding the actual, running node.
   */
  ipfsnode.start = function(ipfsOnlineCallback) {
    if (window.ipfs) {
      // We maybe have a local IPFS. But we only want to use the go one; the JS one as part of an extension hangs the browser when we do anything hard.
      // So ask the node what it is.
      window.ipfs.id((err, id) => {
        if (err) {
          // Couldn't talk to the window node. Use the fallback
          return startFallback(ipfsOnlineCallback)
        }

        if (id.agentVersion && id.agentVersion.indexOf('js-ipfs') != -1) {
          // This is the JS implementation and we don't want to use it.
          // We have our own better JS implementation that doesn't hang the browser chrome.
          console.log('Rejecting blacklisted ' + id.agentVersion + ' via window.ipfs')
          return startFallback(ipfsOnlineCallback)
        }

        // Otherwise the browser node checks out.
        console.log('Using ' + id.agentVersion + ' via window.ipfs')
        ipfsnode.ipfs = window.ipfs

        // We don't need to start the node, since it is started.

        // Find the buffer implementation
        ipfsnode.Buffer = window.Buffer

        // Say we are started
        return ipfsOnlineCallback(null)
      })
    } else {
      // No window.ipfs at all. Use the fallback.
      return startFallback(ipfsOnlineCallback)
    }
  }

  // Return the completed module object, with start method and ipfs field
  return ipfsnode
}())
<|endoftext|>


<commit_before>$(document).ready(function(){

	$('#admin_page_controller').hide();
	$('#text_event_name').text("Error: Invalid event name ");
	var eventName = getURLParameter("q");
	if (eventName != null && eventName !== '' ) {
		$('#text_event_name').text("Event name: " + eventName);

	}

});

angular.module('teamform-admin-app', ['firebase'])
.controller('AdminCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) {

	// TODO: implementation of AdminCtrl

	// Initialize $scope.param as an empty JSON object
	$scope.param = {};

	// Call Firebase initialization code defined in site.js
	initalizeFirebase();

	var refPath, ref, eventName;

	eventName = getURLParameter("q");
	refPath = eventName + "/admin/param";
	ref = firebase.database().ref(refPath);

	// Link and sync a firebase object

	$scope.param = $firebaseObject(ref);
	$scope.param.$loaded()
		.then( function(data) {

			// Fill in some initial values when the DB entry doesn't exist
			if(typeof $scope.param.maxTeamSize == "undefined"){
				$scope.param.maxTeamSize = 10;
			}
			if(typeof $scope.param.minTeamSize == "undefined"){
				$scope.param.minTeamSize = 1;
			}

			// Enable the UI when the data is successfully loaded and synchornized
			$('#admin_page_controller').show();
		})
		.catch(function(error) {
			// Database connection error handling...
			//console.error("Error:", error);
		});

	refPath = eventName + "/team";
	$scope.team = [];
	$scope.team = $firebaseArray(firebase.database().ref(refPath));

	refPath = eventName + "/member";
	$scope.member = [];
	$scope.member = $firebaseArray(firebase.database().ref(refPath));

	$scope.changeMinTeamSize = function(delta) {
		var newVal = $scope.param.minTeamSize + delta;
		if (newVal >=1 && newVal <= $scope.param.maxTeamSize ) {
			$scope.param.minTeamSize = newVal;
		}

		$scope.param.$save();

	}

	$scope.changeMaxTeamSize = function(delta) {
		var newVal = $scope.param.maxTeamSize + delta;
		if (newVal >=1 && newVal >= $scope.param.minTeamSize ) {
			$scope.param.maxTeamSize = newVal;
		}

		$scope.param.$save();

	}

	$scope.saveFunc = function() {

		$scope.param.$save();

		// Finally, go back to the front-end
		window.location.href= "index.html";
	}

}]);<commit_msg>changed the link page in admin.js <commit_after>$(document).ready(function(){

	$('#admin_page_controller').hide();
	$('#text_event_name').text("Error: Invalid event name ");
	var eventName = getURLParameter("q");
	if (eventName != null && eventName !== '' ) {
		$('#text_event_name').text("Event name: " + eventName);

	}

});

angular.module('teamform-admin-app', ['firebase'])
.controller('AdminCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) {

	// TODO: implementation of AdminCtrl

	// Initialize $scope.param as an empty JSON object
	$scope.param = {};

	// Call Firebase initialization code defined in site.js
	initalizeFirebase();

	var refPath, ref, eventName;

	eventName = getURLParameter("q");
	refPath = eventName + "/admin/param";
	ref = firebase.database().ref(refPath);

	// Link and sync a firebase object

	$scope.param = $firebaseObject(ref);
	$scope.param.$loaded()
		.then( function(data) {

			// Fill in some initial values when the DB entry doesn't exist
			if(typeof $scope.param.maxTeamSize == "undefined"){
				$scope.param.maxTeamSize = 10;
			}
			if(typeof $scope.param.minTeamSize == "undefined"){
				$scope.param.minTeamSize = 1;
			}

			// Enable the UI when the data is successfully loaded and synchornized
			$('#admin_page_controller').show();
		})
		.catch(function(error) {
			// Database connection error handling...
			//console.error("Error:", error);
		});

	refPath = eventName + "/team";
	$scope.team = [];
	$scope.team = $firebaseArray(firebase.database().ref(refPath));

	refPath = eventName + "/member";
	$scope.member = [];
	$scope.member = $firebaseArray(firebase.database().ref(refPath));

	$scope.changeMinTeamSize = function(delta) {
		var newVal = $scope.param.minTeamSize + delta;
		if (newVal >=1 && newVal <= $scope.param.maxTeamSize ) {
			$scope.param.minTeamSize = newVal;
		}

		$scope.param.$save();

	}

	$scope.changeMaxTeamSize = function(delta) {
		var newVal = $scope.param.maxTeamSize + delta;
		if (newVal >=1 && newVal >= $scope.param.minTeamSize ) {
			$scope.param.maxTeamSize = newVal;
		}

		$scope.param.$save();

	}

	$scope.saveFunc = function() {

		$scope.param.$save();

		// Finally, go back to the front-end
		window.location.href= "main.html";
	}

}]);<|endoftext|>


<commit_before>
var contentstatus=0;
var count =1;
var timer;
var flag = 1 ;
var mapflag=1;
var page = 1;
////////////////////////////////random img start///////////////////////////////////
setInterval(function()
{
$(".hero").fadeOut( 1500, function() {
$(".hero").attr("style",'background:url("css/img/img'+count+'.jpg")');});
$('.hero').css('display', 'block');
$('.hero').animate({ opacity: 0 }, 0);
$('.hero').animate({ opacity: 1, top: "-10px" }, 2000);
    // Animation complete.
    if(count === 4)
    {
    	count=1;
    }
  count++ ;

}, 10000);

/////////////////////////////////script google analytics//////////////////////////////////////

  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-51359625-1', 'worldresident.net');
  ga('send', 'pageview');

///////////////////////////////////random img end///////////////////////////////////////

$(document).ready(function(){
//////////////////////////////Moblie controller/////////////////////////////////////////////////////////////////////////
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
//alert(navigator.userAgent);
}

$$(".content1").swipeRight(function(){expandmap();});
$$(".content1").swipeLeft(function(){minimizemap();});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////init page//////////////////////////////////////////////////////////
$(".auto_map_info").attr("height","0px");
$(".auto_map_info iframe").attr("height","0px");
$(".auto_map_info").attr("width","66%");
$(".auto_map_info iframe").attr("width","66%");
$("#loginopen").on("click",function(){
$(".loginfrm").css("visibility","visible");
$("#username_txt").focus();
});
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////function zone////////////////////////////////////////
function expandmap(){$(".auto_map_info").animate({height:window.screen.height-385+"px"});$(".auto_map_info iframe").animate({height:window.screen.height-385+"px"});$(".content1").animate({width:"100%"});$("#imgleftside").hide();};
function minimizemap(){$(".content1").animate({width:"23.23176%"});$("#imgleftside").show();$("#menu_index").show();};
function showlogin(){$(".loginfrm").css("visibility","visible");};
function hidelogin(){$(".loginfrm").css("visibility","hidden");};
/////////////////////////////////////////////////////////////////////////////////////////

$("#password_txt").focus(showlogin);
$("#username_txt").focus(showlogin);
$("#password_txt").focusout(hidelogin);
$("#username_txt").focusout(hidelogin);
$("#search_txt").focusout(function(){if(flag==0){minimizemap(); $("#menu_index").show();}});
$("#search_txt").on("click",function(){expandmap(); $("#menu_index").hide();});
$(".content1").on({
    'mouseover': function () {if(flag===1){timer = setTimeout(function () {contentstatus=1;expandmap();}, 1000);}},
    'mouseout' : function () {if(contentstatus===1){minimizemap(); contentstatus=0;}clearTimeout(timer);}
});
$(".pin").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$("#menu_index").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$(".content13").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});

$("#map_canvas").on("click",function(){$(".auto_map_info").animate({height:"0px"});$(".auto_map_info iframe").animate({height:"0px"});});
$("#tbrshow").html("");
$.ajax({type:'GET',url:'http://www.worldresident.net/getdb',success:function(data) {for(var i=0;i<10;i++){
					if(i==0)
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					else
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					}
                    $(".linkme").on({
    'mouseover': function () {$(this).addClass("hover");},
    'mouseout' : function () {$(this).removeClass("hover");}
});
                     $(".linkme").bind("tap",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank");});

				},
				error:function(err) {
					//alert("Sorry, I can't get the feed");
				}
			});

});
///////////////////////zipcode request//////////////////////////////////////////////////////////
$('.sel_amphures_plus').change(function(){

  $('.txt_amphures').val($(this).val());
});

$('.txt_zipcode1').on('input',function(){fetchzip($('.txt_zipcode1'));});
$('.txt_zipcode2').on('input',function(){fetchzip($('.txt_zipcode2'));});
$('.txt_zipcode3').on('input',function(){fetchzip($('.txt_zipcode3'));});

function fetchzip(ele){

  if($(ele).val().length>2)
{
$.ajax({
                type:'GET',
                url:'http://www.worldresident.net/zip?zip='+$(ele).val(),
                success:function(data) {
                    var pro = new Array();
                    var amp =new Array();
                    var dis = new Array();
                    var pos = new Array();
 $('.sel_district').html("");
  $('.sel_provine').html("");
  $('.sel_amphures_plus').html("");
  for(var i=0;i<data.length;i++)
  {
    pos.push(data[i].zipcode);
    pro.push(data[i].province_name);
    dis.push(data[i].amphur_name);
     amp.push(data[i].district_name);
  }
   pro = eliminateDuplicates(pro);
   amp = eliminateDuplicates(amp);
   dis = eliminateDuplicates(dis);
 $(ele).autocomplete({
      source:pos
    });

   $.each(dis, function(key, value) {
     $('.sel_district')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});
     $.each(pro, function(key, value) {
     $('.sel_provine')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});
       $.each(amp, function(key, value) {
     $('.sel_amphures_plus')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
}
if($(ele).val().length==0)
{
  $('.sel_district').html("");
  $('.sel_provine').html("");
  $('.txt_amphures').html("");
    $('.sel_amphures_plus').html("");

}
}

function eliminateDuplicates(arr) {
  var i,
      len=arr.length,
      out=[],
      obj={};

  for (i=0;i<len;i++) {
    obj[arr[i]]=0;
  }
  for (i in obj) {
    out.push(i);
  }
  return out;
}

//$(".linkme").on('tap',window.location="/worldresiden/info?id="+$$(this).id);
/////////////////////////////////////////////////for info request////////////////////////////////
var parameter = window.location.search.replace( "?", "" );
var values = parameter.split("=");
 var lat ;
                    var loong ;
 if(values[0]==="id"&&values[1]!=null)
 {

    $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/info?'+values[0]+"="+values[1],
                success:function(data) {
                     lat = data.location[0];
                     loong = data.location[1];
                     console.log(data.location[1]);
                    $("#nameaprt").html(data.title);
                    $("#detailaprt").html(data.detail);
                       if(data.location!=null)
                       {
                    $("#locationaprt").html('');
                   }
                   else
                   {
                    $("#locationaprt").html(" ")
                   }
                    $("#imageaprt").html(data.image);
                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
 }
if(values[0]==="page"&&values[1]!=null)
{
   $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?'+values[0]+"="+values[1],
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;
				for(var j =0;j<20;j++)
					{
					try{	if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
					   }
					catch(ex){}
					}

					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }
                 $(".pin").on("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank")});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });

}
/////////////////////////////////////////check page action ////////////////////////////////////////
$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
	   page++;
        $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?page='+page,
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;
				for(var j =0;j<20;j++)
					{ try{
						if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
						}
					catch(ex){}
					}
					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }

          $(".pin").unbind();
           $(".pin").bind("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'))});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }

            });
   }
});
<commit_msg>select plus<commit_after>
var contentstatus=0;
var count =1;
var timer;
var flag = 1 ;
var mapflag=1;
var page = 1;
////////////////////////////////random img start///////////////////////////////////
setInterval(function()
{
$(".hero").fadeOut( 1500, function() {
$(".hero").attr("style",'background:url("css/img/img'+count+'.jpg")');});
$('.hero').css('display', 'block');
$('.hero').animate({ opacity: 0 }, 0);
$('.hero').animate({ opacity: 1, top: "-10px" }, 2000);
    // Animation complete.
    if(count === 4)
    {
    	count=1;
    }
  count++ ;

}, 10000);

/////////////////////////////////script google analytics//////////////////////////////////////

  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-51359625-1', 'worldresident.net');
  ga('send', 'pageview');

///////////////////////////////////random img end///////////////////////////////////////

$(document).ready(function(){
//////////////////////////////Moblie controller/////////////////////////////////////////////////////////////////////////
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
//alert(navigator.userAgent);
}

$$(".content1").swipeRight(function(){expandmap();});
$$(".content1").swipeLeft(function(){minimizemap();});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////init page//////////////////////////////////////////////////////////
$(".auto_map_info").attr("height","0px");
$(".auto_map_info iframe").attr("height","0px");
$(".auto_map_info").attr("width","66%");
$(".auto_map_info iframe").attr("width","66%");
$("#loginopen").on("click",function(){
$(".loginfrm").css("visibility","visible");
$("#username_txt").focus();
});
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////function zone////////////////////////////////////////
function expandmap(){$(".auto_map_info").animate({height:window.screen.height-385+"px"});$(".auto_map_info iframe").animate({height:window.screen.height-385+"px"});$(".content1").animate({width:"100%"});$("#imgleftside").hide();};
function minimizemap(){$(".content1").animate({width:"23.23176%"});$("#imgleftside").show();$("#menu_index").show();};
function showlogin(){$(".loginfrm").css("visibility","visible");};
function hidelogin(){$(".loginfrm").css("visibility","hidden");};
/////////////////////////////////////////////////////////////////////////////////////////

$("#password_txt").focus(showlogin);
$("#username_txt").focus(showlogin);
$("#password_txt").focusout(hidelogin);
$("#username_txt").focusout(hidelogin);
$("#search_txt").focusout(function(){if(flag==0){minimizemap(); $("#menu_index").show();}});
$("#search_txt").on("click",function(){expandmap(); $("#menu_index").hide();});
$(".content1").on({
    'mouseover': function () {if(flag===1){timer = setTimeout(function () {contentstatus=1;expandmap();}, 1000);}},
    'mouseout' : function () {if(contentstatus===1){minimizemap(); contentstatus=0;}clearTimeout(timer);}
});
$(".pin").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$("#menu_index").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$(".content13").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});

$("#map_canvas").on("click",function(){$(".auto_map_info").animate({height:"0px"});$(".auto_map_info iframe").animate({height:"0px"});});
$("#tbrshow").html("");
$.ajax({type:'GET',url:'http://www.worldresident.net/getdb',success:function(data) {for(var i=0;i<10;i++){
					if(i==0)
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					else
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					}
                    $(".linkme").on({
    'mouseover': function () {$(this).addClass("hover");},
    'mouseout' : function () {$(this).removeClass("hover");}
});
                     $(".linkme").bind("tap",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank");});

				},
				error:function(err) {
					//alert("Sorry, I can't get the feed");
				}
			});

});
///////////////////////zipcode request//////////////////////////////////////////////////////////
$('.sel_amphures_plus').change(function(){

  $('.txt_amphures').val($(this).val());
});

$('.txt_zipcode1').on('input',function(){fetchzip($('.txt_zipcode1'));});
$('.txt_zipcode2').on('input',function(){fetchzip($('.txt_zipcode2'));});
$('.txt_zipcode3').on('input',function(){fetchzip($('.txt_zipcode3'));});

function fetchzip(ele){

  if($(ele).val().length>=2)
{
$.ajax({
                type:'GET',
                url:'http://www.worldresident.net/zip?zip='+$(ele).val(),
                success:function(data) {
                    var pro = new Array();
                    var amp =new Array();
                    var dis = new Array();
                    var pos = new Array();
 $('.sel_district').html("");
  $('.sel_provine').html("");
  $('.sel_amphures_plus').html("");
  for(var i=0;i<data.length;i++)
  {
    pos.push(data[i].zipcode);
    pro.push(data[i].province_name);
    dis.push(data[i].amphur_name);
     amp.push(data[i].district_name);
  }
   pro = eliminateDuplicates(pro);
   amp = eliminateDuplicates(amp);
   dis = eliminateDuplicates(dis);
 $(ele).autocomplete({
      source:pos
    });

   $.each(dis, function(key, value) {
     $('.sel_district')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});
     $.each(pro, function(key, value) {
     $('.sel_provine')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});
       $.each(amp, function(key, value) {
     $('.sel_amphures_plus')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
}
if($(ele).val().length==0)
{
  $('.sel_district').html("");
  $('.sel_provine').html("");
  $('.txt_amphures').html("");
    $('.sel_amphures_plus').html("");

}
}

function eliminateDuplicates(arr) {
  var i,
      len=arr.length,
      out=[],
      obj={};

  for (i=0;i<len;i++) {
    obj[arr[i]]=0;
  }
  for (i in obj) {
    out.push(i);
  }
  return out;
}

//$(".linkme").on('tap',window.location="/worldresiden/info?id="+$$(this).id);
/////////////////////////////////////////////////for info request////////////////////////////////
var parameter = window.location.search.replace( "?", "" );
var values = parameter.split("=");
 var lat ;
                    var loong ;
 if(values[0]==="id"&&values[1]!=null)
 {

    $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/info?'+values[0]+"="+values[1],
                success:function(data) {
                     lat = data.location[0];
                     loong = data.location[1];
                     console.log(data.location[1]);
                    $("#nameaprt").html(data.title);
                    $("#detailaprt").html(data.detail);
                       if(data.location!=null)
                       {
                    $("#locationaprt").html('');
                   }
                   else
                   {
                    $("#locationaprt").html(" ")
                   }
                    $("#imageaprt").html(data.image);
                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
 }
if(values[0]==="page"&&values[1]!=null)
{
   $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?'+values[0]+"="+values[1],
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;
				for(var j =0;j<20;j++)
					{
					try{	if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
					   }
					catch(ex){}
					}

					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }
                 $(".pin").on("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank")});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });

}
/////////////////////////////////////////check page action ////////////////////////////////////////
$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
	   page++;
        $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?page='+page,
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;
				for(var j =0;j<20;j++)
					{ try{
						if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
						}
					catch(ex){}
					}
					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }

          $(".pin").unbind();
           $(".pin").bind("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'))});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }

            });
   }
});
<|endoftext|>


<commit_before>// Global variables
var csvFields;
var map;
var zoom;
var layer;
var percent;
var fieldSelect;
var fieldsById;
var stat;
var body;
var topology;
var carto;
var geometries;

/*
 * Main program instructions
 */
console.log("Running Cartograms 4 All Web App");

$(document).ready(function() {
  init();
});
/*
 * End of main program instructions
 */

function init() {
  // don't initialize until user has uploaded a .csv file
  if(document.getElementById('input_csv').files[0] == null){
    console.log("Please upload a file");
    return;
  }
  USER_CSV = document.getElementById('input_csv').files[0];
  console.log("Cartograms 4 All: Start init()");
  map = d3.select("#map");
  zoom = d3.behavior.zoom()
    .translate([-38, 32])
    .scale(.94)
    .scaleExtent([0.5, 10.0])
    .on("zoom", updateZoom);
  layer = map.append("g")
    .attr("id", "layer"),
    states = layer.append("g")
    .attr("id", "states")
    .selectAll("path");

  csvFields = getCSVFields(initCartogram);

  var proj = d3.geo.albersUsa(),
    rawData,
    dataById = {};

  carto = d3.cartogram()
    .projection(proj)
    .properties(function(d) {
      return dataById[d.id];
    })
    .value(function(d) {
      return +d.properties[field];
    });

  var topoURL = DATA_DIRECTORY + "us-states.topojson";
  d3.json(topoURL, function(topology) {
    this.topology = topology;
    geometries = topology.objects.states.geometries;
    d3.csv(CSV_URL, function(rawData) {
      dataById = d3.nest()
        .key(function(d) {
          return d.NAME;
        })
        .rollup(function(d) {
          return d[0];
        })
        .map(rawData);
      var features = carto.features(topology, geometries),
        path = d3.geo.path().projection(proj);

      states = states.data(features)
        .enter()
        .append("path")
        .attr("class", "state")
        .attr("id", function(d) {
          return d.properties.NAME;
        })
        .attr("fill", "#fafafa")
        .attr("d", path);
      states.append("title");

      // Waits until fields has been defined
      function waitForFields() {
        if (typeof someVariable !== "undefined") {
          parseHash(fieldsById);
        } else {
          setTimeout(waitForFields, 250);
        }
      }

      // Waits until fields has been defined
      function waitForTopology() {
        if (typeof someVariable !== "undefined") {
          initTopo();
        } else {
          setTimeout(topology, 250);
        }
      }
    });
  });

  console.log("Cartograms 4 All: Finished init()");
}

function initCartogram(csvFields) {
  fields = csvFields;
  // Data info for the cartogram
  percent = (function() {
      var fmt = d3.format(".2f");
      return function(n) {
        return fmt(n) + "%";
      };
    })(),
    fields = csvFields,
    // TODO: Make this customizable
    // NOTE: Might just have this detect if there are digits at the end of the column or beginning, and if there are then use those as a year
    fieldsById = d3.nest()
    .key(function(d) {
      return d.id;
    })
    .rollup(function(d) {
      return d[0];
    })
    .map(fields),
    field = fields[0],
    colors = colorbrewer.RdYlBu[3]
    .reverse()
    .map(function(rgb) {
      return d3.hsl(rgb);
    });

  body = d3.select("body");
  stat = d3.select("#status");

  fieldSelect = d3.select("#field")
    .on("change", function(e) {
      field = fields[this.selectedIndex];
      location.hash = "#" + field.id;
    });

  fieldSelect.selectAll("option")
    .data(fields)
    .enter()
    .append("option")
    .attr("value", function(d) {
      return d.id;
    })
    .text(function(d) {
      return d.name;
    });

  /* TODO: Reincorporate year
  var yearSelect = d3.select("#year")
      .on("change", function(e) {
          year = years[this.selectedIndex];
          location.hash = "#" + [field.id, year].join("/");
      });

  yearSelect.selectAll("option")
      .data(years)
      .enter()
      .append("option")
      .attr("value", function(y) { return y; })
      .text(function(y) { return y; })
  */

  updateZoom();
}

window.onhashchange = function() {
  parseHash(fieldsById);
};

var deferredUpdate = (function() {
  var timeout;
  return function() {
    var args = arguments;
    clearTimeout(timeout);
    stat.text("calculating...");
    return timeout = setTimeout(function() {
      update.apply(null, arguments);
    }, 10);
  };
})();

var hashish = d3.selectAll("a.hashish")
  .datum(function() {
    return this.href;
  });
<commit_msg>changed user-input CSV console message<commit_after>// Global variables
var csvFields;
var map;
var zoom;
var layer;
var percent;
var fieldSelect;
var fieldsById;
var stat;
var body;
var topology;
var carto;
var geometries;

/*
 * Main program instructions
 */
console.log("Running Cartograms 4 All Web App");

$(document).ready(function() {
  init();
});
/*
 * End of main program instructions
 */

function init() {
  // don't initialize until user has uploaded a .csv file
  if(document.getElementById('input_csv').files[0] == null){
    console.log("Cartograms 4 All: Waiting for user inputted CSV file);
    return;
  }
  USER_CSV = document.getElementById('input_csv').files[0];
  console.log("Cartograms 4 All: Start init()");
  map = d3.select("#map");
  zoom = d3.behavior.zoom()
    .translate([-38, 32])
    .scale(.94)
    .scaleExtent([0.5, 10.0])
    .on("zoom", updateZoom);
  layer = map.append("g")
    .attr("id", "layer"),
    states = layer.append("g")
    .attr("id", "states")
    .selectAll("path");

  csvFields = getCSVFields(initCartogram);

  var proj = d3.geo.albersUsa(),
    rawData,
    dataById = {};

  carto = d3.cartogram()
    .projection(proj)
    .properties(function(d) {
      return dataById[d.id];
    })
    .value(function(d) {
      return +d.properties[field];
    });

  var topoURL = DATA_DIRECTORY + "us-states.topojson";
  d3.json(topoURL, function(topology) {
    this.topology = topology;
    geometries = topology.objects.states.geometries;
    d3.csv(CSV_URL, function(rawData) {
      dataById = d3.nest()
        .key(function(d) {
          return d.NAME;
        })
        .rollup(function(d) {
          return d[0];
        })
        .map(rawData);
      var features = carto.features(topology, geometries),
        path = d3.geo.path().projection(proj);

      states = states.data(features)
        .enter()
        .append("path")
        .attr("class", "state")
        .attr("id", function(d) {
          return d.properties.NAME;
        })
        .attr("fill", "#fafafa")
        .attr("d", path);
      states.append("title");

      // Waits until fields has been defined
      function waitForFields() {
        if (typeof someVariable !== "undefined") {
          parseHash(fieldsById);
        } else {
          setTimeout(waitForFields, 250);
        }
      }

      // Waits until fields has been defined
      function waitForTopology() {
        if (typeof someVariable !== "undefined") {
          initTopo();
        } else {
          setTimeout(topology, 250);
        }
      }
    });
  });

  console.log("Cartograms 4 All: Finished init()");
}

function initCartogram(csvFields) {
  fields = csvFields;
  // Data info for the cartogram
  percent = (function() {
      var fmt = d3.format(".2f");
      return function(n) {
        return fmt(n) + "%";
      };
    })(),
    fields = csvFields,
    // TODO: Make this customizable
    // NOTE: Might just have this detect if there are digits at the end of the column or beginning, and if there are then use those as a year
    fieldsById = d3.nest()
    .key(function(d) {
      return d.id;
    })
    .rollup(function(d) {
      return d[0];
    })
    .map(fields),
    field = fields[0],
    colors = colorbrewer.RdYlBu[3]
    .reverse()
    .map(function(rgb) {
      return d3.hsl(rgb);
    });

  body = d3.select("body");
  stat = d3.select("#status");

  fieldSelect = d3.select("#field")
    .on("change", function(e) {
      field = fields[this.selectedIndex];
      location.hash = "#" + field.id;
    });

  fieldSelect.selectAll("option")
    .data(fields)
    .enter()
    .append("option")
    .attr("value", function(d) {
      return d.id;
    })
    .text(function(d) {
      return d.name;
    });

  /* TODO: Reincorporate year
  var yearSelect = d3.select("#year")
      .on("change", function(e) {
          year = years[this.selectedIndex];
          location.hash = "#" + [field.id, year].join("/");
      });

  yearSelect.selectAll("option")
      .data(years)
      .enter()
      .append("option")
      .attr("value", function(y) { return y; })
      .text(function(y) { return y; })
  */

  updateZoom();
}

window.onhashchange = function() {
  parseHash(fieldsById);
};

var deferredUpdate = (function() {
  var timeout;
  return function() {
    var args = arguments;
    clearTimeout(timeout);
    stat.text("calculating...");
    return timeout = setTimeout(function() {
      update.apply(null, arguments);
    }, 10);
  };
})();

var hashish = d3.selectAll("a.hashish")
  .datum(function() {
    return this.href;
  });
<|endoftext|>


<commit_before>/* file: learning.js
 * authors: H. Bouakaz, S. van Vliet, S. de Jong & E. Werkema
 * date: 25/3/2016
 * version 1.2
 *
 * Description:
 * Main script for initiating the learning app.
 */

/*jshint esversion: 6 */
define(['jquery', 'app/lang', 'app/string', 'bootstrap', 'app/config', 'app/database', 'app/messages', 'app/question', 'app/timer', 'app/ready', 'app/user', 'app/time'], function ($, lang, string, bootstrap, config, db, messages, questions, timer, ready, user, time) {

  const THOUSAND = 1000;
  var waitingForEnter = false;

  function disableAutocomplete() {
    $('input').attr('autocomplete', 'off');
  }

	function inputIsEmpty() {
		return $.trim($("#answer").val()).length === 0;
	}

  function nextQuestion() {
    clearTimeout(timeout);
    timer.clearCountdown();
    messages.clear();
    questions.nextQuestion();
    $( "#answer" ).prop("disabled", false);
    $( "#answer" ).val( "" );
    $( "#answer" ).focus();
    questions.show();
    waitingForEnter = false;
  }

  function handleEnter() {
    if (waitingForEnter) {
      nextQuestion();
    } else if (!inputIsEmpty()) {
      $( "#answer" ).prop("disabled", true);
      questions.checkAnswer();
      waitingForEnter = true;
      timeout = setTimeout(nextQuestion,time.secondsToMilliseconds( $(".countdown").data("seconds") ) );
    }
  }

  function formatFactList(items) {
    var newList = [];
    items.forEach(function(item) {
      newItem = {
        id: item.item_id,
        text: item.item_question,
        answer: item.item_answer,
        hint: item.item_hint
      };
      newList.push(newItem);
    });
    return newList;
  }

	// Write localisable text to the page
	string.fillinTextClasses();
	$("#answer").prop("placeholder", lang("placeholder_typeanswerhere"));

  disableAutocomplete();

	// Replace user data in view from database
	$("span[data-replace]").each(function() {
		var user_info = $(this).data("replace");
		var text = user.get(user_info);
		$(this).html(text);
	});
	$("span[data-username]").html(user.get("user_firstname")+" "+user.get("user_lastname"));

  // When the page is loaded we get the datasetId from the page url and load the dataset from the database
  ready.on(function() {
    var url = window.location.href;
    var datasetId = url.substring(url.indexOf('?')+1);
    var factList = formatFactList(db.getQuery("getDatasetItems",[datasetId]));
    questions.initialize(factList);
  	questions.show();

    timer.startTimer(".timer", config.constant("TIME_LIMIT"));
  });

  // Temporary hint button
  $("#hintButton").click(function() {
    if (questions.hint()!=="")
      messages.showHint(questions.hint());
  });

  // Read the user input when the Enter key is pressed and evaluate it.
  // Then show the next question.
  $(document).bind("keypress", function (e) {
  	if (e.keyCode == config.key("ENTER")) {
      handleEnter();
  	}
  });
});
<commit_msg>removed constant THOUSAND<commit_after>/* file: learning.js
 * authors: H. Bouakaz, S. van Vliet, S. de Jong & E. Werkema
 * date: 25/3/2016
 * version 1.2
 *
 * Description:
 * Main script for initiating the learning app.
 */

/*jshint esversion: 6 */
define(['jquery', 'app/lang', 'app/string', 'bootstrap', 'app/config', 'app/database', 'app/messages', 'app/question', 'app/timer', 'app/ready', 'app/user', 'app/time'], function ($, lang, string, bootstrap, config, db, messages, questions, timer, ready, user, time) {
  var waitingForEnter = false;

  function disableAutocomplete() {
    $('input').attr('autocomplete', 'off');
  }

	function inputIsEmpty() {
		return $.trim($("#answer").val()).length === 0;
	}

  function nextQuestion() {
    clearTimeout(timeout);
    timer.clearCountdown();
    messages.clear();
    questions.nextQuestion();
    $( "#answer" ).prop("disabled", false);
    $( "#answer" ).val( "" );
    $( "#answer" ).focus();
    questions.show();
    waitingForEnter = false;
  }

  function handleEnter() {
    if (waitingForEnter) {
      nextQuestion();
    } else if (!inputIsEmpty()) {
      $( "#answer" ).prop("disabled", true);
      questions.checkAnswer();
      waitingForEnter = true;
      timeout = setTimeout(nextQuestion,time.secondsToMilliseconds( $(".countdown").data("seconds") ) );
    }
  }

  function formatFactList(items) {
    var newList = [];
    items.forEach(function(item) {
      newItem = {
        id: item.item_id,
        text: item.item_question,
        answer: item.item_answer,
        hint: item.item_hint
      };
      newList.push(newItem);
    });
    return newList;
  }

	// Write localisable text to the page
	string.fillinTextClasses();
	$("#answer").prop("placeholder", lang("placeholder_typeanswerhere"));

  disableAutocomplete();

	// Replace user data in view from database
	$("span[data-replace]").each(function() {
		var user_info = $(this).data("replace");
		var text = user.get(user_info);
		$(this).html(text);
	});
	$("span[data-username]").html(user.get("user_firstname")+" "+user.get("user_lastname"));

  // When the page is loaded we get the datasetId from the page url and load the dataset from the database
  ready.on(function() {
    var url = window.location.href;
    var datasetId = url.substring(url.indexOf('?')+1);
    var factList = formatFactList(db.getQuery("getDatasetItems",[datasetId]));
    questions.initialize(factList);
  	questions.show();

    timer.startTimer(".timer", config.constant("TIME_LIMIT"));
  });

  // Temporary hint button
  $("#hintButton").click(function() {
    if (questions.hint()!=="")
      messages.showHint(questions.hint());
  });

  // Read the user input when the Enter key is pressed and evaluate it.
  // Then show the next question.
  $(document).bind("keypress", function (e) {
  	if (e.keyCode == config.key("ENTER")) {
      handleEnter();
  	}
  });
});
<|endoftext|>


<commit_before>var Dispatcher = require('./Dispatcher');
var Constants = require('./Constants');
var EventEmitter = require('events').EventEmitter;
var ProfileActions = require('./actions/ProfileActions');

var CHANGE_EVENT = "CHANGE";

var Auth = {

  emitter: new EventEmitter(),

  logout: function() {
    store.clear();
    Dispatcher.dispatch({
      actionType: Constants.USER_LOGGED_OUT
    });
  },

  login: function(callback) {
    var lock = window.lock;
    lock.show({
      closable: false,
      connections: [config.auth0_connection]
    }, (function(err, profile, token) {
      if (err) {
        // Error callback
        throw err;
        console.log(err);
      } else {
        this.authenticate(token, profile);
        callback();
      }
    }).bind(this));
  },

  authenticate: function(id_token, profile) {
    this.setIdToken(id_token);
    Dispatcher.dispatch({
      actionType: Constants.RECEIVED_PROFILE,
      profile: profile
    });
    Dispatcher.dispatch({
      actionType: Constants.USER_AUTHENTICATED,
      id_token: id_token
    });
  },

  reauthenticate: function() {
    var id_token = this.getIdToken();
    if (id_token) {
      ProfileActions.loadProfile(id_token);
    }
  },

  setIdToken: function(id_token) {
    store.set('id_token', id_token);
    this.emitChange();
  },

  getIdToken: function() {
    return store.get('id_token');
  },

  isAuthenticated: function() {
    var id_token = this.getIdToken();
    if (id_token) {
      return true;
    }
    return false;
  },

  setTaskTokens: function(task_tokens) {
    this.task_tokens = task_tokens;
    this.emitChange();
  },

  getTaskTokens: function() {
    return this.task_tokens;
  },

  loadAwsCredentials: function(is_admin) {
    var options = {
      id_token:  this.getIdToken(),
      client_id: config.auth0_client_id,
      role: is_admin ? config.aws_iam_admin : config.aws_iam_user,
      principal: config.aws_iam_principal
    };
    lock.$auth0.getDelegationToken(options, (function(err, delegationResult) {
      if (err) throw err;
      this.setAwsCredentials(delegationResult.Credentials);
    }).bind(this));
  },

  setAwsCredentials: function(credentials) {
    this.aws_creds = credentials;
    this.emitChange();
  },

  getAwsCredentials: function() {
    return this.aws_creds;
  },

  emitChange: function() {
    this.emitter.emit(CHANGE_EVENT);
  },

  addChangeListener: function(callback) {
    this.emitter.on(CHANGE_EVENT, callback);
  },

  removeChangeListener: function(callback) {
    this.emitter.removeListener(CHANGE_EVENT, callback);
  },
}

module.exports = Auth;

Dispatcher.register(function(action) {

  switch(action.actionType) {
    case Constants.RECEIVED_PROFILE:
      Auth.loadAwsCredentials(action.profile.is_admin);
      Auth.setTaskTokens(action.profile.task_tokens);
      break;
    default:
      // no op
  }
});
<commit_msg>Handled expired token bug<commit_after>var Dispatcher = require('./Dispatcher');
var Constants = require('./Constants');
var EventEmitter = require('events').EventEmitter;
var ProfileActions = require('./actions/ProfileActions');

var CHANGE_EVENT = "CHANGE";

var Auth = {

  emitter: new EventEmitter(),

  logout: function() {
    this.clearSession();
    Dispatcher.dispatch({
      actionType: Constants.USER_LOGGED_OUT
    });
  },

  clearSession: function() {
    this.task_tokens = null;
    this.aws_creds = null;
    store.remove('id_token');
  },

  login: function(callback) {
    var lock = window.lock;
    lock.show({
      closable: false,
      connections: [config.auth0_connection]
    }, (function(err, profile, token) {
      if (err) {
        // Error callback
        throw err;
        console.log(err);
      } else {
        this.authenticate(token, profile);
        callback();
      }
    }).bind(this));
  },

  authenticate: function(id_token, profile) {
    this.setIdToken(id_token);
    Dispatcher.dispatch({
      actionType: Constants.RECEIVED_PROFILE,
      profile: profile
    });
    Dispatcher.dispatch({
      actionType: Constants.USER_AUTHENTICATED,
      id_token: id_token
    });
  },

  reauthenticate: function() {
    var id_token = this.getIdToken();
    if (id_token) {
      ProfileActions.loadProfile(id_token);
    }
  },

  setIdToken: function(id_token) {
    store.set('id_token', id_token);
    this.emitChange();
  },

  getIdToken: function() {
    return store.get('id_token');
  },

  isAuthenticated: function() {
    var id_token = this.getIdToken();
    if (id_token) {
      return true;
    }
    return false;
  },

  setTaskTokens: function(task_tokens) {
    this.task_tokens = task_tokens;
    this.emitChange();
  },

  getTaskTokens: function() {
    return this.task_tokens;
  },

  loadAwsCredentials: function(is_admin) {
    var options = {
      id_token:  this.getIdToken(),
      client_id: config.auth0_client_id,
      role: is_admin ? config.aws_iam_admin : config.aws_iam_user,
      principal: config.aws_iam_principal
    };
    lock.$auth0.getDelegationToken(options, (function(err, delegationResult) {
      if (err) throw err;
      this.setAwsCredentials(delegationResult.Credentials);
    }).bind(this));
  },

  setAwsCredentials: function(credentials) {
    this.aws_creds = credentials;
    this.emitChange();
  },

  getAwsCredentials: function() {
    return this.aws_creds;
  },

  emitChange: function() {
    this.emitter.emit(CHANGE_EVENT);
  },

  addChangeListener: function(callback) {
    this.emitter.on(CHANGE_EVENT, callback);
  },

  removeChangeListener: function(callback) {
    this.emitter.removeListener(CHANGE_EVENT, callback);
  },
}

module.exports = Auth;

Dispatcher.register(function(action) {

  switch(action.actionType) {
    case Constants.USER_LOGGED_OUT:
      Auth.clearSession();
      break;
    case Constants.RECEIVED_PROFILE:
      Auth.loadAwsCredentials(action.profile.is_admin);
      Auth.setTaskTokens(action.profile.task_tokens);
      break;
    default:
      // no op
  }
});
<|endoftext|>


<commit_before>require('jquery');
require('handlebars');
require('ember');
require('ember-data');
require('dashboard/ext');

Dashboard = Ember.Application.create({
  VERSION: '0.0.3'
});
<commit_msg>Update Dashboard#VERSION to 0.0.4<commit_after>require('jquery');
require('handlebars');
require('ember');
require('ember-data');
require('dashboard/ext');

Dashboard = Ember.Application.create({
  VERSION: '0.0.4'
});
<|endoftext|>


<commit_before>import postJSON from "./postJSON";
import globals from "./globals";
import login from "./login";
import getProfile from "./getProfile";
import languages from "./languages";

export default Ember.Object.extend({
  isLoggedIn: false,
  init: function(){
    var raw = window.localStorage.getItem("user");
    if(!raw){ return; }

    try {
      var self = JSON.parse(raw);
    } catch(e) { return; }

    if(!self){ return; }
    this.set("isLoggedIn", !! self.accessToken);
    this.set("accessToken", self.accessToken);
    this.set("expiresAt", self.expiresAt);
    this.set("refreshToken", self.refreshToken);
    this.set("avatar", self.avatar);
    this.set("username", self.username);
    this.set("joinedAt", self.joinedAt);
    this.set("exclude", self.exclude);
    this.set("include", self.include);
    this.set("language", self.language);
  },
  defaultLanguage: function() {
    return this.get("language") || "None";
  },
  defaultLanguageKey: function(){
    return languages.content[this.defaultLanguage()];
  },
  getAccessToken: function() {
    var today = new Date();

    var data = {
      "client_id": globals.getClientID(),
      "client_secret": globals.getClientSecret(),
      "redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
      "grant_type": "refresh_token",
      "refresh_token": this.get("refreshToken")
    };

    var headers = {
      "Content-Type": "application/json",
    };

    var options = {
      url: "https://api-v2launch.trakt.tv/oauth/token",
      headers: headers,
      form: data
    };

    var self = this;

    return new Promise(function(resolve, failed) {
      if(!self.get("isLoggedIn")){
        console.error("User not logged in");
        return failed("User not logged in");
      }
      if(!self.get("refreshToken")) {
        console.error("No refreshToken set on user");
        return failed("No refreshToken set on user");
      }

      if(today < self.get("expiresAt")){
        console.info("Return already existing token");
        console.info(today, self.get("expiresAt"));
        return resolve(self.get("accessToken"));
      }

      postJSON(options).then(function(data){
        if(data["error"]) {
          console.error("failed", data);
          return failed(data);
        }

        var expiresAt = new Date();
        expiresAt.setSeconds(
          expiresAt.getSeconds() +
          (data["expires_in"] / 1000)
        );

        console.info("Set new accessToken", data["access_token"]);
        console.info("expires in", expiresAt);
        console.info("plain expires", data["expires_in"]);

        self.set("accessToken", data["access_token"]);
        self.set("refreshToken", data["refresh_token"]);
        self.set("expiresAt", expiresAt);
        self.set("isLoggedIn", true);
        resolve(data["access_token"]);
      }).catch(failed);
    });
  },
  loadProfile: function(){
    var self = this;
    return new Promise(function(resolve, reject){
      self.getAccessToken().then(function(token){
        getProfile(token).then(function(data){
          self.set("username", data.user.username);
          self.set("avatar", data.user.images.avatar.full);
          self.set("joinedAt", new Date(data.user.joined_at));
          resolve();
        }, reject);
      }, reject);
    })
  },

  save: function(){
    var self = {
      accessToken: this.get("accessToken"),
      expiresAt: this.get("expiresAt"),
      refreshToken: this.get("refreshToken"),
      avatar: this.get("avatar"),
      username: this.get("username"),
      joinedAt: this.get("joinedAt"),
      exclude: this.get("exclude"),
      include: this.get("include"),
      language: this.get("language")
    };

    window.localStorage.setItem("user", JSON.stringify(self));
  }.observes("accessToken", "expiresAt", "refreshToken", "username", "avatar", "joinedAt", "include", "exclude", "language"),
  logout: function(){
    window.localStorage.setItem("user", null);
    this.set("isLoggedIn", false);
  },
  clearFields: function(){
    if(this.get("isLoggedIn")) { return; }
    this.set("accessToken", null);
    this.set("expiresAt", null);
    this.set("refreshToken", null);
    this.set("avatar", null);
    this.set("username", null);
    this.set("joinedAt", null);
    this.set("exclude", null);
    this.set("include", null);
    this.set("language", null);
  }.observes("isLoggedIn"),
  login: function(authToken){
    var self = this;
    return new Promise(function(resolve, reject) {
      if(self.get("isLoggedIn")){
        return reject("Already logged in");
      }

      login(authToken).then(function(token){
        var expiresAt = new Date();
        expiresAt.setSeconds(
          expiresAt.getSeconds() + token["expires_in"]
        );

        self.set("accessToken", token.access_token);
        self.set("expiresAt", expiresAt);
        self.set("refreshToken", token.refresh_token);
        self.set("isLoggedIn", true);
        self.loadProfile();
        resolve();
      }, reject);
    });
  }
});<commit_msg>Expire token in 1 day<commit_after>import postJSON from "./postJSON";
import globals from "./globals";
import login from "./login";
import getProfile from "./getProfile";
import languages from "./languages";

export default Ember.Object.extend({
  isLoggedIn: false,
  init: function(){
    var raw = window.localStorage.getItem("user");
    if(!raw){ return; }

    try {
      var self = JSON.parse(raw);
    } catch(e) { return; }

    if(!self){ return; }
    this.set("isLoggedIn", !! self.accessToken);
    this.set("accessToken", self.accessToken);
    this.set("expiresAt", self.expiresAt);
    this.set("refreshToken", self.refreshToken);
    this.set("avatar", self.avatar);
    this.set("username", self.username);
    this.set("joinedAt", self.joinedAt);
    this.set("exclude", self.exclude);
    this.set("include", self.include);
    this.set("language", self.language);
  },
  defaultLanguage: function() {
    return this.get("language") || "None";
  },
  defaultLanguageKey: function(){
    return languages.content[this.defaultLanguage()];
  },
  getAccessToken: function() {
    var today = new Date();
    var data = {
      "client_id": globals.getClientID(),
      "client_secret": globals.getClientSecret(),
      "redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
      "grant_type": "refresh_token",
      "refresh_token": this.get("refreshToken")
    };
    var headers = {
      "Content-Type": "application/json",
    };
    var options = {
      url: "https://api-v2launch.trakt.tv/oauth/token",
      headers: headers,
      form: data
    };

    var self = this;

    return new Promise(function(resolve, failed) {
      if(!self.get("isLoggedIn")){
        console.error("User not logged in");
        return failed("User not logged in");
      }
      if(!self.get("refreshToken")) {
        console.error("No refreshToken set on user");
        return failed("No refreshToken set on user");
      }

      if(today < self.get("expiresAt")){
        console.info("Return already existing token");
        console.info(today, self.get("expiresAt"));
        return resolve(self.get("accessToken"));
      }

      postJSON(options).then(function(data){
        if(data["error"]) {
          console.error("failed", data);
          return failed(data);
        }

        var expiresAt = new Date();
        expiresAt.setSeconds(
          expiresAt.getSeconds() +
          // (data["expires_in"] / 1000)
          24 * 60 * 60 // One day
        );

        console.info("Set new accessToken", data["access_token"]);
        console.info("expires in", expiresAt);
        console.info("plain expires", data["expires_in"]);

        self.set("accessToken", data["access_token"]);
        self.set("refreshToken", data["refresh_token"]);
        self.set("expiresAt", expiresAt);
        self.set("isLoggedIn", true);
        resolve(data["access_token"]);
      }).catch(failed);
    });
  },
  loadProfile: function(){
    var self = this;
    return new Promise(function(resolve, reject){
      self.getAccessToken().then(function(token){
        getProfile(token).then(function(data){
          self.set("username", data.user.username);
          self.set("avatar", data.user.images.avatar.full);
          self.set("joinedAt", new Date(data.user.joined_at));
          resolve();
        }, reject);
      }, reject);
    })
  },

  save: function(){
    var self = {
      accessToken: this.get("accessToken"),
      expiresAt: this.get("expiresAt"),
      refreshToken: this.get("refreshToken"),
      avatar: this.get("avatar"),
      username: this.get("username"),
      joinedAt: this.get("joinedAt"),
      exclude: this.get("exclude"),
      include: this.get("include"),
      language: this.get("language")
    };

    window.localStorage.setItem("user", JSON.stringify(self));
  }.observes("accessToken", "expiresAt", "refreshToken", "username", "avatar", "joinedAt", "include", "exclude", "language"),
  logout: function(){
    window.localStorage.setItem("user", null);
    this.set("isLoggedIn", false);
  },
  clearFields: function(){
    if(this.get("isLoggedIn")) { return; }
    this.set("accessToken", null);
    this.set("expiresAt", null);
    this.set("refreshToken", null);
    this.set("avatar", null);
    this.set("username", null);
    this.set("joinedAt", null);
    this.set("exclude", null);
    this.set("include", null);
    this.set("language", null);
  }.observes("isLoggedIn"),
  login: function(authToken){
    var self = this;
    return new Promise(function(resolve, reject) {
      if(self.get("isLoggedIn")){
        return reject("Already logged in");
      }

      login(authToken).then(function(token){
        var expiresAt = new Date();
        expiresAt.setSeconds(
          expiresAt.getSeconds() + token["expires_in"]
        );

        self.set("accessToken", token.access_token);
        self.set("expiresAt", expiresAt);
        self.set("refreshToken", token.refresh_token);
        self.set("isLoggedIn", true);
        self.loadProfile();
        resolve();
      }, reject);
    });
  }
});<|endoftext|>