Example #1
0
            .then(function () {
                function fetchCollection() {
                    if (roleInstance) {
                        userCollection
                            .query('join', 'roles_users', 'roles_users.user_id', '=', 'users.id')
                            .query('where', 'roles_users.role_id', '=', roleInstance.id);
                    }

                    return userCollection
                        .query('orderBy', 'last_login', 'DESC')
                        .query('orderBy', 'name', 'ASC')
                        .query('orderBy', 'created_at', 'DESC')
                        .fetch(_.omit(options, 'page', 'limit'));
                }

                function fetchPaginationData() {
                    var qb,
                        tableName = _.result(userCollection, 'tableName'),
                        idAttribute = _.result(userCollection, 'idAttribute');

                    // After we're done, we need to figure out what
                    // the limits are for the pagination values.
                    qb = ghostBookshelf.knex(tableName);

                    if (options.where) {
                        qb.where(options.where);
                    }

                    if (roleInstance) {
                        qb.join('roles_users', 'roles_users.user_id', '=', 'users.id');
                        qb.where('roles_users.role_id', '=', roleInstance.id);
                    }

                    return qb.count(tableName + '.' + idAttribute + ' as aggregate');
                }

                return Promise.join(fetchCollection(), fetchPaginationData());
            })
Example #2
0
 const items = yield children.map(item => {
     if (source.isPage(item)) {
         const nameMatch = `${item.name}.`;
         const configFile = _.find(configs, f => f.name.startsWith(nameMatch));
         const contents = item.read();
         const props = data.getConfig(configFile, {
             name:     item.name,
             isHidden: item.isHidden,
             order:    item.order,
             lang:     item.lang,
             filePath: item.path,
             file:     item
         });
         return Promise.join(props, contents, function (props, contents) {
             props.parent = collection;
             props.source = source;
             return Page.create(props, contents);
         });
     } else if (item.isDirectory) {
         return build(item, collection);
     }
     return Promise.resolve(null);
 });
    it('should unsubscribe a subscription correctly', function() {
      var count = 0;
      var onSubscribeCount = 0;
      var d = defer();

      var subscribe = this.client.subscribe('/datetime', function() {
        count++;
        if (count === 2) {
          d.resolve();
        }
      }, null, function() {
        onSubscribeCount++;
      });

      return Promise.join(subscribe, d.promise, function(subscription) {
          return subscription.unsubscribe();
        })
        .bind(this)
        .then(function() {
          assert.strictEqual(onSubscribeCount, 1);
          assert.deepEqual(this.client.listChannels(), []);
        });
    });
router.post('/:id/restaurants', function(req, res, next) {
  var dayId = req.params.id;
  var restaurantId = req.body.restaurantId;

  Promise.join(Day.findOne({
    where:{
      number : dayId,
    }
  }),
  Restaurant.findOne({
    where:{
      id : restaurantId,
    }
  })
  ).spread(function(day, restaurant){
    return day.addRestaurant(restaurant);

  })
  .then(function(){
    res.sendStatus(200);
  })
  .catch(next);
});
Example #5
0
 .spread((privateKey, publicKey) => {
   if (privateKey && publicKey) {
     config.set('private_key', privateKey)
     config.set('public_key', publicKey)
     if (environment === 'production') {
       console.log('RSA key pair loaded')
       console.log(config.get('public_key'))
     }
   } else {
     let keypair = require('keypair')
     let pair = keypair({bits: 1024})
     config.set('private_key', pair.private)
     config.set('public_key', pair.public)
     if (environment === 'production') {
       console.log('RSA key pair generated')
       console.log(config.get('public_key'))
     }
     return Promise.join(
       redis.client.setAsync(`${environment}:id_rsa`, pair.private),
       redis.client.setAsync(`${environment}:id_rsa.pub`, pair.public)
     )
   }
 })
  onBeforeShow: function() {
    var that = this,
        collectionManager = new CollectionManager();

    Promise.join(collectionManager.getDiscussionModelPromise(),
        collectionManager.getNotificationsDiscussionCollectionPromise(),
            function(Discussion, NotificationsDiscussion) {

              var defaultNotif = new defaultNotification({
                model: Discussion
              });
              that.getRegion('autoSubscribe').show(defaultNotif);

              var notif = new notificationList({
                collection: NotificationsDiscussion
              });
              that.getRegion('notification').show(notif);

            });
    
    var menu = new AdminNavigationMenu({selectedSection: "notifications"});
    this.getRegion('navigationMenuHolder').show(menu);
  },
 beforeEach(() => {
   req = {
     session: {},
     params: {},
     param: function(key) {
       return this.params[key];
     }
   };
   res = {
     locals: {},
     ok: spy(function(data) {
       res.body = data;
     })
   };
   community = new Community({name: 'foo', slug: 'foo', beta_access_code: 'sekrit'});
   user = new User();
   return Promise.join(user.save(), community.save())
   .then(() => user.joinCommunity(community))
   .then(() => {
     req.params.communityId = community.id;
     req.session.userId = user.id;
   });
 });
    return files.map(function (file, index) {
      var info = Promise.resolve({
        task: index,
        index: file.index,
        name: file.name,
        stamp: file.stamp
      })

      var stat = fs.statAsync(path.join(principle, file.name))

      var contents = fs.readFileAsync(path.join(principle, file.name))

      return Promise.join(info, stat, contents, function (info, stat, contents) {
        return {
          task: info.task,
          index: info.index,
          name: info.name,
          stamp: info.stamp,
          size: stat.size,
          length: contents.length
        }
      })
    })
Example #9
0
 .then(contract => (
   Promise.join(
     contract.call('name'),
     contract.call('decimals'),
     contract.call('symbol'),
     contract.call('balanceOf', [hett.web3h.coinbase()]),
     contract.call('totalSupply'),
     (name, decimalsR, symbol, balance, totalSupply) => {
       const decimalsFormat = _.toNumber(decimalsR)
       let decimals = decimalsFormat
       if (decimals > 0) {
         decimals = Math.pow(10, decimals)
       } else {
         decimals = 1
       }
       return {
         name,
         balance: (_.toNumber(balance) / decimals).toFixed(decimalsFormat) + ' ' + symbol,
         totalSupply: (_.toNumber(totalSupply) / decimals).toFixed(decimalsFormat) + ' ' + symbol
       }
     }
   )
 ))
Example #10
0
            .then(function then(results) {
                const adminRole = results[0];
                const user = results[1];

                if (!user) {
                    return Promise.reject(new common.errors.NotFoundError({
                        message: common.i18n.t('errors.models.user.userNotFound')
                    }));
                }

                const currentRoles = user.toJSON(options).roles;

                if (!_.some(currentRoles, {id: adminRole.id})) {
                    return Promise.reject(new common.errors.ValidationError({
                        message: common.i18n.t('errors.models.user.onlyAdmCanBeAssignedOwnerRole')
                    }));
                }

                // convert owner to admin
                return Promise.join(contextUser.roles().updatePivot({role_id: adminRole.id}),
                    user.roles().updatePivot({role_id: ownerRole.id}),
                    user.id);
            })
 .then(function(body) {
     if (!_.isUndefined(query.page)) {
         self.body = {
             list: body.dishes.map(_dishMapper)
         };
         return self.body;
     } else {
         self.body = {
             count: body.stats.count,
             list: body.dishes.map(_dishMapper)
         };
         return Bluebird.join(
             getExtremes.call(self, query, 'date'),
             getExtremes.call(self, query, 'date', true),
             getExtremes.call(self, query, 'popularity'),
             function(oldest, newest, popular) {
                 self.body.oldest = _dishMapper(oldest.dishes[0]);
                 self.body.newest = _dishMapper(newest.dishes[0]);
                 self.body.mostPopular = _dishMapper(popular.dishes[0]);
                 return self.body;
             });
     }
 });
	bot.onText(/^\/stats(?:@\w*)?/i, function(msg) {
		console.log('Getting stats for user: '******'*STATS FOR ' + user.displayName + ' OVER LAST 25 GAMES*\n';
			for (var property in results) {
				response += property + ': ' + results[property].displayValue;
				if (results[property].match) {
					response += ' ([' + results[property].match + '](http://dotabuff.com/matches/' +
						results[property].match + '))';
				}
				response += '\n';
			}
			return bot.sendMessage(msg.chat.id, response, { parse_mode: 'Markdown'});
		})
		.catch(err => {
			console.error('an error occurred getting stats: ', err);
			return bot.sendMessage(msg.chat.id, 'An error occurred');
		});
	});
Example #13
0
                  .then(function () {
                    human.team = 'zombie';

                    humanIdObj.active = false;

                    zombie.humansTagged++;

                    Promise.join(
                      human.save(),
                      humanIdObj.save(),
                      zombie.save(),
                      function() {
                        sails.log.info(zombie.email + " infected " + human.email);

                        res.ok({
                          human: human.getPublicData(),
                          zombie: zombie.getPublicData()
                        });
                      }
                    ).catch(function (err) {
                      res.negotiate(err);
                    });
                  }, function (err) {
Example #14
0
  getExtractslist: function() {
    var that = this,
        collectionManager = new CollectionManager();

    if (this.extractListSubset) {
      Promise.join(collectionManager.getAllExtractsCollectionPromise(),
                  collectionManager.getAllUsersCollectionPromise(),
                  collectionManager.getAllMessageStructureCollectionPromise(),
                function(allExtractsCollection, allUsersCollection, allMessagesCollection) {

                  that.extractListView = new SegmentList.SegmentListView({
                    collection: that.extractListSubset,
                    allUsersCollection: allUsersCollection,
                    allMessagesCollection: allMessagesCollection
                  });

                  that.getRegion('segmentList').show(that.extractListView);
                  that.renderTemplateGetExtractsLabel();
                });
    } else {
      this.renderTemplateGetExtractsLabel();
    }
  },
router.post('/:id/activities', function(req, res, next) {
 var dayId = req.params.id;
 var activityId = req.body.activityId;

  Promise.join(Day.findOne({
    where:{
      number : dayId,
    }
  }),
  Activity.findOne({
    where:{
      id : activityId,
    }
  })
  ).spread(function(day, activity){
    return day.addActivity(activity);

  })
  .then(function(){
    res.sendStatus(200);
  })
  .catch(next);
});
Example #16
0
  handler: function(request, reply) {
    var opts = {
      userId: request.auth.credentials.id,
      priority: request.pre.priority,
      limit: request.query.limit,
      page: request.query.page
    };

    var getThreads = request.db.threads.posted(opts);
    var getCount = request.db.threads.postedCount(opts);

    var promise = Promise.join(getThreads, getCount, function(threads, count) {
      return {
        threads: threads,
        page: request.query.page,
        limit: request.query.limit,
        count: count
      };
    })
    .error(request.errorMap.toHttpError);

    return reply(promise);
  }
Example #17
0
            .spread(function(manager, user, otherUser) {
                self.manager = manager;
                self.user = user;
                self.otherUser = otherUser;

                return Promise.join(
                    Ticket.create(
                        "The Ticket",
                        "Will get notifications",
                        self.user
                    ),
                    Ticket.create(
                        "An other ticket",
                        "This is other ticket without any notifications for the user",
                        self.otherUser
                    ),
                    Ticket.create(
                        "Yet another ticket",
                        "This is an yet another ticket",
                        self.otherUser
                    )
                );
            })
Example #18
0
      utils.newQueue().then(function(queue){
        var resultPromise = new Promise(function (resolve) {
          queue.process(function (job, jobDone) {
            expect(ispaused).to.be(false);
            expect(job.data.foo).to.be.equal('paused');
            jobDone();
            counter--;
            if(counter === 0) {
              resolve(queue.close());
            }
          });
        });

        return Promise.join(queue.pause().then(function () {
          ispaused = true;
          return queue.add({ foo: 'paused' });
        }).then(function () {
          return queue.add({ foo: 'paused' });
        }).then(function () {
          ispaused = false;
          queue.resume();
        }), resultPromise);
      });
Example #19
0
confirmtest('multiple confirms', function(ch) {
  var q = 'test.multiple-confirms';
  return Promise.join(
    ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q))
    .then(function() {
      var multipleRainbows = false;
      ch.on('ack', function(a) {
        if (a.multiple) multipleRainbows = true;
      });

      function prod(num) {
        var cs = [];

        function sendAndPushPromise() {
          var conf = Promise.fromCallback(function(cb) {
            return ch.sendToQueue(q, Buffer.from('bleep'), {}, cb);
          });
          cs.push(conf);
        }

        for (var i=0; i < num; i++) sendAndPushPromise();

        return Promise.all(cs).then(function() {
          if (multipleRainbows) return true;
          else if (num > 500) throw new Error(
            "Couldn't provoke the server" +
              " into multi-acking with " + num +
              " messages; giving up");
          else {
            //console.warn("Failed with " + num + "; trying " + num * 2);
            return prod(num * 2);
          }
        });
      }
      return prod(5);
    });
});
Example #20
0
function save (dir, pkginfo, opts, cb) {
  // copy the keys over in a well defined order
  // because javascript objects serialize arbitrarily
  BB.join(
    checkPackageFile(dir, SHRINKWRAP),
    checkPackageFile(dir, PKGLOCK),
    checkPackageFile(dir, 'package.json'),
    (shrinkwrap, lockfile, pkg) => {
      const info = (
        shrinkwrap ||
        lockfile ||
        {
          path: path.resolve(dir, opts.defaultFile || PKGLOCK),
          data: '{}',
          indent: (pkg && pkg.indent) || 2
        }
      )
      const updated = updateLockfileMetadata(pkginfo, pkg && JSON.parse(pkg.raw))
      const swdata = JSON.stringify(updated, null, info.indent) + '\n'
      if (swdata === info.raw) {
        // skip writing if file is identical
        log.verbose('shrinkwrap', `skipping write for ${path.basename(info.path)} because there were no changes.`)
        cb(null, pkginfo)
      } else {
        writeFileAtomic(info.path, swdata, (err) => {
          if (err) return cb(err)
          if (opts.silent) return cb(null, pkginfo)
          if (!shrinkwrap && !lockfile) {
            log.notice('', `created a lockfile as ${path.basename(info.path)}. You should commit this file.`)
          }
          cb(null, pkginfo)
        })
      }
    }
  ).then((file) => {
  }, cb)
}
  lab.test('Get subscribers valid', function(done) {
    var userPromise1 = Service.createNewUser(bob);
    var userPromise2 = Service.createNewUser(alice);
    var userPromise3 = Service.createNewUser(carlos);

    // First subscription
    Promise.join(userPromise1, userPromise2, userPromise3,
      function(user1, user2, user3) {
        testAccount.userId = user1.userId;
        Router.inject({method: 'POST',
                        url: '/api/subscriptions/' + user2.userId,
                        credentials: testAccount}, (res) => {
          subscribePromise(user2, user3);
        });
      });

    // Second subscription
    function subscribePromise(user2, user3) {
      testAccount.userId = user3.userId;
      Router.inject({method: 'POST',
                     url: '/api/subscriptions/' + user2.userId,
                     credentials: testAccount}, (res) => {
        querySubscribers(user2);
      });
    }

    function querySubscribers(user2) {
      Router.inject({method: 'GET',
                     url: '/api/subscriptions/subscribers/' + user2.userId,
                     credentials: testAccount}, function(res) {
        Code.expect(res.result).to.have.length(2);
        Code.expect(res.result[0].username).to.equal(bob.username);
        Code.expect(res.result[1].username).to.equal(carlos.username);
        done();
      });
    }
  });
Example #22
0
module.exports = function (req, res) {
    var query_meta = {user_id: req.user._id, _id: req.params.ObjectID},
        query_items = {user_id: req.user._id, meta_id: req.params.ObjectID},
        n_unread_promise, posts_promise;

    n_unread_promise = db.posts.call('aggregateAsync', [
        {$match: {user_id: req.user._id, meta_id: req.params.ObjectID, read: {$ne: true}}},
        {$group: {_id: '$meta_id', unread: {$sum: 1}}}
    ]);

    if (req.query.older_than) {
        query_items.pubdate = {$lt: req.query.older_than};
    }
    if (req.query.N===0) {
        posts_promise = Promise.resolve([]);
    } else {
        posts_promise = db.posts.find(query_items).sort({pubdate: -1});
        if (req.query.N) {
            posts_promise = posts_promise.limit(req.query.N);
        }
        posts_promise = posts_promise.toArrayAsync().reduce(util.reducer.bind(null, util.cleanItem), []);
    }
    Promise.join(
        db.feeds.findOneAsync(query_meta).then(util.cleanMeta),
        posts_promise,
        n_unread_promise,
        function (meta, items, n_unread) {
            if (n_unread[0]) {
                meta.unread = n_unread[0].unread;
            } else {
                meta.unread = 0;
            }
            res.status(200)
            .json({meta: [meta], items: items});
        }
    );
};
Example #23
0
    it('should process delayed jobs in correct order even in case of restart', function(done){
      var QUEUE_NAME = 'delayed queue multiple';
      var order = 1;

      queue = new Queue(QUEUE_NAME);

      var fn = function(job, jobDone){
        expect(order).to.be.equal(job.data.order);
        jobDone();

        if(order === 4 ){
          done();
        }

        order++;
      };

      Promise.join(
        queue.add({order: 2}, {delay: 300}),
        queue.add({order: 4}, {delay: 500}),
        queue.add({order: 1}, {delay: 200}),
        queue.add({order: 3}, {delay: 400})).then(function(){

          //
          // Start processing so that jobs get into the delay set.
          //
          queue.process(fn);
        }).delay(20).then(function(){
          //We simulate a restart
          return queue.close().then(function() {
            return Promise.delay(100).then(function() {
              queue = new Queue(QUEUE_NAME);
              queue.process(fn);
            });
          });
        });
    });
  findWithMatch: function(id) {
    var getMatchRequest = MatchRequest.findOne({ uuid: id });
    var getResults = Result.find();
    var addAttribute = function(attr, src, dest) {
      var properties = {};

      if (src) {
        properties[attr] = { value: src[attr] };
        return Object.create(dest, properties);
      } else {
        return dest;
      }
    };

    return Promise.join(getMatchRequest, getResults)
      .spread(function(matchRequest, foundResults) {
        this.matchRequest = matchRequest;
        return []
          .concat(foundResults)
          .map(function(r) { return r.matchId });
      })
      .then(function(finishedMatchIds) {
        if (finishedMatchIds.length) {
          return Participant.findOne({
            matchRequestUuid: id,
            matchId: { '!': finishedMatchIds }
          });
        } else if (this.matchRequest) {
          return Participant.findOne({
            matchRequestUuid: id
          });
        }
      })
      .then(function(participant) {
        return addAttribute('matchId', participant, this.matchRequest);
      });
  },
Example #25
0
PageController.prototype._enterCompanyDetail = P.method(function(entity, vacancies, upgrade)
{
        var doc = this.context.document;
        doc.editButtonEnabled = entity.editableByCurrentUser;
        this._companyEntity = entity;

        if (upgrade)
        {

        }
        else
        {
                doc.title = entity.name + ' :: DealPort.co';

                this.pageView = new CompanyDetailPage(
                        doc.document,
                        this.context.urlStateMap,
                        entity,
                        vacancies
                );

                doc.appendChild(this.pageView);
        }

        this.child = new CompanyDetailPageController(
                this.context,
                this.pageView,
                entity
        );

        this.pageView.on('domv-add-vacancy', this._companyDetailOnAddVacancy, false, this);

        return P.join(
                this._watchEntityNameChangeInState('company', entity._id),
                this.pageView.attachEditingContexts(this._contextManager)
        );
});
Example #26
0
function saveFightInMentionedInboxes(message, author, room) {
	if (!message || !author || !room) return;

	// Check if this message mentions anyone
	// Completely async process that shouldn't disrupt the normal message flow
	return Promise.join(
		RoomMember.find({room: message.room}).populate('user')
	)
		.spread(function (roomMembers) {
			return Promise.each(roomMembers, function (roomMember) {
				var regex = new RegExp(roomMember.user.nick + '\\b|@[Aa]ll', 'i');
				if (regex.test(message.text)) {
					return InboxMessage.create({user: roomMember.user.id, message: message.id})
						.then(function (inboxMessage) {
							return InboxMessage.findOne(inboxMessage.id).populateAll();
						})
						.then(function (inboxMessage) {
							inboxMessage.message.author = author; // Attach populated author data
							InboxMessage.message(roomMember.user.id, inboxMessage);
						});
				}
			});
		});
}
Example #27
0
  lab.test('Get streams from subscriptions valid', function(done) {
    var userPromise1 = Service.createNewUser(bob);
    var userPromise2 = Service.createNewUser(alice);

    Promise.join(userPromise1, userPromise2,
      function(bob, alice) {
        return Service.createSubscription(bob.userId, alice.userId)
        .then((subscription) => {
          return Service.createNewStream(alice.userId, testStream);
        }).then((stream) => {
          return Service.createNewStream(alice.userId, testStream2);
        }).then((stream) => {
          return Service.getStreamsFromSubscriptions(bob.userId);
        }).then((res) => {
          Code.expect(res[0].title).to.be.equal(testStream2.title);
          Code.expect(res[0].streamer.username).to.be.equal(alice.username);
          Code.expect(res[0].streamer.isSubscribed).to.be.true();
          Code.expect(res[1].title).to.be.equal(testStream.title);
          Code.expect(res[1].streamer.username).to.be.equal(alice.username);
          Code.expect(res[1].streamer.isSubscribed).to.be.true();
          done();
        });
      });
  });
Example #28
0
PSP.saveParsoidResult = function(hyper, req, format, tid, parsoidResp) {
    var self = this;
    var rp = req.params;
    return P.join(
        hyper.put({
            uri: self.getBucketURI(rp, 'data-parsoid', tid),
            headers: parsoidResp.body['data-parsoid'].headers,
            body: parsoidResp.body['data-parsoid'].body
        }),
        hyper.put({
            uri: self.getBucketURI(rp, 'section.offsets', tid),
            headers: { 'content-type': 'application/json' },
            body: parsoidResp.body['data-parsoid'].body.sectionOffsets
        })
    )
    // Save HTML last, so that any error in metadata storage suppresses HTML.
    .then(function() {
        return hyper.put({
            uri: self.getBucketURI(rp, 'html', tid),
            headers: parsoidResp.body.html.headers,
            body: parsoidResp.body.html.body
        });
    });
};
Example #29
0
    return function (req, res, next) {
        var smsNotifKey = 'SMS:NOTIF:' + req.uid + ':' + req.houseshareKey;
        var emailNotifKey = 'EMAIL:NOTIF:' + req.uid + ':' + req.houseshareKey;
        Promise.join(redisClient.hmsetAsync(smsNotifKey, ['uid', req.uid,
                'houseshareKey', req.houseshareKey,
                'addToGroup', true,
                'addBill', true,
                'editBill', true,
                'commentOnBill', true,
                'dueBills', true,
                'monthlySummary', true,
                'otherNotifications', true,
                'lastmodified', moment().format('YYYY-MM-DD')
            ]),

            redisClient.hmsetAsync(emailNotifKey, ['uid', req.uid,
                'houseshareKey', req.houseshareKey,
                'addToGroup', true,
                'addBill', true,
                'editBill', true,
                'commentOnBill', true,
                'dueBills', true,
                'monthlySummary', true,
                'otherNotifications', true,
                'lastmodified', moment().format('YYYY-MM-DD')
            ]),
            function (smsTransactionStatus, emailTransactionStatus) {
                if (smsTransactionStatus && emailTransactionStatus) {
                    next();
                } else {
                    next('Internal Server error');
                }
            }).catch(function (err) {
            next(err);
        });
    };
Example #30
0
            .then(function () {
                return Promise.join(prepareUriObj(opts), prepareBody(opts), function (uriObj, body) {
                    if (self.virtual && !self.scenario) {
                        let err = new Error('No virtual ' + virtual + ' scenario found for ' + method + ':' + uri);
                        if (_eventHandlers && _eventHandlers.error) {
                            opts.error = err;
                            _eventHandlers.error(opts);
                        }
                        throw err;
                    }

                    opts.uri = uriObj.uri;
                    opts.qs = uriObj.qs;
                    opts.preparedBody = body;
                    opts.virtual = virtual;
                    if (_eventHandlers && _eventHandlers.send) {
                        _eventHandlers.send(opts);
                    }

                    return self.scenario
                        ? self._sendVirtual(opts)
                        : self._sendReal(opts);
                });
            });