Example #1
0
 .then(() => {
   // Remove the beacon and beaconLocation for both users
   return P.props({
     removeBeaconSelf: firebase.database().ref().child(`beacons/${auth.id}`).set(null),
     removeBeaconLocationSelf: firebase.database().ref().child(`beaconLocations/${auth.id}`).set(null),
     removeBeaconOther: firebase.database().ref().child(`beacons/${otherId}`).set(null),
     removeBeaconLocationOther: firebase.database().ref().child(`beaconLocations/${otherId}`).set(null),
   })
 })
            _.each(statsData.groups, function(groupBilling) {
                var statistics = createStatisticsObject();
                aggregateGroupStats(statistics, groupBilling);

                result.push(Promise.props({
                    entity: groupService.findSingle({ id: groupBilling.groupId }),
                    statistics: statistics
                }));
            });
Example #3
0
 }).finally(function () {
   // Remove the beacons
   return P.props({
     removeBeaconFrom: db.child('beacons/' + from).set(null),
     removeBeaconLocationFrom: db.child('beaconLocations/' + from).set(null),
     removeBeaconTo: db.child('beacons/' + to).set(null),
     removeBeaconLocationTo: db.child('beaconLocations/' + to).set(null)
   });
 });
 var parsedSubs = subInfos.map(function(sub){
     var outputName = "" + sub.index + "." + sub.codec;
     var outputPath = Path.join(tmpdir, outputName);
     var output = VideoUtils.extractSubtitleAsync(videoPath, sub.index , sub.codec, outputPath);
     var lines = output.then(function(output){
       return parser.parseSubAsync(output, sub.codec);
     });
     return Promise.props({info:sub, path: output, lines: lines});
   }, {concurrency:1});
Example #5
0
fetchRelationData = function fetchRelationData(relation, options) {
    var fromOptions = _.extend({}, options, {withRelated: [relation.from.relation]}),
        props = {
            from: models[relation.from.model].findAll(fromOptions),
            to: models[relation.to.model].findAll(options)
        };

    return Promise.props(props);
};
Example #6
0
 .then(oldValues => {
   // Actually make the change in the database.
   const updatePromise = query('update_expertise', user, id, experience, interest, reason || '');
   return Promise.props({
     oldValues,
     // We need to wait for the update to resolve, but do we care about the result?
     updatePromise,
   });
 })
Example #7
0
 Action.find(req.params.id).then(function (action){ 
   console.log(action.related('responder').attributes)
   return Promise.props({
     action: action.toJSON({shallow: true}),
     feedback: action.run(),
     type: action.related('responder').get('responderType')
   });
 
 }).then(function(all) {
Example #8
0
reader.readMarkdown(listsToProcess).then(function(lists) {
  var htmlMap = _.mapValues(lists, function(markdownStr, listName) {
    var tree = converter.getTree(markdownStr);
    return converter.convertListToTable(tree).then(function(newTree) {
      return converter.toHTML(newTree);
    });
  });
  return Promise.props(htmlMap).then(writer.writeFilesAsync);
}).then(function() {
Example #9
0
 .then(function (rows) {
     return Promise.props(_.chain(rows).map(function (row) {
         row.children = (shallow) ?
             countChildren(row.marketGroupID) :
             fetchChildren(row.marketGroupID);
         row = mungeMarketGroup(row);
         return [row.marketGroupID, Promise.props(row)];
     }).object().value());
 });
Example #10
0
        .then(function(data) {
            logger.info('get video data for broadcast `%s`', data.broadcast.broadcastId);

            data.res = common.request(common.URI.videoInfo, {
                broadcastId: data.broadcast.broadcastId
            });

            return Promise.props(data);
        })
Example #11
0
 json: function(req, state) {
   switch(req.method) {
     case 'GET':
       return Promise.props({
         nodes:  this.router.get('/nodes')
       });
       break;
   }
 }
Example #12
0
function fetchSingleResult(result, options) {
	let model = this;
	const object = {};

	if (this.abstract) {
		if (!this.children[result._type]) {
			throw new Error(`Model has no child with name ${result._type}`);
		}

		model = this.children[result._type];
		object._type = result._type;
	}

	if (options.populate && !Array.isArray(options.populate)) {
		options.populate = [options.populate];
	}

	if (_.isEmpty(result)) {
		return null;
	}

	Object.keys(model.fields).forEach((key) => {
		const field = model.fields[key];

		const resultsField = field.map || key;

		/* XXX: Validate return data by field type. */
		if (field.type !== 'ref') {
			object[key] = result[resultsField];
		}
		else {
			if (!_.contains(options.populate, key)) {
				object[key] = null;
				return;
			}

			if (!field.model || !registered[field.model]) {
				throw new Error('Reference field model is not defined');
			}

			if (!result[resultsField]) {
				return;
			}

			/* Choose function to call based on whether we expect a list. */
			const findFunc = field.many ? 'find' : 'findOne';

			object[key] = registered[field.model][findFunc]({
				path: result[resultsField],
				session: options.session
			});
		}
	});

	return Promise.props(object);
};
Example #13
0
    generateDailyAggregates(dailyMsgs, dayTimestamp, auth) {
        var me = this;
        return Promise.props(
                _.mapValues(dailyMsgs, function(msgs, group) {
                    if (group[0] === 'C') {
                        return me.api.channels.info({'token': auth, 'channel': group})
                            .then(function(channelData) {
                                var msg = {
                                    'project': 'xxx',
                                    'time': '',
                                    'text': msgs.length + ' messages in #' + channelData.channel.name,
                                    'timestamp': dayTimestamp,
                                    'type': 'slack',
                                    'comment': false,
                                    'graph': {'label': channelData.channel.name + ' - ' + msgs.length, 'value': msgs.length }
                                };
                                return msg;
                            });
                    } else {
                        return me.api.users.info({'token': auth, 'user': group})
                            .then(function(userData) {
                                var msg = {
                                    'project': 'xxx',
                                    'time': '',
                                    'text': msgs.length + ' messages with ' + userData.user.name,
                                    'timestamp': dayTimestamp,
                                    'type': 'slack',
                                    'graph': {'label': userData.user.name + ' - ' + msgs.length, 'value': msgs.length },
                                    'comment': false
                                };
                                return msg;
                            });
                    }
                })
            )
            .then(function(msgs) {
                var mergedMsgs = _.map(msgs, function(msg, key) {
                    return msg;
                });
                if (me.options.pie) {
                    var pieArgs = _.map(mergedMsgs, function(msg) {
                        return msg.graph;
                    });
                    var pie = new Pie(10, pieArgs, { legend: true });

                    var msg = {
                        'raw': pie.toString(),
                        'timestamp': dayTimestamp,
                        'type': 'slack',
                    };
                    return [msg];
                } else {
                    return mergedMsgs;
                }
            });
    }
hooks.exec = function exec (hooks, scope, args, data, argNames) {
	// threads run in parallel.  if no thread is specified, we use the 'default' thread.
	var threads = {}, hdata;

	util.each(hooks, function(hook) {

		// if the thread hasn't been initallized yet...
		if (!threads[hook.thread]) threads[hook.thread] = Promise.resolve();
		// middleware data is thread-specific.
		if (!data[hook.thread]) data[hook.thread] = {};

		hdata = data[hook.thread];

						// if the option argArray is set to true, we pass it as an object so it can be mutated.
		var hookArgs =	(hook.argArray) ? [args, hdata] : 
						// if the option argMap is set to true, we map named params to an object.  
						// Unnamed params keep their numerical index.

						(hook.argMap) ? [util.argsToObj(args, argNames), hdata] : 

						//	Otherwise we make sure we're always passing a consistent number of arguments.
						//	
						//	If the function has a variable argument length, and only names the first few, 
						//	
						//	the unnnamed parameters will be unavailable in hooks unless argMap or argArray is set to true.
						(argNames.length) ? args.slice(0, argNames.length-1).concat(hdata) : [hdata];

		// add the next middleware to the thread...
		threads[hook.thread] = threads[hook.thread].then(function() { 
			var out;
			if (typeof hook.fn === 'object') {
				// if the "fn" is actually an array/hash of functions, execute them in parallel.
				var parallel = (Array.isArray(hook.fn)) ? [] : {};
				util.each(hook.fn, function(fn, i) {
					parallel[i] = (typeof fn !== 'function') ? fn : fn.apply(scope, hookArgs);
				});
				// return a combined promise the resolves when all parallel functions are completed.
				out = Promise.props(parallel);
			} else {
				// otherwise, execute this middleware.
				out = hook.fn.apply(scope, hookArgs) 
			};

			if (!hook.argMap) return out;

			// if it _was_ set to map the args, we have to merge any changes back into the arg array.
			return out.then(function(res) {
				util.objToArgs(hookArgs[0], argNames, args);
				return res;
			});
		});
	});

	// return a combined promise that resolves when all threads are finished.
	return Promise.props(threads);
};
Example #15
0
    }).then(function (models) {
      var cloud = models.environment.getCompute();

      models.images = Promise.promisify(cloud.listImages, cloud)();
      models.packages = Promise.promisify(cloud.listPackages, cloud)();

      Promise.props(models).then(function (models) {
        res.render('tier/new', models);
      });
    });
Example #16
0
exports.getClient = function($) {
  var client = new BlueprintClient({
    authorization: 'Bearer ' + $.jwt,
    docsUrl: 'https://' + $.env.XIVELY_BLUEPRINT_HOST + '/docs',
  }).ready;

  return Promise.props(_.assign({}, $, {
    client: client,
  }));
};
 .then(() => {
   return Promise.props({
     machines: Machine.find({
         user: null
       }),
     images: Image.find({
       deleted: false
     })
   });
 })
Example #18
0
function fetchDetailsFromDep(dep) {
  let infoPromise = fetchInfo(dep);
  return Promise.props({
    name: dep,
    licenses: fetchLicense(dep),
    description: infoPromise.then(info => _.get(info, 'description')),
    homepage: infoPromise.then(info => _.get(info, 'homepage')),
    author: infoPromise.then(info => _.get(info, 'author'))
  });
}
Example #19
0
 .then(function (userIds) {
     return bluebird
         .props({
             date: ts,
             count: userIds.length,
             R1: r1(date, userIds),
             R: r(date, userIds),
             purchase: purchase(date, userIds)
         });
 });
Example #20
0
 app.get('/', function(req, res) {
   Promise.props({
     'recent_games': self.dispatch('recent_games'),
     'challenges_current': self.dispatch('challenges_current'),
     'challenges_history': self.dispatch('challenges_history')
   })
   .then(function(result) {
     res.render('index.jade', result);
   });
 });
 }).then((jobIds) => {
   return Promise.props({
     jobIds,
     removeResult: q.r.db(q.db)
     .table(q.name)
     .getAll(...jobIds)
     .delete()
     .run(q.queryRunOptions)
   })
 }).then((result) => {
Example #22
0
 .then((user) => {
   return Promise.props({
     access: AccessToken.find({
       userId: user.id
     }),
     refresh: RefreshToken.find({
       userId: user.id
     })
   });
 })
 /**
  * Whenever user B installs app with user A's referral, B sends a request to let the server know
  * This method sends a notification to user A, saying that this guy has installed the app using your referral
  * @param referrerSocialId Social Id of user A
  * @param newUserSocialId Social Id of user B
  */
 static referralInstalled(/*string*/ referrerSocialId, /*string*/ newUserSocialId) {
   return Promise.props({
     referrer: UserDao.findUserWithSocialId(referrerSocialId),
     newUser: UserDao.findUserWithSocialId(newUserSocialId)
   }).then((/*{referrer, newUser}*/ users) => {
     if (!users.referrer) throw new Error(`Referrer is empty, socialId: ${referrerSocialId}`);
     if (!users.newUser) throw new Error(`newUser is empty, socialId: ${newUserSocialId}`);
     PushController.pushReferralInstalled(users.referrer._id.toString(), users.newUser.name);
   });
 }
Example #24
0
    var batch = function(req, res, next) {
        // Here we assume it the request has already been validated, either by
        // our included middleware or otherwise by the app developer.

        // We also assume it has been run through some middleware like
        // express.bodyParser() or express.json() to parse the requests

        var requests = req.body;

        // First, let's fire off all calls without any dependencies, accumulate their promises
        var requestPromises = _.reduce(requests, function(promises, r, key) {
            if (!r.dependency || r.dependency === 'none') {
                promises[key] = requestGet(r).spread(function(response, body) {
                    return body;
                });
            }
            // And while we do that, build the dependency object with those items as keys
            // { key: Promise }
            return promises;
        }, {});

        // Then recursively iterate over all items with dependencies, resolving some at each pass
        var recurseDependencies = function (requests) {
            // End state hit when the number of promises we have matches the number
            // of request objects we started with.
            if (_.size(requestPromises) >= _.size(requests)) {
                return;
            } else {
                _.each(requestPromises, function(rp, key) {
                    var dependentKey = null;
                    var dependent = _.find(requests, function(request, dKey) {
                        dependentKey = dKey;
                        return request.dependency === key && (typeof requestPromises[dKey] === 'undefined');
                    });
                    if (dependent) {
                        requestPromises[dependentKey] = rp.then(function() {
                            return requestGet(dependent);
                        }).spread(function(response, body) {
                            return response;
                        });
                    }
                });
                recurseDependencies(requests);
            }
        };

        // Recurse dependencies
        recurseDependencies(requests);

        // Wait for all to complete before responding
        Promise.props(requestPromises).then(function(result) {
            res.json(result);
            //next();
        });
    };
Example #25
0
git.status = (repoPath, file) => {
  return Bluebird.props({
    numStatsStaged: git(['diff', '--no-renames', '--numstat', '--cached', '--', (file || '')], repoPath)
      .then(gitParser.parseGitStatusNumstat),
    numStatsUnstaged: git(['diff', '--no-renames', '--numstat', '--', (file || '')], repoPath)
      .then(gitParser.parseGitStatusNumstat),
    status: git(['status', '-s', '-b', '-u', (file || '')], repoPath)
      .then(gitParser.parseGitStatus)
      .then((status) => {
        return Bluebird.props({
          isRebaseMerge: fs.isExists(path.join(repoPath, '.git', 'rebase-merge')),
          isRebaseApply: fs.isExists(path.join(repoPath, '.git', 'rebase-apply')),
          isMerge: fs.isExists(path.join(repoPath, '.git', 'MERGE_HEAD')),
          inCherry: fs.isExists(path.join(repoPath, '.git', 'CHERRY_PICK_HEAD'))
        }).then((result) => {
          status.inRebase = result.isRebaseMerge || result.isRebaseApply;
          status.inMerge = result.isMerge;
          status.inCherry = result.inCherry;
        }).then(() => {
          if (status.inMerge || status.inCherry) {
            return fs.readFileAsync(path.join(repoPath, '.git', 'MERGE_MSG'), { encoding: 'utf8' })
              .then((commitMessage) => {
                status.commitMessage = commitMessage;
                return status;
              }).catch(err => {
                // 'MERGE_MSG' file is gone away, which means we are no longer in merge state
                // and state changed while this call is being made.
                status.inMerge = status.inCherry = false;
                return status;
              });
          }
          return status;
        });
      })
  }).then((result) => {
    const numstats = [result.numStatsStaged, result.numStatsUnstaged].reduce(_.extend, {});
    const status = result.status;
    status.inConflict = false;

    // merge numstats
    Object.keys(status.files).forEach((filename) => {
      // git diff returns paths relative to git repo but git status does not
      const absoluteFilename = filename.replace(/\.\.\//g, '');
      const stats = numstats[absoluteFilename] || { additions: '-', deletions: '-' };
      const fileObj = status.files[filename];
      fileObj.additions = stats.additions;
      fileObj.deletions = stats.deletions;
      if (!status.inConflict && fileObj.conflict) {
        status.inConflict = true;
      }
    });

    return status;
  });
}
Example #26
0
  router.delete('/:personas_id', function (req, res) {
    Promise.props({
      personas: CfPersonas.findOne({ _id: req.param('personas_id') }).exec()
    }).then(function (models) {
      models.personas.remove();

      req.flash('success', 'cfEngine personas "%s" has been deleted', models.personas.name);

      res.redirect('/cf/personas');
    });
  });
Example #27
0
        it('should pipe all data to both streams', function(done) {
          rindle.bifurcate(this.stream, this.output1, this.output2);

          Promise.props({
            one: rindle.extract(this.output1),
            two: rindle.extract(this.output2)
          }).then(function(data) {
            m.chai.expect(data.one).to.equal('Hello World');
            m.chai.expect(data.two).to.equal('Hello World');
          }).nodeify(done);
        });
Example #28
0
  router.delete('/:stingray_id', function (req, res) {
    Promise.props({
      stingray: Stingray.findOne({ _id: req.param('stingray_id') }).exec()
    }).then(function (models) {
      models.stingray.remove();

      req.flash('success', 'Stingray "%s" has been deleted', models.stingray.name);

      res.redirect('/stingray');
    });
  });
const updateFirstTransaction = (transaction, subscription, paypalTransaction) => {
  const updateTransaction = () => {
    transaction.data = paypalTransaction;
    return transaction.save();
  };

  return Bluebird.props({ // for testing
    transaction: updateTransaction(),
    subscription: subscription.activate()
  });
};
Example #30
0
function setRepresentationName(representation, diff, done){
  return P.props({
    document: documentsService.retrieve({_id:representation.document}),
    assessment: assessmentsService.retrieveLean({_id: representation.assessment})
  })
    .then((values)=>{
      representation.name = values.assessment.name + " - " + values.document.name;
      return representation;
    })
    .asCallback(done);
}