<commit_before>
var express = require('express');
var router = express.Router();

// Users
var userController = require("../../controllers/api/Users/UserController.js");
router.get('/users', userController.getAll);
router.get('/users/me', userController.getMe);
router.post('/users', userController.signIn);
router.post('/users/signOut', userController.signOut);
router.put('/users', userController.update);

router.route('/users/:id')
    .delete(userController.delete)
    .get(userController.get);uk

// Suppliers
var supplierController = require("../../controllers/api/SupplierController.js");

router.get('/suppliers', supplierController.getAll);
router.post('/suppliers/signUp', supplierController.signUp);
router.post('/suppliers/signIn', supplierController.signIn);
router.post('/suppliers/signOut', supplierController.signOut);
router.put('/suppliers', supplierController.update);

router.route('/suppliers/:supplier_id')
    .delete(supplierController.delete)
    .get(supplierController.get);

// Supplier
router.route('/suppliers/events/:event_id/users')
    .get(supplierController.getAllUserEvent);
router.get('/suppliers/events', supplierController.getEventAllOfSupplierRoleSupplier);
router.get('/suppliers/locations', supplierController.getLocationAllOfSupplier);
router.get('/suppliers/items', supplierController.getItemAllOfSupplier);
router.get('/suppliers/awards', supplierController.getAwardAllOfSupplier);
router.get('/suppliers/notifications', supplierController.getNotificationAllOfSupplier);
router.get('/suppliers/me', supplierController.getMe);

// Event
var eventController = require("../../controllers/api/EventController");
router.post('/events', eventController.createEvent);

router.route('/events/:event_id')
      .get(eventController.getDetail)
      .put(eventController.updateEvent)
      .delete(eventController.deleteEvent);

router.get('/events', eventController.getAllEventOfSupplier);

// User Event
var userEventController = require("../../controllers/api/Users/UserEventController");
router.route('/userevents')
    .get(userEventController.getAll)
    .post(userEventController.joinEvent);

router.route('/userevents/:user_event_id')
    .post(userEventController.completeEvent)
    .delete(userEventController.outEvent);

// Tasks
var taskController = require("../../controllers/api/TaskController");
router.route('/events/:event_id/tasks')
      .post(taskController.postTask);

router.route('/events/:event_id/tasks/:task_id')
      .get(taskController.getTask)
      .put(taskController.updateTask)
      .delete(taskController.deleteTask)

// User Task
var userTaskController = require("../../controllers/api/Users/UserTaskController");
router.route('/userevents/:user_event_id/tasks')
    .post(userTaskController.joinTask);

router.route('/userevents/:user_event_id/tasks/:user_task_id')
    .delete(userTaskController.outTask)
    .post(userTaskController.completeTask);

// Awards
var awardController = require("../../controllers/api/AwardController");
router.post('/awards', awardController.createAward);

router.route('/awards/:award_id')
      .get(awardController.getDetail)
      .put(awardController.updateAward)
      .delete(awardController.deleteAward)

// Locations
var locationController = require("../../controllers/api/LocationController");
router.post('/locations', locationController.create);

router.route('/locations/:location_id')
      .get(locationController.getDetail)
      .put(locationController.update)
      .delete(locationController.delete)

// Items
var itemController = require("../../controllers/api/ItemController");
router.post('/items', itemController.create);

router.route('/items/:item_id')
      .get(itemController.getDetail)
      .put(itemController.update)
      .delete(itemController.delete);

// Push notification
var pushNotification = require("../../controllers/api/PushNotificationController");
router.get('/notifications',pushNotification.getNotification);
router.post('/notifications', pushNotification.pushNotification);

// UserAward
var userAwardController = require("../../controllers/api/Users/UserAwardController");
router.route('/userawards')
    .get(userAwardController.getAll)
    .post(userAwardController.post);
router.route('/userawards/:user_award_id')
    .get(userAwardController.get)
    .put(userAwardController.put)
    .delete(userAwardController.delete);

// UserNotification
var userNotificationController = require("../../controllers/api/Users/UserNotification");
router.route('/usernotifications')
    .get(userNotificationController.getAll)
    .post(userNotificationController.post);
router.route('/usernotifications/:user_notification_id')
    .get(userNotificationController.get)
    .put(userNotificationController.put)
    .delete(userNotificationController.delete);

module.exports = router;
<commit_msg>[HotFix] Syntax<commit_after>
var express = require('express');
var router = express.Router();

// Users
var userController = require("../../controllers/api/Users/UserController.js");
router.get('/users', userController.getAll);
router.get('/users/me', userController.getMe);
router.post('/users', userController.signIn);
router.post('/users/signOut', userController.signOut);
router.put('/users', userController.update);

router.route('/users/:id')
    .delete(userController.delete)
    .get(userController.get);

// Suppliers
var supplierController = require("../../controllers/api/SupplierController.js");

router.get('/suppliers', supplierController.getAll);
router.post('/suppliers/signUp', supplierController.signUp);
router.post('/suppliers/signIn', supplierController.signIn);
router.post('/suppliers/signOut', supplierController.signOut);
router.put('/suppliers', supplierController.update);

router.route('/suppliers/:supplier_id')
    .delete(supplierController.delete)
    .get(supplierController.get);

// Supplier
router.route('/suppliers/events/:event_id/users')
    .get(supplierController.getAllUserEvent);
router.get('/suppliers/events', supplierController.getEventAllOfSupplierRoleSupplier);
router.get('/suppliers/locations', supplierController.getLocationAllOfSupplier);
router.get('/suppliers/items', supplierController.getItemAllOfSupplier);
router.get('/suppliers/awards', supplierController.getAwardAllOfSupplier);
router.get('/suppliers/notifications', supplierController.getNotificationAllOfSupplier);
router.get('/suppliers/me', supplierController.getMe);

// Event
var eventController = require("../../controllers/api/EventController");
router.post('/events', eventController.createEvent);

router.route('/events/:event_id')
      .get(eventController.getDetail)
      .put(eventController.updateEvent)
      .delete(eventController.deleteEvent);

router.get('/events', eventController.getAllEventOfSupplier);

// User Event
var userEventController = require("../../controllers/api/Users/UserEventController");
router.route('/userevents')
    .get(userEventController.getAll)
    .post(userEventController.joinEvent);

router.route('/userevents/:user_event_id')
    .post(userEventController.completeEvent)
    .delete(userEventController.outEvent);

// Tasks
var taskController = require("../../controllers/api/TaskController");
router.route('/events/:event_id/tasks')
      .post(taskController.postTask);

router.route('/events/:event_id/tasks/:task_id')
      .get(taskController.getTask)
      .put(taskController.updateTask)
      .delete(taskController.deleteTask)

// User Task
var userTaskController = require("../../controllers/api/Users/UserTaskController");
router.route('/userevents/:user_event_id/tasks')
    .post(userTaskController.joinTask);

router.route('/userevents/:user_event_id/tasks/:user_task_id')
    .delete(userTaskController.outTask)
    .post(userTaskController.completeTask);

// Awards
var awardController = require("../../controllers/api/AwardController");
router.post('/awards', awardController.createAward);

router.route('/awards/:award_id')
      .get(awardController.getDetail)
      .put(awardController.updateAward)
      .delete(awardController.deleteAward)

// Locations
var locationController = require("../../controllers/api/LocationController");
router.post('/locations', locationController.create);

router.route('/locations/:location_id')
      .get(locationController.getDetail)
      .put(locationController.update)
      .delete(locationController.delete)

// Items
var itemController = require("../../controllers/api/ItemController");
router.post('/items', itemController.create);

router.route('/items/:item_id')
      .get(itemController.getDetail)
      .put(itemController.update)
      .delete(itemController.delete);

// Push notification
var pushNotification = require("../../controllers/api/PushNotificationController");
router.get('/notifications',pushNotification.getNotification);
router.post('/notifications', pushNotification.pushNotification);

// UserAward
var userAwardController = require("../../controllers/api/Users/UserAwardController");
router.route('/userawards')
    .get(userAwardController.getAll)
    .post(userAwardController.post);
router.route('/userawards/:user_award_id')
    .get(userAwardController.get)
    .put(userAwardController.put)
    .delete(userAwardController.delete);

// UserNotification
var userNotificationController = require("../../controllers/api/Users/UserNotification");
router.route('/usernotifications')
    .get(userNotificationController.getAll)
    .post(userNotificationController.post);
router.route('/usernotifications/:user_notification_id')
    .get(userNotificationController.get)
    .put(userNotificationController.put)
    .delete(userNotificationController.delete);

module.exports = router;
<|endoftext|>


<commit_before>var MediumEditorMultiPlaceholders = MediumEditor.Extension.extend({
  name: 'multi_placeholder',
  init:  function() {
    this.placeholderElements = [];
    this.initPlaceholders(this.placeholders, this.placeholderElements);
    this.watchChanges();
  },

  initPlaceholders: function (placeholders, elements) {
      this.getEditorElements().forEach(function (editor) {
          this.placeholders.map(function(placeholder) {
            // Create the placeholder element
            var el = document.createElement(placeholder.tag);
            el.appendChild(document.createElement('br'));
            el.setAttribute('data-placeholder', placeholder.text);
            elements.push(el);
            // Append it to Medium Editor element
            editor.appendChild(el);
            this.updatePlaceholder(el);
          }, this);
      }, this);
  },

  destroy: function () {
      this.getEditorElements().forEach(function (editor) {
        editor.querySelectorAll('[data-placeholder]').map(function(el) {
          el.removeAttribute('data-placeholder');
        }, this);
      }, this);
  },

  showPlaceholder: function (el) {
      if (el) {
          el.classList.add('medium-editor-placeholder');
      }
  },

  hidePlaceholder: function (el) {
      if (el) {
          el.classList.remove('medium-editor-placeholder');
      }
  },

  updatePlaceholder: function (el) {
      // if one of these element ('img, blockquote, ul, ol') are found inside the given element, we won't display the placeholder
      if (el.textContent === '') {
          return this.showPlaceholder(el);
      }
      this.hidePlaceholder(el);
  },

  updateAllPlaceholders: function() {
    this.placeholderElements.map(function(el){
      this.updatePlaceholder(el);
    }, this);
  },

  watchChanges: function() {
    this.subscribe('editableInput', this.updateAllPlaceholders.bind(this));
    this.subscribe('externalInteraction', this.updateAllPlaceholders.bind(this));
  }
});
<commit_msg>Update main.js<commit_after>var MediumEditorMultiPlaceholders = MediumEditor.Extension.extend({
  name: 'multi_placeholder',
  init:  function() {
    this.placeholderElements = [];
    this.initPlaceholders(this.placeholders, this.placeholderElements);
    this.watchChanges();
  },

  initPlaceholders: function (placeholders, elements) {
      this.getEditorElements().forEach(function (editor) {
          this.placeholders.map(function(placeholder) {
            // Create the placeholder element
            var el = document.createElement(placeholder.tag);
            el.appendChild(document.createElement('br'));
            el.setAttribute('data-placeholder', placeholder.text);
            elements.push(el);
            // Append it to Medium Editor element
            editor.appendChild(el);
            this.updatePlaceholder(el);
          }, this);
      }, this);
  },

  destroy: function () {
      this.getEditorElements().forEach(function (editor) {
        editor.querySelectorAll('[data-placeholder]').map(function(el) {
          el.removeAttribute('data-placeholder');
        }, this);
      }, this);
  },

  showPlaceholder: function (el) {
      if (el) {
          el.classList.add('medium-editor-placeholder');
      }
  },

  hidePlaceholder: function (el) {
      if (el) {
          el.classList.remove('medium-editor-placeholder');
      }
  },

  updatePlaceholder: function (el) {
      if (el.textContent === '') {
          return this.showPlaceholder(el);
      }
      this.hidePlaceholder(el);
  },

  updateAllPlaceholders: function() {
    this.placeholderElements.map(function(el){
      this.updatePlaceholder(el);
    }, this);
  },

  watchChanges: function() {
    this.subscribe('editableInput', this.updateAllPlaceholders.bind(this));
    this.subscribe('externalInteraction', this.updateAllPlaceholders.bind(this));
  }
});
<|endoftext|>


<commit_before>'use strict';

/*
 * Dependencies
 */
var ip        = require('ip');
var zoologist = require('zoologist');

function ZoologistConfig () {
  this.initialised = false;
  this.client = null;
  this.serviceInstance = null;
  this.serviceDiscovery = null;
};

ZoologistConfig.prototype.init = function (options) {

  // Zoologist Setup
  var Zoologist               = zoologist.Zoologist;
  var ServiceDiscoveryBuilder = zoologist.ServiceDiscoveryBuilder;
  var ServiceInstanceBuilder  = zoologist.ServiceInstanceBuilder;

  // Init Zoologist Framework Client
  this.client = Zoologist.newClient(options.zookeeper.connectionString, options.zookeeper.retry.count);

  // Init Service Instance
  this.serviceInstance =
    ServiceInstanceBuilder
      .builder()
      .address(ip.address())
      .port(process.env.PORT || options.server.port)
      .name(options.serviceName)
      .build();

  // Init Service Discovery
  this.serviceDiscovery =
    ServiceDiscoveryBuilder
      .builder()
      .client(this.client)
      .thisInstance(this.serviceInstance)
      .basePath(options.serviceBasePath)
      .build();

  this.initialised = true;
}

ZoologistConfig.prototype.close = function() {
  this.client, this.serviceInstance, this.serviceDiscovery = null;
};

ZoologistConfig.prototype.getClient = function() {
  return this.client;
};

ZoologistConfig.prototype.getServiceInstance = function() {
  return this.serviceInstance;
};

ZoologistConfig.prototype.getServiceDiscovery = function() {
  return this.serviceDiscovery;
};

ZoologistConfig.prototype.isInitialised = function() {
  return this.initialised;
};

// Export ZoologistConfig instance
var zoologistConfig = module.exports = exports = new ZoologistConfig;
<commit_msg>added clean-up of expired services<commit_after>'use strict';

/*
 * Dependencies
 */
var EventEmitter = require('events').EventEmitter;
var util         = require('util');
var ip           = require('ip');
var zoologist    = require('zoologist');
var log          = require('bunyan').createLogger({ name: 'microservice:zoologist' });

// Inherit from EventEmitter
util.inherits(ZoologistConfig, EventEmitter);

function ZoologistConfig () {
  this.initialised = false;
  this.client = null;
  this.serviceInstance = null;
  this.serviceDiscovery = null;
};

ZoologistConfig.prototype.init = function (options) {
  // Zoologist Setup
  var Zoologist               = zoologist.Zoologist;
  var ServiceDiscoveryBuilder = zoologist.ServiceDiscoveryBuilder;
  var ServiceInstanceBuilder  = zoologist.ServiceInstanceBuilder;

  // Init Zoologist Framework Client
  this.client = Zoologist.newClient(options.zookeeper.connectionString, options.zookeeper.retry.count);
  this.client.start();

  this.initialised = true;

  var self = this;

  this.client.on('connected', function () {
    log.info('zookeeper connected');

    if (self.isRegisteredService()) {
      var svcId = self.serviceDiscovery.getData().id;

      self.serviceDiscovery.unRegisterService(svcId, function (err) {
        log.info({ id: svcId }, 'unregistered expired service');
      });
    }

    // Init Service Instance
    self.serviceInstance =
      ServiceInstanceBuilder
        .builder()
        .address(ip.address())
        .port(process.env.PORT || options.server.port)
        .name(options.serviceName)
        .build();

    // Init Service Discovery
    self.serviceDiscovery =
      ServiceDiscoveryBuilder
        .builder()
        .client(self.client)
        .thisInstance(self.serviceInstance)
        .basePath(options.serviceBasePath)
        .build();

    self.emit('ready');
  });

  this.client.on('disconnected', function () {
    log.warn('zookeeper disconnected');
  });
}

ZoologistConfig.prototype.close = function() {
  this.client, this.serviceInstance, this.serviceDiscovery = null;
};

ZoologistConfig.prototype.getClient = function() {
  return this.client;
};

ZoologistConfig.prototype.getServiceInstance = function() {
  return this.serviceInstance;
};

ZoologistConfig.prototype.getServiceDiscovery = function() {
  return this.serviceDiscovery;
};

ZoologistConfig.prototype.isInitialised = function() {
  return this.initialised;
};

ZoologistConfig.prototype.isRegisteredService = function() {
  return (this.getServiceDiscovery() && this.getServiceDiscovery().getData()) ? true : false;
};

// Export ZoologistConfig instance
var zoologistConfig = module.exports = exports = new ZoologistConfig;
<|endoftext|>


<commit_before>'use strict';

(function(app) {

  /**
   * Defines a player service factory to manipulate a media in a playing context.
   *
   * Media is not only a media file but also timecodes (slides), chapters and
   * eventually a virtual cut with a start and end edge to display present only
   * small part of the video.
   * PlayerService helps dealing with cut edges, its helps synchronize information
   * returned from the player to apply it to the cut range.
   * Term "real" is relative to the full video (wihtout cut edges).
   *
   * @module ov.player
   * @class PlayerService
   */
  function PlayerService() {
    var media = null;
    var cutStart = 0;
    var cutEnd = null;
    var realMediaDuration = null;
    var isCut = false;

    /**
     * Gets cut start edge in milliseconds.
     *
     * The beginning of the media can be virtually cut, thus the start time may be
     * not 0 but a virtual start.
     *
     * @method getRealCutStart
     * @return {Number} The start time in milliseconds according to the cut
     */
    function getRealCutStart() {
      if (realMediaDuration)
        return (cutStart) ? realMediaDuration * cutStart : 0;

      return 0;
    }

    /**
     * Gets cut end edge in milliseconds.
     *
     * The media can be virtually cut, thus the end time may not be the media
     * duration but a virtual end time.
     *
     * @method getRealCutEnd
     * @return {Number} The end time in milliseconds according to the cut
     */
    function getRealCutEnd() {
      if (realMediaDuration)
        return (cutEnd) ? realMediaDuration * cutEnd : realMediaDuration;

      return 0;
    }

    /**
     * Gets the real time based on the time relative to the cut media.
     *
     * @method getRealTime
     * @param {Number} time Time in milliseconds relative to the cut media
     * @return {Number} time Time in milliseconds relative to the full media
     */
    function getRealTime(time) {
      return time + getRealCutStart();
    }

    /**
     * Gets the cut time based on the real time (relative to the full media).
     *
     * @method getCutTime
     * @param {Number} time Time in milliseconds relative to the full media
     * @return {Number} Time in milliseconds relative to the cut media
     */
    function getCutTime(time) {
      return Math.max(time - getRealCutStart(), 0);
    }

    /**
     * Sets player media.
     *
     * @method setMedia
     * @param {Object} newMedia The media object
     */
    function setMedia(newMedia) {
      media = newMedia;
      isCut = media.cut && media.cut.length;

      // Media is cut
      if (isCut) {

        // Retrive cut edges (start and end)
        for (var i = 0; i < media.cut.length; i++) {
          if (media.cut[i].type === 'begin')
            cutStart = Math.max(media.cut[i].value, 0);
          else if (media.cut[i].type === 'end')
            cutEnd = Math.min(media.cut[i].value, 1);
        }

        // Media duration can't be equal to 0
        if (cutStart === cutEnd) {
          cutStart = 0;
          cutEnd = null;
        }

      } else {
        cutStart = 0;
        cutEnd = null;
      }

    }

    /**
     * Gets media timecodes.
     *
     * Only timecodes within the cut range are returned.
     *
     * @method getMediaTimecodes
     * @return {Array} The list of media timecodes
     */
    function getMediaTimecodes() {

      // Media is cut
      if (isCut && realMediaDuration && media.timecodes) {
        var filteredTimecodes = [];
        var realCutStart = getRealCutStart();
        var realCutEnd = getRealCutEnd();

        // Filter timecodes depending on cut edges
        // Timecodes not in the range [startCut - endCut] must be removed
        for (var i = 0; i < media.timecodes.length; i++) {
          var timecode = media.timecodes[i].timecode;

          if (timecode >= realCutStart && timecode <= realCutEnd)
            filteredTimecodes.push(media.timecodes[i]);
        }

        return filteredTimecodes;
      }

      return media.timecodes;
    }

    /**
     * Gets media timecodes ordered by time.
     *
     * Index timecodes by time to avoid parsing the whole array several times.
     *
     * @method getMediaTimecodesByTime
     * @return {Object} The list of media timecodes ordered by time
     */
    function getMediaTimecodesByTime() {
      var timecodesByTime = {};
      var timecodes = getMediaTimecodes();
      if (timecodes) {

        for (var i = 0; i < timecodes.length; i++) {
          var timecode = timecodes[i];
          timecodesByTime[timecode.timecode] = {
            image: {
              small: timecode.image.small,
              large: timecode.image.large
            }
          };
        }

      }
      return timecodesByTime;
    }

    /**
     * Gets the list of chapters.
     *
     * Only chapters within the cut range are returned.
     *
     * @method getMediaChapters
     * @return {Object} The media chapter
     */
    function getMediaChapters() {

      // Media is cut
      if (isCut && realMediaDuration && media.chapters) {
        var filteredChapters = [];

        // Filter chapters depending on cut edges
        // Chapters not in the range [startCut - endCut] must be removed
        for (var i = 0; i < media.chapters.length; i++) {
          var valuePercent = media.chapters[i].value;

          if (valuePercent >= cutStart && valuePercent <= cutEnd)
            filteredChapters.push(media.chapters[i]);
        }
        return filteredChapters;
      }
      return media.chapters;
    }

    /**
     * Change a list of chapters which value is a percent in a timestamp value according to media duration
     * @param {Array} chapters chapters array to modify from percent to timestamp
     * @param {int} mediaDuration media original duration in ms
     */
    function processChaptersTime(chapters) {
      for (var i = 0; i < chapters.length; i++) {
        chapters[i].value = (chapters[i].value * realMediaDuration) - Math.floor(cutStart * realMediaDuration);
      }
    }

    /**
     * Gets media virtual duration according to cut.
     *
     * The beginning and the end of the media can be virtually cut, thus
     * the duration is not systematically the real duration of the media but
     * can be a virtual duration.
     *
     * @method getCutDuration
     * @return {Number} The duration in milliseconds according to the cut
     */
    function getCutDuration() {
      if (realMediaDuration) {
        var end = getRealCutEnd();
        var start = getRealCutStart();
        return end - start;
      }
      return 0;
    }

    /**
     * Converts a percentage relative to the full media into a percentage relative
     * to the cut media.
     *
     * @method getCutPercent
     * @param {Number} percent The percentage of the video corresponding to
     * beginning of the loaded data (from 0 to 100)
     * @return {Number} The percentage of the video corresponding to
     * beginning of the loaded data (from 0 to 100)
     */
    function getCutPercent(percent) {
      if (realMediaDuration) {
        var time = realMediaDuration * (percent / 100);
        return Math.min(Math.max(((time - getRealCutStart()) / getCutDuration()) * 100, 0), 100);
      }
      return percent;
    }

    /**
     * Sets real media duration.
     *
     * @method setRealMediaDuration
     * @param {Number} duration Real media duration in milliseconds
     */
    function setRealMediaDuration(duration) {
      realMediaDuration = duration;
    }

    return {
      setMedia: setMedia,
      setRealMediaDuration: setRealMediaDuration,
      getMediaTimecodes: getMediaTimecodes,
      getMediaTimecodesByTime: getMediaTimecodesByTime,
      getMediaChapters: getMediaChapters,
      getCutDuration: getCutDuration,
      getRealTime: getRealTime,
      getRealCutStart: getRealCutStart,
      getRealCutEnd: getRealCutEnd,
      getCutPercent: getCutPercent,
      getCutTime: getCutTime,
      processChaptersTime: processChaptersTime
    };

  }

  app.factory('playerService', PlayerService);
  PlayerService.$inject = [];

})(angular.module('ov.player'));
<commit_msg>#0000170 Chapter tab was hidden when there was only a begin cut<commit_after>'use strict';

(function(app) {

  /**
   * Defines a player service factory to manipulate a media in a playing context.
   *
   * Media is not only a media file but also timecodes (slides), chapters and
   * eventually a virtual cut with a start and end edge to display present only
   * small part of the video.
   * PlayerService helps dealing with cut edges, its helps synchronize information
   * returned from the player to apply it to the cut range.
   * Term "real" is relative to the full video (wihtout cut edges).
   *
   * @module ov.player
   * @class PlayerService
   */
  function PlayerService() {
    var media = null;
    var cutStart = 0;
    var cutEnd = null;
    var realMediaDuration = null;
    var isCut = false;

    /**
     * Gets cut start edge in milliseconds.
     *
     * The beginning of the media can be virtually cut, thus the start time may be
     * not 0 but a virtual start.
     *
     * @method getRealCutStart
     * @return {Number} The start time in milliseconds according to the cut
     */
    function getRealCutStart() {
      if (realMediaDuration)
        return (cutStart) ? realMediaDuration * cutStart : 0;

      return 0;
    }

    /**
     * Gets cut end edge in milliseconds.
     *
     * The media can be virtually cut, thus the end time may not be the media
     * duration but a virtual end time.
     *
     * @method getRealCutEnd
     * @return {Number} The end time in milliseconds according to the cut
     */
    function getRealCutEnd() {
      if (realMediaDuration)
        return (cutEnd) ? realMediaDuration * cutEnd : realMediaDuration;

      return 0;
    }

    /**
     * Gets the real time based on the time relative to the cut media.
     *
     * @method getRealTime
     * @param {Number} time Time in milliseconds relative to the cut media
     * @return {Number} time Time in milliseconds relative to the full media
     */
    function getRealTime(time) {
      return time + getRealCutStart();
    }

    /**
     * Gets the cut time based on the real time (relative to the full media).
     *
     * @method getCutTime
     * @param {Number} time Time in milliseconds relative to the full media
     * @return {Number} Time in milliseconds relative to the cut media
     */
    function getCutTime(time) {
      return Math.max(time - getRealCutStart(), 0);
    }

    /**
     * Sets player media.
     *
     * @method setMedia
     * @param {Object} newMedia The media object
     */
    function setMedia(newMedia) {
      media = newMedia;
      isCut = media.cut && media.cut.length;

      // Media is cut
      if (isCut) {

        // Retrive cut edges (start and end)
        for (var i = 0; i < media.cut.length; i++) {
          if (media.cut[i].type === 'begin')
            cutStart = Math.max(media.cut[i].value, 0);
          else if (media.cut[i].type === 'end')
            cutEnd = Math.min(media.cut[i].value, 1);
        }

        // Media duration can't be equal to 0
        if (cutStart === cutEnd) {
          cutStart = 0;
          cutEnd = null;
        }

      } else {
        cutStart = 0;
        cutEnd = null;
      }

    }

    /**
     * Gets media timecodes.
     *
     * Only timecodes within the cut range are returned.
     *
     * @method getMediaTimecodes
     * @return {Array} The list of media timecodes
     */
    function getMediaTimecodes() {

      // Media is cut
      if (isCut && realMediaDuration && media.timecodes) {
        var filteredTimecodes = [];
        var realCutStart = getRealCutStart();
        var realCutEnd = getRealCutEnd();

        // Filter timecodes depending on cut edges
        // Timecodes not in the range [startCut - endCut] must be removed
        for (var i = 0; i < media.timecodes.length; i++) {
          var timecode = media.timecodes[i].timecode;

          if (timecode >= realCutStart && timecode <= realCutEnd)
            filteredTimecodes.push(media.timecodes[i]);
        }

        return filteredTimecodes;
      }

      return media.timecodes;
    }

    /**
     * Gets media timecodes ordered by time.
     *
     * Index timecodes by time to avoid parsing the whole array several times.
     *
     * @method getMediaTimecodesByTime
     * @return {Object} The list of media timecodes ordered by time
     */
    function getMediaTimecodesByTime() {
      var timecodesByTime = {};
      var timecodes = getMediaTimecodes();
      if (timecodes) {

        for (var i = 0; i < timecodes.length; i++) {
          var timecode = timecodes[i];
          timecodesByTime[timecode.timecode] = {
            image: {
              small: timecode.image.small,
              large: timecode.image.large
            }
          };
        }

      }
      return timecodesByTime;
    }

    /**
     * Gets the list of chapters.
     *
     * Only chapters within the cut range are returned.
     *
     * @method getMediaChapters
     * @return {Object} The media chapter
     */
    function getMediaChapters() {

      // Media is cut
      if (isCut && realMediaDuration && media.chapters) {
        var filteredChapters = [];
        var realCutStart = getRealCutStart();
        var realCutEnd = getRealCutEnd();

        // Filter chapters depending on cut edges
        // Chapters not in the range [startCut - endCut] must be removed
        for (var i = 0; i < media.chapters.length; i++) {
          var timecode = realMediaDuration * media.chapters[i].value;

          if (timecode >= realCutStart && timecode <= realCutEnd)
            filteredChapters.push(media.chapters[i]);
        }
        return filteredChapters;
      }
      return media.chapters;
    }

    /**
     * Change a list of chapters which value is a percent in a timestamp value according to media duration
     * @param {Array} chapters chapters array to modify from percent to timestamp
     * @param {int} mediaDuration media original duration in ms
     */
    function processChaptersTime(chapters) {
      for (var i = 0; i < chapters.length; i++) {
        chapters[i].value = (chapters[i].value * realMediaDuration) - Math.floor(cutStart * realMediaDuration);
      }
    }

    /**
     * Gets media virtual duration according to cut.
     *
     * The beginning and the end of the media can be virtually cut, thus
     * the duration is not systematically the real duration of the media but
     * can be a virtual duration.
     *
     * @method getCutDuration
     * @return {Number} The duration in milliseconds according to the cut
     */
    function getCutDuration() {
      if (realMediaDuration) {
        var end = getRealCutEnd();
        var start = getRealCutStart();
        return end - start;
      }
      return 0;
    }

    /**
     * Converts a percentage relative to the full media into a percentage relative
     * to the cut media.
     *
     * @method getCutPercent
     * @param {Number} percent The percentage of the video corresponding to
     * beginning of the loaded data (from 0 to 100)
     * @return {Number} The percentage of the video corresponding to
     * beginning of the loaded data (from 0 to 100)
     */
    function getCutPercent(percent) {
      if (realMediaDuration) {
        var time = realMediaDuration * (percent / 100);
        return Math.min(Math.max(((time - getRealCutStart()) / getCutDuration()) * 100, 0), 100);
      }
      return percent;
    }

    /**
     * Sets real media duration.
     *
     * @method setRealMediaDuration
     * @param {Number} duration Real media duration in milliseconds
     */
    function setRealMediaDuration(duration) {
      realMediaDuration = duration;
    }

    return {
      setMedia: setMedia,
      setRealMediaDuration: setRealMediaDuration,
      getMediaTimecodes: getMediaTimecodes,
      getMediaTimecodesByTime: getMediaTimecodesByTime,
      getMediaChapters: getMediaChapters,
      getCutDuration: getCutDuration,
      getRealTime: getRealTime,
      getRealCutStart: getRealCutStart,
      getRealCutEnd: getRealCutEnd,
      getCutPercent: getCutPercent,
      getCutTime: getCutTime,
      processChaptersTime: processChaptersTime
    };

  }

  app.factory('playerService', PlayerService);
  PlayerService.$inject = [];

})(angular.module('ov.player'));
<|endoftext|>


<commit_before>var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
const Application = mongoose.model('Application');
const Version = mongoose.model('Version');
const Dependency = mongoose.model('Dependency');
const DependencyVersion = mongoose.model('DependencyVersion');
const escapeStringRegexp = require('escape-string-regexp');

var queryPromise = function (params) {
	var query = { hidden: false, nightly: false, released: { $ne : false } };

	if (params.filename) {
		query.filename = filenameToInsensitive(params.filename);
	}

	var promise = Promise.resolve(query);

	if (params.app) {
		promise = promise
			.then(result => Application.findOne({ id: params.app }, '_id'))
			.then(app => {
				query.app = app._id;

				return query;
			});
	}

	if (params.deptype && params.depver) {
		promise = promise
			.then(r => Dependency.findOne({name: params.deptype }, '_id'))
			.then(dep => DependencyVersion.findOne({ type: dep._id, version: params.depver }, '_id'))
			.then(function(depVer) {
				query.compatible = depVer._id;

				return query;
			});
	}

	return promise;
};

var downloadFile = function(req, res, next) {
	return queryPromise(req.params)
		.then(query => Version.findOne(query, 'apk filename downloads').sort({ sortingCode : -1}))
		.then(version => {
			var options = {
				root: __dirname.replace("routes", ""),
				headers: {
					'Content-Type': 'application/vnd.android.package-archive',
					'Content-Disposition': 'attachment; filename="' + version.filename + '"'
				}
			};

			res.sendFile(version.apk, options);

			return version;
		})
		.then(version => {
			version.downloads++;
			version.save((err, result) => {
				if (err)
					console.error("Failed updating download count for " + version);
			});

			return version;
		})
		.catch(catcher(req, res));
};

var getMeta = function(req, res, next) {
	return queryPromise(req.params)
		.then(query => Version.findOne(query, 'name compatible')
			.populate({
				path: 'compatible',
				select: 'version type',
				options: {
					sort: {version: -1}
				},
				populate: {
					path: 'type',
					select: 'name'
				}
			})
			.sort({ sortingCode : -1})
		)
		.then((version) => {
			var response = {
				version: version.name,
				compatible: {}
			};

			version.compatible.forEach((v) => {
				if (!response.compatible[v.type.name]) {
					response.compatible[v.type.name] = [];
				}

				response.compatible[v.type.name].push(v.version)
			});

			res.set('Content-Type', 'application/json');
			res.send(response);
		/*	res.send();*/

			return version;
		})
		.catch(catcher(req, res));
};

var catcher = function(req, res) {
	return (err) => {
		console.error("Failed on path: " + req.path + " with err: " + err);
		res.sendStatus(404);

		return value;
	}
};

var filenameToInsensitive = function(filename) {
	return new RegExp("^" + escapeStringRegexp(filename) + "$", "i");
};

router.get('/', function(req, res, next) {

	var query = {hidden: false, nightly: false};

	if (req.session.admin) {
		query = {nightly: false};
	}

	Application.find({hidden: {$ne: true}})
		.select("_id")
		.then(apps => {
			query.app = { $in : apps };

			return Version.find(query)
				.select('name filename app changelog')
				.sort({_id: -1})
				.populate({path: 'app', select: 'id title hidden' })
				.limit(10);
		})
		.then(apps => {
			return res.render('download', {versions: apps});
		})
		.catch(next);
});

router.get('/:filename', downloadFile);
router.get('/:filename/meta', getMeta);

router.get('/:app/latest', downloadFile);
router.get('/:app/:filename', downloadFile);
router.get('/:app/latest/meta', getMeta);
router.get('/:app/:filename/meta', getMeta);

router.get('/:deptype/:depver/:filename', downloadFile);
router.get('/:deptype/:depver/:filename/meta', getMeta);

router.get('/:app/:deptype/:depver/latest', downloadFile);
router.get('/:app/:deptype/:depver/:filename', downloadFile);
router.get('/:app/:deptype/:depver/latest/meta', getMeta);
router.get('/:app/:deptype/:depver/:filename/meta', getMeta);

module.exports = router;
<commit_msg>fix: Allow downloading of hidden apps<commit_after>var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
const Application = mongoose.model('Application');
const Version = mongoose.model('Version');
const Dependency = mongoose.model('Dependency');
const DependencyVersion = mongoose.model('DependencyVersion');
const escapeStringRegexp = require('escape-string-regexp');

var queryPromise = function (params) {
	var query = { nightly: false, released: { $ne : false } };

	if (params.filename) {
		query.filename = filenameToInsensitive(params.filename);
	}

	var promise = Promise.resolve(query);

	if (params.app) {
		promise = promise
			.then(result => Application.findOne({ id: params.app }, '_id'))
			.then(app => {
				query.app = app._id;

				return query;
			});
	}

	if (params.deptype && params.depver) {
		promise = promise
			.then(r => Dependency.findOne({name: params.deptype }, '_id'))
			.then(dep => DependencyVersion.findOne({ type: dep._id, version: params.depver }, '_id'))
			.then(function(depVer) {
				query.compatible = depVer._id;

				return query;
			});
	}

	return promise;
};

var downloadFile = function(req, res, next) {
	return queryPromise(req.params)
		.then(query => Version.findOne(query, 'apk filename downloads').sort({ sortingCode : -1}))
		.then(version => {
			var options = {
				root: __dirname.replace("routes", ""),
				headers: {
					'Content-Type': 'application/vnd.android.package-archive',
					'Content-Disposition': 'attachment; filename="' + version.filename + '"'
				}
			};

			res.sendFile(version.apk, options);

			return version;
		})
		.then(version => {
			version.downloads++;
			version.save((err, result) => {
				if (err)
					console.error("Failed updating download count for " + version);
			});

			return version;
		})
		.catch(catcher(req, res));
};

var getMeta = function(req, res, next) {
	return queryPromise(req.params)
		.then(query => Version.findOne(query, 'name compatible')
			.populate({
				path: 'compatible',
				select: 'version type',
				options: {
					sort: {version: -1}
				},
				populate: {
					path: 'type',
					select: 'name'
				}
			})
			.sort({ sortingCode : -1})
		)
		.then((version) => {
			var response = {
				version: version.name,
				compatible: {}
			};

			version.compatible.forEach((v) => {
				if (!response.compatible[v.type.name]) {
					response.compatible[v.type.name] = [];
				}

				response.compatible[v.type.name].push(v.version)
			});

			res.set('Content-Type', 'application/json');
			res.send(response);
		/*	res.send();*/

			return version;
		})
		.catch(catcher(req, res));
};

var catcher = function(req, res) {
	return (err) => {
		console.error("Failed on path: " + req.path + " with err: " + err);
		console.error(err.stack);
		res.sendStatus(404);

		return value;
	}
};

var filenameToInsensitive = function(filename) {
	return new RegExp("^" + escapeStringRegexp(filename) + "$", "i");
};

router.get('/', function(req, res, next) {

	var query = {hidden: false, nightly: false};

	if (req.session.admin) {
		query = {nightly: false};
	}

	Application.find({hidden: {$ne: true}})
		.select("_id")
		.then(apps => {
			query.app = { $in : apps };

			return Version.find(query)
				.select('name filename app changelog')
				.sort({_id: -1})
				.populate({path: 'app', select: 'id title hidden' })
				.limit(10);
		})
		.then(apps => {
			return res.render('download', {versions: apps});
		})
		.catch(next);
});

router.get('/:filename', downloadFile);
router.get('/:filename/meta', getMeta);

router.get('/:app/latest', downloadFile);
router.get('/:app/:filename', downloadFile);
router.get('/:app/latest/meta', getMeta);
router.get('/:app/:filename/meta', getMeta);

router.get('/:deptype/:depver/:filename', downloadFile);
router.get('/:deptype/:depver/:filename/meta', getMeta);

router.get('/:app/:deptype/:depver/latest', downloadFile);
router.get('/:app/:deptype/:depver/:filename', downloadFile);
router.get('/:app/:deptype/:depver/latest/meta', getMeta);
router.get('/:app/:deptype/:depver/:filename/meta', getMeta);

module.exports = router;
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Detail description of a node with edit possibilities
////////////////////////////////////////////////////////////////////////////////

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

Session.set("file", null);
Session.set("uploadStopped", false);

// -- Template helpers ---------------------------------------------------------

Template.NodeDetail.helpers({

  node: function() {
    return GV.collections.Nodes.findOne({_id: Session.get('nodeInFocus')});
  },

  file: function() {
    return GV.collections.Files.findOne({ _id: Session.get("file") || this._af.doc && this._af.doc.fileId || null });
  },

  uploadStopped: function() {
    return Session.get("uploadStopped");
  }

});

// -- Template events ----------------------------------------------------------

Template.NodeDetail.events({

  /**
   * Reset the form on click on cancel button
   */
  'click .cancel': function(event, tmpl) {
    var fileObj = GV.collections.Files.findOne({ _id: Session.get("file")});

    FS.HTTP.uploadQueue.pause();

    FS.HTTP.uploadQueue.cancel(fileObj);
    GV.collections.Files.remove({ _id: Session.get('file')});

    Session.set('file', null);
    AutoForm.resetForm("update-node-form");
  },

  'click .download': function(event, tmpl) {
    event.preventDefault && event.preventDefault();

    console.log(this)
    //var fs = require('fs');
    var cp = require("child_process");

    var filename = this.copies.filesStore.key.replace(new RegExp(" ", 'g'), '\\ ');

    cp.exec("open ~/GrandView/files/" + filename, function(error, result) {
      console.log(error);
      console.log(result);
    });
    //process.exit(0); // exit this nodejs process
  },

  /**
   * Reset the form on click on cancel button
   */
  'click .upload-field': function(event, tmpl) {
    tmpl.find('input[type="file"]').click();
  },

  /**
   * Reset the form on click on cancel button
   */
  'click .stop-upload': function(event, tmpl) {
    var fileObj = GV.collections.Files.findOne({ _id: Session.get("file")});

    FS.HTTP.uploadQueue.pause();
    Session.set("uploadStopped", true);
  },

  /**
   * Reset the form on click on cancel button
   */
  'click .resume-upload': function(event, tmpl) {
    var fileObj = GV.collections.Files.findOne({ _id: Session.get("file")});

    FS.HTTP.uploadQueue.resume();
    Session.set("uploadStopped", false);
  },

  'click .delete-reference': function(event, tmpl) {
    // A confirmation prompt before removing the document
    var confirmationPrompt = {
      title: "Bekreftelse på slettingen",
      message: 'Er du sikker på at du vil slette referansen? NB: Vil slette alle underkategorier til referansen!',
      buttons: {
        cancel: {
          label: "Nei"
        },
        confirm: {
          label: "Ja",
          callback: function(result) {
            if(result) {

              deleteNode(Session.get('nodeInFocus'));

              // Set the main document in focus
              Session.set('nodeInFocus', Session.get('mainDocument'));

              Notifications.success('Sletting fullført', 'Referansen ble slettet fra systemet.');
            }
          }
        }
      }
    }
    bootbox.dialog(confirmationPrompt);
  },

  'change .file-upload': function(event, tmpl, args) {
    var self = this;

    // remove file if it currently is a file in the session variable
    if(Session.get("file")) {

      var fileObj = GV.collections.Files.findOne({ _id: Session.get("file")});

      FS.HTTP.uploadQueue.pause();

      FS.HTTP.uploadQueue.cancel(fileObj);
      GV.collections.Files.remove({ _id: Session.get('file')});
    }

    Session.set("uploadStopped", false);
    // upload new file
    var file = new FS.File(event.target.files[0]);

    var meta = {
      owner: GV.helpers.userId(),
      docId: this._id,
      nodeId: this._af.doc._id,
      path: file.path
    };

    FS.Utility.extend(file, meta);

    GV.collections.Files.insert(file, function (err, fileObj) {
      //Inserted new doc with ID fileObj._id, and kicked off the data upload using HTTP
      Session.set("file", fileObj._id);
      Router.current().subscribe('fileById', fileObj._id);
      GV.collections.Nodes.update({ _id: self._af.doc._id }, { $set: { fileId: fileObj._id }});
    });
  }

});

Template.GeneralInfo.events({

'click .delete-document': function(event, tmpl) {
  var self = this;
    // A confirmation prompt before removing the document
    var confirmationPrompt = {
      title: "Bekreftelse på slettingen",
      message: 'Er du sikker på at du vil slette hele dokumentet?',
      buttons: {
        cancel: {
          label: "Nei"
        },
        confirm: {
          label: "Ja",
          callback: function(result) {
            if(result) {
              // Remove the document
              GV.collections.Documents.remove({_id: self._id}, function(error) {
                if(error) {
                  Notifications.warn('Feil', error.message);
                } else {
                  // Remove all the children nodes that rely on the document
                  Meteor.call('removeNodes', self.children);

                  // Notify the user
                  Notifications.success('Sletting fullført', 'Dokument sammen med alle referanser er nå slettet.');
                  Router.go('Dashboard');
                }
              });
            }
          }
        }
      }
    }
    bootbox.dialog(confirmationPrompt);
  }

});
<commit_msg>Removed some trash console logs etc.<commit_after>////////////////////////////////////////////////////////////////////////////////
// Detail description of a node with edit possibilities
////////////////////////////////////////////////////////////////////////////////

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

Session.set("file", null);
Session.set("uploadStopped", false);

// -- Template helpers ---------------------------------------------------------

Template.NodeDetail.helpers({

  node: function() {
    return GV.collections.Nodes.findOne({_id: Session.get('nodeInFocus')});
  },

  file: function() {
    return GV.collections.Files.findOne({ _id: Session.get("file") || this._af.doc && this._af.doc.fileId || null });
  },

  uploadStopped: function() {
    return Session.get("uploadStopped");
  }

});

// -- Template events ----------------------------------------------------------

Template.NodeDetail.events({

  /**
   * Reset the form on click on cancel button
   */
  'click .cancel': function(event, tmpl) {
    var fileObj = GV.collections.Files.findOne({ _id: Session.get("file")});

    FS.HTTP.uploadQueue.pause();

    FS.HTTP.uploadQueue.cancel(fileObj);
    GV.collections.Files.remove({ _id: Session.get('file')});

    Session.set('file', null);
    AutoForm.resetForm("update-node-form");
  },

  'click .download': function(event, tmpl) {
    event.preventDefault && event.preventDefault();

    var cp = require("child_process");

    var filename = this.copies.filesStore.key.replace(new RegExp(" ", 'g'), '\\ ');

    cp.exec("open ~/GrandView/files/" + filename, function(error, result) {
      console.log(error);
      console.log(result);
    });
  },

  /**
   * Reset the form on click on cancel button
   */
  'click .upload-field': function(event, tmpl) {
    tmpl.find('input[type="file"]').click();
  },

  /**
   * Reset the form on click on cancel button
   */
  'click .stop-upload': function(event, tmpl) {
    var fileObj = GV.collections.Files.findOne({ _id: Session.get("file")});

    FS.HTTP.uploadQueue.pause();
    Session.set("uploadStopped", true);
  },

  /**
   * Reset the form on click on cancel button
   */
  'click .resume-upload': function(event, tmpl) {
    var fileObj = GV.collections.Files.findOne({ _id: Session.get("file")});

    FS.HTTP.uploadQueue.resume();
    Session.set("uploadStopped", false);
  },

  'click .delete-reference': function(event, tmpl) {
    // A confirmation prompt before removing the document
    var confirmationPrompt = {
      title: "Bekreftelse på slettingen",
      message: 'Er du sikker på at du vil slette referansen? NB: Vil slette alle underkategorier til referansen!',
      buttons: {
        cancel: {
          label: "Nei"
        },
        confirm: {
          label: "Ja",
          callback: function(result) {
            if(result) {

              deleteNode(Session.get('nodeInFocus'));

              // Set the main document in focus
              Session.set('nodeInFocus', Session.get('mainDocument'));

              Notifications.success('Sletting fullført', 'Referansen ble slettet fra systemet.');
            }
          }
        }
      }
    }
    bootbox.dialog(confirmationPrompt);
  },

  'change .file-upload': function(event, tmpl, args) {
    var self = this;

    // remove file if it currently is a file in the session variable
    if(Session.get("file")) {

      var fileObj = GV.collections.Files.findOne({ _id: Session.get("file")});

      FS.HTTP.uploadQueue.pause();

      FS.HTTP.uploadQueue.cancel(fileObj);
      GV.collections.Files.remove({ _id: Session.get('file')});
    }

    Session.set("uploadStopped", false);
    // upload new file
    var file = new FS.File(event.target.files[0]);

    var meta = {
      owner: GV.helpers.userId(),
      docId: this._id,
      nodeId: this._af.doc._id,
      path: file.path
    };

    FS.Utility.extend(file, meta);

    GV.collections.Files.insert(file, function (err, fileObj) {
      //Inserted new doc with ID fileObj._id, and kicked off the data upload using HTTP
      Session.set("file", fileObj._id);
      Router.current().subscribe('fileById', fileObj._id);
      GV.collections.Nodes.update({ _id: self._af.doc._id }, { $set: { fileId: fileObj._id }});
    });
  }

});

Template.GeneralInfo.events({

'click .delete-document': function(event, tmpl) {
  var self = this;
    // A confirmation prompt before removing the document
    var confirmationPrompt = {
      title: "Bekreftelse på slettingen",
      message: 'Er du sikker på at du vil slette hele dokumentet?',
      buttons: {
        cancel: {
          label: "Nei"
        },
        confirm: {
          label: "Ja",
          callback: function(result) {
            if(result) {
              // Remove the document
              GV.collections.Documents.remove({_id: self._id}, function(error) {
                if(error) {
                  Notifications.warn('Feil', error.message);
                } else {
                  // Remove all the children nodes that rely on the document
                  Meteor.call('removeNodes', self.children);

                  // Notify the user
                  Notifications.success('Sletting fullført', 'Dokument sammen med alle referanser er nå slettet.');
                  Router.go('Dashboard');
                }
              });
            }
          }
        }
      }
    }
    bootbox.dialog(confirmationPrompt);
  }

});
<|endoftext|>


<commit_before>'use strict';
// Pulling in Google Analytics for all the page views.
require('./ga.js');
// Pulling the scss stylesheet, applied at runtime to the page.
require('./styles/index.scss');
// Pulling in the root component.
require('./components/Root.jsx');
<commit_msg>adding localstorage error report<commit_after>'use strict';
// Pulling in Google Analytics for all the page views.
require('./ga.js');
// Pulling the scss stylesheet, applied at runtime to the page.
require('./styles/index.scss');
// Pulling in the root component.
require('./components/Root.jsx');

window.onerror = function (message, source, lineno, colno, error) {
  const report = { message, source, lineno, colno, error };
  localStorage.setItem('crashReport', JSON.stringify(report));
};
<|endoftext|>


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

/**
 * This script gathers dates and payload names from the subreddit launch manifest,
 * fuzzy checks them against existing upcoming payload id's and updates the date if a
 * change is made in the wiki. The proper time zone is calculated from the launch site
 * id of the launch. It also updates the flight number order based on the launch manifest order.
 *
 * Hopefully the format of the wiki does not change, but there's no real reason for it to change in the
 * forseeable future. If it does change, this script will have to be updated as necessary.
 */

const MongoClient = require('mongodb');
const moment = require('moment-timezone');
const cheerio = require('cheerio');
const request = require('request-promise-native');
const fuzz = require('fuzzball');

moment.suppressDeprecationWarnings = true;

let client;
let location;
let calculatedTimes;
let localTime;
let date;

const sites = [];
const payloads = [];
const promises = [];
const precision = [];
const flight_numbers = [];

// RegEx expressions for matching dates in the wiki manifest
// Allows for long months or short months ex. September vs Sep
// Allows for time with or without brackets ex [23:45] vs 23:45
const hour = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}\s(\[[0-9]{2}:[0-9]{2}\]|[0-9]{2}:[0-9]{2})$/;
const day = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}$/;
const month = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})$/;
const year = /^[0-9]{4}$/;

(async () => {
  try {
    client = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true });

    const db = client.db('spacex-api');
    const col = db.collection('launch');

    const launches = await col.find({ upcoming: true }).sort({ flight_number: 1 }).toArray();
    const base_flight_number = launches[0].flight_number;

    // Collect site names for time zone and payload name for fuzzy check
    launches.forEach(launch => {
      // Add temp fix for last Iridium NEXT launch because we need fuzzy
      // search to return 100% substring match, else we get SSO-A and SSO-B changing
      // because of a slight difference.
      // NOTE: Will be removed after launch
      if (launch.rocket.second_stage.payloads[0].payload_id === 'Iridium NEXT 8') {
        payloads.push('Iridium 8');
      } else {
        payloads.push(launch.rocket.second_stage.payloads[0].payload_id);
      }
      sites.push(launch.launch_site.site_id);
    });

    // Grab subreddit wiki manifest
    const result = await request('https://www.reddit.com/r/spacex/wiki/launches/manifest');
    const $ = cheerio.load(result);

    // Grab entire row, clean date, and convert to valid UTC moment date
    const manifest = $('body > div.content > div > div > table:nth-child(6) > tbody').text();
    const manifest_row = manifest.split('\n').filter(v => v !== '');

    // Filter to collect manaifest dates
    const manifest_dates = manifest_row.filter((value, index) => {
      return index % 8 === 0;
    });

    // Filter to collect payload names
    const manifest_payloads = manifest_row.filter((value, index) => {
      return (index + 3) % 8 === 0;
    });

    // Compare each payload against entire list of manifest payloads, and fuzzy match the
    // payload id against the manifest payload name. The partial match must be 100%, to avoid
    // conflicts like SSO-A and SSO-B, where a really close match would produce wrong results.
    payloads.forEach((payload, p_index) => {
      manifest_payloads.forEach((manifest_payload, m_index) => {
        if (fuzz.partial_ratio(payload, manifest_payload) === 100) {
          // Check and see if dates match a certain patten depending on the length of the
          // date given. This sets the amount of precision needed for the date.
          let mdate = manifest_dates[m_index];
          if (mdate.includes('Q')) {
            mdate = mdate.replace('Q', '');
            precision[m_index] = 'quarter';
          } else if (mdate.includes('H1')) {
            mdate = mdate.replace('H1', '1');
            precision[m_index] = 'half';
          } else if (mdate.includes('H2')) {
            mdate = mdate.replace('H2', '3');
            precision[m_index] = 'half';
          } else if (year.test(mdate)) {
            precision[m_index] = 'year';
          } else if (month.test(mdate)) {
            precision[m_index] = 'month';
          } else if (day.test(mdate)) {
            precision[m_index] = 'day';
          } else if (hour.test(mdate)) {
            precision[m_index] = 'hour';
          } else {
            console.log('Date did not match any of the existing regular expressions');
            process.exit(1);
          }

          // Store site_id for update query
          // Store manifest date for cleaning
          location = sites[p_index];
          date = manifest_dates[m_index];

          console.log(date);
          console.log(`${payload} : ${manifest_payload}`);

          // Strip brackets from time given, and tack on UTC time offset at the end for date parser
          const stripped_time = `${date.replace('[', '').replace(']', '')} +0000`;
          // Feed stripped time into all possible date formats in the wiki currently
          const time = moment(stripped_time, ['YYYY MMM D HH:mm Z', 'YYYY MMM D Z', 'YYYY MMM Z', 'YYYY Q Z', 'YYYY Z']);
          const zone = moment.tz(time, 'UTC');

          // Set timezone based on launch site id
          if (location === 'ccafs_slc_40' || location === 'ksc_lc_39a' || location === 'ccafs_lc_13') {
            localTime = time.tz('America/New_York').format();
          } else if (location === 'vafb_slc_4e' || location === 'vafb_slc_4w') {
            localTime = time.tz('America/Los_Angeles').format();
          } else {
            localTime = time.tz('America/Chicago').format();
          }

          // Add flight numbers to array to check for duplicates
          flight_numbers.push(base_flight_number + m_index);

          // Build launch time objects to update
          calculatedTimes = {
            flight_number: (base_flight_number + m_index),
            launch_date_unix: zone.unix(),
            launch_date_utc: zone.toISOString(),
            launch_date_local: localTime,
            is_tentative: true,
            tentative_max_precision: precision[m_index],
          };
          console.log(calculatedTimes);
          console.log('');

          // Another special case added for last Iridium launch
          // NOTE: Will be removed after launch
          if (payload === 'Iridium 8') {
            payload = 'Iridium NEXT 8';
          }

          // Add to array of promises to update all at once after the forEach iterations finish
          // promises.push(col.updateOne({ 'rocket.second_stage.payloads.payload_id': payload }, { $set: calculatedTimes }));
        }
      });
    });

    // Check if duplicate flight numbers exist
    if ([...new Set(flight_numbers)].length < flight_numbers.length) {
      console.log('Duplicate flight numbers found');
      process.exit(1);
    }

    // Execute all our stored update promises
    const output = await Promise.all(promises);

    // Display if the document was found, and if it was modified or not
    output.forEach(doc => {
      console.log(`N: ${doc.result.n}`);
      console.log(`Modified: ${doc.result.nModified}`);
    });
  } catch (err) {
    console.log(err.stack);
  }

  if (client) {
    client.close();
  }
})();
<commit_msg>upcoming updater typo fix<commit_after>#!/usr/bin/env node

/**
 * This script gathers dates and payload names from the subreddit launch manifest,
 * fuzzy checks them against existing upcoming payload id's and updates the date if a
 * change is made in the wiki. The proper time zone is calculated from the launch site
 * id of the launch. It also updates the flight number order based on the launch manifest order.
 *
 * Hopefully the format of the wiki does not change, but there's no real reason for it to change in the
 * forseeable future. If it does change, this script will have to be updated as necessary.
 */

const MongoClient = require('mongodb');
const moment = require('moment-timezone');
const cheerio = require('cheerio');
const request = require('request-promise-native');
const fuzz = require('fuzzball');

moment.suppressDeprecationWarnings = true;

let client;
let location;
let calculatedTimes;
let localTime;
let date;

const sites = [];
const payloads = [];
const promises = [];
const precision = [];
const flight_numbers = [];

// RegEx expressions for matching dates in the wiki manifest
// Allows for long months or short months ex. September vs Sep
// Allows for time with or without brackets ex [23:45] vs 23:45
const hour = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}\s(\[[0-9]{2}:[0-9]{2}\]|[0-9]{2}:[0-9]{2})$/;
const day = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}$/;
const month = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})$/;
const year = /^[0-9]{4}$/;

(async () => {
  try {
    client = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true });

    const db = client.db('spacex-api');
    const col = db.collection('launch');

    const launches = await col.find({ upcoming: true }).sort({ flight_number: 1 }).toArray();
    const base_flight_number = launches[0].flight_number;

    // Collect site names for time zone and payload name for fuzzy check
    launches.forEach(launch => {
      // Add temp fix for last Iridium NEXT launch because we need fuzzy
      // search to return 100% substring match, else we get SSO-A and SSO-B changing
      // because of a slight difference.
      // NOTE: Will be removed after launch
      if (launch.rocket.second_stage.payloads[0].payload_id === 'Iridium NEXT 8') {
        payloads.push('Iridium 8');
      } else {
        payloads.push(launch.rocket.second_stage.payloads[0].payload_id);
      }
      sites.push(launch.launch_site.site_id);
    });

    // Grab subreddit wiki manifest
    const result = await request('https://www.reddit.com/r/spacex/wiki/launches/manifest');
    const $ = cheerio.load(result);

    // Grab entire row, clean date, and convert to valid UTC moment date
    const manifest = $('body > div.content > div > div > table:nth-child(6) > tbody').text();
    const manifest_row = manifest.split('\n').filter(v => v !== '');

    // Filter to collect manaifest dates
    const manifest_dates = manifest_row.filter((value, index) => {
      return index % 8 === 0;
    });

    // Filter to collect payload names
    const manifest_payloads = manifest_row.filter((value, index) => {
      return (index + 3) % 8 === 0;
    });

    // Compare each payload against entire list of manifest payloads, and fuzzy match the
    // payload id against the manifest payload name. The partial match must be 100%, to avoid
    // conflicts like SSO-A and SSO-B, where a really close match would produce wrong results.
    payloads.forEach((payload, p_index) => {
      manifest_payloads.forEach((manifest_payload, m_index) => {
        if (fuzz.partial_ratio(payload, manifest_payload) === 100) {
          // Check and see if dates match a certain patten depending on the length of the
          // date given. This sets the amount of precision needed for the date.
          let mdate = manifest_dates[m_index];
          if (mdate.includes('Q')) {
            mdate = mdate.replace('Q', '');
            precision[m_index] = 'quarter';
          } else if (mdate.includes('H1')) {
            mdate = mdate.replace('H1', '1');
            precision[m_index] = 'half';
          } else if (mdate.includes('H2')) {
            mdate = mdate.replace('H2', '3');
            precision[m_index] = 'half';
          } else if (year.test(mdate)) {
            precision[m_index] = 'year';
          } else if (month.test(mdate)) {
            precision[m_index] = 'month';
          } else if (day.test(mdate)) {
            precision[m_index] = 'day';
          } else if (hour.test(mdate)) {
            precision[m_index] = 'hour';
          } else {
            console.log('Date did not match any of the existing regular expressions');
            process.exit(1);
          }

          // Store site_id for update query
          // Store manifest date for cleaning
          location = sites[p_index];
          date = manifest_dates[m_index];

          console.log(date);
          console.log(`${payload} : ${manifest_payload}`);

          // Strip brackets from time given, and tack on UTC time offset at the end for date parser
          const stripped_time = `${date.replace('[', '').replace(']', '')} +0000`;
          // Feed stripped time into all possible date formats in the wiki currently
          const time = moment(stripped_time, ['YYYY MMM D HH:mm Z', 'YYYY MMM D Z', 'YYYY MMM Z', 'YYYY Q Z', 'YYYY Z']);
          const zone = moment.tz(time, 'UTC');

          // Set timezone based on launch site id
          if (location === 'ccafs_slc_40' || location === 'ksc_lc_39a' || location === 'ccafs_lc_13') {
            localTime = time.tz('America/New_York').format();
          } else if (location === 'vafb_slc_4e' || location === 'vafb_slc_4w') {
            localTime = time.tz('America/Los_Angeles').format();
          } else {
            localTime = time.tz('America/Chicago').format();
          }

          // Add flight numbers to array to check for duplicates
          flight_numbers.push(base_flight_number + m_index);

          // Build launch time objects to update
          calculatedTimes = {
            flight_number: (base_flight_number + m_index),
            launch_date_unix: zone.unix(),
            launch_date_utc: zone.toISOString(),
            launch_date_local: localTime,
            is_tentative: true,
            tentative_max_precision: precision[m_index],
          };
          console.log(calculatedTimes);
          console.log('');

          // Another special case added for last Iridium launch
          // NOTE: Will be removed after launch
          if (payload === 'Iridium 8') {
            payload = 'Iridium NEXT 8';
          }

          // Add to array of promises to update all at once after the forEach iterations finish
          promises.push(col.updateOne({ 'rocket.second_stage.payloads.payload_id': payload }, { $set: calculatedTimes }));
        }
      });
    });

    // Check if duplicate flight numbers exist
    if ([...new Set(flight_numbers)].length < flight_numbers.length) {
      console.log('Duplicate flight numbers found');
      process.exit(1);
    }

    // Execute all our stored update promises
    const output = await Promise.all(promises);

    // Display if the document was found, and if it was modified or not
    output.forEach(doc => {
      console.log(`N: ${doc.result.n}`);
      console.log(`Modified: ${doc.result.nModified}`);
    });
  } catch (err) {
    console.log(err.stack);
  }

  if (client) {
    client.close();
  }
})();
<|endoftext|>


<commit_before>// Copyright 2018-2022, University of Colorado Boulder

/**
 * Shape for the 'stop' icon that appears on buttons and other UI components.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

import { Shape } from '../../kite/js/imports.js';
import sceneryPhet from './sceneryPhet.js';

class StopIconShape extends Shape {

  /**
   * @param {number} width
   */
  constructor( width ) {
    super();

    // rectangle
    this.rect( 0, 0, width, width );
  }
}

sceneryPhet.register( 'StopIconShape', StopIconShape );
export default StopIconShape;<commit_msg>// @ts-nocheck<commit_after>// Copyright 2018-2022, University of Colorado Boulder

// @ts-nocheck
/**
 * Shape for the 'stop' icon that appears on buttons and other UI components.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

import { Shape } from '../../kite/js/imports.js';
import sceneryPhet from './sceneryPhet.js';

class StopIconShape extends Shape {

  /**
   * @param {number} width
   */
  constructor( width ) {
    super();

    // rectangle
    this.rect( 0, 0, width, width );
  }
}

sceneryPhet.register( 'StopIconShape', StopIconShape );
export default StopIconShape;<|endoftext|>


<commit_before>var request = require('request');
var passport = {};
var os = require('os');

passport.getIP = function (port) {
    var self = this;

    self.ip = getIpAddress(port);
    return self.ip;

};

function getIpAddress(port) {
    var ifaces = os.networkInterfaces();
    var ipAddress = 'localhost';
    for (var dev in ifaces) {
        ifaces[dev].forEach(function (details) {
            if (details.family == 'IPv4' && !details.internal) {
                ipAddress = details.address;
            }
        });
    }
    var link = 'http://' + ipAddress + ':' + port;
    return link;
}

passport.authorize = function (req, res, next) {
  console.log('req.session.passportToken:::'+req.session.passportToken);
    if (req.session.passportToken) {
        next(req, res);
    } else {
        res.redirect(passport.opt.passport + '/login?backUrl=' + passport.opt.backUrl + '/passportAuth');
    }
};

passport.init = function (router, opt) {
    passport.opt = opt;
    router.get('/passportAuth', function (req, res) {
        var code = req.query.code;
        request(passport.opt.passport+'/token', {
            method: 'POST',
            form: {code: code}
        }, function (re, rs, obj) {
          console.log(obj)
            obj = JSON.parse(obj);
            req.session.passportToken = obj.model.token;
            passport.login(req, res, function () {
                res.redirect(passport.opt.backUrl);
            });

        });
    });
};

passport.login = function (req, res, cb) {
    var passportToken = req.session.passportToken;
  console.log(passportToken)
  console.log(passport.opt.passport)
  var url=passport.opt.passport+"/user?token="+passportToken
  console.log("url::"+url)
    request({uri:url}, function (error, response, body) {
      console.log("error:"+error)
      console.log("response:"+response)
      console.log("body::"+body)
        obj = JSON.parse(body);
        if (obj.success) {
            if(obj.model.user.__v!=undefined){
                delete obj.model.user.__v;
            }
            req.session.user = obj.model.user;
            cb(obj);
        } else {
            req.session.passportToken = null;
            res.redirect(passport.opt.passport + '/login?backUrl=' + passport.opt.backUrl + '/passportAuth');
        }

    });
};

passport.logout = function (req, res, cb) {
    req.session.destroy(function (err) {
        if (err) {
            res.status(500).send({
                success: false,
                model: {
                    error: '注销失败'
                }
            });
        } else {
            res.status(200).send({
                success: true
            });
        }
    });
};

module.exports = passport;
<commit_msg>swich mongodb ip<commit_after>var request = require('request');
var passport = {};
var os = require('os');

passport.getIP = function (port) {
    var self = this;

    self.ip = getIpAddress(port);
    return self.ip;

};

function getIpAddress(port) {
    var ifaces = os.networkInterfaces();
    var ipAddress = 'localhost';
    for (var dev in ifaces) {
        ifaces[dev].forEach(function (details) {
            if (details.family == 'IPv4' && !details.internal) {
                ipAddress = details.address;
            }
        });
    }
    var link = 'http://' + ipAddress + ':' + port;
    return link;
}

passport.authorize = function (req, res, next) {
  console.log('req.session.passportToken:::'+req.session.passportToken);
    if (req.session.passportToken) {
        next(req, res);
    } else {
        res.redirect(passport.opt.passport + '/login?backUrl=' + passport.opt.backUrl + '/passportAuth');
    }
};

passport.init = function (router, opt) {
    passport.opt = opt;
    router.get('/passportAuth', function (req, res) {
        var code = req.query.code;
        request(passport.opt.passport+'/token', {
            method: 'POST',
            form: {code: code}
        }, function (re, rs, obj) {
          console.log("objobj:::"+obj)
            obj = JSON.parse(obj);
            req.session.passportToken = obj.model.token;
            passport.login(req, res, function () {
                res.redirect(passport.opt.backUrl);
            });

        });
    });
};

passport.login = function (req, res, cb) {
    var passportToken = req.session.passportToken;
  console.log(passportToken)
  console.log(passport.opt.passport)
  var url=passport.opt.passport+"/user?token="+passportToken
  console.log("url::"+url)
    request({uri:url}, function (error, response, body) {
      console.log("error:"+error)
      console.log("response:"+response)
      console.log("body::"+body)
        obj = JSON.parse(body);
        if (obj.success) {
            if(obj.model.user.__v!=undefined){
                delete obj.model.user.__v;
            }
            req.session.user = obj.model.user;
            cb(obj);
        } else {
            req.session.passportToken = null;
            res.redirect(passport.opt.passport + '/login?backUrl=' + passport.opt.backUrl + '/passportAuth');
        }

    });
};

passport.logout = function (req, res, cb) {
    req.session.destroy(function (err) {
        if (err) {
            res.status(500).send({
                success: false,
                model: {
                    error: '注销失败'
                }
            });
        } else {
            res.status(200).send({
                success: true
            });
        }
    });
};

module.exports = passport;
<|endoftext|>


<commit_before>app.factory('AuthFactory', ['$http', '$firebaseAuth', function($http, $firebaseAuth){
  console.log('AuthFactory running');

  var auth = $firebaseAuth();
  var currentUser;
  var loggedIn = false;
  var userStatus = {};

  function logIn(userType) {
    return auth.$signInWithPopup("google").then(function(firebaseUser) {
      // console.log("Firebase Authenticated as: ", firebaseUser.user.displayName);
      // console.log('firebaseUser.user.email: ', firebaseUser.user.email);
      currentUser = firebaseUser.user;
      // console.log('currentUser: ', currentUser);
      // console.log('firebaseUser: ', firebaseUser);
      console.log('USER TYPE:', userType);
      if(currentUser) {
        getUser(currentUser, userType);
      }
    });
  }

  function getUser(currentUser, userType){
    currentUser.getToken().then(function(idToken){
      console.log('ID TOKEN:', idToken);
      $http({
        method: 'GET',
        url: '/users.route',
        headers: {
          id_token: idToken,
          type: userType
        }
      })
      .then(function(response) {
        // console.log(response.data);
        userStatus.userType = response.data.userType;
        console.log(userStatus);
      });
      userStatus.isLoggedIn = true;
      // console.log(userStatus);
    });
  }

  auth.$onAuthStateChanged(function(firebaseUser){

    // firebaseUser will be null if not logged in
    currentUser = firebaseUser;
    console.log("CURRENT USER", currentUser);
    if(currentUser) {
      getUser(currentUser);
    } else {
      userStatus.isLoggedIn = false;
    }
    console.log('User is logged in:', userStatus.isLoggedIn);
  });

  function logOut() {
    return auth.$signOut().then(function() {
      currentUser = undefined;
      userStatus.isLoggedIn = false;
      userStatus.userType = "None";
      console.log('logged out');
      console.log('currentUser: ', currentUser);
    });
  }

  // TODO: Have Oliver explain what these variables are
  var publicApi = {
    auth: auth,
    userStatus: userStatus,
    logIn: function(userType) {
      return logIn(userType);
    },
    logOut: function() {
      return logOut();
    }
  };

  return publicApi;

}]);
<commit_msg>Add currentUser to public api<commit_after>app.factory('AuthFactory', ['$http', '$firebaseAuth', function($http, $firebaseAuth){
  console.log('AuthFactory running');

  var auth = $firebaseAuth();
  var currentUser;
  var loggedIn = false;
  var userStatus = {};

  function logIn(userType) {
    return auth.$signInWithPopup("google").then(function(firebaseUser) {
      // console.log("Firebase Authenticated as: ", firebaseUser.user.displayName);
      // console.log('firebaseUser.user.email: ', firebaseUser.user.email);
      currentUser = firebaseUser.user;
      // console.log('currentUser: ', currentUser);
      // console.log('firebaseUser: ', firebaseUser);
      console.log('USER TYPE:', userType);
      if(currentUser) {
        getUser(currentUser, userType);
      }
    });
  }

  function getUser(currentUser, userType){
    currentUser.getToken().then(function(idToken){
      console.log('ID TOKEN:', idToken);
      $http({
        method: 'GET',
        url: '/users.route',
        headers: {
          id_token: idToken,
          type: userType
        }
      })
      .then(function(response) {
        // console.log(response.data);
        userStatus.userType = response.data.userType;
        userStatus.newUser = response.data.newUser;
        console.log(userStatus);
      });
      userStatus.isLoggedIn = true;
      // console.log(userStatus);
    });
  }

  auth.$onAuthStateChanged(function(firebaseUser){

    // firebaseUser will be null if not logged in
    currentUser = firebaseUser;
    console.log("CURRENT USER", currentUser);
    if(currentUser) {
      getUser(currentUser);
    } else {
      userStatus.isLoggedIn = false;
    }
    console.log('User is logged in:', userStatus.isLoggedIn);
  });

  function logOut() {
    return auth.$signOut().then(function() {
      currentUser = undefined;
      userStatus.isLoggedIn = false;
      userStatus.userType = "None";
      console.log('logged out');
      console.log('currentUser: ', currentUser);
    });
  }

  // TODO: Have Oliver explain what these variables are
  var publicApi = {
    auth: auth,
    userStatus: userStatus,
    currentUser: currentUser,
    logIn: function(userType) {
      return logIn(userType);
    },
    logOut: function() {
      return logOut();
    }
  };

  return publicApi;

}]);
<|endoftext|>


<commit_before>var debug = require('debug')('bankai.graph-service-worker')
var findup = require('@choojs/findup')
var assert = require('assert')
var path = require('path')

var browserify = require('browserify')
var watchify = require('watchify')
var tinyify = require('tinyify')
var brfs = require('brfs')

var ttyError = require('./tty-error')
var exorcise = require('./exorcise')
var utils = require('./utils')

var filenames = [
  'service-worker.js',
  'sw.js'
]

module.exports = node

function node (state, createEdge) {
  var entry = state.metadata.entry
  var self = this
  var unwatch

  assert.equal(typeof entry, 'string', 'bankai.service-worker: state.metadata.entries should be type string')

  var basedir = state.metadata.dirname

  if (state.metadata.watch && !state.metadata.watchers.serviceWorker) {
    state.metadata.watchers.serviceWorker = true
    debug('watching ' + basedir + ' for ' + filenames.join(', '))
    unwatch = utils.watch(basedir, filenames, parse)
    this.on('close', function () {
      debug('closing file watcher')
      if (unwatch) unwatch()
    })
  }

  parse()

  function parse () {
    find(basedir, filenames, function (err, filename) {
      if (err) {
        state.metadata.serviceWorker = 'service-worker.js'
        return createEdge('bundle', Buffer.from(''), {
          mime: 'application/javascript'
        })
      }

      // Expose what the original file name of the service worker was
      state.metadata.serviceWorker = path.basename(filename)

      var b = browserify(browserifyOpts([ filename ]))

      if (state.metadata.watch && !state.metadata.watchers.serviceWorker) {
        if (unwatch) unwatch() // File now exists, no need to have double watchers
        state.metadata.watchers.serviceWorker = true
        debug('watchify: watching ' + filename)
        b = watchify(b)
        b.on('update', function () {
          debug('watchify: update detected in ' + filename)
          bundleScripts()
        })
        self.on('close', function () {
          debug('closing file watcher')
          b.close()
        })
      }

      var env = Object.assign({}, process.env, fileEnv(state))
      b.transform(brfs)
      if (!state.metadata.watch) b.plugin(tinyify, { env: env })

      bundleScripts()

      function bundleScripts () {
        b.bundle(function (err, bundle) {
          if (err) {
            delete err.stream
            err = ttyError('service-worker', 'browserify.bundle', err)
            return self.emit('error', 'scripts', 'browserify.bundle', err)
          }
          var mapName = 'bankai-service-worker.js.map'
          exorcise(bundle, mapName, function (err, bundle, map) {
            if (err) return self.emit('error', 'service-worker', 'exorcise', err)
            createEdge(mapName, map, {
              mime: 'application/json'
            })
            createEdge('bundle', bundle, {
              mime: 'application/javascript'
            })
          })
        })
      }
    })
  }
}

function browserifyOpts (entries) {
  assert.ok(Array.isArray(entries), 'browserifyOpts: entries should be an array')
  return {
    debug: true,
    entries: entries,
    packageCache: {},
    cache: {}
  }
}

function find (rootname, arr, done) {
  if (!arr.length) return done(new Error('Could not find files'))
  var filename = arr[0]
  var newArr = arr.slice(1)
  findup(rootname, filename, function (err, dirname) {
    if (err) return find(rootname, newArr, done)
    done(null, path.join(dirname, filename))
  })
}

function fileEnv (state) {
  var script = [
    `${state.scripts.bundle.hash.toString('hex').slice(0, 16)}/bundle.js`
  ]
  var style = [`${state.styles.bundle.hash.toString('hex').slice(0, 16)}/bundle.css`]
  var assets = split(state.assets.list.buffer)
  var doc = split(state.documents.list.buffer)
  var manifest = ['/manifest.json']

  var files = [].concat(script, style, assets, doc, manifest)
  files = files.filter(function (file) {
    return file
  })

  return {
    STYLE_LIST: style,
    SCRIPT_LIST: script,
    ASSET_LIST: assets,
    DOCUMENT_LIST: doc,
    MANIFEST_LIST: manifest,
    FILE_LIST: files
  }

  function split (buf) {
    var str = String(buf)
    return str.split(',')
  }
}
<commit_msg>use utils.find() (#482)<commit_after>var debug = require('debug')('bankai.graph-service-worker')
var assert = require('assert')
var path = require('path')

var browserify = require('browserify')
var watchify = require('watchify')
var tinyify = require('tinyify')
var brfs = require('brfs')

var ttyError = require('./tty-error')
var exorcise = require('./exorcise')
var utils = require('./utils')

var filenames = [
  'service-worker.js',
  'sw.js'
]

module.exports = node

function node (state, createEdge) {
  var entry = state.metadata.entry
  var self = this
  var unwatch

  assert.equal(typeof entry, 'string', 'bankai.service-worker: state.metadata.entries should be type string')

  var basedir = state.metadata.dirname

  if (state.metadata.watch && !state.metadata.watchers.serviceWorker) {
    state.metadata.watchers.serviceWorker = true
    debug('watching ' + basedir + ' for ' + filenames.join(', '))
    unwatch = utils.watch(basedir, filenames, parse)
    this.on('close', function () {
      debug('closing file watcher')
      if (unwatch) unwatch()
    })
  }

  parse()

  function parse () {
    utils.find(basedir, filenames, function (err, filename) {
      if (err) {
        state.metadata.serviceWorker = 'service-worker.js'
        return createEdge('bundle', Buffer.from(''), {
          mime: 'application/javascript'
        })
      }

      // Expose what the original file name of the service worker was
      state.metadata.serviceWorker = path.basename(filename)

      var b = browserify(browserifyOpts([ filename ]))

      if (state.metadata.watch && !state.metadata.watchers.serviceWorker) {
        if (unwatch) unwatch() // File now exists, no need to have double watchers
        state.metadata.watchers.serviceWorker = true
        debug('watchify: watching ' + filename)
        b = watchify(b)
        b.on('update', function () {
          debug('watchify: update detected in ' + filename)
          bundleScripts()
        })
        self.on('close', function () {
          debug('closing file watcher')
          b.close()
        })
      }

      var env = Object.assign({}, process.env, fileEnv(state))
      b.transform(brfs)
      if (!state.metadata.watch) b.plugin(tinyify, { env: env })

      bundleScripts()

      function bundleScripts () {
        b.bundle(function (err, bundle) {
          if (err) {
            delete err.stream
            err = ttyError('service-worker', 'browserify.bundle', err)
            return self.emit('error', 'scripts', 'browserify.bundle', err)
          }
          var mapName = 'bankai-service-worker.js.map'
          exorcise(bundle, mapName, function (err, bundle, map) {
            if (err) return self.emit('error', 'service-worker', 'exorcise', err)
            createEdge(mapName, map, {
              mime: 'application/json'
            })
            createEdge('bundle', bundle, {
              mime: 'application/javascript'
            })
          })
        })
      }
    })
  }
}

function browserifyOpts (entries) {
  assert.ok(Array.isArray(entries), 'browserifyOpts: entries should be an array')
  return {
    debug: true,
    entries: entries,
    packageCache: {},
    cache: {}
  }
}

function fileEnv (state) {
  var script = [
    `${state.scripts.bundle.hash.toString('hex').slice(0, 16)}/bundle.js`
  ]
  var style = [`${state.styles.bundle.hash.toString('hex').slice(0, 16)}/bundle.css`]
  var assets = split(state.assets.list.buffer)
  var doc = split(state.documents.list.buffer)
  var manifest = ['/manifest.json']

  var files = [].concat(script, style, assets, doc, manifest)
  files = files.filter(function (file) {
    return file
  })

  return {
    STYLE_LIST: style,
    SCRIPT_LIST: script,
    ASSET_LIST: assets,
    DOCUMENT_LIST: doc,
    MANIFEST_LIST: manifest,
    FILE_LIST: files
  }

  function split (buf) {
    var str = String(buf)
    return str.split(',')
  }
}
<|endoftext|>


<commit_before>var Project = require('../models/project');
var User = require('../models/user');
var express = require('express');
var router = express.Router();

router.route('/projects').post(createProject);
router.route('/projects').get(getProjects);
router.route('/projects/:project_id').get(getProject);
router.route('/projects/:project_id').put(editProject);
router.route('/projects/:project_id').delete(deleteProject);

module.exports = router;

function createProject(req, res)
{
    var project = new Project();

    if (!("name" in req.body)){
        res.json({message : "Error : No name given !"});
        return ;
    } else
        project.name = req.body.name;

    if (!("type" in req.body)){
        res.json({message : "Error : No type given !"});
        return ;
    } else
        project.type = req.body.type;

    if (!("authorID" in req.body)){
        res.json({message : "Error : No authorID given !"});
        return ;
    }
    else {
        User.findOne({username : req.body.authorID}, function(err, user){
            if (err) {
                res.send(err);
            } else if (user === null){
                res.send({message : "Error : authorID not found !"});
            } else {
                project.author = user;
                project.save(function(err){
                    if (err) res.send(err);
                    res.json({ message: 'Project created !' });
                });
            }
        });
    }
}

function getProjects(req, res)
{
    Project.find(function(err, projects)
    {
        if (err) res.send(err);
        res.json(projects);
    });
}

function getProject(req, res)
{
    Project.findById(req.params.project_id, function(err, project)
    {
        if (err) res.send(err);
        res.json(project);
    });
}

function editProject(req, res)
{
    // use our bear model to find the bear we want
    Project.findById(req.params.project_id, function(err, project)
    {
        if (err) res.send(err);
        project.name = req.body.name;  // update the bears info

        // save the bear
        project.save(function(err)
        {
            if (err) res.send(err);
            res.json({ message: 'Project updated!' });
        });

    });
}
function deleteProject(req, res)
{
    Project.remove({_id: req.params.project_id}, function(err, project)
    {
        if (err) res.send(err);
        res.json({ message: 'Project deleted!' });
    });
}<commit_msg>Modification of authorID to authorUsername (more explicit)<commit_after>var Project = require('../models/project');
var User = require('../models/user');
var express = require('express');
var router = express.Router();

router.route('/projects').post(createProject);
router.route('/projects').get(getProjects);
router.route('/projects/:project_id').get(getProject);
router.route('/projects/:project_id').put(editProject);
router.route('/projects/:project_id').delete(deleteProject);

module.exports = router;

function createProject(req, res)
{
    var project = new Project();

    if (!("name" in req.body)){
        res.json({message : "Error : No name given !"});
        return ;
    } else
        project.name = req.body.name;

    if (!("type" in req.body)){
        res.json({message : "Error : No type given !"});
        return ;
    } else
        project.type = req.body.type;

    if (!("authorUsername" in req.body)){
        res.json({message : "Error : No authorUsername given !"});
        return ;
    }
    else {
        User.findOne({username : req.body.authorUsername}, function(err, user){
            if (err) {
                res.send(err);
            } else if (user === null){
                res.send({message : "Error : authorUsername not found !"});
            } else {
                project.author = user;
                project.save(function(err){
                    if (err) res.send(err);
                    res.json({ message: 'Project created !' });
                });
            }
        });
    }
}

function getProjects(req, res)
{
    Project.find(function(err, projects)
    {
        if (err) res.send(err);
        res.json(projects);
    });
}

function getProject(req, res)
{
    Project.findById(req.params.project_id, function(err, project)
    {
        if (err) res.send(err);
        res.json(project);
    });
}

function editProject(req, res)
{
    // use our bear model to find the bear we want
    Project.findById(req.params.project_id, function(err, project)
    {
        if (err) res.send(err);
        project.name = req.body.name;  // update the bears info

        // save the bear
        project.save(function(err)
        {
            if (err) res.send(err);
            res.json({ message: 'Project updated!' });
        });

    });
}
function deleteProject(req, res)
{
    Project.remove({_id: req.params.project_id}, function(err, project)
    {
        if (err) res.send(err);
        res.json({ message: 'Project deleted!' });
    });
}<|endoftext|>


<commit_before>/*globals alert*/
var $        = require('jquery'),
    _        = require('underscore'),
    Facility = require('cloud/models/facility');

var location = function() {
  var lat, lon;

  if ( navigator.geolocation ) {
    navigator.geolocation.getCurrentPosition(function(position) {
      lat = position.coords.latitude;
      lon = position.coords.longitude;
    }, function(error) {
      console.log(error);
    });
  }

  if (!(lat && lon)) {
    lat = 37.782355;
    lon = -122.409825;
  }

  return {lat: lat, lon: lon};
};

var queryFunction = function(runWhere) {
  if ( runWhere === 'cloud' ) {
    return _.partial(Parse.Cloud.run, "browse");
  } else {
    return require('cloud/lib/browse');
  }
};

var submit = function(params) {
  // to keep track of when it finishes
  var deferred = $.Deferred();

  // choose where to run the query
  // var query = queryFunction(params.runwhere);
  var query = queryFunction('browser');

  // add location if proximity sorting
  if ( params.sort === 'near' ) {
    $.extend(params, location());
  }

  query(params, {
    success: function(result) {
      deferred.resolve(result);
      // dumpToDOM(result);
    },

    error: function(err) {
      deferred.reject(err);
    }
  });

  return deferred.promise();
};

// TODO -- hoist this up a layer into "browse" -- or wherever we keep the direct parse communication lib.
var getByID = function(id) {
  var deferred = $.Deferred();

  var q = new Parse.Query(Facility);
  q.include("services");
  q.get(id, {
    success: function(result) {
      deferred.resolve(result);
    },
    error: function(err) {
      deferred.reject(err);
    }
  });

  return deferred.promise();
};

module.exports = { submit: submit, getByID: getByID };
<commit_msg>actually searching using current location<commit_after>/*globals alert*/
var $        = require('jquery'),
    _        = require('underscore'),
    Facility = require('cloud/models/facility');

var runWithLocation = function(callback) {
  if ( navigator.geolocation ) {
    navigator.geolocation.getCurrentPosition(function(position) {
      callback(position.coords.latitude,
               position.coords.longitude);
    }, function(error) {
      callback(37.782355, -122.409825);
    });
  }
};

var queryFunction = function(runWhere) {
  if ( runWhere === 'cloud' ) {
    return _.partial(Parse.Cloud.run, "browse");
  } else {
    return require('cloud/lib/browse');
  }
};

var submit = function(params) {
  // to keep track of when it finishes
  var deferred = $.Deferred();

  // choose where to run the query
  // var query = queryFunction(params.runwhere);

  // add location if proximity sorting
  if ( params.sort === 'near' ) {
    runWithLocation(function(lat, lon) {
      $.extend(params, {lat: lat, lon: lon});
      performQuery(params, deferred);
    });
  } else {
    performQuery(params, deferred);
  }

  return deferred.promise();
};

var performQuery = function(params, deferred) {
  var query = queryFunction('browser');

  query(params, {
    success: function(result) {
      deferred.resolve(result);
      // dumpToDOM(result);
    },

    error: function(err) {
      deferred.reject(err);
    }
  });
};

// TODO -- hoist this up a layer into "browse" -- or wherever we keep the direct parse communication lib.
var getByID = function(id) {
  var deferred = $.Deferred();

  var q = new Parse.Query(Facility);
  q.include("services");
  q.get(id, {
    success: function(result) {
      deferred.resolve(result);
    },
    error: function(err) {
      deferred.reject(err);
    }
  });

  return deferred.promise();
};

module.exports = { submit: submit, getByID: getByID };
<|endoftext|>