<commit_before>// CL API integration with the Grist API
// Docs: https://europepmc.org/GristAPI
// Fields you can search by: https://europepmc.org/GristAPI#API

// Example, get info by grant ID: http://www.ebi.ac.uk/europepmc/GristAPI/rest/get/query=gid:088130&resultType=core&format=json
// Use case: To get the name of a Principal Investigator, call CLapi.internals.use.grist.grant_id(the_grant_id).data.Person
//           Will return {FamilyName: "Friston", GivenName: "Karl", Initials: "KJ", Title: "Prof"}

CLapi.addRoute('/use/grist', {
    get: {
        action: function () {
            var routes = [];
            for ( var k in CLapi.internals.use.grist ) routes.push(k);
            return {status: 'success', routes: routes, data: {info: 'returns a subset of the Grist API functionality'} };
        }
    }
});

CLapi.addRoute('use/grist/grant_id/:qry', {
    get: {
        action: function() {
            var res = CLapi.internals.use.grist.grant_id(this.urlParams.qry);
            console.log(res);
            try {
                return {status: 'success', data: res.data , total: res.total}
            } catch(err) {
                return {status: 'success', data: res.data , total: res.total}
            }
        }
    }
});

CLapi.internals.use.grist = {};

CLapi.internals.use.grist.grant_id = function(grant_id) {
    var res = CLapi.internals.use.grist.search('gid:' + grant_id);
    return res;
};

CLapi.internals.use.grist.search = function(qrystr,from,page) {
    const GRIST_API_PAGE_SIZE = 25;  // it's hardcoded to 25 according to the docs
    // note in Grist API one of the params is resultType, in EPMC REST API the same param is resulttype .
    var url = 'http://www.ebi.ac.uk/europepmc/GristAPI/rest/get/query=' + qrystr + '&resultType=core&format=json';
    console.log("Grist API HTTP Get to " + url);
    if (from !== undefined) url += '&page=' + (Math.floor(from/GRIST_API_PAGE_SIZE)+1);
    var res = Meteor.http.call('GET', url);
    console.log(res.data.RecordList.Record);
    return { status: 'success', total: res.data.HitCount, data: res.data.RecordList.Record};  // RecordList is an object?!
};<commit_msg>refactor Grist api user<commit_after>// CL API integration with the Grist API
// Docs: https://europepmc.org/GristAPI
// Fields you can search by: https://europepmc.org/GristAPI#API

// Example, get info by grant ID: http://www.ebi.ac.uk/europepmc/GristAPI/rest/get/query=gid:088130&resultType=core&format=json
// Use case: To get the name of a Principal Investigator, call CLapi.internals.use.grist.grant_id(the_grant_id).data.Person
//           Will return {FamilyName: "Friston", GivenName: "Karl", Initials: "KJ", Title: "Prof"}

CLapi.addRoute('/use/grist', {
    get: {
        action: function () {
            var routes = [];
            for ( var k in CLapi.internals.use.grist ) routes.push(k);
            return {status: 'success', routes: routes, data: {info: 'returns a subset of the Grist API functionality'} };
        }
    }
});

CLapi.addRoute('use/grist/grant_id/:qry', {
    get: {
        action: function() {
            var res = CLapi.internals.use.grist.grant_id(this.urlParams.qry);
            try {
                return {status: 'success', data: res.data , total: res.total}
            } catch(err) {
                return {status: 'success', data: res.data , total: res.total}
            }
        }
    }
});

CLapi.internals.use.grist = {};

CLapi.internals.use.grist.grant_id = function(grant_id) {
    return CLapi.internals.use.grist.search('gid:' + grant_id);
};

CLapi.internals.use.grist.search = function(qrystr,from,page) {
    const GRIST_API_PAGE_SIZE = 25;  // it's hardcoded to 25 according to the docs
    // note in Grist API one of the params is resultType, in EPMC REST API the same param is resulttype .
    var url = 'http://www.ebi.ac.uk/europepmc/GristAPI/rest/get/query=' + qrystr + '&resultType=core&format=json';
    console.log("Grist API HTTP Get to " + url);
    if (from !== undefined) url += '&page=' + (Math.floor(from/GRIST_API_PAGE_SIZE)+1);
    var res = Meteor.http.call('GET', url);
    return { status: 'success', total: res.data.HitCount, data: res.data.RecordList.Record};  // RecordList is an object?!
};<|endoftext|>


<commit_before>angular.module('youwont.services', [])
  .service('VideoService', function($q) {

    var deferred = $q.defer();
    var promise = deferred.promise;

    promise.success = function(fn) {
      promise.then(fn);
      return promise;
    }

    promise.error = function(fn) {
      promise.then(null, fn);
      return promise;
    }

    // Resolve the URL to the local file
    // Start the copy process
    function createFileEntry(fileURI) {
      window.resolveLocalFileSystemURL(fileURI, function(entry) {
        return copyFile(entry);
      }, fail);
    }

    // Create a unique name for the videofile
    // Copy the recorded video to the app dir
    function copyFile(fileEntry) {

      var name = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf('/') + 1);
      var newName = makeid() + name;

      window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {
        fileEntry.copyTo(fileSystem2, newName, function(succ) {
          return onCopySuccess(succ);
        }, fail);
      }, fail);

    }

    // Called on successful copy process
    // Creates a thumbnail from the movie
    // The name is the moviename but with .png instead of .mov
    function onCopySuccess(entry) {
      var name = entry.nativeURL.slice(0, -4);
      window.PKVideoThumbnail.createThumbnail(entry.nativeURL, name + '.png', function(prevSucc) {
        return prevImageSuccess(prevSucc);
      }, fail);
    }

    // Called on thumbnail creation success
    // Generates the currect URL to the local moviefile
    // Finally resolves the promies and returns the name
    function prevImageSuccess(succ) {
      var correctUrl = succ.slice(0, -4);
      correctUrl += '.MOV';
      deferred.resolve(correctUrl);
    }

    // Called when anything fails
    // Rejects the promise with an Error
    function fail(error) {
      console.log('FAIL: ' + error.code);
      deferred.reject('ERROR');
    }

    // Function to make a unique filename
    function makeid() {
      var text = '';
      var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      for (var i = 0; i < 5; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      }
      return text;
    }

    // The object and functions returned from the Service
    return {
      // This is the initial function we call from our controller
      // Gets the videoData and calls the first service function
      // with the local URL of the video and returns the promise
      saveVideo: function(data) {
        createFileEntry(data[0].localURL);
        return promise;
      }
    }

  })
  .service("DatabaseService", function($cordovaFile) {

    var db = {};
    db.ref = new Firebase("https://sayiwont.firebaseio.com/");

    function getBase64FromFile(file, callback) {
      window.resolveLocalFileSystemURL(file,
        // success callback; generates the FileEntry object needed to convert to Base64 string
        function (fileEntry) {
            // convert to Base64 string
            function win(file) {
              var reader = new FileReader();
              reader.onloadend = function (evt) {
                callback(evt.target.result); // this is the Base64 string
              };
              reader.readAsDataURL(file);
            };
            var fail = function (evt) { };
            fileEntry.file(win, fail);
        },
        // error callback
        function () {
          console.log("error");
        }
      );
    }

    db.addNewUser = function(userName, userProfilePicture, facebookID, uid) {
      //Adding new user to our database
      var ref = new Firebase("https://sayiwont.firebaseio.com/");
      if (userName && userProfilePicture && facebookID && uid) {
        ref.child("users").child(uid).set({
          id: facebookID,
          name: userName,
          profilePicture: userProfilePicture,
          friends: { "Mark Robson" :{id:"10153502325756226",name:"Mark Robson"}},
          challenges: []
        });
      }
    };

        db.addToFriendsChallenges = function(friendsList,challenge){
        //loop through that users list of friends and add that challenge to their challenges list
        for (var i = 0; i <friendsList.length; i++){
          if (challenge){
            console.dir(friendsList[i].id)
            var ref = new Firebase("https://sayiwont.firebaseio.com/users/");
            ref.child("facebook:"+friendsList[i].id).child('challenges').set(challenge);
          }
        }

    }

    db.addNewChallenge = function(challenge) {

      var currentUser = db.ref.getAuth().uid;
      var obj = {};
      db.ref = new Firebase("https://sayiwont.firebaseio.com/challenges/");
      db.getFriends(function(friendsList){
        if (challenge && challenge.title && challenge.description){
          challenge['friends'] = friendsList;
          obj[challenge.id] = challenge;
          getBase64FromFile(challenge.clip, function (data) {
            challenge.clip = data;
            getBase64FromFile(challenge.img, function (data) {
              challenge.img = data;
              db.ref.child(currentUser).set(obj);
            });
          });

          db.addToFriendsChallenges(friendsList,challenge);

        } else {
          console.error('addNewChallenge is missing params')
        }
      })

    };

    db.addFriend = function(friend,callback){
        //get user object

        var currentUser = db.ref.getAuth().uid;
        var ref = new Firebase("https://sayiwont.firebaseio.com/users/"+currentUser+"/friends");
        if (friend){
           //
           var friendObject = {
            id: friend.id,
            name: friend.name,
            profilePicture: friend.profilePicture
           }

        ref.child(friendObject.id).set(friendObject);
      }

    }

   db.updateUserChallenges = function(callback){
      var currentUser = db.ref.getAuth().uid;
      var ref = new Firebase("https://sayiwont.firebaseio.com/users/"+currentUser+"/");
       var challenges = [];
       ref.orderByChild('challenges').on('child_added',function(snapshot){

        if(snapshot.val().id){
          console.dir(snapshot.val)
          challenges.push(snapshot.val())
        }
        if(callback){
          callback(challenges)
        }
        });
   }

    db.getFriends = function(callback){
      var ref = new Firebase("https://sayiwont.firebaseio.com/users")
      var friends = [];
      //db.addFriend();
      ref.orderByKey().on("child_added", function(snapshot) {

        friends.push(snapshot.val());
        if (callback){
          callback(friends)
        }
      });

    }

    db.addResponseToChallenge = function(currentChallenge,response){
      var ref = new Firebase("https://sayiwont.firebaseio.com/challenges/");
      ref.child("").child('responses').set(response);
    }
    return db;
  });<commit_msg>fixing merge coflicts<commit_after>angular.module('youwont.services', [])
  .service('VideoService', function($q) {

    var deferred = $q.defer();
    var promise = deferred.promise;

    promise.success = function(fn) {
      promise.then(fn);
      return promise;
    }

    promise.error = function(fn) {
      promise.then(null, fn);
      return promise;
    }

    // Resolve the URL to the local file
    // Start the copy process
    function createFileEntry(fileURI) {
      window.resolveLocalFileSystemURL(fileURI, function(entry) {
        return copyFile(entry);
      }, fail);
    }

    // Create a unique name for the videofile
    // Copy the recorded video to the app dir
    function copyFile(fileEntry) {

      var name = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf('/') + 1);
      var newName = makeid() + name;

      window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {
        fileEntry.copyTo(fileSystem2, newName, function(succ) {
          return onCopySuccess(succ);
        }, fail);
      }, fail);

    }

    // Called on successful copy process
    // Creates a thumbnail from the movie
    // The name is the moviename but with .png instead of .mov
    function onCopySuccess(entry) {
      var name = entry.nativeURL.slice(0, -4);
      window.PKVideoThumbnail.createThumbnail(entry.nativeURL, name + '.png', function(prevSucc) {
        return prevImageSuccess(prevSucc);
      }, fail);
    }

    // Called on thumbnail creation success
    // Generates the currect URL to the local moviefile
    // Finally resolves the promies and returns the name
    function prevImageSuccess(succ) {
      var correctUrl = succ.slice(0, -4);
      correctUrl += '.MOV';
      deferred.resolve(correctUrl);
    }

    // Called when anything fails
    // Rejects the promise with an Error
    function fail(error) {
      console.log('FAIL: ' + error.code);
      deferred.reject('ERROR');
    }

    // Function to make a unique filename
    function makeid() {
      var text = '';
      var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      for (var i = 0; i < 5; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      }
      return text;
    }

    // The object and functions returned from the Service
    return {
      // This is the initial function we call from our controller
      // Gets the videoData and calls the first service function
      // with the local URL of the video and returns the promise
      saveVideo: function(data) {
        createFileEntry(data[0].localURL);
        return promise;
      }
    }

  })
  .service("DatabaseService", function($cordovaFile) {

    var db = {};
    db.ref = new Firebase("https://sayiwont.firebaseio.com/");

    function getBase64FromFile(file, callback) {
      window.resolveLocalFileSystemURL(file,
        // success callback; generates the FileEntry object needed to convert to Base64 string
        function (fileEntry) {
            // convert to Base64 string
            function win(file) {
              var reader = new FileReader();
              reader.onloadend = function (evt) {
                callback(evt.target.result); // this is the Base64 string
              };
              reader.readAsDataURL(file);
            };
            var fail = function (evt) { };
            fileEntry.file(win, fail);
        },
        // error callback
        function () {
          console.log("error");
        }
      );
    }

    db.addNewUser = function(userName, userProfilePicture, facebookID, uid) {
      //Adding new user to our database
      var ref = new Firebase("https://sayiwont.firebaseio.com/");
      if (userName && userProfilePicture && facebookID && uid) {
        ref.child("users").child(uid).set({
          id: facebookID,
          name: userName,
          profilePicture: userProfilePicture,
          friends: { "Mark Robson" :{id:"10153502325756226",name:"Mark Robson"}},
          challenges: []
        });
      }
    };

    db.addNewChallenge = function(challenge) {

      var currentUser = db.ref.getAuth().uid;
      var obj = {};
      db.ref = new Firebase("https://sayiwont.firebaseio.com/challenges/");
      db.getFriends(function(friendsList){
        if (challenge && challenge.title && challenge.description){
          challenge['friends'] = friendsList;
          obj[challenge.id] = challenge;
          getBase64FromFile(challenge.clip, function (data) {
            challenge.clip = data;
            getBase64FromFile(challenge.img, function (data) {
              challenge.img = data;
              db.ref.child(currentUser).set(obj);
            });
          });

          db.addToFriendsChallenges(friendsList,challenge);

        } else {
          console.error('addNewChallenge is missing params')
        }
      })

    };

    db.addFriend = function(friend,callback){
        //get user object

        var currentUser = db.ref.getAuth().uid;
        var ref = new Firebase("https://sayiwont.firebaseio.com/users/"+currentUser+"/friends");
        if (friend){
           //
           var friendObject = {
            id: friend.id,
            name: friend.name,
            profilePicture: friend.profilePicture
           }

        ref.child(friendObject.id).set(friendObject);
      }

    }

   db.updateUserChallenges = function(callback){
      var currentUser = db.ref.getAuth().uid;
      var ref = new Firebase("https://sayiwont.firebaseio.com/users/"+currentUser+"/");
       var challenges = [];
       ref.orderByChild('challenges').on('child_added',function(snapshot){

        if(snapshot.val().id){
          console.dir(snapshot.val)
          challenges.push(snapshot.val())
        }
        if(callback){
          callback(challenges)
        }
        });
   }

    db.getFriends = function(callback){
      var ref = new Firebase("https://sayiwont.firebaseio.com/users")
      var friends = [];

      ref.orderByKey().on("child_added", function(snapshot) {

        friends.push(snapshot.val());
        if (callback){
          callback(friends)
        }
      });

    }

    db.addResponseToChallenge = function(currentChallenge,response){
      var ref = new Firebase("https://sayiwont.firebaseio.com/challenges/");
      ref.child("").child('responses').set(response);
    }

        db.addToFriendsChallenges = function(friendsList,challenge){
        //loop through that users list of friends and add that challenge to their challenges list
        for (var i = 0; i <friendsList.length; i++){
          if (challenge){
            console.dir(friendsList[i].id)
            var ref = new Firebase("https://sayiwont.firebaseio.com/users/");
            ref.child("facebook:"+friendsList[i].id).child('challenges').set(challenge);
          }
        }

    }
    return db;
  });<|endoftext|>


<commit_before>// Underscore-contrib (underscore.function.arity.js 0.0.1)
// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors
// Underscore-contrib may be freely distributed under the MIT license.

(function(root) {

  // Baseline setup
  // --------------

  // Establish the root object, `window` in the browser, or `global` on the server.
  var _ = root._ || require('underscore');

  // Helpers
  // -------

  // Curry
  // -------
  var curry = (function () {
    function checkArguments (argsCount) {
      if (argsCount !== 1) {
        throw new RangeError('Only a single argument may be accepted.');
      }
    }
    function collectArgs(func, that, argCount, args, newArg, reverse) {
      if (reverse == true) {
          args.unshift(newArg);
      } else {
          args.push(newArg);
      }
      if (args.length == argCount) {
        return func.apply(that, args);
      } else {
        return function () {
          checkArguments(arguments.length);
          return collectArgs(func, that, argCount, args.slice(0), arguments[0], reverse);
        };
      }
    }
    return function curry (func, reverse) {
      var that = this;
      return function () {
        checkArguments(arguments.length);
        return collectArgs(func, that, func.length, [], arguments[0], reverse);
      };
    };
  }());

  // Enforce Arity
  // --------------------
  var enforce = (function () {
    var CACHE = [];
    return function enforce (func) {
      var funcLength = func.length;
      if (CACHE[funcLength] === undefined) {
        CACHE[funcLength] = function (enforceFunc) {
          return function () {
            if (arguments.length !== funcLength) {
              throw new Error(funcLength + ' arguments must be applied.');
            }
            return enforceFunc.apply(this, arguments);
          };
        };
      }
      if (typeof func !== 'function') {
        throw new Error('Argument 1 must be a function.');
      } else {
        return CACHE[funcLength](func);
      }
    };
  }());

  // Mixing in the arity functions
  // -----------------------------

  _.mixin({
    // ### Fixed arguments

    // Fixes the arguments to a function based on the parameter template defined by
    // the presence of values and the `_` placeholder.
    fix: function(fun) {
      var args = _.rest(arguments);

      var f = function() {
        var arg = 0;

        for ( var i = 0; i < args.length && arg < arguments.length; i++ ) {
          if ( args[i] === _ ) {
            args[i] = arguments[arg++];
          }
        }

        return fun.apply(null, args);
      };

      f._original = fun;

      return f;
    },

    unary: function (fun) {
      return function unary (a) {
        return fun.call(this, a);
      };
    },

    binary: function (fun) {
      return function binary (a, b) {
        return fun.call(this, a, b);
      };
    },

    ternary: function (fun) {
      return function ternary (a, b, c) {
        return fun.call(this, a, b, c);
      };
    },

    quaternary: function (fun) {
      return function quaternary (a, b, c, d) {
        return fun.call(this, a, b, c, d);
      };
    },

    // Flexible curry function with strict arity.
    // Argument application left to right.
    // source: https://github.com/eborden/js-curry
    curry: curry,

    // Flexible right to left curry with strict arity.
    rCurry: function (func) {
        return curry.call(this, func, true);
    },
    // Dynamic decorator to enforce function arity and defeat varargs.
    enforce: enforce
  });

  _.arity = (function () {
    var FUNCTIONS = {};
    return function arity (numberOfArgs, fun) {
      if (FUNCTIONS[numberOfArgs] == null) {
        var parameters = new Array(numberOfArgs);
        for (var i = 0; i < numberOfArgs; ++i) {
          parameters[i] = "__" + i;
        }
        var pstr = parameters.join();
        var code = "return function ("+pstr+") { return fun.apply(this, arguments); };";
        FUNCTIONS[numberOfArgs] = new Function(['fun'], code);
      }
      if (fun == null) {
        return function (fun) { return arity(numberOfArgs, fun); };
      }
      else return FUNCTIONS[numberOfArgs](fun);
    };
  })();

})(this);
<commit_msg>moved function check.<commit_after>// Underscore-contrib (underscore.function.arity.js 0.0.1)
// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors
// Underscore-contrib may be freely distributed under the MIT license.

(function(root) {

  // Baseline setup
  // --------------

  // Establish the root object, `window` in the browser, or `global` on the server.
  var _ = root._ || require('underscore');

  // Helpers
  // -------

  // Curry
  // -------
  var curry = (function () {
    function checkArguments (argsCount) {
      if (argsCount !== 1) {
        throw new RangeError('Only a single argument may be accepted.');
      }
    }
    function collectArgs(func, that, argCount, args, newArg, reverse) {
      if (reverse == true) {
          args.unshift(newArg);
      } else {
          args.push(newArg);
      }
      if (args.length == argCount) {
        return func.apply(that, args);
      } else {
        return function () {
          checkArguments(arguments.length);
          return collectArgs(func, that, argCount, args.slice(0), arguments[0], reverse);
        };
      }
    }
    return function curry (func, reverse) {
      var that = this;
      return function () {
        checkArguments(arguments.length);
        return collectArgs(func, that, func.length, [], arguments[0], reverse);
      };
    };
  }());

  // Enforce Arity
  // --------------------
  var enforce = (function () {
    var CACHE = [];
    return function enforce (func) {
      if (typeof func !== 'function') {
        throw new Error('Argument 1 must be a function.');
      }
      var funcLength = func.length;
      if (CACHE[funcLength] === undefined) {
        CACHE[funcLength] = function (enforceFunc) {
          return function () {
            if (arguments.length !== funcLength) {
              throw new RangeError(funcLength + ' arguments must be applied.');
            }
            return enforceFunc.apply(this, arguments);
          };
        };
      }
      return CACHE[funcLength](func);
    };
  }());

  // Mixing in the arity functions
  // -----------------------------

  _.mixin({
    // ### Fixed arguments

    // Fixes the arguments to a function based on the parameter template defined by
    // the presence of values and the `_` placeholder.
    fix: function(fun) {
      var args = _.rest(arguments);

      var f = function() {
        var arg = 0;

        for ( var i = 0; i < args.length && arg < arguments.length; i++ ) {
          if ( args[i] === _ ) {
            args[i] = arguments[arg++];
          }
        }

        return fun.apply(null, args);
      };

      f._original = fun;

      return f;
    },

    unary: function (fun) {
      return function unary (a) {
        return fun.call(this, a);
      };
    },

    binary: function (fun) {
      return function binary (a, b) {
        return fun.call(this, a, b);
      };
    },

    ternary: function (fun) {
      return function ternary (a, b, c) {
        return fun.call(this, a, b, c);
      };
    },

    quaternary: function (fun) {
      return function quaternary (a, b, c, d) {
        return fun.call(this, a, b, c, d);
      };
    },

    // Flexible curry function with strict arity.
    // Argument application left to right.
    // source: https://github.com/eborden/js-curry
    curry: curry,

    // Flexible right to left curry with strict arity.
    rCurry: function (func) {
        return curry.call(this, func, true);
    },
    // Dynamic decorator to enforce function arity and defeat varargs.
    enforce: enforce
  });

  _.arity = (function () {
    var FUNCTIONS = {};
    return function arity (numberOfArgs, fun) {
      if (FUNCTIONS[numberOfArgs] == null) {
        var parameters = new Array(numberOfArgs);
        for (var i = 0; i < numberOfArgs; ++i) {
          parameters[i] = "__" + i;
        }
        var pstr = parameters.join();
        var code = "return function ("+pstr+") { return fun.apply(this, arguments); };";
        FUNCTIONS[numberOfArgs] = new Function(['fun'], code);
      }
      if (fun == null) {
        return function (fun) { return arity(numberOfArgs, fun); };
      }
      else return FUNCTIONS[numberOfArgs](fun);
    };
  })();

})(this);
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Project = mongoose.model('Project');
var User = mongoose.model('User');
var bodyParser = require("body-parser");
var fs = require('fs');
var formidable = require('formidable');
var path = require('path');
var archiver = require('archiver');

//var _ = require( 'lodash' );

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

	var coll = req.body.collaborators;

    User.findOne({'userName': req.body.userName}, function (err, obj){
        if (err || obj.id === null || obj.id === undefined){
            console.log("something went wrong");
        } else {

            project.projectName = req.body.projectName;
            project.uniqueKey = req.body.uniqueKey;
            project.ownerID = obj._id;
            project.info = req.body.info;
            project.dateCreated = Date.now();

			for(var zaehl = 0; zaehl < coll.length; zaehl++){
				console.log(coll[zaehl]);
				User.findOne({'email': coll[zaehl]}, {'email': 1}, function (err, collabo) {
					if (err) {
						console.log("something went wrong");
					} else if (collabo === null) {
						console.log("Passed email address is not a registered user; collaborator was not added");
					} else {
						console.log(collabo);
						project.collaborators.push(collabo.email);
					}
				});
			}

            setTimeout( function () {
				project.save(function(err) {
					res.status(200);
					res.json({
						"status": "everything worked fine"
					});
					setTimeout( function ()
					{
						obj.ownProjects.push({projectName: req.body.projectName, projectID: project._id});
						obj.save(function(error){
							if(error){
								console.log("something went wrong");
							}
						});
					}, 50);
				});
			}, 50);

            for(var i = 0; i < coll.length; i++){
                User.findOne({'email': coll[i]}, function (err, collabo){
                    if (err){
                        console.log("something went wrong");
                    } else if (collabo === null) {
                        console.log(coll[i] + " is not a registered user; collaborator was not added");
                    } else {
                        collabo.coopProjects.push({projectName: project.projectName, projectID: project._id});
                        collabo.save(function(e){
                            if(e){
                                console.log("something went wrong");
                            }
                        })
                    }
                });
            }
        }
    });
    for(var j=0; j < req.body.collaborators.length; j++){
        User.findOne({'email': req.body.collaborators[j]}, function (e, col){
            if(e) {
                console.log("something went wrong");
            } else if (col === null)
            {
                console.log(req.body.collaborators[j] + " is not a valid collaborator")

            } else {
                project.collaboratorID.push(col._id);
                project.update();
            }
        });
    }
    var exec = require('child_process').exec;
    function puts(error, stdout, stderr) { if(error){ console.log(error)}else{console.log(stdout)} };
	var projDirName = req.body.uniqueKey;
	projDirName = projDirName.replace(/(\s)/g, "__");
	console.log(projDirName);
    exec("cd projectData && mkdir "+projDirName+"", puts);
    setTimeout(function () {
        exec("cd projectData/"+projDirName+" && mkdir rScripts", puts);
        exec("cd projectData/"+projDirName+" && mkdir txtFiles", puts);
        exec("cd projectData/"+projDirName+" && mkdir geoTiffs", puts);
        exec("cd projectData/"+projDirName+" && echo {} > datatxt.json", puts);
        exec("cd projectData/"+projDirName+" && echo {} > datarScripts.json", puts);
        project.filePath.push("projectData", "projectData/"+req.body.uniqueKey, "projectData/"+req.body.uniqueKey+"/rScripts", "projectData/"+req.body.uniqueKey+"/txtFiles", "projectData/"+req.body.uniqueKey+"/geoTiffs", "projectData/"+req.body.uniqueKey+"/datatxt.json", "projectData/"+req.body.uniqueKey+"/datarScript.json");

    }, 40);

    setTimeout(function () {
		console.log("read datatxt.json");
        fs.readFile('projectData/' + req.body.uniqueKey + '/datatxt.json', function (err, data) {
            if (err) throw err;
            var newData = JSON.parse(data);
            newData.id = "../../projectData/" + req.body.uniqueKey + "/txtFiles/";
            newData.value = "txtFiles";
            newData.data = [];
            console.log(newData);
            newData = JSON.stringify(newData);
            console.log(newData);

            var fileName = path.join(__dirname, '../../projectData/' + projDirName + '/datatxt') + '.json';

            fs.writeFile(fileName, newData, function(err) {
                if (err) {
                    console.error('Something when wrong when saving the temp file' + err);
                    res.send('Something when wrong when saving the temp file');
                }
            });

        });
    }, 120);

    setTimeout(function () {
		console.log("read datarScripts.json");
        fs.readFile('projectData/' + projDirName + '/datarScripts.json', function (err, data) {
            if (err) throw err;
            var newData = JSON.parse(data);
            newData.id = "../../projectData/" + projDirName + "/rScripts/";
            newData.value = "rScripts";
            newData.data = [];
            console.log(newData);
            newData = JSON.stringify(newData);
            console.log(newData);

            var fileName = path.join(__dirname, '../../projectData/' + projDirName + '/datarScripts') + '.json';

            fs.writeFile(fileName, newData, function(err) {
                if (err) {
                    console.error('Something when wrong when saving the temp file' + err);
                    res.send('Something when wrong when saving the temp file');
                }
            });

        });
    }, 120);

};

module.exports.projectRead = function(req, res) {

    /*
     Important notice:
     for triggering this function,
     req must contain the Projects ID;

     this means, the respective project._id must be provided as JSON to the function (or otherwise attribute of function call, in this case, change attribute formatting).
     */
    /*
    Project
        .findOne({'ownerID': req.payload._id}, function(err, obj){
            if(err){
                res.status(401).json("couldnt load the project");
            }else{
                res.status(200).json(obj);
            }
        });
        */

    Project
        .findById(req.params.id, function(err, obj){
            if(err){
                res.status(401).json("could not load the project");
            } else {
                res.status(200).json(obj);
            }
        });
};

// ***********
// ** TODO: **
// ***********

// adapt dependencies and mechanics
// to project management requirements

// create and handle edit logging

module.exports.projectUpdate = function(req, res) {

    //var query = {'ownerID': req.payload._id};

    Project
        .findByIdAndUpdate(req.params.id, req.body, function(err, obj) {
            if(err){
                res.status(401).json("couldnt update the project");
            } else{
                res.status(200).json(obj);
            }
        });

    /*
     if (!req.payload._id) {
     res.status(401).json({
     "message": "UnauthorizedError: cannot update project without being logged in as a user"
     });
     } else {
     // authorization needed, so not every user can change a project
     // validate user as author or collaborator,
     // otherwise shoot down request
     Project.findById(req.body._id)
     .exec(function (err, project) {
     if (err) {
     res.status(401).json({
     "message": "dbError: Error performing FindById"
     });
     } else if ( req.payload._id === project.ownerID ) {
     // Editor is owner
     Project.findByIdAndUpdate(req.payload._id, req.body, {runValidators: true, upsert: true})
     .exec(function (err, user) {
     res.status(200).json(project);
     })
     } else if ( _.includes( project.collaborators, req.payload._id )) {
     // Editor is collaborator
     Project.findByIdAndUpdate(req.payload._id, req.body, {runValidators: true, upsert: true})
     .exec(function (err, user) {
     res.status(200).json(project);
     })
     } else {
     res.status(401).json({
     "message": "UnauthorizedError: Must be owner or collaborator to edit project"
     })
     }
     });
     }*/
};

module.exports.projectDelete = function (req, res) {

    //var query = {'ownerID': req.payload._id};

    Project
        .findById(req.params.id, function(err, obj) {
            if(err){
                res.status(401).json("couldnt delete the project");
            } else{
                User.findOneAndUpdate({_id: obj.ownerID}, {$pull: {ownProjects: {projectID: obj._id}}}, function(err, data){
                    if(err){
                        console.log("something went wrong");
                    } else {
                        console.log("perfect");
                    }
                });

                for(var i = 0; i < obj.collaborators.length; i++){
                    User.findOneAndUpdate({email: obj.collaborators[i]}, {$pull: {coopProjects: {projectID: obj._id}}}, function(err, data){
                        if(err){
                            console.log("something went wrong");
                        } else {
                            console.log("nice");
                        }
                    });
                }

                var exec = require('child_process').exec;
                function puts(error, stdout, stderr) { if(error){ console.log(error)}else{console.log(stdout)} };

				/**
				 * Geht kürzer!!
				exec("cd projectData/"+obj.uniqueKey+" && rd geoTiffs", puts);
                exec("cd projectData/"+obj.uniqueKey+" && rd txtFiles", puts);
                exec("cd projectData/"+obj.uniqueKey+" && rd rScripts", puts);
                exec("cd projectData && rd "+obj.uniqueKey+"", puts);
				 * rm -r löscht rekursiv sämtliche Unterstrukturen eines Directory's, und dann den Ordner selbst!
				 */
				var projDirName = obj.uniqueKey.replace(/(\s)/g, "__");
				exec("cd projectData && rm -r " +projDirName +"", puts);

				obj.remove();
				res.status(200).json("removed the project");
                /*
                User
                    .findById(obj.ownerID, function (e, owner){
                        if(e){
                            console.log("something went wrong");
                        }else {
                            //owner.ownProjects.pull({projectName: obj.projectName, projectID: obj._id});
                            //for(var j=0; j < owner.ownProjects.length; j++){
                            //if (owner.ownProjects[j].projectID === obj._id) {
                                //delete owner.ownProjects[{projectName: obj.projectName, projectID:obj._id}];
                            //}
                        //}
                        }});
*/

                /*
                var coll = obj.collaborators;
                for(var i = 0; i < coll.length; i++){
                    User.findOne({'email': coll[i]}, function (error, collabo) {
                        if (error) {
                            console.log("something went wrong");
                        } else {
                            //collabo.coopProjects.pull({projectName: obj.projectName, projectID: obj._id});
                            //for(var m=0; m < collabo.coopProjects.length; m++){
                            //if (collabo.coopProjects[m].projectID === obj._id) {
                                //delete collabo.coopProjects[{projectName: obj.projectName, projectID:obj._id}];
                            //}}
                        }
                    });
            }
            */
        }});

    /*
     if (!req.payload._id) {
     res.status(401).json({
     "message": "UnauthorizedError: cannot delete profile without being logged in to it"
     });
     } else {
     Project.findById(req.payload._id)
     .exec(function (err, value) {
     if (err) {
     res.status(401).json({
     "message": "DeleteError: could not delete feature"
     });
     } else if ( req.payload._id === project.ownerID ) {
     console.log('feature removed (logging just for testing)');
     value.remove();
     res.status(200).send('removed Feature');
     } else {
     res.status(401).json({
     "message": "UnauthorizedError: Must be owner to delete project"
     });
     }
     });
     }*/
};

module.exports.uploadFile = function(req, res) {

    var form = new formidable.IncomingForm();

    form.multiples = false;

    // TODO: Abfrage ob Dateiendung r oder txt ist und dann Error werfen, damit kein Datenmüll hochgeladen wird

    form.uploadDir = path.join(__dirname, '../../projectData');

    console.log(path.join(__dirname, '../../projectData'));

	var projDirName = req.params.key.replace(/(\s)/g, "__");
// every time a file has been uploaded successfully,
// rename it to it's original name
    form.on('file', function (field, file) {
        if(file.type === 'text/plain'){
            fs.rename(file.path, path.join(form.uploadDir+'/'+projDirName+'/txtFiles', file.name));

            fs.readFile('projectData/' + projDirName + '/datatxt.json', function (err, jsondata) {
                if (err) throw err;
                var newData = JSON.parse(jsondata);
                newData.data.push({id: "../../projectData/" + projDirName + "/txtFiles/" + file.name , value: file.name});
                newData = JSON.stringify(newData);
                console.log(JSON.parse(newData))

                var fileName = path.join(__dirname, '../../projectData/' + projDirName + '/datatxt') + '.json';

                fs.writeFile(fileName, newData, function(err) {
                    if (err) {
                        console.error('Something when wrong when saving the temp file' + err);
                        res.send('Something when wrong when saving the temp file');
                    }
                });

            });
        }
        if(file.type === 'application/octet-stream'){
            fs.rename(file.path, path.join(form.uploadDir+'/'+projDirName+'/rScripts', file.name));

            fs.readFile('projectData/' + projDirName + '/datarScripts.json', function (err, data) {
                if (err) throw err;
                var newData = JSON.parse(data);
                newData.data.push({id: "../../projectData/" + projDirName + "/rScripts/" + file.name , value: file.name});
                newData = JSON.stringify(newData);

                var fileName = path.join(__dirname, '../../projectData/' + projDirName + '/datarScripts') + '.json';

                fs.writeFile(fileName, newData, function (err) {
                    if (err) {
                        console.error('Something when wrong when saving the temp file' + err);
                        res.send('Something when wrong when saving the temp file');
                    }
                });
            });
        }
    });

// log any errors that occur
    form.on('error', function (err) {
        console.log('An error has occured: \n' + err);
    });

// once all the files have been uploaded, send a response to the client
    form.on('end', function () {
        res.end('success');
    });

// parse the incoming request containing the form data
    form.parse(req);
};

module.exports.downloadZip = function(req, res){

    var output = fs.createWriteStream(__dirname + '/'+req.params.key+'.zip');
    var archive = archiver('zip', {
        store: false // Sets the compression method to STORE.
    });

    archive.directory('projectData/'+req.params.key+'/');

    archive.on('close', function() {
        console.log(archive.pointer() + ' total bytes');
        console.log('archiver has been finalized and the output file descriptor has closed.');
        res.status(200).send('okay').end();
    });

    res.attachment(req.params.key+'.zip');

    archive.on('error', function(err) {
        if(err) {
            res.status(400).json("could not zip the file");
        }
    });

    archive.finalize();
};<commit_msg>fixed my stupidity... sort of.<commit_after>var mongoose = require('mongoose');
var Project = mongoose.model('Project');
var User = mongoose.model('User');
var bodyParser = require("body-parser");
var fs = require('fs');
var formidable = require('formidable');
var path = require('path');
var archiver = require('archiver');

//var _ = require( 'lodash' );

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

	var coll = req.body.collaborators;

    User.findOne({'userName': req.body.userName}, function (err, obj){
        if (err || obj.id === null || obj.id === undefined){
            console.log("something went wrong");
        } else {

            project.projectName = req.body.projectName;
            project.uniqueKey = req.body.uniqueKey;
            project.ownerID = obj._id;
            project.info = req.body.info;
            project.dateCreated = Date.now();

			for(var zaehl = 0; zaehl < coll.length; zaehl++){
				console.log(coll[zaehl]);
				User.findOne({'email': coll[zaehl]}, {'email': 1}, function (err, collabo) {
					if (err) {
						console.log("something went wrong");
					} else if (collabo === null) {
						console.log("Passed email address is not a registered user; collaborator was not added");
					} else {
						console.log(collabo);
						project.collaborators.push(collabo.email);
					}
				});
			}

            setTimeout( function () {
				project.save(function(err) {
					res.status(200);
					res.json({
						"status": "everything worked fine"
					});
					setTimeout( function ()
					{
						obj.ownProjects.push({projectName: req.body.projectName, projectID: project._id});
						obj.save(function(error){
							if(error){
								console.log("something went wrong");
							}
						});
					}, 50);
				});
			}, 50);

            for(var i = 0; i < coll.length; i++){
                User.findOne({'email': coll[i]}, function (err, collabo){
                    if (err){
                        console.log("something went wrong");
                    } else if (collabo === null) {
                        console.log(coll[i] + " is not a registered user; collaborator was not added");
                    } else {
                        collabo.coopProjects.push({projectName: project.projectName, projectID: project._id});
                        collabo.save(function(e){
                            if(e){
                                console.log("something went wrong");
                            }
                        })
                    }
                });
            }
        }
    });
    for(var j=0; j < req.body.collaborators.length; j++){
        User.findOne({'email': req.body.collaborators[j]}, function (e, col){
            if(e) {
                console.log("something went wrong");
            } else if (col === null)
            {
                console.log(req.body.collaborators[j] + " is not a valid collaborator")

            } else {
                project.collaboratorID.push(col._id);
                project.update();
            }
        });
    }
    var exec = require('child_process').exec;
    function puts(error, stdout, stderr) { if(error){ console.log(error)}else{console.log(stdout)} };
	var projDirName = req.body.uniqueKey;
	projDirName = projDirName.replace(/(\s)/g, "__");
	console.log(projDirName);
    exec("cd projectData && mkdir "+projDirName+"", puts);
    setTimeout(function () {
        exec("cd projectData/"+projDirName+" && mkdir rScripts", puts);
        exec("cd projectData/"+projDirName+" && mkdir txtFiles", puts);
        exec("cd projectData/"+projDirName+" && mkdir geoTiffs", puts);
        exec("cd projectData/"+projDirName+" && echo {} > datatxt.json", puts);
        exec("cd projectData/"+projDirName+" && echo {} > datarScripts.json", puts);
        project.filePath.push("projectData", "projectData/"+req.body.uniqueKey, "projectData/"+req.body.uniqueKey+"/rScripts", "projectData/"+req.body.uniqueKey+"/txtFiles", "projectData/"+req.body.uniqueKey+"/geoTiffs", "projectData/"+req.body.uniqueKey+"/datatxt.json", "projectData/"+req.body.uniqueKey+"/datarScript.json");

    }, 40);

    setTimeout(function () {
		console.log("read datatxt.json");
        fs.readFile('projectData/' + projDirName + '/datatxt.json', function (err, data) {
            if (err) throw err;
            var newData = JSON.parse(data);
            newData.id = "../../projectData/" + projDirName + "/txtFiles/";
            newData.value = "txtFiles";
            newData.data = [];
            console.log(newData);
            newData = JSON.stringify(newData);
            console.log(newData);

            var fileName = path.join(__dirname, '../../projectData/' + projDirName + '/datatxt') + '.json';

            fs.writeFile(fileName, newData, function(err) {
                if (err) {
                    console.error('Something when wrong when saving the temp file' + err);
                    res.send('Something when wrong when saving the temp file');
                }
            });

        });
    }, 120);

    setTimeout(function () {
		console.log("read datarScripts.json");
        fs.readFile('projectData/' + projDirName + '/datarScripts.json', function (err, data) {
            if (err) throw err;
            var newData = JSON.parse(data);
            newData.id = "../../projectData/" + projDirName + "/rScripts/";
            newData.value = "rScripts";
            newData.data = [];
            console.log(newData);
            newData = JSON.stringify(newData);
            console.log(newData);

            var fileName = path.join(__dirname, '../../projectData/' + projDirName + '/datarScripts') + '.json';

            fs.writeFile(fileName, newData, function(err) {
                if (err) {
                    console.error('Something when wrong when saving the temp file' + err);
                    res.send('Something when wrong when saving the temp file');
                }
            });

        });
    }, 120);

};

module.exports.projectRead = function(req, res) {

    /*
     Important notice:
     for triggering this function,
     req must contain the Projects ID;

     this means, the respective project._id must be provided as JSON to the function (or otherwise attribute of function call, in this case, change attribute formatting).
     */
    /*
    Project
        .findOne({'ownerID': req.payload._id}, function(err, obj){
            if(err){
                res.status(401).json("couldnt load the project");
            }else{
                res.status(200).json(obj);
            }
        });
        */

    Project
        .findById(req.params.id, function(err, obj){
            if(err){
                res.status(401).json("could not load the project");
            } else {
                res.status(200).json(obj);
            }
        });
};

// ***********
// ** TODO: **
// ***********

// adapt dependencies and mechanics
// to project management requirements

// create and handle edit logging

module.exports.projectUpdate = function(req, res) {

    //var query = {'ownerID': req.payload._id};

    Project
        .findByIdAndUpdate(req.params.id, req.body, function(err, obj) {
            if(err){
                res.status(401).json("couldnt update the project");
            } else{
                res.status(200).json(obj);
            }
        });

    /*
     if (!req.payload._id) {
     res.status(401).json({
     "message": "UnauthorizedError: cannot update project without being logged in as a user"
     });
     } else {
     // authorization needed, so not every user can change a project
     // validate user as author or collaborator,
     // otherwise shoot down request
     Project.findById(req.body._id)
     .exec(function (err, project) {
     if (err) {
     res.status(401).json({
     "message": "dbError: Error performing FindById"
     });
     } else if ( req.payload._id === project.ownerID ) {
     // Editor is owner
     Project.findByIdAndUpdate(req.payload._id, req.body, {runValidators: true, upsert: true})
     .exec(function (err, user) {
     res.status(200).json(project);
     })
     } else if ( _.includes( project.collaborators, req.payload._id )) {
     // Editor is collaborator
     Project.findByIdAndUpdate(req.payload._id, req.body, {runValidators: true, upsert: true})
     .exec(function (err, user) {
     res.status(200).json(project);
     })
     } else {
     res.status(401).json({
     "message": "UnauthorizedError: Must be owner or collaborator to edit project"
     })
     }
     });
     }*/
};

module.exports.projectDelete = function (req, res) {

    //var query = {'ownerID': req.payload._id};

    Project
        .findById(req.params.id, function(err, obj) {
            if(err){
                res.status(401).json("couldnt delete the project");
            } else{
                User.findOneAndUpdate({_id: obj.ownerID}, {$pull: {ownProjects: {projectID: obj._id}}}, function(err, data){
                    if(err){
                        console.log("something went wrong");
                    } else {
                        console.log("perfect");
                    }
                });

                for(var i = 0; i < obj.collaborators.length; i++){
                    User.findOneAndUpdate({email: obj.collaborators[i]}, {$pull: {coopProjects: {projectID: obj._id}}}, function(err, data){
                        if(err){
                            console.log("something went wrong");
                        } else {
                            console.log("nice");
                        }
                    });
                }

                var exec = require('child_process').exec;
                function puts(error, stdout, stderr) { if(error){ console.log(error)}else{console.log(stdout)} };

				/**
				 * Geht kürzer!!
				exec("cd projectData/"+obj.uniqueKey+" && rd geoTiffs", puts);
                exec("cd projectData/"+obj.uniqueKey+" && rd txtFiles", puts);
                exec("cd projectData/"+obj.uniqueKey+" && rd rScripts", puts);
                exec("cd projectData && rd "+obj.uniqueKey+"", puts);
				 * rm -r löscht rekursiv sämtliche Unterstrukturen eines Directory's, und dann den Ordner selbst!
				 */
				var projDirName = obj.uniqueKey.replace(/(\s)/g, "__");
				exec("cd projectData && rm -r " +projDirName +"", puts);

				obj.remove();
				res.status(200).json("removed the project");
                /*
                User
                    .findById(obj.ownerID, function (e, owner){
                        if(e){
                            console.log("something went wrong");
                        }else {
                            //owner.ownProjects.pull({projectName: obj.projectName, projectID: obj._id});
                            //for(var j=0; j < owner.ownProjects.length; j++){
                            //if (owner.ownProjects[j].projectID === obj._id) {
                                //delete owner.ownProjects[{projectName: obj.projectName, projectID:obj._id}];
                            //}
                        //}
                        }});
*/

                /*
                var coll = obj.collaborators;
                for(var i = 0; i < coll.length; i++){
                    User.findOne({'email': coll[i]}, function (error, collabo) {
                        if (error) {
                            console.log("something went wrong");
                        } else {
                            //collabo.coopProjects.pull({projectName: obj.projectName, projectID: obj._id});
                            //for(var m=0; m < collabo.coopProjects.length; m++){
                            //if (collabo.coopProjects[m].projectID === obj._id) {
                                //delete collabo.coopProjects[{projectName: obj.projectName, projectID:obj._id}];
                            //}}
                        }
                    });
            }
            */
        }});

    /*
     if (!req.payload._id) {
     res.status(401).json({
     "message": "UnauthorizedError: cannot delete profile without being logged in to it"
     });
     } else {
     Project.findById(req.payload._id)
     .exec(function (err, value) {
     if (err) {
     res.status(401).json({
     "message": "DeleteError: could not delete feature"
     });
     } else if ( req.payload._id === project.ownerID ) {
     console.log('feature removed (logging just for testing)');
     value.remove();
     res.status(200).send('removed Feature');
     } else {
     res.status(401).json({
     "message": "UnauthorizedError: Must be owner to delete project"
     });
     }
     });
     }*/
};

module.exports.uploadFile = function(req, res) {

    var form = new formidable.IncomingForm();

    form.multiples = false;

    // TODO: Abfrage ob Dateiendung r oder txt ist und dann Error werfen, damit kein Datenmüll hochgeladen wird

    form.uploadDir = path.join(__dirname, '../../projectData');

    console.log(path.join(__dirname, '../../projectData'));

	var projDirName = req.params.key.replace(/(\s)/g, "__");
// every time a file has been uploaded successfully,
// rename it to it's original name
    form.on('file', function (field, file) {
        if(file.type === 'text/plain'){
            fs.rename(file.path, path.join(form.uploadDir+'/'+projDirName+'/txtFiles', file.name));

            fs.readFile('projectData/' + projDirName + '/datatxt.json', function (err, jsondata) {
                if (err) throw err;
                var newData = JSON.parse(jsondata);
                newData.data.push({id: "../../projectData/" + projDirName + "/txtFiles/" + file.name , value: file.name});
                newData = JSON.stringify(newData);
                console.log(JSON.parse(newData))

                var fileName = path.join(__dirname, '../../projectData/' + projDirName + '/datatxt') + '.json';

                fs.writeFile(fileName, newData, function(err) {
                    if (err) {
                        console.error('Something when wrong when saving the temp file' + err);
                        res.send('Something when wrong when saving the temp file');
                    }
                });

            });
        }
        if(file.type === 'application/octet-stream'){
            fs.rename(file.path, path.join(form.uploadDir+'/'+projDirName+'/rScripts', file.name));

            fs.readFile('projectData/' + projDirName + '/datarScripts.json', function (err, data) {
                if (err) throw err;
                var newData = JSON.parse(data);
                newData.data.push({id: "../../projectData/" + projDirName + "/rScripts/" + file.name , value: file.name});
                newData = JSON.stringify(newData);

                var fileName = path.join(__dirname, '../../projectData/' + projDirName + '/datarScripts') + '.json';

                fs.writeFile(fileName, newData, function (err) {
                    if (err) {
                        console.error('Something when wrong when saving the temp file' + err);
                        res.send('Something when wrong when saving the temp file');
                    }
                });
            });
        }
    });

// log any errors that occur
    form.on('error', function (err) {
        console.log('An error has occured: \n' + err);
    });

// once all the files have been uploaded, send a response to the client
    form.on('end', function () {
        res.end('success');
    });

// parse the incoming request containing the form data
    form.parse(req);
};

module.exports.downloadZip = function(req, res){

    var output = fs.createWriteStream(__dirname + '/'+req.params.key+'.zip');
    var archive = archiver('zip', {
        store: false // Sets the compression method to STORE.
    });

    archive.directory('projectData/'+req.params.key+'/');

    archive.on('close', function() {
        console.log(archive.pointer() + ' total bytes');
        console.log('archiver has been finalized and the output file descriptor has closed.');
        res.status(200).send('okay').end();
    });

    res.attachment(req.params.key+'.zip');

    archive.on('error', function(err) {
        if(err) {
            res.status(400).json("could not zip the file");
        }
    });

    archive.finalize();
};<|endoftext|>


<commit_before>import _ from "lodash";
import app from "app";
import Backbone from "backbone";
import Toast from "libs/toast";
import modal from "../modal";
import View from "../../view";

class SkeletonTracingView extends View {

  constructor(model) {
    super(model);
    _.extend(this, Backbone.Events);

    this.listenTo(this.model.skeletonTracing, "emptyBranchStack", () => Toast.error("No more branchpoints", false));
    this.listenTo(this.model.skeletonTracing, "noBranchPoints", () => Toast.error("Setting branchpoints isn't necessary in this tracing mode.", false));
    this.listenTo(this.model.skeletonTracing, "wrongDirection", () => Toast.error("You're tracing in the wrong direction"));

    const autoSaveFailureMessage = "Auto-Save failed!";
    this.listenTo(this.model.skeletonTracing.stateLogger, "pushFailed", function () {
      if (this.reloadDenied) {
        Toast.error(autoSaveFailureMessage, true);
      } else {
        modal.show(
          "Several attempts to reach our server have failed. You should \
reload the page to make sure that your work won't be lost.",
          "Connection error",
          [
            {
              id: "reload-button",
              label: "OK, reload",
              callback() {
                app.router.off("beforeunload");
                app.router.reload();
              },
            },
            {
              id: "cancel-button",
              label: "Cancel",
              callback: () => { this.reloadDenied = true; },
            },
          ],
        );
      }
    });
    this.listenTo(this.model.skeletonTracing.stateLogger, "pushDone", () => Toast.delete("danger", autoSaveFailureMessage));
  }

  showFirstVisToggle() {
    modal.show("You just toggled the skeleton visibility. To toggle back, just hit the 1-Key.",
      "Skeleton visibility",
      [{ id: "ok-button", label: "OK, Got it." }],
    );
  }
}

export default SkeletonTracingView;
<commit_msg>flow type checking for skeletontracing_view.js<commit_after>/**
 * skeletontracing_view.js
 * @flow weak
 */

import _ from "lodash";
import app from "app";
import Backbone from "backbone";
import Toast from "libs/toast";
import modal from "../modal";
import View from "../../view";

class SkeletonTracingView extends View {
  // Copied from backbone events (TODO: handle this better)
  listenTo: Function;

  constructor(model) {
    super(model);
    _.extend(this, Backbone.Events);

    this.listenTo(this.model.skeletonTracing, "emptyBranchStack", () => Toast.error("No more branchpoints", false));
    this.listenTo(this.model.skeletonTracing, "noBranchPoints", () => Toast.error("Setting branchpoints isn't necessary in this tracing mode.", false));
    this.listenTo(this.model.skeletonTracing, "wrongDirection", () => Toast.error("You're tracing in the wrong direction"));

    const autoSaveFailureMessage = "Auto-Save failed!";
    this.listenTo(this.model.skeletonTracing.stateLogger, "pushFailed", function () {
      if (this.reloadDenied) {
        Toast.error(autoSaveFailureMessage, true);
      } else {
        modal.show(
          "Several attempts to reach our server have failed. You should \
reload the page to make sure that your work won't be lost.",
          "Connection error",
          [
            {
              id: "reload-button",
              label: "OK, reload",
              callback() {
                app.router.off("beforeunload");
                app.router.reload();
              },
            },
            {
              id: "cancel-button",
              label: "Cancel",
              callback: () => { this.reloadDenied = true; },
            },
          ],
        );
      }
    });
    this.listenTo(this.model.skeletonTracing.stateLogger, "pushDone", () => Toast.delete("danger", autoSaveFailureMessage));
  }

  showFirstVisToggle() {
    modal.show("You just toggled the skeleton visibility. To toggle back, just hit the 1-Key.",
      "Skeleton visibility",
      [{ id: "ok-button", label: "OK, Got it." }],
    );
  }
}

export default SkeletonTracingView;
<|endoftext|>


<commit_before>export default class GLTexture {
  constructor({
    gl,
    data = null,
    width = undefined,
    height = undefined,
    level = 0,
    internalformat = gl.RGBA,
    format = gl.RGBA,
    type = gl.UNSIGNED_BYTE,
    minFilter = gl.NEAREST_MIPMAP_LINEAR,
    magFilter = gl.LINEAR,
    wrapS = gl.REPEAT,
    wrapT = gl.REPEAT,
    generateMipmap = false
  } = {}) {
    this.gl = gl;
    this._texture = this.gl.createTexture();
    this._width = width;
    this._height = height;

    this.level = level;
    this.internalformat = internalformat;
    this.format = format;
    this.type = type;
    if(this.data || (this._width && this._height)) {
      this.data = data;
    }
    this.minFilter = minFilter;
    this.magFilter = magFilter;
    this.wrapS = wrapS;
    this.wrapT = wrapT;
  }

  generateMipmap() {
    this.gl.generateMipmap(this.gl.TEXTURE_2D);
  }

  set data(value) {
    this._data = value;
    this.bind();
    this._width = this._width || this._data.width || this._data.videoWidth;
    this._height = this._height || this._data.height || this._data.videoHeight;
    this.gl.texImage2D(this.gl.TEXTURE_2D, this.level, this.internalformat, this._width, this._height, 0, this.format, this.type, this._data);
  }

  get data() {
    return this._data;
  }

  get width() {
    return this._width;
  }

  get height() {
    return this._height;
  }

  set minFilter(value) {
    if(this._minFilter === value) {
      return;
    }
    this._minFilter = value;
    this.bind();
    this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this._minFilter);
  }

  get minFilter() {
    return this._minFilter;
  }

  set magFilter(value) {
    if(this._magFilter === value) {
      return;
    }
    this._magFilter = value;
    this.bind();
    this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this._magFilter);
  }

  get magFilter() {
    return this._magFilter;
  }

  set wrapS(value) {
    if(this._wrapS === value) {
      return;
    }
    this._wrapS = value;
    this.bind();
    this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this._wrapS);
  }

  get wrapS() {
    return this._wrapS;
  }

  set wrapT(value) {
    if(this._wrapT === value) {
      return;
    }
    this._wrapT = value;
    this.bind();
    this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this._wrapT);
  }

  get wrapT() {
    return this._wrapT;
  }

  bind({unit = 0} = {}) {
    this.gl.activeTexture(this.gl[`TEXTURE${unit}`]);
    this.gl.bindTexture(this.gl.TEXTURE_2D, this._texture);
  }

  unbind() {
    this.gl.bindTexture(this.gl.TEXTURE_2D, null);
  }
};
<commit_msg>small GLTexture fixes<commit_after>export default class GLTexture {
  constructor({
    gl,
    data = null,
    width = undefined,
    height = undefined,
    level = 0,
    internalformat = gl.RGBA,
    format = gl.RGBA,
    type = gl.UNSIGNED_BYTE,
    minFilter = gl.NEAREST_MIPMAP_LINEAR,
    magFilter = gl.LINEAR,
    wrapS = gl.REPEAT,
    wrapT = gl.REPEAT
  } = {}) {
    this.gl = gl;
    this._texture = this.gl.createTexture();
    this._width = width;
    this._height = height;

    this.level = level;
    this.internalformat = internalformat;
    this.format = format;
    this.type = type;
    this.minFilter = minFilter;
    this.magFilter = magFilter;
    this.wrapS = wrapS;
    this.wrapT = wrapT;
    if(data || (this._width && this._height)) {
      this.data = data;
    }
  }

  generateMipmap() {
    this.gl.generateMipmap(this.gl.TEXTURE_2D);
  }

  set data(value) {
    this._data = value;
    this.bind();
    const width = this._width || this._data.width || this._data.videoWidth;
    const height = this._height || this._data.height || this._data.videoHeight;
    this.gl.texImage2D(this.gl.TEXTURE_2D, this.level, this.internalformat, width, height, 0, this.format, this.type, this._data);
  }

  get data() {
    return this._data;
  }

  get width() {
    return this._width;
  }

  get height() {
    return this._height;
  }

  set minFilter(value) {
    if(this._minFilter === value) {
      return;
    }
    this._minFilter = value;
    this.bind();
    this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this._minFilter);
  }

  get minFilter() {
    return this._minFilter;
  }

  set magFilter(value) {
    if(this._magFilter === value) {
      return;
    }
    this._magFilter = value;
    this.bind();
    this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this._magFilter);
  }

  get magFilter() {
    return this._magFilter;
  }

  set wrapS(value) {
    if(this._wrapS === value) {
      return;
    }
    this._wrapS = value;
    this.bind();
    this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this._wrapS);
  }

  get wrapS() {
    return this._wrapS;
  }

  set wrapT(value) {
    if(this._wrapT === value) {
      return;
    }
    this._wrapT = value;
    this.bind();
    this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this._wrapT);
  }

  get wrapT() {
    return this._wrapT;
  }

  bind({unit = 0} = {}) {
    this.gl.activeTexture(this.gl[`TEXTURE${unit}`]);
    this.gl.bindTexture(this.gl.TEXTURE_2D, this._texture);
  }

  unbind() {
    this.gl.bindTexture(this.gl.TEXTURE_2D, null);
  }
};
<|endoftext|>


<commit_before>var Fiware = Fiware || {};

Fiware.signOut = (function($, undefined) {
  var portals = {
    cloud: {
      name:      'Cloud',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'cloud',
      path:      '/logout'
    },
    mashup: {
      name:      'Mashup',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'mashup',
      path:      '/logout'
    },
    store: {
      name:      'Store',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'store',
      path:      '/logout'
    },
    data: {
      name:      'Data',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'data',
      path:      '/user/logout'
    },
    health: {
      name:      'Health',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'fi-health',
      path:      '/logout'
    },
    account: {
      name:      'Account',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'account',
      path:      '/auth/logout'
    }
  };

  var match = window.location.hostname.match(/\.(.*)/);
  var domain = match && match[1];

  // If domain exists, we are in production environment,
  // such as account.testbed.fi-ware.org
  var productionCall = function(currentPortal) {
    portalCalls = $.map(portals, function(portal) {
      url = portal.protocol + '://' + portal.subdomain + '.' + domain + portal.path;

      return $.ajax(url, {
        type: portal.verb,
        xhrFields: { withCredentials: true },
        error: function() { console.error("Error signing out " + portal.name); }
      });
    });

    deferredCall(portalCalls);
  };

  var deferredCall = function(calls) {
    $.when.apply($, calls).then(
      // success
      finish,
      // fail
      function() {
        if (calls.length === 1) {
          finish();
        } else {
          var unfinished = $.grep(calls, function(call) {
            return call.state() === "pending";
          });

          deferredCall(unfinished);
        }
      });
  };

  var finish = function() {
    // Use window.debugSignOut to debug
    if (window.debugSignOut === undefined) {
      window.location.replace('http://' + domain);
    }
  };

  // Development environment
  var developmentCall = function(currentPortal) {
    var url = 'http://' + window.location.host + portals[currentPortal].path;

    $.ajax(url, {
      type: portals[currentPortal].verb,
      success: function() {
        window.location.replace('http://' + window.location.host);
      }
    });
  };

  var call = function(currentPortal) {
      // productionCall(currentPortal);
      developmentCall(currentPortal);
  };

  return call;

})(jQuery);
<commit_msg>XMerge branch 'master' of https://github.com/ging/horizon<commit_after>var Fiware = Fiware || {};

Fiware.signOut = (function($, undefined) {
  var portals = {
    cloud: {
      name:      'Cloud',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'cloud',
      path:      '/logout'
    },
    mashup: {
      name:      'Mashup',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'mashup',
      path:      '/logout'
    },
    store: {
      name:      'Store',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'store',
      path:      '/logout'
    },
    data: {
      name:      'Data',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'data',
      path:      '/user/logout'
    },
    health: {
      name:      'Health',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'fi-health',
      path:      '/logout'
    },
    account: {
      name:      'Account',
      verb:      'GET',
      protocol:  'https',
      subdomain: 'account',
      path:      '/auth/logout'
    }
  };

  var match = window.location.hostname.match(/\.(.*)/);
  var domain = match && match[1];

  // If domain exists, we are in production environment,
  // such as account.testbed.fi-ware.org
  var productionCall = function(currentPortal) {
    portalCalls = $.map(portals, function(portal) {
      url = portal.protocol + '://' + portal.subdomain + '.' + domain + portal.path;

      return $.ajax(url, {
        type: portal.verb,
        xhrFields: { withCredentials: true },
        error: function() { console.error("Error signing out " + portal.name); }
      });
    });

    deferredCall(portalCalls);
  };

  var deferredCall = function(calls) {
    $.when.apply($, calls).then(
      // success
      finish,
      // fail
      function() {
        if (calls.length === 1) {
          finish();
        } else {
          var unfinished = $.grep(calls, function(call) {
            return call.state() === "pending";
          });

          deferredCall(unfinished);
        }
      });
  };

  var finish = function() {
    // Use window.debugSignOut to debug
    if (window.debugSignOut === undefined) {
      window.location.replace(window.location.protocol + '//' + domain);
    }
  };

  // Development environment
  var developmentCall = function(currentPortal) {
    var url = window.location.protocol + '//' + window.location.host + portals[currentPortal].path;

    $.ajax(url, {
      type: portals[currentPortal].verb,
      success: function() {
        window.location.replace(window.location.protocol + '//' + window.location.host);
      }
    });
  };

  var call = function(currentPortal) {
      // productionCall(currentPortal);
      developmentCall(currentPortal);
  };

  return call;

})(jQuery);
<|endoftext|>