<commit_before>angular.module('starter.controllers', [])

    .controller('FileCtrl', function ($scope) {
        var self = this;

        self.loading = true;

        self.openFile = function (filename) {
            var finder = new Appworks.Finder(showContents, showContents);

            function showContents(data) {
                console.log(data);
                $scope.$apply(self.openedFile = data);
            }

            finder.open('/', filename);
        };

        self.listDirectory = function () {
            var finder = new Appworks.Finder(showContents, showContents);

            function showContents(data) {
                console.log(data);
                $scope.$apply(self.openedDirectory = data);
            }

            finder.list('/');
        };

        self.storeFile = function () {
            var storage = new Appworks.SecureStorage(setFile, stopLoading);
            self.imgSrc = null;
            self.loading = true;
            self.showStoredFileAsImage = false;

            function setFile(file) {
                self.storedFile = file.nativeURL;
                stopLoading();
            }

            function stopLoading() {
                console.log('AWJS: File downloaded successfully.');
                self.loading = false;
                $scope.$apply();
            }

            storage.store('http://thecatapi.com/api/images/get', 'file.jpg');
        };

        self.downloadFile = function (shared) {
            var fileTransfer = new Appworks.AWFileTransfer(showFile, errorHandler);

            function showFile(file) {
                console.log(file);
                self.downloadedFile = file.nativeURL;
                $scope.$apply();
            }

            fileTransfer.progressHandler(function (progress) {
                console.log(progress);
            });

            fileTransfer.download('http://thecatapi.com/api/images/get', 'file.jpg');
        };

        self.downloadFileShared = function () {
            var fileTransfer = new Appworks.AWFileTransfer(showFile, errorHandler);

            function showFile(file) {
                console.log(file);
                self.downloadedFileShared = file;
                $scope.$apply();
            }

            fileTransfer.download('http://thecatapi.com/api/images/get', 'file.jpg', null, true);
        };

        self.getFile = function () {
            var storage = new Appworks.SecureStorage(showImage, errorHandler);

            self.showStoredFileAsImage = false;

            function showImage(file) {
                self.storedFile = file.nativeURL;
                self.showStoredFileAsImage = true;
                $scope.$apply();
            }

            storage.retrieve('file.jpg');
        };

        function errorHandler(err) {
            console.log(err);
            self.loading = false;
            $scope.$apply();
        }
    })

    .controller('CacheCtrl', function () {

        var self = this;

        self.key = 'myKey';
        self.data = 1234;

        self.setItem = function (key, data) {
            self.data = null;
            self.cacheData = null;
            appworks.cache.setItem(key, data);
        };

        self.getItem = function (key) {
            appworks.cache.getItem(key, function (data) {
                if (!data) {
                    alert('This key does not exist in the cache');
                }
                self.cacheData = data;
            });
        };

        self.clear = function () {
            self.cacheData = null;
            self.key = null;
            self.data = null;
            appworks.cache.clear();
            self.$applyAsync();
        };
    })

    .controller('OfflineCtrl', function ($scope, $timeout) {
        var self = this,
            url = 'https://randomuser.me/api/',
            options1 = {eventListener: 'myEvent1', method: 'GET'},
            options2 = {eventListener: 'myEvent2', method: 'GET'},
            options3 = {eventListener: 'myEvent3', method: 'GET'};

        self.users = [];

        self.queue = function (options) {
            self.err = null;
            if (options) {
                appworks.offline.queue(options.url, options.options).then(options.success, options.error);
            } else {
                appworks.offline.queue(url, options1).then(successFn, errorFn);
            }
        };

        self.queueMultiple = function () {
            self.users = [];
            $timeout(function () {
                self.queue({url: url, options: options1, success: successFn, error: errorFn});
            }, 1000);
            $timeout(function () {
                self.queue({url: url, options: options2, success: successFn2, error: errorFn});
            }, 1000);
            $timeout(function () {
                self.queue({url: url, options: options3, success: successFn3, error: errorFn});
            }, 1000);
        };

        function addUser(user) {
            $scope.$apply(self.users.push(user));
        }

        function successFn(res) {
            res = JSON.parse(res.data);
            addUser(res.results[0]);
            appworks.offline.removeEventHandler('myEvent1', successFn);
        }

        function successFn2(res) {
            res = JSON.parse(res.data);
            addUser(res.results[0]);
            appworks.offline.removeEventHandler('myEvent2', successFn2);
        }

        function successFn3(res) {
            res = JSON.parse(res.data);
            addUser(res.results[0]);
            appworks.offline.removeEventHandler('myEvent3', successFn3);
        }

        function errorFn(err) {
            $scope.$apply(self.err = err);
        }
    })

    .controller('DeviceCtrl', function ($scope) {
        var self = this;

        self.notifications = [];
        self.notificationsEnabled = true;

        $scope.$watch('device.notificationsEnabled', function (on) {
            if (on) {
                self.enableNotifications();
            } else {
                self.stopNotifications();
            }
        });

        self.scanQRCode = function () {
            var qrScanner = new Appworks.QRReader(onScan, onScan);

            qrScanner.scan();

            function onScan(data) {
                $scope.$apply(self.qrScanResult = data);
            }
        };

        self.openContactPicker = function () {
            var contacts = new Appworks.AWContacts(onContactSuccess, errorHandler);

            function onContactSuccess(contact) {
                self.contactPickerResult = {
                    name: contact.name.formatted,
                    number: contact.phoneNumbers[0].value,
                    photo: contact.photos[0].value
                };
                $scope.$apply();
            }
            contacts.pickContact();
        };

        function errorHandler(err) {
            console.log(err);
        }

        self.openCamera = function () {
            var camera = new Appworks.AWCamera(function (dataUrl) {
                $scope.$apply(self.imgSrc = dataUrl);
            }, function (err) {
                self.err = err;
                $scope.$apply();
            });
            self.err = null;
            self.imgSrc = null;
            camera.takePicture();
        };

        self.openGallery = function () {
            var gallery = new Appworks.AWCamera(function (dataUrl) {
                $scope.$apply(self.imgSrc = dataUrl);
            }, function (err) {
                self.err = err;
                $scope.$apply();
            });
            self.err = null;
            self.imgSrc = null;
            gallery.openGallery();
        };

        //self.getLocation = function () {
        //    Appworks.Geolocation.getCurrentPosition(onSuccess, onError);
        //
        //    function onSuccess(position) {
        //        console.log(position);
        //        alert(
        //            'Latitude: '          + position.coords.latitude          + '\n' +
        //            'Longitude: '         + position.coords.longitude         + '\n' +
        //            'Altitude: '          + position.coords.altitude          + '\n' +
        //            'Accuracy: '          + position.coords.accuracy          + '\n' +
        //            'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
        //            'Heading: '           + position.coords.heading           + '\n' +
        //            'Speed: '             + position.coords.speed             + '\n' +
        //            'Timestamp: '         + position.timestamp                + '\n');
        //    }
        //
        //    function onError(err) {
        //        console.log(err);
        //        alert('Unable to get current location.' +
        //            ' In general this means the device has no network connectivity and/or cannot get a satellite fix');
        //    }
        //};

        //Appworks.Notifications.handler(function (notification) {
        //    $scope.$apply(self.notifications.push(notification));
        //});

        self.clearNotifications = function () {
            self.notifications = [];
        };

        //self.stopNotifications = function () {
        //    appworks.notifications.off();
        //};

        //self.enableNotifications = function () {
        //    appworks.notifications.on();
        //};

        self.getNotifications = function () {
            self.syncNotifications();
        };

        //self.syncNotifications = function () {
        //    $scope.$applyAsync(self.notifications = appworks.notifications.get());
        //};
    })

    .controller('AuthCtrl', function ($scope) {

        var auth = new Appworks.Auth(onAuth, onAuth);

        function onAuth(data) {
            console.log(data);
            $scope.$apply($scope.response = data.data);
        }

        this.authenticate = function () {
            auth.authenticate();
        };
    });
<commit_msg>bug fixes for contacts<commit_after>angular.module('starter.controllers', [])

    .controller('FileCtrl', function ($scope) {
        var self = this;

        self.loading = true;

        self.openFile = function (filename) {
            var finder = new Appworks.Finder(showContents, showContents);

            function showContents(data) {
                console.log(data);
                $scope.$apply(self.openedFile = data);
            }

            finder.open('/', filename);
        };

        self.listDirectory = function () {
            var finder = new Appworks.Finder(showContents, showContents);

            function showContents(data) {
                console.log(data);
                $scope.$apply(self.openedDirectory = data);
            }

            finder.list('/');
        };

        self.storeFile = function () {
            var storage = new Appworks.SecureStorage(setFile, stopLoading);
            self.imgSrc = null;
            self.loading = true;
            self.showStoredFileAsImage = false;

            function setFile(file) {
                self.storedFile = file.nativeURL;
                stopLoading();
            }

            function stopLoading() {
                console.log('AWJS: File downloaded successfully.');
                self.loading = false;
                $scope.$apply();
            }

            storage.store('http://thecatapi.com/api/images/get', 'file.jpg');
        };

        self.downloadFile = function (shared) {
            var fileTransfer = new Appworks.AWFileTransfer(showFile, errorHandler);

            function showFile(file) {
                console.log(file);
                self.downloadedFile = file.nativeURL;
                $scope.$apply();
            }

            fileTransfer.progressHandler(function (progress) {
                console.log(progress);
            });

            fileTransfer.download('http://thecatapi.com/api/images/get', 'file.jpg');
        };

        self.downloadFileShared = function () {
            var fileTransfer = new Appworks.AWFileTransfer(showFile, errorHandler);

            function showFile(file) {
                console.log(file);
                self.downloadedFileShared = file;
                $scope.$apply();
            }

            fileTransfer.download('http://thecatapi.com/api/images/get', 'file.jpg', null, true);
        };

        self.getFile = function () {
            var storage = new Appworks.SecureStorage(showImage, errorHandler);

            self.showStoredFileAsImage = false;

            function showImage(file) {
                self.storedFile = file.nativeURL;
                self.showStoredFileAsImage = true;
                $scope.$apply();
            }

            storage.retrieve('file.jpg');
        };

        function errorHandler(err) {
            console.log(err);
            self.loading = false;
            $scope.$apply();
        }
    })

    .controller('CacheCtrl', function () {

        var self = this;

        self.key = 'myKey';
        self.data = 1234;

        self.setItem = function (key, data) {
            self.data = null;
            self.cacheData = null;
            appworks.cache.setItem(key, data);
        };

        self.getItem = function (key) {
            appworks.cache.getItem(key, function (data) {
                if (!data) {
                    alert('This key does not exist in the cache');
                }
                self.cacheData = data;
            });
        };

        self.clear = function () {
            self.cacheData = null;
            self.key = null;
            self.data = null;
            appworks.cache.clear();
            self.$applyAsync();
        };
    })

    .controller('OfflineCtrl', function ($scope, $timeout) {
        var self = this,
            url = 'https://randomuser.me/api/',
            options1 = {eventListener: 'myEvent1', method: 'GET'},
            options2 = {eventListener: 'myEvent2', method: 'GET'},
            options3 = {eventListener: 'myEvent3', method: 'GET'};

        self.users = [];

        self.queue = function (options) {
            self.err = null;
            if (options) {
                appworks.offline.queue(options.url, options.options).then(options.success, options.error);
            } else {
                appworks.offline.queue(url, options1).then(successFn, errorFn);
            }
        };

        self.queueMultiple = function () {
            self.users = [];
            $timeout(function () {
                self.queue({url: url, options: options1, success: successFn, error: errorFn});
            }, 1000);
            $timeout(function () {
                self.queue({url: url, options: options2, success: successFn2, error: errorFn});
            }, 1000);
            $timeout(function () {
                self.queue({url: url, options: options3, success: successFn3, error: errorFn});
            }, 1000);
        };

        function addUser(user) {
            $scope.$apply(self.users.push(user));
        }

        function successFn(res) {
            res = JSON.parse(res.data);
            addUser(res.results[0]);
            appworks.offline.removeEventHandler('myEvent1', successFn);
        }

        function successFn2(res) {
            res = JSON.parse(res.data);
            addUser(res.results[0]);
            appworks.offline.removeEventHandler('myEvent2', successFn2);
        }

        function successFn3(res) {
            res = JSON.parse(res.data);
            addUser(res.results[0]);
            appworks.offline.removeEventHandler('myEvent3', successFn3);
        }

        function errorFn(err) {
            $scope.$apply(self.err = err);
        }
    })

    .controller('DeviceCtrl', function ($scope) {
        var self = this;

        self.notifications = [];
        self.notificationsEnabled = true;

        $scope.$watch('device.notificationsEnabled', function (on) {
            if (on) {
                self.enableNotifications();
            } else {
                self.stopNotifications();
            }
        });

        self.scanQRCode = function () {
            var qrScanner = new Appworks.QRReader(onScan, onScan);

            qrScanner.scan();

            function onScan(data) {
                $scope.$apply(self.qrScanResult = data);
            }
        };

        self.openContactPicker = function () {
            var contacts = new Appworks.AWContacts(onContactSuccess, errorHandler);

            function onContactSuccess(contact) {
                self.contactPickerResult = {
                    name: contact.name.formatted,
                    number: contact.phoneNumbers[0].value,
                    photo: contact.photos && contact.photos[0].value
                };
                console.log('selected contact:', contact);
                $scope.$apply();
            }

            contacts.pickContact();
        };

        function errorHandler(err) {
            console.log(err);
        }

        self.openCamera = function () {
            var camera = new Appworks.AWCamera(function (dataUrl) {
                $scope.$apply(self.imgSrc = dataUrl);
            }, function (err) {
                self.err = err;
                $scope.$apply();
            });
            self.err = null;
            self.imgSrc = null;
            camera.takePicture();
        };

        self.openGallery = function () {
            var gallery = new Appworks.AWCamera(function (dataUrl) {
                $scope.$apply(self.imgSrc = dataUrl);
            }, function (err) {
                self.err = err;
                $scope.$apply();
            });
            self.err = null;
            self.imgSrc = null;
            gallery.openGallery();
        };

        //self.getLocation = function () {
        //    Appworks.Geolocation.getCurrentPosition(onSuccess, onError);
        //
        //    function onSuccess(position) {
        //        console.log(position);
        //        alert(
        //            'Latitude: '          + position.coords.latitude          + '\n' +
        //            'Longitude: '         + position.coords.longitude         + '\n' +
        //            'Altitude: '          + position.coords.altitude          + '\n' +
        //            'Accuracy: '          + position.coords.accuracy          + '\n' +
        //            'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
        //            'Heading: '           + position.coords.heading           + '\n' +
        //            'Speed: '             + position.coords.speed             + '\n' +
        //            'Timestamp: '         + position.timestamp                + '\n');
        //    }
        //
        //    function onError(err) {
        //        console.log(err);
        //        alert('Unable to get current location.' +
        //            ' In general this means the device has no network connectivity and/or cannot get a satellite fix');
        //    }
        //};

        //Appworks.Notifications.handler(function (notification) {
        //    $scope.$apply(self.notifications.push(notification));
        //});

        self.clearNotifications = function () {
            self.notifications = [];
        };

        //self.stopNotifications = function () {
        //    appworks.notifications.off();
        //};

        //self.enableNotifications = function () {
        //    appworks.notifications.on();
        //};

        self.getNotifications = function () {
            self.syncNotifications();
        };

        //self.syncNotifications = function () {
        //    $scope.$applyAsync(self.notifications = appworks.notifications.get());
        //};
    })

    .controller('AuthCtrl', function ($scope) {

        var auth = new Appworks.Auth(onAuth, onAuth);

        function onAuth(data) {
            console.log(data);
            $scope.$apply($scope.response = data.data);
        }

        this.authenticate = function () {
            auth.authenticate();
        };
    });
<|endoftext|>


<commit_before>var mongoose = require('mongoose');

var ErrorObject = require('./lib/ErrorObject');
var modelCollection = require('./lib/ModelCollection');
var GenericEntity = require('./lib/GenericEntity');
var GenericEntityProperty = require('./lib/GenericEntityProperty');
var SavedGenericEntity = require('./lib/GenericEntityModel');

var properties = require("properties");
properties.parse ("db.properties", { path: true }, function (error, obj){
  if (error) return console.error (error);

  var uri = "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.dbname;
  var options = {};

  var dbuser = process.env.FLOW2_DBUSER;
  var dbpass = process.env.FLOW2_DBPASS;
  if(dbuser && dbpass){
    options.user = dbuser;
    options.pass = dbpass;
    console.log(options);
  }

  mongoose.connect(uri, options, function(err, res) {
      if(err) {
          console.log("Error connecting to DB.");
      } else {
          console.log("Successfully connected to DB.");
      }
  });
});

modelCollection.add("GenericEntityModel", SavedGenericEntity);

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express', layout: 'layouts/layout' });
});

router.get('/resetDB', function(req, res){
    mongoose.connection.db.dropDatabase();
    res.send({status: 'OK'});
});

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

    res.render("eag_home");
});

router.get('/listEntities', function(req, res){
  SavedGenericEntity.find({}, function(err, result){
    if(err){
      console.log("An error occurred while listing entity definitions.");
      console.log(err);
      res.status(30).send(ErrorObject.create("EntityDefinitionListError", 30));
    }
    res.send({entityList: result});
  });
});

router.get('/createEntity', function(req, res) {
  res.render('create_entity', { title: 'Express', layout: 'layouts/layout' });
});

var checkEntityNameExists = function(entityName, doesNotExist, exists) {
  SavedGenericEntity.findOne({name: entityName}, function(err, entity) {
    if(err){
      console.log(err);
    }

    if(entity == undefined){
      doesNotExist();
    } else {
      exists();
    }
  });
}

router.post("/createEntity", function(req, res) {
  var entityName = req.body.entityName;
  var entity = new GenericEntity(req.body.entityName);

  checkEntityNameExists(entityName, function(){
    if(req.property1_name != undefined){  // Probably a form post
      for(var i = 1; i < Object.keys(req.body).length / 2; i++){
          var prop = new GenericEntityProperty(req.body['property' + i + '_name'], "", req.body['property' + i + '_type']);
          entity.addProperty(prop);
      }
    } else {  // It must be an AJAX post
      for(var i = 0; i < req.body.properties.length; i++){
        var property = req.body.properties[i];
        if(GenericEntityProperty.isValidType(property.type) == false){
          res.status(422).send({name: property.name, type: property.type});
          return;
        }
        var prop = new GenericEntityProperty(property.name, "", property.type);
        entity.addProperty(prop);
      }
    }

    console.log(entity.name + "entity has been created.");
    console.log(entity);

    var dbGenericEntity = new SavedGenericEntity();
    dbGenericEntity.name = entity.name;
    dbGenericEntity.active = true;
    dbGenericEntity.properties = entity.properties;
    dbGenericEntity.save();

    webbifyEntity(entity);
    res.send(entity);
  }, function(){
    res.status(409).send(ErrorObject.create("EntityExistsError", 409));
  })
});

var findEntityDefinitionById = function(entityId, found, notFound){
  SavedGenericEntity.findOne({_id: new mongoose.Types.ObjectId(entityId)}, function(err, entity) {
    if(err){
      console.log(err);
      found();
      return;
    }

    if(entity == undefined){
      notFound();
      return;
    }

    found(entity);
    return;
  });
};

router.get("/readEntity/:entityId", function(req, res){
  var entityId = req.params.entityId;
  findEntityDefinitionById(entityId, function(entity){
    if(entity != undefined)
      res.send(entity);
    else
      res.status(500).send("Internal Server Error");
  }, function(){
    res.status(401).send("EntityNotFoundException");
  });
});

router.get("/deleteEntity/:entityId", function(req, res){
  var entityId = req.params.entityId;

  SavedGenericEntity.findOne({_id: new mongoose.Types.ObjectId(entityId)}, function(err, entity){
    if(err){
      console.log(err);
      res.send(ErrorObject.create("EntityDefinitionListError", 30));
    }

    if(entity == undefined){
      res.send({});
      return;
    }

    var entityName = entity.name;
    var EntityObject = entityObjectModels[entity.name];

    //mongoose.connection.collections[entity.name].drop( function(err) {
    mongoose.connection.db.dropCollection(entityName, function(err){
      if(err){
        console.log(err);
      }

      delete entityObjectModels[entityName];  // Removing from our cache of object schemas.
      entity.remove();
      console.log("Entity deleted.");
      res.send({ status: "OK", description: "Entity deleted." });
    });
  });
});

var entityObjectModels = {};

var getEntityObjectModel = function(entity){  // Call once per entity
  if(entityObjectModels[entity.name] != undefined){
    return entityObjectModels[entity.name];
  }

  var mongooseSchemaObject = {};
  for(var i = 0; i < entity.properties.length; i++){
    mongooseSchemaObject[entity.properties[i].name] = GenericEntityProperty.getMongooseType(entity.properties[i].type);
  }

  console.log("Mongoose schema object created for " + entity.name + ".");

  var entitySchema = mongoose.Schema(mongooseSchemaObject);
  var EntityObject = mongoose.model(entity.name, entitySchema, entity.name);

  entityObjectModels[entity.name] = EntityObject;

  return EntityObject;
}

var webbifyEntity = function(entity){

  var EntityObject = getEntityObjectModel(entity);

  router.get('/EAG/access/' + entity.name + '/list', function(req, res){
    SavedGenericEntity.findOne({name: entity.name}, function(err, result){
      if(err){
        console.log(err);
        res.send(ErrorObject.create("EntityDefinitionListError", 30));
        return;
      }

      if(result == undefined){
        res.status(401).send("EntityDoesNotExistError");
        return;
      }

      EntityObject.find({}).exec(function(err, result){
        if(err){
            console.log("Error finding " + entity.name);
            res.send(ErrorObject.create("NullPointerException", 500));
        } else {
            res.send({ instanceList: result });
        }
      });
    });
  });

  router.post("/EAG/access/" + entity.name + "/create", function(req, res){
    SavedGenericEntity.findOne({name: entity.name}, function(err, result){
      if(err){
        console.log(err);
        res.send(ErrorObject.create("EntityDefinitionListError", 30));
        return;
      }

      if(result == undefined){
        res.status(401).send("EntityDoesNotExistError");
        return;
      }

      var newObject = new EntityObject();
      for(var i = 0; i < entity.properties.length; i++){
        console.log("Validating properties:");
        console.log(entity.properties);
        if(req.body[entity.properties[i].name] == undefined && entity.properties[i].required == true){
            res.send(entity.properties[i].name + " field is a required field.");
            return;
        }
      }

      for(var i = 0; i < entity.properties.length; i++){
        newObject[entity.properties[i].name] = req.body[entity.properties[i].name];
      }

      newObject.save();
      res.send(newObject);
    });
  });

  router.get('/EAG/access/' + entity.name + '/findByProperty/:propertyName/:propertyValue', function(req, res){
    var propertyName = req.params.propertyName;
    var propertyValue = req.params.propertyValue;

    var queryObject = {};
    queryObject[propertyName] = propertyValue;

    EntityObject.find(queryObject, function(err, result) {
      if(err){
        console.log(err);
        res.status(404).send({error: "InstanceNotFound", queryObject: queryObject});
        return;
      }

      res.send({result: result});
    });
  });
};

var reloadEntities = function() {
  SavedGenericEntity.find({}, function(err, entities){
    if(err){
      console.log("Error has occurred while reloading entities.");
      console.log(err);
      return;
    }

    if(entities == undefined){
      console.log("Undefined entities to reload.");
      return;
    }

    for(var i = 0; i < entities.length; i++){
      var entity = entities[i];
      webbifyEntity(entity);
    }
  });
};

// Only do this once.
reloadEntities();

module.exports = router;
<commit_msg>Validation + cleanup.<commit_after>var mongoose = require('mongoose');

var ErrorObject = require('./lib/ErrorObject');
var modelCollection = require('./lib/ModelCollection');
var GenericEntity = require('./lib/GenericEntity');
var GenericEntityProperty = require('./lib/GenericEntityProperty');
var SavedGenericEntity = require('./lib/GenericEntityModel');

var properties = require("properties");
properties.parse ("db.properties", { path: true }, function (error, obj){
  if (error) return console.error (error);
  var hostname = obj.hostname || "localhost";
  var port = obj.port || 27017;
  var dbname = obj.dbname || "flow2";

  var uri = "mongodb://" + hostname + ":" + port + "/" + dbname;
  var options = {};

  var dbuser = process.env.FLOW2_DBUSER;
  var dbpass = process.env.FLOW2_DBPASS;
  if(dbuser && dbpass){
    options.user = dbuser;
    options.pass = dbpass;
  }

  mongoose.connect(uri, options, function(err, res) {
      if(err) {
          console.log("Error connecting to DB.");
      } else {
          console.log("Successfully connected to DB.");
      }
  });
});

modelCollection.add("GenericEntityModel", SavedGenericEntity);

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express', layout: 'layouts/layout' });
});

router.get('/resetDB', function(req, res){
    mongoose.connection.db.dropDatabase();
    res.send({status: 'OK'});
});

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

    res.render("eag_home");
});

router.get('/listEntities', function(req, res){
  SavedGenericEntity.find({}, function(err, result){
    if(err){
      console.log("An error occurred while listing entity definitions.");
      console.log(err);
      res.status(30).send(ErrorObject.create("EntityDefinitionListError", 30));
    }
    res.send({entityList: result});
  });
});

router.get('/createEntity', function(req, res) {
  res.render('create_entity', { title: 'Express', layout: 'layouts/layout' });
});

var checkEntityNameExists = function(entityName, doesNotExist, exists) {
  SavedGenericEntity.findOne({name: entityName}, function(err, entity) {
    if(err){
      console.log(err);
    }

    if(entity == undefined){
      doesNotExist();
    } else {
      exists();
    }
  });
}

router.post("/createEntity", function(req, res) {
  var entityName = req.body.entityName;
  var entity = new GenericEntity(req.body.entityName);

  checkEntityNameExists(entityName, function(){
    if(req.property1_name != undefined){  // Probably a form post
      for(var i = 1; i < Object.keys(req.body).length / 2; i++){
          var prop = new GenericEntityProperty(req.body['property' + i + '_name'], "", req.body['property' + i + '_type']);
          entity.addProperty(prop);
      }
    } else {  // It must be an AJAX post
      for(var i = 0; i < req.body.properties.length; i++){
        var property = req.body.properties[i];
        if(GenericEntityProperty.isValidType(property.type) == false){
          res.status(422).send({name: property.name, type: property.type});
          return;
        }
        var prop = new GenericEntityProperty(property.name, "", property.type);
        entity.addProperty(prop);
      }
    }

    console.log(entity.name + "entity has been created.");
    console.log(entity);

    var dbGenericEntity = new SavedGenericEntity();
    dbGenericEntity.name = entity.name;
    dbGenericEntity.active = true;
    dbGenericEntity.properties = entity.properties;
    dbGenericEntity.save();

    webbifyEntity(entity);
    res.send(entity);
  }, function(){
    res.status(409).send(ErrorObject.create("EntityExistsError", 409));
  })
});

var findEntityDefinitionById = function(entityId, found, notFound){
  SavedGenericEntity.findOne({_id: new mongoose.Types.ObjectId(entityId)}, function(err, entity) {
    if(err){
      console.log(err);
      found();
      return;
    }

    if(entity == undefined){
      notFound();
      return;
    }

    found(entity);
    return;
  });
};

router.get("/readEntity/:entityId", function(req, res){
  var entityId = req.params.entityId;
  findEntityDefinitionById(entityId, function(entity){
    if(entity != undefined)
      res.send(entity);
    else
      res.status(500).send("Internal Server Error");
  }, function(){
    res.status(401).send("EntityNotFoundException");
  });
});

router.get("/deleteEntity/:entityId", function(req, res){
  var entityId = req.params.entityId;

  SavedGenericEntity.findOne({_id: new mongoose.Types.ObjectId(entityId)}, function(err, entity){
    if(err){
      console.log(err);
      res.send(ErrorObject.create("EntityDefinitionListError", 30));
    }

    if(entity == undefined){
      res.send({});
      return;
    }

    var entityName = entity.name;
    var EntityObject = entityObjectModels[entity.name];

    //mongoose.connection.collections[entity.name].drop( function(err) {
    mongoose.connection.db.dropCollection(entityName, function(err){
      if(err){
        console.log(err);
      }

      delete entityObjectModels[entityName];  // Removing from our cache of object schemas.
      entity.remove();
      console.log("Entity deleted.");
      res.send({ status: "OK", description: "Entity deleted." });
    });
  });
});

var entityObjectModels = {};

var getEntityObjectModel = function(entity){  // Call once per entity
  if(entityObjectModels[entity.name] != undefined){
    return entityObjectModels[entity.name];
  }

  var mongooseSchemaObject = {};
  for(var i = 0; i < entity.properties.length; i++){
    mongooseSchemaObject[entity.properties[i].name] = GenericEntityProperty.getMongooseType(entity.properties[i].type);
  }

  console.log("Mongoose schema object created for " + entity.name + ".");

  var entitySchema = mongoose.Schema(mongooseSchemaObject);
  var EntityObject = mongoose.model(entity.name, entitySchema, entity.name);

  entityObjectModels[entity.name] = EntityObject;

  return EntityObject;
}

var webbifyEntity = function(entity){

  var EntityObject = getEntityObjectModel(entity);

  router.get('/EAG/access/' + entity.name + '/list', function(req, res){
    SavedGenericEntity.findOne({name: entity.name}, function(err, result){
      if(err){
        console.log(err);
        res.send(ErrorObject.create("EntityDefinitionListError", 30));
        return;
      }

      if(result == undefined){
        res.status(401).send("EntityDoesNotExistError");
        return;
      }

      EntityObject.find({}).exec(function(err, result){
        if(err){
            console.log("Error finding " + entity.name);
            res.send(ErrorObject.create("NullPointerException", 500));
        } else {
            res.send({ instanceList: result });
        }
      });
    });
  });

  router.post("/EAG/access/" + entity.name + "/create", function(req, res){
    SavedGenericEntity.findOne({name: entity.name}, function(err, result){
      if(err){
        console.log(err);
        res.send(ErrorObject.create("EntityDefinitionListError", 30));
        return;
      }

      if(result == undefined){
        res.status(401).send("EntityDoesNotExistError");
        return;
      }

      var newObject = new EntityObject();
      for(var i = 0; i < entity.properties.length; i++){
        console.log("Validating properties:");
        console.log(entity.properties);
        if(req.body[entity.properties[i].name] == undefined && entity.properties[i].required == true){
            res.send(entity.properties[i].name + " field is a required field.");
            return;
        }
      }

      for(var i = 0; i < entity.properties.length; i++){
        newObject[entity.properties[i].name] = req.body[entity.properties[i].name];
      }

      newObject.save();
      res.send(newObject);
    });
  });

  router.get('/EAG/access/' + entity.name + '/findByProperty/:propertyName/:propertyValue', function(req, res){
    var propertyName = req.params.propertyName;
    var propertyValue = req.params.propertyValue;

    var queryObject = {};
    queryObject[propertyName] = propertyValue;

    EntityObject.find(queryObject, function(err, result) {
      if(err){
        console.log(err);
        res.status(404).send({error: "InstanceNotFound", queryObject: queryObject});
        return;
      }

      res.send({result: result});
    });
  });
};

var reloadEntities = function() {
  SavedGenericEntity.find({}, function(err, entities){
    if(err){
      console.log("Error has occurred while reloading entities.");
      console.log(err);
      return;
    }

    if(entities == undefined){
      console.log("Undefined entities to reload.");
      return;
    }

    for(var i = 0; i < entities.length; i++){
      var entity = entities[i];
      webbifyEntity(entity);
    }
  });
};

// Only do this once.
reloadEntities();

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

angular.module('app.controllers', []).
    controller('homeController', function($scope, $rootScope, $log, cryptocoinchartsAPIService, utilService, settingsService, customService) {
		$scope.getPriceCompareClass = function(price1, price2) {
			//$log.info('price compare:', price1, price2);
			return utilService.getPriceCompareClass(price1, price2);
		}

        $scope.currency = settingsService.getCurrency();
        $scope.latest_trade = settingsService.getNumValue('latest_trade'); // GMT date of the latest trade in database
        $scope.price_before_24h = settingsService.getNumValue('price_before_24h'); // last traded price 24 hours before
        $scope.price = settingsService.getNumValue('price'); // last traded price of best market
        $scope.best_market = settingsService.getBestMarket(); // market with the most volume for this trading pair
        $scope.volume = settingsService.getNumValue('volume'); // trading volume expressed as the selected currency
        $scope.volume_ltc = settingsService.getNumValue('volume_ltc'); // trading volume expressed as LTC
		$scope.price_btc = settingsService.getNumValue('price_btc'); // price of LTC in BTC

        $scope.loadData = function() {
            cryptocoinchartsAPIService.getLTCTrading('BTC').success(function (response) {
				if (response) {
					//$log.info('BTC response:', response);

                    settingsService.setNumValue('price_btc', response.price);
                    $scope.price_btc = settingsService.getNumValue('price_btc');
				}
				else {
					$log.warn('Warning: No trading data returned from cryptocoinchartsAPIService.getLTCTrading(BTC)', response);
				}
			});

            cryptocoinchartsAPIService.getLTCTrading($scope.currency).success(function (response) {
				if (response) {
					//$log.info($scope.currency, 'response:', response);

                    settingsService.setNumValue('latest_trade', Date.parse(response.latest_trade + ' GMT'));
                    $scope.latest_trade = settingsService.getNumValue('latest_trade');

                    settingsService.setNumValue('price_before_24h', response.price_before_24h);
                    $scope.price_before_24h = settingsService.getNumValue('price_before_24h');

                    settingsService.setNumValue('price', response.price);
                    $scope.price = settingsService.getNumValue('price');

                    settingsService.setBestMarket(response.best_market);
                    $scope.best_market = settingsService.getBestMarket();

                    settingsService.setNumValue('volume', response.volume_second);
                    $scope.volume = settingsService.getNumValue('volume');

                    settingsService.setNumValue('volume_ltc', response.volume_first);
                    $scope.volume_ltc = settingsService.getNumValue('volume_ltc');
				}
				else {
					$log.warn('Warning: No trading data returned from cryptocoinchartsAPIService.getLTCTrading(' + $scope.currency + ')', response);
				}
            });
        }

        $scope.$on('cryptocoinchartsAPIService.refresh', function(event, path) {
            if (path && path === '/home') {
                $scope.loadData();
            }
        });

        $rootScope.loadData();

		customService.trackPage('/home');
    }).
    controller('settingsController', function($scope, $rootScope, $log, settingsService, customService) {
		$scope.selectedCurrency = settingsService.getCurrency();

		$scope.$watch('selectedCurrency', function() {
			settingsService.setCurrency($scope.selectedCurrency);
			$log.info('Set selected currency to', settingsService.getCurrency());
		});

		$scope.symbols = settingsService.symbols;

		customService.trackPage('/settings');
    }).
    controller('aboutController', function($scope, utilService, customService) {
		$scope.version = utilService.getAppVersion();

		customService.trackPage('/about');
    });

<commit_msg>fixing date parsing to work in iPhone<commit_after>'use strict';

angular.module('app.controllers', []).
    controller('homeController', function($scope, $rootScope, $log, cryptocoinchartsAPIService, utilService, settingsService, customService) {
		$scope.getPriceCompareClass = function(price1, price2) {
			//$log.info('price compare:', price1, price2);
			return utilService.getPriceCompareClass(price1, price2);
		}

        $scope.currency = settingsService.getCurrency();
        $scope.latest_trade = settingsService.getNumValue('latest_trade'); // GMT date of the latest trade in database
        $scope.price_before_24h = settingsService.getNumValue('price_before_24h'); // last traded price 24 hours before
        $scope.price = settingsService.getNumValue('price'); // last traded price of best market
        $scope.best_market = settingsService.getBestMarket(); // market with the most volume for this trading pair
        $scope.volume = settingsService.getNumValue('volume'); // trading volume expressed as the selected currency
        $scope.volume_ltc = settingsService.getNumValue('volume_ltc'); // trading volume expressed as LTC
		$scope.price_btc = settingsService.getNumValue('price_btc'); // price of LTC in BTC

        $scope.loadData = function() {
            cryptocoinchartsAPIService.getLTCTrading('BTC').success(function (response) {
				if (response) {
					//$log.info('BTC response:', response);

                    settingsService.setNumValue('price_btc', response.price);
                    $scope.price_btc = settingsService.getNumValue('price_btc');
				}
				else {
					$log.warn('Warning: No trading data returned from cryptocoinchartsAPIService.getLTCTrading(BTC)', response);
				}
			});

            cryptocoinchartsAPIService.getLTCTrading($scope.currency).success(function (response) {
				if (response) {
					var latestTradeStr = response.latest_trade.replace(/\-/g, '/') + ' GMT';
					//$log.info('latest_trade', latestTradeStr);
                    settingsService.setNumValue('latest_trade', Date.parse(latestTradeStr));
                    $scope.latest_trade = settingsService.getNumValue('latest_trade');

                    settingsService.setNumValue('price_before_24h', response.price_before_24h);
                    $scope.price_before_24h = settingsService.getNumValue('price_before_24h');

                    settingsService.setNumValue('price', response.price);
                    $scope.price = settingsService.getNumValue('price');

                    settingsService.setBestMarket(response.best_market);
                    $scope.best_market = settingsService.getBestMarket();

                    settingsService.setNumValue('volume', response.volume_second);
                    $scope.volume = settingsService.getNumValue('volume');

                    settingsService.setNumValue('volume_ltc', response.volume_first);
                    $scope.volume_ltc = settingsService.getNumValue('volume_ltc');
				}
				else {
					$log.warn('Warning: No trading data returned from cryptocoinchartsAPIService.getLTCTrading(' + $scope.currency + ')', response);
				}
            });
        }

        $scope.$on('cryptocoinchartsAPIService.refresh', function(event, path) {
            if (path && path === '/home') {
                $scope.loadData();
            }
        });

        $rootScope.loadData();

		customService.trackPage('/home');
    }).
    controller('settingsController', function($scope, $rootScope, $log, settingsService, customService) {
		$scope.selectedCurrency = settingsService.getCurrency();

		$scope.$watch('selectedCurrency', function() {
			settingsService.setCurrency($scope.selectedCurrency);
			$log.info('Set selected currency to', settingsService.getCurrency());
		});

		$scope.symbols = settingsService.symbols;

		customService.trackPage('/settings');
    }).
    controller('aboutController', function($scope, utilService, customService) {
		$scope.version = utilService.getAppVersion();

		customService.trackPage('/about');
    });

<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var uploadFile = require('../uploadFile.js');
var request = require('request');
var AWS = require('aws-sdk');
var twilio = require('twilio');
var AWS = require('aws-sdk');
var S3 = new AWS.S3();
var gm = require('gm').subClass({
    imageMagick: true
});
var mime = require('mime');

router.get('/s3upload', function(req, res, next) {
    uploadFile.sendToS3();
    res.json("Upload success?");
});

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index');
});

router.post('/image', function(req, res) {
    // Validate Twilio req
    // if (twilio.validateExpressRequest(req, config.authToken)) {

    var image = req.body;
    console.log(req.body);

    var imageName = image.From + '/' + image.SmsMessageSid + '.jpg';

    gm(request(image.MediaUrl0), imageName)
        .resize('100^', '100^')
        .stream(function(err, stdout, stderr) {
            var buf = new Buffer('');
            stdout.on('data', function(data) {
                buf = Buffer.concat([buf, data]);
            });
            stdout.on('end', function(data) {
                var data = {
                    Bucket: 'disruptny',
                    Key: imageName,
                    Body: buf,
                    ContentType: mime.lookup(imageName)
                };
                S3.putObject(data, function(err, response) {
                    if (err) console.log(err);
                    console.log('imageName: ' + imageName);
                    res.status(200).send('OK');
                });
            });
        });

    // } else {
    //   return res.send('Nice try imposter.');
    // }
});

module.exports = router;
<commit_msg>resize fix + image hardcoded to test<commit_after>var express = require('express');
var router = express.Router();
var uploadFile = require('../uploadFile.js');
var request = require('request');
var AWS = require('aws-sdk');
var twilio = require('twilio');
var AWS = require('aws-sdk');
var S3 = new AWS.S3();
var gm = require('gm').subClass({
    imageMagick: true
});
var mime = require('mime');

router.get('/s3upload', function(req, res, next) {
    uploadFile.sendToS3();
    res.json("Upload success?");
});

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index');
});

router.post('/image', function(req, res) {
    // Validate Twilio req
    // if (twilio.validateExpressRequest(req, config.authToken)) {

    var image = req.body;
    // var image = {
    //     "SmsMessageSid": "aksjhdflkjhasdf",
    //     "From": "+12062526252",
    //     "MediaUrl0": "http://www.vetprofessionals.com/catprofessional/images/home-cat.jpg"
    // }
    console.log(req.body);

    var imageName = image.From + '/' + image.SmsMessageSid + '.jpg';

    // request(image.MediaUrl0).pipe(res);

    gm(request(image.MediaUrl0), imageName)
        .resize(400, 400)
        .stream(function(err, stdout, stderr) {
            if (err) console.log(err);
            var buf = new Buffer('');
            stdout.on('data', function(data) {
                buf = Buffer.concat([buf, data]);
            });
            stdout.on('end', function() {
                var data = {
                    Bucket: 'disruptny',
                    Key: imageName,
                    Body: buf,
                    ACL: 'public-read',
                    ContentType: mime.lookup(imageName)
                };
                S3.putObject(data, function(err, response) {
                    if (err) console.log(err);
                    console.log('imageName: ' + imageName);
                    res.status(200).send('OK');
                });
            });
        });

    // } else {
    //   return res.send('Nice try imposter.');
    // }
});

module.exports = router;
<|endoftext|>


<commit_before>angular.module('skjutsgruppen.controllers', [])

    .controller('AppCtrl', function ($scope, $ionicModal, $timeout, $state) {

        // With the new view caching in Ionic, Controllers are only called
        // when they are recreated or on app start, instead of every page change.
        // To listen for when this page is active (for example, to refresh data),
        // listen for the $ionicView.enter event:
        //$scope.$on('$ionicView.enter', function(e) {
        //});

        // Form data for the login modal
        $scope.loginData = {};

        // Create the login modal that we will use later
        $ionicModal.fromTemplateUrl('templates/login.html', {
            scope: $scope
        }).then(function (modal) {
            $scope.modal = modal;
        });

        // Triggered in the login modal to close it
        $scope.closeLogin = function () {
            $scope.modal.hide();
        };

        // Open the login modal
        $scope.login = function () {
            $scope.modal.show();
        };

        // Perform the login action when the user submits the login form
        $scope.doLogin = function () {
            console.log('Doing login', $scope.loginData);

            // Simulate a login delay. Remove this and replace with your login
            // code if using a login system
            $timeout(function () {
                $scope.closeLogin();
            }, 1000);
        };

        $scope.goHome = function () {
            $state.go('app.startpage');
        };
    })

    .controller('registerTripDriverCtrl', function ($scope, $state) {
        $scope.myForm = {};
        var listOfViaLocations = [];

        $scope.addTripDriver = function(form) {

            window.localStorage['result'] = JSON.stringify($scope.myForm);
            window.localStorage['listOfViaLocations'] = JSON.stringify(listOfViaLocations);

            $state.go('app.summary');
        };

        $scope.addLocation = function() {
            listOfViaLocations.push($scope.myForm.viaLocation);
        };
    })

    .controller('StartpageCtrl', function ($scope) {
    })

    .controller('ResultCtrl', function ($scope) {
      var result = JSON.parse(window.localStorage['resultForResult'] || '{}');
    })

    .controller('PushCtrl', function ($scope) {
    })

    .controller('SummaryCtrl', function ($scope) {

      var result = JSON.parse(window.localStorage['result'] || '{}');
      var listOfViaLocations = JSON.parse(window.localStorage['listOfViaLocations'] || '{}');
      // console.log("result: ");
      // console.log(result);
      $scope.listHasLocations = false;
      $scope.item =
        {from: result.from, to: result.to, firstTime: result.firstTime, secondTime: result.secondTime, availableSeats: result.availableSeats, viaLocation: listOfViaLocations};

        if(listOfViaLocations.length > 1){
            $scope.listHasLocations = true;
        }
        else{
            $scope.listHasLocations = false;
        }
    })

    .controller('AchievementsCtrl', function ($scope, AchievementsFactory) {
        AchievementsFactory.getAchievements().all().then(function (data) {
            $scope.achievements = data;
        });
    })

    .controller('MapCtrl', function ($scope, $state, $cordovaGeolocation, MapFactory) {
        var options = { timeout: 10000, enableHighAccuracy: true };

        $cordovaGeolocation.getCurrentPosition(options).then(function (position) {

            var currentLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

            var mapOptions = {
                center: currentLatLng,
                zoom: 15,
                mapTypeId: google.maps.MapTypeId.HYBRID
            };

            $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);

            google.maps.event.addListenerOnce($scope.map, 'idle', function () {
                var marker = new google.maps.Marker({
                    map: $scope.map,
                    animation: google.maps.Animation.NONE,
                    position: currentLatLng
                });

                console.log(marker.position);

                var infoWindow = new google.maps.InfoWindow({
                    content: "Here I am!"
                });

                google.maps.event.addListener(marker, 'click', function () {
                    infoWindow.open($scope.map, marker);
                });
            });

            MapFactory.getCoordinates.all().then(function (data) {
                $scope.mapCoordinates = data;

                console.log(data);

                if (data !== undefined && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var coordinate = data[i];
                        console.log(coordinate);

                        google.maps.event.addListenerOnce($scope.map, 'idle', function () {
                            var marker = new google.maps.Marker({
                                map: $scope.map,
                                animation: google.maps.Animation.DROP,
                                position: new google.maps.LatLng(coordinate.longitud, coordinate.latitud)
                            });

                            console.log(marker.position);

                            var infoWindow = new google.maps.InfoWindow({
                                content: "Here are another person!"
                            });

                            google.maps.event.addListener(marker, 'click', function () {
                                infoWindow.open($scope.map, marker);
                            });
                        });
                    }
                }
                else {
                    console.log("Coordinates data is empty or undefined!")
                }
            });

        }, function (error) {
            console.log("Could not get location");
        })
    })

    .controller('SettingsCtrl', function ($scope, SettingsFactory) {

        SettingsFactory.getSettings().all().then(function (data) {
            $scope.settings = data;
        });

        $scope.toggleSetting = function (settingId, newValue) {
            SettingsFactory.updateSetting(settingId, newValue);
        }
    })

    .controller('registerTripPassengerCtrl', function ($scope, $state) {
        $scope.myForm = {};

        $scope.addTripDriver = function(form) {

            window.localStorage['resultForResult'] = JSON.stringify($scope.myForm);

            $state.go('app.result');
        };

        $scope.addLocation = function() {
            listOfViaLocations.push($scope.myForm.viaLocation);
        };
    })

    .controller('ProfileCtrl', function ($scope) {
        $scope.recurringTrips = [{
            title: 'Malmö - Göteborg'
        }, {
            title: 'Rådhusgatan 3, Stockholm - Storgatan 22, Stockholm'
        }];

        $scope.achievements = [{
            name: 'Full car'
        }, {
            name: 'More than 100k'
        }, {
            name: 'Week streak'
        }];
    });
<commit_msg>Continued on the form for passangers<commit_after>angular.module('skjutsgruppen.controllers', [])

    .controller('AppCtrl', function ($scope, $ionicModal, $timeout, $state) {

        // With the new view caching in Ionic, Controllers are only called
        // when they are recreated or on app start, instead of every page change.
        // To listen for when this page is active (for example, to refresh data),
        // listen for the $ionicView.enter event:
        //$scope.$on('$ionicView.enter', function(e) {
        //});

        // Form data for the login modal
        $scope.loginData = {};

        // Create the login modal that we will use later
        $ionicModal.fromTemplateUrl('templates/login.html', {
            scope: $scope
        }).then(function (modal) {
            $scope.modal = modal;
        });

        // Triggered in the login modal to close it
        $scope.closeLogin = function () {
            $scope.modal.hide();
        };

        // Open the login modal
        $scope.login = function () {
            $scope.modal.show();
        };

        // Perform the login action when the user submits the login form
        $scope.doLogin = function () {
            console.log('Doing login', $scope.loginData);

            // Simulate a login delay. Remove this and replace with your login
            // code if using a login system
            $timeout(function () {
                $scope.closeLogin();
            }, 1000);
        };

        $scope.goHome = function () {
            $state.go('app.startpage');
        };
    })

    .controller('registerTripDriverCtrl', function ($scope, $state) {
        $scope.myForm = {};
        var listOfViaLocations = [];

        $scope.addTripDriver = function(form) {

            window.localStorage['result'] = JSON.stringify($scope.myForm);
            window.localStorage['listOfViaLocations'] = JSON.stringify(listOfViaLocations);

            $state.go('app.summary');
        };

        $scope.addLocation = function() {
            listOfViaLocations.push($scope.myForm.viaLocation);
        };
    })

    .controller('StartpageCtrl', function ($scope) {
    })

    .controller('ResultCtrl', function ($scope) {
      var result = JSON.parse(window.localStorage['resultForResult'] || '{}');

      $scope.items = [
        {from: result.from, to: result.to, firstTime: result.firstTime, secondTime: result.secondTime, availableSeats: result.availableSeats}
      ];
    })

    .controller('PushCtrl', function ($scope) {
    })

    .controller('SummaryCtrl', function ($scope) {

      var result = JSON.parse(window.localStorage['result'] || '{}');
      var listOfViaLocations = JSON.parse(window.localStorage['listOfViaLocations'] || '{}');

      $scope.listHasLocations = false;
      $scope.item =
        {from: result.from, to: result.to, firstTime: result.firstTime, secondTime: result.secondTime, availableSeats: result.availableSeats, viaLocation: listOfViaLocations};

        if(listOfViaLocations.length > 1){
            $scope.listHasLocations = true;
        }
        else{
            $scope.listHasLocations = false;
        }
    })

    .controller('AchievementsCtrl', function ($scope, AchievementsFactory) {
        AchievementsFactory.getAchievements().all().then(function (data) {
            $scope.achievements = data;
        });
    })

    .controller('MapCtrl', function ($scope, $state, $cordovaGeolocation, MapFactory) {
        var options = { timeout: 10000, enableHighAccuracy: true };

        $cordovaGeolocation.getCurrentPosition(options).then(function (position) {

            var currentLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

            var mapOptions = {
                center: currentLatLng,
                zoom: 15,
                mapTypeId: google.maps.MapTypeId.HYBRID
            };

            $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);

            google.maps.event.addListenerOnce($scope.map, 'idle', function () {
                var marker = new google.maps.Marker({
                    map: $scope.map,
                    animation: google.maps.Animation.NONE,
                    position: currentLatLng
                });

                console.log(marker.position);

                var infoWindow = new google.maps.InfoWindow({
                    content: "Here I am!"
                });

                google.maps.event.addListener(marker, 'click', function () {
                    infoWindow.open($scope.map, marker);
                });
            });

            MapFactory.getCoordinates.all().then(function (data) {
                $scope.mapCoordinates = data;

                console.log(data);

                if (data !== undefined && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var coordinate = data[i];
                        console.log(coordinate);

                        google.maps.event.addListenerOnce($scope.map, 'idle', function () {
                            var marker = new google.maps.Marker({
                                map: $scope.map,
                                animation: google.maps.Animation.DROP,
                                position: new google.maps.LatLng(coordinate.longitud, coordinate.latitud)
                            });

                            console.log(marker.position);

                            var infoWindow = new google.maps.InfoWindow({
                                content: "Here are another person!"
                            });

                            google.maps.event.addListener(marker, 'click', function () {
                                infoWindow.open($scope.map, marker);
                            });
                        });
                    }
                }
                else {
                    console.log("Coordinates data is empty or undefined!")
                }
            });

        }, function (error) {
            console.log("Could not get location");
        })
    })

    .controller('SettingsCtrl', function ($scope, SettingsFactory) {

        SettingsFactory.getSettings().all().then(function (data) {
            $scope.settings = data;
        });

        $scope.toggleSetting = function (settingId, newValue) {
            SettingsFactory.updateSetting(settingId, newValue);
        }
    })

    .controller('registerTripPassengerCtrl', function ($scope, $state) {
        $scope.myForm = {};

        $scope.addTripPassanger = function(form) {

            window.localStorage['resultForResult'] = JSON.stringify($scope.myForm);

            $state.go('app.result');
        };
    })

    .controller('ProfileCtrl', function ($scope) {
        $scope.recurringTrips = [{
            title: 'Malmö - Göteborg'
        }, {
            title: 'Rådhusgatan 3, Stockholm - Storgatan 22, Stockholm'
        }];

        $scope.achievements = [{
            name: 'Full car'
        }, {
            name: 'More than 100k'
        }, {
            name: 'Week streak'
        }];
    });
<|endoftext|>


<commit_before>import {concat, flatten, map, pipe} from "ramda";

import {SITES_COLLECTION_NAME} from "./config";
import {getCollection} from "./services/mongodb";

function getSensorsIds (sensor) {
    return pipe(
        map(getSensorsIds),
        flatten,
        concat([sensor.id])
    )(sensor.children || []);
}

export default async function handleUpsert (event, actionDelete) {
    const site = {
        ...event.data.element
    };
    const id = event.data.id;
    const sensorsIds = pipe(
        map(getSensorsIds),
        flatten
    )(site.sensors || []);

    const update = actionDelete ?
        {$set: {isDeleted: true}} :
        {...site, sensorsIds, isDeleted: actionDelete, _id: id};

    const sitesCollection = await getCollection(SITES_COLLECTION_NAME);
    await sitesCollection.update(
        {_id: id},
        {$set: update},
        {upsert: true}
    );
    return null;
}
<commit_msg>Fix delete query<commit_after>import {concat, flatten, map, pipe} from "ramda";

import {SITES_COLLECTION_NAME} from "./config";
import {getCollection} from "./services/mongodb";

function getSensorsIds (sensor) {
    return pipe(
        map(getSensorsIds),
        flatten,
        concat([sensor.id])
    )(sensor.children || []);
}

export default async function handleUpsert (event, actionDelete) {
    const site = {
        ...event.data.element
    };
    const id = event.data.id;
    const sensorsIds = pipe(
        map(getSensorsIds),
        flatten
    )(site.sensors || []);

    const update = actionDelete ?
        {...site, isDeleted: true} :
        {...site, sensorsIds, isDeleted: actionDelete, _id: id};

    const sitesCollection = await getCollection(SITES_COLLECTION_NAME);
    await sitesCollection.update(
        {_id: id},
        {$set: update},
        {upsert: true}
    );
    return null;
}
<|endoftext|>


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

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
<commit_msg>Garbage comment deletion.<commit_after>var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var Git = require("nodegit");
var fs = require('fs');
var md = require("markdown").markdown;
var cheerio = require("cheerio");
var sprintf = require("sprintf-js").sprintf;
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
var router = express.Router();
var GITHUB_TOKEN = process.env.GITHUB_TOKEN;
var FILE_NAME = "index.htm";
var FOLDER_NAME = "./tmp";
var BRANCH_NAME = "gh-pages";
var REFS = "refs/heads/" + BRANCH_NAME;
var repo;
var head;
var oid;
var result;
var $;

router.post('/issues', function(req, res, next) {
  fse.remove(FOLDER_NAME).then(function(){
    return Git.Clone("https://" + GITHUB_TOKEN + ":x-oauth-basic@github.com/kewang/information-people", FOLDER_NAME, {
      checkoutBranch: BRANCH_NAME
    });
  }).then(function(repoResult){
    repo = repoResult;

    return repo.getHeadCommit();
  }).then(function(headResult){
    head = headResult;

    return head.getEntry(FILE_NAME);
  }).then(function(entry){
    return entry.getBlob();
  }).then(function(blob){
    $ = cheerio.load(String(blob));

    result = processing(req.body);

    console.log("test: " + JSON.stringify(result));

    fs.writeFileSync(FOLDER_NAME + "/" + FILE_NAME, $.html());

    return repo.index();
  }).then(function(index){
    index.addByPath(FILE_NAME);
    index.write();

    return index.writeTree();
  }).then(function(oidResult){
    oid = oidResult;

    var author = Git.Signature.now("information-people", "cpckewang@gmail.com");

    if(!result.page){
      return res.json({
        result: "Add fail"
      });
    }

    return repo.createCommit("HEAD", author, author, sprintf("Add %s success", result.page.name), oid, [head]);
  }).then(function(commitId){
    console.log("New Commit: " + commitId);

    return repo.getRemote("origin");
  }).then(function(remote){
    return remote.push([REFS + ":" + REFS]);
  }).catch(function(err){
    console.error(err);
  }).done(function(){
    console.log(result + " OK");

    return res.json({
      result: result
    });
  });
});

function processing(body){
  if(body.action !== "labeled"){
    return false;
  }

  var label_type = body.label.name;

  switch(label_type){
  case "開放討論中":
    return discussPeople(body);

    break;
  case "已新增":
    return addPeople(body);

    break;
  case "已刪除":
    return removePeople(body);

    break;
  case "已重複":
    return duplicatePeople(body);

    break;
  }
}

function discussPeople(body){
  // add people to pending list
  // add comment to content

  return "discussing";
}

function addPeople(body){
  // add people from pending list to content
  // add comment like "Added"
  // close issue

  // parse Markdown to JSON
  var tree = JSON.stringify(md.parse(body.issue.body));
  var ret = {};

  console.log(tree);
  console.log(tree[2][0]);
  console.log(tree[2][0] !== "bulletlist");
  console.log(typeof tree[2][0]);
  console.log(typeof "bulletlist");

  if(tree[2][0] !== "bulletlist"){
    ret.msg = "added fail";

    return ret;
  }

  var page = {};

  if(tree[2][1][0] === "listitem" && tree[2][2][0] === "listitem"){
    page.id = tree[2][1][1].split("Pages ID:")[1].trim();
    page.name = tree[2][2][1].split("Pages Name:")[1].trim();
  }

  var html_format = '

%(name)

';

  $("#page-list > .panel > .panel-body").append(sprintf(html_format, page));

  ret.msg = "added success";
  ret.page = page;

  return ret;
}

function removePeople(body){
  // remove people from content
  // add comment like "Removed"
  // close issue
  return "removed success";
}

function duplicatePeople(body){
  // add comment like "Duplicated"
  // close issue
  return "duplicated success";
}

module.exports = router;
<commit_msg>Add trim()<commit_after>var express = require('express');
var Git = require("nodegit");
var fs = require('fs');
var md = require("markdown").markdown;
var cheerio = require("cheerio");
var sprintf = require("sprintf-js").sprintf;
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
var router = express.Router();
var GITHUB_TOKEN = process.env.GITHUB_TOKEN;
var FILE_NAME = "index.htm";
var FOLDER_NAME = "./tmp";
var BRANCH_NAME = "gh-pages";
var REFS = "refs/heads/" + BRANCH_NAME;
var repo;
var head;
var oid;
var result;
var $;

router.post('/issues', function(req, res, next) {
  fse.remove(FOLDER_NAME).then(function(){
    return Git.Clone("https://" + GITHUB_TOKEN + ":x-oauth-basic@github.com/kewang/information-people", FOLDER_NAME, {
      checkoutBranch: BRANCH_NAME
    });
  }).then(function(repoResult){
    repo = repoResult;

    return repo.getHeadCommit();
  }).then(function(headResult){
    head = headResult;

    return head.getEntry(FILE_NAME);
  }).then(function(entry){
    return entry.getBlob();
  }).then(function(blob){
    $ = cheerio.load(String(blob));

    result = processing(req.body);

    console.log("test: " + JSON.stringify(result));

    fs.writeFileSync(FOLDER_NAME + "/" + FILE_NAME, $.html());

    return repo.index();
  }).then(function(index){
    index.addByPath(FILE_NAME);
    index.write();

    return index.writeTree();
  }).then(function(oidResult){
    oid = oidResult;

    var author = Git.Signature.now("information-people", "cpckewang@gmail.com");

    if(!result.page){
      return res.json({
        result: "Add fail"
      });
    }

    return repo.createCommit("HEAD", author, author, sprintf("Add %s success", result.page.name), oid, [head]);
  }).then(function(commitId){
    console.log("New Commit: " + commitId);

    return repo.getRemote("origin");
  }).then(function(remote){
    return remote.push([REFS + ":" + REFS]);
  }).catch(function(err){
    console.error(err);
  }).done(function(){
    console.log(result + " OK");

    return res.json({
      result: result
    });
  });
});

function processing(body){
  if(body.action !== "labeled"){
    return false;
  }

  var label_type = body.label.name;

  switch(label_type){
  case "開放討論中":
    return discussPeople(body);

    break;
  case "已新增":
    return addPeople(body);

    break;
  case "已刪除":
    return removePeople(body);

    break;
  case "已重複":
    return duplicatePeople(body);

    break;
  }
}

function discussPeople(body){
  // add people to pending list
  // add comment to content

  return "discussing";
}

function addPeople(body){
  // add people from pending list to content
  // add comment like "Added"
  // close issue

  // parse Markdown to JSON
  var tree = JSON.stringify(md.parse(body.issue.body));
  var ret = {};

  console.log(tree);
  console.log(tree[2][0].trim());
  console.log(tree[2][0].trim() !== "bulletlist");
  console.log(typeof tree[2][0]);
  console.log(typeof "bulletlist");

  if(tree[2][0].trim() !== "bulletlist"){
    ret.msg = "added fail";

    return ret;
  }

  var page = {};

  if(tree[2][1][0] === "listitem" && tree[2][2][0] === "listitem"){
    page.id = tree[2][1][1].split("Pages ID:")[1].trim();
    page.name = tree[2][2][1].split("Pages Name:")[1].trim();
  }

  var html_format = '

%(name)

';

  $("#page-list > .panel > .panel-body").append(sprintf(html_format, page));

  ret.msg = "added success";
  ret.page = page;

  return ret;
}

function removePeople(body){
  // remove people from content
  // add comment like "Removed"
  // close issue
  return "removed success";
}

function duplicatePeople(body){
  // add comment like "Duplicated"
  // close issue
  return "duplicated success";
}

module.exports = router;
<|endoftext|>


<commit_before>
var f = module.exports = {};

// json:  two way
//  - get: JSON.stringify
//  - set: JSON.parse
//  - example: `{ title|json }`
f.json = {
  get: function( value ){
    return typeof JSON !== 'undefined'? JSON.stringify(value): value;
  },
  set: function( value ){
    return typeof JSON !== 'undefined'? JSON.parse(value) : value;
  }
}

// last: one-way
//  - get: return the last item in list
//  - example: `{ list|last }`
f.last = function(arr){
  return arr && arr[arr.length - 1];
}

// average: one-way
//  - get: copute the average of the list
//  - example: `{ list| average: "score" }`
f.average = function(array, key){
  array = array || [];
  return array.length? f.total(array, key)/ array.length : 0;
}

// total: one-way
//  - get: copute the total of the list
//  - example: `{ list| average: "score" }`
f.total = function(array, key){
  var total = 0;
  if(!array) return;
  array.forEach(function( item ){
    total += key? item[key] : item;
  })
  return total;
}

// var basicSortFn = function(a, b){return b - a}

// f.sort = function(array, key, reverse){
//   var type = typeof key, sortFn;
//   switch(type){
//     case 'function': sortFn = key; break;
//     case 'string': sortFn = function(a, b){};break;
//     default:
//       sortFn = basicSortFn;
//   }
//   // need other refernce.
//   return array.slice().sort(function(a,b){
//     return reverse? -sortFn(a, b): sortFn(a, b);
//   })
//   return array
// }

<commit_msg>Update filter.js<commit_after>
var f = module.exports = {};

// json:  two way
//  - get: JSON.stringify
//  - set: JSON.parse
//  - example: `{ title|json }`
f.json = {
  get: function( value ){
    return typeof JSON !== 'undefined'? JSON.stringify(value): value;
  },
  set: function( value ){
    return typeof JSON !== 'undefined'? JSON.parse(value) : value;
  }
}

// last: one-way
//  - get: return the last item in list
//  - example: `{ list|last }`
f.last = function(arr){
  return arr && arr[arr.length - 1];
}

// average: one-way
//  - get: copute the average of the list
//  - example: `{ list| average: "score" }`
f.average = function(array, key){
  array = array || [];
  return array.length? f.total(array, key)/ array.length : 0;
}

// total: one-way
//  - get: copute the total of the list
//  - example: `{ list| total: "score" }`
f.total = function(array, key){
  var total = 0;
  if(!array) return;
  array.forEach(function( item ){
    total += key? item[key] : item;
  })
  return total;
}

// var basicSortFn = function(a, b){return b - a}

// f.sort = function(array, key, reverse){
//   var type = typeof key, sortFn;
//   switch(type){
//     case 'function': sortFn = key; break;
//     case 'string': sortFn = function(a, b){};break;
//     default:
//       sortFn = basicSortFn;
//   }
//   // need other refernce.
//   return array.slice().sort(function(a,b){
//     return reverse? -sortFn(a, b): sortFn(a, b);
//   })
//   return array
// }

<|endoftext|>