Example #1
0
topicsController.get = function(req, res, next) {
	var tid = req.params.topic_id,
		sort = req.query.sort,
		userPrivileges;

	if (req.params.post_index && !utils.isNumber(req.params.post_index)) {
		return helpers.notFound(req, res);
	}

	async.waterfall([
		function (next) {
			async.parallel({
				privileges: function(next) {
					privileges.topics.get(tid, req.uid, next);
				},
				settings: function(next) {
					user.getSettings(req.uid, next);
				},
				topic: function(next) {
					topics.getTopicFields(tid, ['slug', 'postcount', 'deleted'], next);
				}
			}, next);
		},
		function (results, next) {
			userPrivileges = results.privileges;

			if (!userPrivileges.read || (parseInt(results.topic.deleted, 10) && !userPrivileges.view_deleted)) {
				return helpers.notAllowed(req, res);
			}

			if ((!req.params.slug || results.topic.slug !== tid + '/' + req.params.slug) && (results.topic.slug && results.topic.slug !== tid + '/')) {
				return helpers.redirect(res, '/topic/' + encodeURI(results.topic.slug));
			}

			var settings = results.settings;
			var postCount = parseInt(results.topic.postcount, 10);
			var pageCount = Math.max(1, Math.ceil((postCount - 1) / settings.postsPerPage));
			var page = parseInt(req.query.page, 10) || 1;

			if (utils.isNumber(req.params.post_index) && (req.params.post_index < 1 || req.params.post_index > postCount)) {
				return helpers.redirect(res, '/topic/' + req.params.topic_id + '/' + req.params.slug + (req.params.post_index > postCount ? '/' + postCount : ''));
			}

			if (settings.usePagination && (page < 1 || page > pageCount)) {
				return helpers.notFound(req, res);
			}

			var set = 'tid:' + tid + ':posts',
				reverse = false;

			// `sort` qs has priority over user setting
			if (sort === 'oldest_to_newest') {
				reverse = false;
			} else if (sort === 'newest_to_oldest') {
				reverse = true;
			} else if (sort === 'most_votes') {
				reverse = true;
				set = 'tid:' + tid + ':posts:votes';
			} else if (settings.topicPostSort === 'newest_to_oldest') {
				reverse = true;
			} else if (settings.topicPostSort === 'most_votes') {
				reverse = true;
				set = 'tid:' + tid + ':posts:votes';
			}

			var postIndex = 0;

			req.params.post_index = parseInt(req.params.post_index, 10) || 0;
			if (reverse && req.params.post_index === 1) {
				req.params.post_index = 0;
			}
			if (!settings.usePagination) {
				if (reverse) {
					postIndex = Math.max(0, postCount - (req.params.post_index || postCount) - (settings.postsPerPage / 2));
				} else {
					postIndex = Math.max(0, (req.params.post_index || 1) - (settings.postsPerPage / 2));
				}
			} else if (!req.query.page) {
				var index = 0;
				if (reverse) {
					index = Math.max(0, postCount - (req.params.post_index || postCount));
				} else {
					index = Math.max(0, req.params.post_index - 1) || 0;
				}

				page = Math.max(1, Math.ceil(index / settings.postsPerPage));
			}

			var start = (page - 1) * settings.postsPerPage + postIndex,
				stop = start + settings.postsPerPage - 1;

			topics.getTopicWithPosts(tid, set, req.uid, start, stop, reverse, function (err, topicData) {
				if (err && err.message === '[[error:no-topic]]' && !topicData) {
					return helpers.notFound(req, res);
				}

				if (err && !topicData) {
					return next(err);
				}

				topicData.pageCount = pageCount;
				topicData.currentPage = page;

				if (page > 1) {
					topicData.posts.splice(0, 1);
				}

				plugins.fireHook('filter:controllers.topic.get', topicData, next);
			});
		},
		function (topicData, next) {
			var breadcrumbs = [
				{
					text: topicData.category.name,
					url: nconf.get('relative_path') + '/category/' + topicData.category.slug
				},
				{
					text: topicData.title,
					url: nconf.get('relative_path') + '/topic/' + topicData.slug
				}
			];

			helpers.buildCategoryBreadcrumbs(topicData.category.parentCid, function(err, crumbs) {
				if (err) {
					return next(err);
				}
				topicData.breadcrumbs = crumbs.concat(breadcrumbs);
				next(null, topicData);
			});
		},
		function (topicData, next) {
			var description = '';

			if (topicData.posts[0] && topicData.posts[0].content) {
				description = S(topicData.posts[0].content).stripTags().decodeHTMLEntities().s;
			}

			if (description.length > 255) {
				description = description.substr(0, 255) + '...';
			}

			description = validator.escape(description);
			description = description.replace(/&apos;/g, '&#x27;');

			var ogImageUrl = '';
			if (topicData.thumb) {
				ogImageUrl = topicData.thumb;
			} else if(topicData.posts.length && topicData.posts[0] && topicData.posts[0].user && topicData.posts[0].user.picture){
				ogImageUrl = topicData.posts[0].user.picture;
			} else if(meta.config['brand:logo']) {
				ogImageUrl = meta.config['brand:logo'];
			} else {
				ogImageUrl = '/logo.png';
			}

			if (ogImageUrl.indexOf('http') === -1) {
				ogImageUrl = nconf.get('url') + ogImageUrl;
			}

			description = description.replace(/\n/g, ' ');

			res.locals.metaTags = [
				{
					name: "title",
					content: topicData.title
				},
				{
					name: "description",
					content: description
				},
				{
					property: 'og:title',
					content: topicData.title.replace(/&amp;/g, '&')
				},
				{
					property: 'og:description',
					content: description
				},
				{
					property: "og:type",
					content: 'article'
				},
				{
					property: "og:url",
					content: nconf.get('url') + '/topic/' + topicData.slug
				},
				{
					property: 'og:image',
					content: ogImageUrl
				},
				{
					property: "og:image:url",
					content: ogImageUrl
				},
				{
					property: "article:published_time",
					content: utils.toISOString(topicData.timestamp)
				},
				{
					property: 'article:modified_time',
					content: utils.toISOString(topicData.lastposttime)
				},
				{
					property: 'article:section',
					content: topicData.category ? topicData.category.name : ''
				}
			];

			res.locals.linkTags = [
				{
					rel: 'alternate',
					type: 'application/rss+xml',
					href: nconf.get('url') + '/topic/' + tid + '.rss'
				},
				{
					rel: 'canonical',
					href: nconf.get('url') + '/topic/' + topicData.slug
				}
			];

			if (topicData.category) {
				res.locals.linkTags.push({
					rel: 'up',
					href: nconf.get('url') + '/category/' + topicData.category.slug
				});
			}

			next(null, topicData);
		}
	], function (err, data) {
		if (err) {
			return next(err);
		}

		data.privileges = userPrivileges;
		data['reputation:disabled'] = parseInt(meta.config['reputation:disabled'], 10) === 1;
		data['downvote:disabled'] = parseInt(meta.config['downvote:disabled'], 10) === 1;
		data['feeds:disableRSS'] = parseInt(meta.config['feeds:disableRSS'], 10) === 1;
		data.rssFeedUrl = nconf.get('relative_path') + '/topic/' + data.tid + '.rss';
		data.pagination = pagination.create(data.currentPage, data.pageCount);
		data.pagination.rel.forEach(function(rel) {
			res.locals.linkTags.push(rel);
		});

		topics.increaseViewCount(tid);

		plugins.fireHook('filter:topic.build', {req: req, res: res, templateData: data}, function(err, data) {
			if (err) {
				return next(err);
			}
			res.render('topic', data.templateData);
		});
	});
};
Example #2
0
extend.console.register('server', 'Run server', function(args){
  var app = express(),
    //admin = args.a || args.admin ? true : false,
    admin = false,
    statics = args.s || args.static ? true : false,
    log = args.l || args.log,
    port = args.p || args.port || config.port,
    generate = require('../../generate');

  app.set('views', hexo.core_dir + 'views');
  app.set('view engine', 'ejs');
  app.locals.config = config;
  app.locals.version = hexo.version;
  //app.locals.layout = 'layout';
  //app.locals.cache = true;
  app.engine('ejs', require('../../render').renderFile);

  app.resource = function(){
    var args = _.toArray(arguments),
      path = args.shift(),
      obj = args.pop();

    if (obj.index) app.get.apply(app, [].concat(path, args, obj.index));
    if (obj.new) app.get.apply(app, [].concat(path + '/new', args, obj.new));
    if (obj.create) app.post.apply(app, [].concat(path, args, obj.create));
    if (obj.show) app.get.apply(app, [].concat(path + '/:id', args, obj.show));
    if (obj.edit) app.get.apply(app, [].concat(path + '/:id/edit', args, obj.edit));
    if (obj.update) app.put.apply(app, [].concat(path + '/:id', args, obj.update));
    if (obj.destroy) app.del.apply(app, [].concat(path + '/:id', args, obj.destroy));

    return this;
  };

  if (log){
    app.use(express.logger(log));
  } else if (config.logger){
    if (config.logger_format) app.use(express.logger(config.logger_format));
    else app.use(express.logger());
  } else if (hexo.debug){
    app.use(express.logger());
  }

  var startServer = function(){
    app.use(config.root, express.static(publicDir));

    if (config.root !== '/'){
      app.get('/', function(req, res){
        res.redirect(config.root);
      });
    }

    app.use(function(req, res){
      res.status(404).end('404 Not Found');
    });

    app.listen(port, function(){
      console.log('Hexo is running at %s. Press Ctrl+C to stop.', ('http://localhost:' + port + config.root).bold);
      if (admin && !statics) console.log('Admin password: %s', adminPass.bold);
      hexo.emit('server');
    });
  };

  if (statics){
    app.use(express.compress());

    async.waterfall([
      function(next){
        if (args.g || args.generate) return next(null, true);
        fs.exists(publicDir, function(exist){
          next(null, !exist);
        });
      },
      function(generate, next){
        if (!generate) return next();
        hexo.call('generate', next);
      }
    ], startServer);

    return;
  }

  if (admin){
    var adminPass = config.admin_pass || randomPass(8);

    app.use(express.bodyParser());
    app.use(express.cookieParser('nAL1o1D5wlBn96T'));
    app.use(express.session());

    app.get('/admin/auth', function(req, res, next){
      if (req.session.authed){
        next();
      } else {
        res.render('auth', {error: req.query.error});
      }
    });

    app.post('/admin/auth', function(req, res, next){
      var pass = req.body.pass;
      if (pass === adminPass){
        req.session.authed = true;
        res.redirect('/admin');
      } else {
        res.redirect('/admin/auth?error=1');
      }
    });

    var auth = function(req, res, next){
      if (req.session.authed) return next();
      res.redirect('/admin/auth');
    };

    app.get('/admin', auth, function(req, res, next){
      res.render('list');
    });

    app.use('/admin', express.static(hexo.core_dir + 'public'));
  }

  app.get(config.root + '*', function(req, res, next){
    var uri = route.format(req.params[0]),
      target = route.get(uri);

    if (!target){
      if (uri.substr(uri.length - 1, 1) === '/') return next();
      res.redirect(req.url + '/');
      return;
    }

    target(function(err, result){
      if (err) throw new Error('Route Error: ' + uri);

      res.type(path.extname(uri));

      if (result.readable){
        result.pipe(res).on('error', function(err){
          if (err) next();
        });
      } else {
        res.end(result);
      }
    });
  });

  console.log('Loading.');
  generate({watch: true}, startServer);
});
Example #3
0
	Topics.notifyFollowers = function(postData, exceptUid, callback) {
		callback = callback || function() {};
		var followers, title;

		async.waterfall([
			function(next) {
				Topics.getFollowers(postData.topic.tid, next);
			},
			function(followers, next) {
				if (!Array.isArray(followers) || !followers.length) {
					return callback();
				}
				var index = followers.indexOf(exceptUid.toString());
				if (index !== -1) {
					followers.splice(index, 1);
				}
				if (!followers.length) {
					return callback();
				}

				privileges.topics.filterUids('read', postData.topic.tid, followers, next);
			},
			function(_followers, next) {
				followers = _followers;
				if (!followers.length) {
					return callback();
				}
				title = postData.topic.title;
				if (title) {
					title = S(title).decodeHTMLEntities().s;
				}

				notifications.create({
					bodyShort: '[[notifications:user_posted_to, ' + postData.user.username + ', ' + title + ']]',
					bodyLong: postData.content,
					pid: postData.pid,
					nid: 'new_post:tid:' + postData.topic.tid + ':pid:' + postData.pid + ':uid:' + exceptUid,
					tid: postData.topic.tid,
					from: exceptUid
				}, function(err, notification) {
					if (err) {
						return next(err);
					}

					if (notification) {
						notifications.push(notification, followers);
					}
					next();
				});
			},
			function(next) {
				async.eachLimit(followers, 3, function(toUid, next) {
					async.parallel({
						userData: async.apply(user.getUserFields, toUid, ['username', 'userslug']),
						userSettings: async.apply(user.getSettings, toUid)
					}, function(err, data) {
						if (data.userSettings.hasOwnProperty('sendPostNotifications') && data.userSettings.sendPostNotifications) {
							emailer.send('notif_post', toUid, {
								pid: postData.pid,
								subject: '[' + (meta.config.title || 'NodeBB') + '] ' + title,
								intro: '[[notifications:user_posted_to, ' + postData.user.username + ', ' + title + ']]',
								postBody: postData.content.replace(/"\/\//g, '"http://'),
								site_title: meta.config.title || 'NodeBB',
								username: data.userData.username,
								userslug: data.userData.userslug,
								url: nconf.get('url') + '/topic/' + postData.topic.tid,
								base_url: nconf.get('url')
							}, next);
						} else {
							winston.debug('[topics.notifyFollowers] uid ' + toUid + ' does not have post notifications enabled, skipping.');
						}
					});
				});
				next();
			}
		], callback);
	};
async.waterfall([
    function(cb)
    {
        dc.init(function(err){
            cb(err);
        });
    },
    //start web
    function(cb)
    {
        lineReader.eachLine('scheme.txt', function(line, last, callback) {
            var id = line;
            log.info(id);
            handle(id, function(err, data){
                if (last) {
                    callback(false); // stop reading
                }
                else
                {
                    callback();
                }
            });
        }).then(function () {
            cb(null, "finished--------------------------");
        });
    }
], function (err, rst) {
    log.info("执行结果---------------");
    log.info(err);
    log.info(rst);
});
Example #5
0
MongoClient.connect('mongodb://' + dbCfg.host + '/' + dbCfg.name, function (err, db) {
  if (err) {
    console.log(err);
    process.kill();
  }

  console.log("Connected correctly to server");

  // Get the Timeline, Event & Game collection
  var Timeline = db.collection('Timeline');
  var Champion = db.collection('champions');
  var Game = db.collection('Game');
  var Event = db.collection('Event');
  var Statistique = db.collection('Statistique');

  var _moment = moment();

  async.waterfall([
      // get list of champions
      function (callback) {
        Champion.find({}).toArray(function (err, champions) {
          if (err) {
            return callback(err);
          }

          console.log('Champions loaded: ' + champions.length);
          return callback(null, champions);
        });
      },
      // get last GLOBAL timeline
      function (champions, callback) {
        var timelines = [];
        Timeline.findOne({type: "GLOBAL"}, {sort: [["lastEvent", -1]]}, function (err, timeline) {
          if (err) {
            return callback(err);
          }

          if (timeline) {
            console.log('Timeline from DB: ' + timeline._id);
            timelines.push(timeline);
            return callback(null, champions, timelines);
          } else {
            console.log('Create new timeline');
            // create new timeline with lastEvent 1970-01-01
            var originMoment = moment("1990-08-11");
            var newTimeline = createNewTimeline(REGION, originMoment);
            Timeline.insert(newTimeline, function (err) {
              if (err) {
                return callback(err);
              }
              timelines.push(newTimeline);
              return callback(null, champions, timelines);
            })
          }
        });
      },
      // get 10 games after lastEvent date
      function (champions, timelines, callback) {
        var lastEventMoment = moment(_.last(timelines).lastEvent).add(1, 'seconds');
        console.log('Lookup games after ' + lastEventMoment.toISOString());
        Game.find({matchCreation: {$gte: lastEventMoment.toDate()}}, {
          limit: 10,
          sort: [['matchCreation', 1]]
        }).toArray(function (err, games) {
          if (err) {
            return callback(err);
          }

          if (games && games.length > 0) {
            console.log('Games found: ' + games.length);
            return callback(null, champions, timelines, games);
          } else {
            return callback('No game after ' + lastEventMoment.toISOString());
          }
        });
      },
      // get stats
      function (champions, timelines, games, callback) {
        var dailyReports, globalReport;

        async.parallel([
          //get global report
          function (cb) {
            Statistique.findOne({type: 'GLOBAL', period: 'GLOBAL'}, function (err, global) {
              if (err) {
                return cb(err);
              }

              if (global) {
                console.log('Global report found: ' + global._id);
                globalReport = global;
                return cb();
              } else {
                console.log('Create new global report');
                globalReport = {
                  type: 'GLOBAL',
                  period: 'GLOBAL',
                  createdDate: moment().toDate(),
                  data: {
                    game: 0,
                    gold: 0,
                    minion: 0,
                    totalDeath: 0,
                    totalKill: 0,
                    totalDoubleKill: 0,
                    totalTripleKill: 0,
                    totalQuadraKill: 0,
                    totalPentaKill: 0,
                    totalAssist: 0,
                    totalMinion: 0,
                    totalTime: 0
                  }
                };
                Statistique.insert(globalReport, function (err) {
                  if (err) {
                    return cb(err);
                  }

                  return cb();
                });
              }
            });
          },
          // get daily report
          function (cb) {
            Statistique.find({
              type: 'GLOBAL',
              period: 'DAILY'
            }).toArray(function (err, reports) {
              if (err) {
                return cb(err);
              }

              console.log('Daily reports found: ' + reports.length);

              dailyReports = reports;
              return cb();
            });
          }
        ], function (err) {
          if (err) {
            return callback(err);
          }

          return callback(null, champions, timelines, games, globalReport, dailyReports);
        });
      },
      // process Stats
      function (champions, timelines, games, globalReport, dailyReports, callback) {
        // global stats
        var matchDurationTotal = 0;
        var killTotal = 0;
        var doubleKillTotal = 0;
        var tripleKillTotal = 0;
        var quadraKillTotal = 0;
        var pentaKillTotal = 0;
        var deathTotal = 0;
        var assistTotal = 0;
        var minionTotal = 0;
        var goldTotal = 0;

        async.eachSeries(games, function (game, cb) {
          console.log('Check game: ' + game._id);
          // get stats
          var matchCreationDate = moment(game.matchCreation);
          var matchDuration = game.data.matchDuration;
          var kill = 0;
          var doubleKill = 0;
          var tripleKill = 0;
          var quadraKill = 0;
          var pentaKill = 0;
          var death = 0;
          var assist = 0;
          var minion = 0;
          var gold = 0;
          var killRed = 0;
          var doubleKillRed = 0;
          var tripleKillRed = 0;
          var quadraKillRed = 0;
          var pentaKillRed = 0;
          var deathRed = 0;
          var assistRed = 0;
          var minionRed = 0;
          var goldRed = 0;
          var killBlue = 0;
          var doubleKillBlue = 0;
          var tripleKillBlue = 0;
          var quadraKillBlue = 0;
          var pentaKillBlue = 0;
          var deathBlue = 0;
          var assistBlue = 0;
          var minionBlue = 0;
          var goldBlue = 0;
          var blueTeam = [];
          var redTeam = [];
          var winner = game.data.teams[0].winner ? 'blue' : 'red';
          var champ;
          game.data.participants.forEach(function (participant) {
            champ = _.findWhere(champions, {riotId: participant.championId});
            kill += participant.stats.kills;
            doubleKill += participant.stats.doubleKills;
            tripleKill += participant.stats.tripleKills;
            quadraKill += participant.stats.quadraKills;
            pentaKill += participant.stats.pentaKills;
            death += participant.stats.deaths;
            assist += participant.stats.assists;
            minion += participant.stats.minionsKilled;
            gold += participant.stats.goldEarned;
            if (participant.teamId === 100) {
              blueTeam.push({
                championId: champ._id,
                riotId: champ.riotId,
                key: champ.key
              });
              killBlue += participant.stats.kills;
              doubleKillBlue += participant.stats.doubleKills;
              tripleKillBlue += participant.stats.tripleKills;
              quadraKillBlue += participant.stats.quadraKills;
              pentaKillBlue += participant.stats.pentaKills;
              deathBlue += participant.stats.deaths;
              assistBlue += participant.stats.assists;
              minionBlue += participant.stats.minionsKilled;
              goldBlue += participant.stats.goldEarned;
            } else {
              redTeam.push({
                championId: champ._id,
                riotId: champ.riotId,
                key: champ.key
              });
              killRed += participant.stats.kills;
              doubleKillRed += participant.stats.doubleKills;
              tripleKillRed += participant.stats.tripleKills;
              quadraKillRed += participant.stats.quadraKills;
              pentaKillRed += participant.stats.pentaKills;
              deathRed += participant.stats.deaths;
              assistRed += participant.stats.assists;
              minionRed += participant.stats.minionsKilled;
              goldRed += participant.stats.goldEarned;
            }
          });

          // update total stats
          matchDurationTotal += matchDuration;
          killTotal += kill;
          doubleKillTotal += doubleKill;
          tripleKillTotal += tripleKill;
          quadraKillTotal += quadraKill;
          pentaKillTotal += pentaKill;
          deathTotal += death;
          assistTotal += assist;
          minionTotal += minion;
          goldTotal += gold;

          // create event
          var newEvent = {
            name: 'URF Match #' + game.riotId,
            type: 'MATCH',
            winnerMatch: winner,
            teams: [blueTeam, redTeam],
            statsTeams: [
              {
                gold: goldBlue,
                minion: minionBlue,
                death: deathBlue,
                kill: killBlue,
                doubleKill: doubleKillBlue,
                tripleKill: tripleKillBlue,
                quadraKill: quadraKillBlue,
                pentaKill: pentaKillBlue,
                assist: assistBlue
              },
              {
                gold: goldRed,
                minion: minionRed,
                death: deathRed,
                kill: killRed,
                doubleKill: doubleKillRed,
                tripleKill: tripleKillRed,
                quadraKill: quadraKillRed,
                pentaKill: pentaKillRed,
                assist: assistRed
              }
            ],
            durationMatch: matchDuration,
            description: 'Winner ' + winner + ' team',
            icon: 'match',
            share: false,
            comment: false,
            date: matchCreationDate.toDate()
          };

          // get last timeline
          var lastTimeline = _.last(timelines);

          if (lastTimeline.events.length < 20) {
            // add events
            lastTimeline.events.push(newEvent);

            lastTimeline.lastEvent = matchCreationDate.toDate();
          } else {
            var newTimeline = createNewTimeline(REGION, matchCreationDate);
            newTimeline.events.push(newEvent);
            timelines.push(newTimeline);
          }

          // update daily report
          var daily = _.findWhere(dailyReports, {dailyDate: matchCreationDate.format('DD/MM/YYYY')});

          if (daily) {
            console.log('Daily found: ' + matchCreationDate.format('DD/MM/YYYY'));
            // update
            Statistique.update({_id: daily._id}, {
              $inc: {
                'data.game': 1,
                'data.gold': gold,
                'data.minion': minion,
                'data.totalDeath': death,
                'data.totalKill': kill,
                'data.totalDoubleKill': doubleKill,
                'data.totalTripleKill': tripleKill,
                'data.totalQuadraKill': quadraKill,
                'data.totalPentaKill': pentaKill,
                'data.totalAssist': assist,
                'data.totalMinion': minion,
                'data.totalTime': matchDuration
              }
            }, function (err) {
              if (err) {
                return cb(err);
              }

              console.log('Daily updated: ' + matchCreationDate.format('DD/MM/YYYY'));

              // next game
              return cb();
            });
          } else {
            var newDaily = {
              type: 'GLOBAL',
              period: 'DAILY',
              createdDate: moment().toDate(),
              dailyDate: matchCreationDate.format('DD/MM/YYYY'),
              data: {
                game: 1,
                gold: gold,
                minion: minion,
                totalDeath: death,
                totalKill: kill,
                totalDoubleKill: doubleKill,
                totalTripleKill: tripleKill,
                totalQuadraKill: quadraKill,
                totalPentaKill: pentaKill,
                totalAssist: assist,
                totalMinion: minion,
                totalTime: matchDuration
              }
            };
            // create
            Statistique.insert(newDaily, function (err) {
              if (err) {
                return cb(err);
              }
              console.log('Daily created: ' + matchCreationDate.format('DD/MM/YYYY'));

              // add to list of dailyReports
              dailyReports.push(newDaily);

              return cb();
            });
          }
        }, function (err) {
          if (err) {
            return cb(err);
          }

          // update global report
          Statistique.update({_id: globalReport._id}, {
            $inc: {
              'data.game': games.length,
              'data.gold': goldTotal,
              'data.minion': minionTotal,
              'data.totalDeath': deathTotal,
              'data.totalKill': killTotal,
              'data.totalDoubleKill': doubleKillTotal,
              'data.totalTripleKill': tripleKillTotal,
              'data.totalQuadraKill': quadraKillTotal,
              'data.totalPentaKill': pentaKillTotal,
              'data.totalAssist': assistTotal,
              'data.totalMinion': minionTotal,
              'data.totalTime': matchDurationTotal
            }
          }, function (err) {
            if (err) {
              return callback(err);
            }

            async.each(timelines, function (timeline, cb) {
              timeline.lastUpdated = moment().toDate();

              // update timeline document
              Timeline.update({_id: timeline._id}, timeline, {upsert: true}, function (err) {
                if (err) {
                  return cb(err);
                }

                console.log('Global created or updated: ' + timeline._id);

                return cb();
              });
            }, function (err) {
              if (err) {
                return callback(err);
              }

              console.log('Timelines updated');

              return callback();
            });
          });
        });
      }
    ],
    function (err) {
      if (err) {
        console.log(err);
      }

      console.log('jobGlobalTimeline done');
      db.close();
    }
  );
});
Example #6
0
        passport.authenticate('service-token-hash', function (err, user, info) {

            // var responseJson = function (status, json, message, code) {
            //     if (!code) {
            //         if (status)
            //             code = 200;
            //         else
            //             code = 400;
            //     }

            //     return res.status(code).json({
            //         status: status,
            //         data: json,
            //         code: code,
            //         message: message
            //     });
            // };
            // console.log("/open-api/regid")

            // return responseJson(true, {});

            if (err) {
                console.log("/open-api/regid::error", err);
                return next(err);
            }

            if (!user) {
                return res.json({
                    status: false,
                    message: 'user is not found'
                });
            }

            if (!req.body.regid) {
                return res.json({
                    status: false,
                    message: 'no regid'
                });
            }

            var sns    = new AWS.SNS();
            var ARN    = config.awsSnsApp.ARN_GCM;
            var regid  = req.body.regid;
            var userId = "" + user._id;
            var sns    = new AWS.SNS();

            //save in AWS SNS and Update customer
            async.waterfall([
                    function (asyncCallback) { //delete aws ARN if diferent
                        //TODO: delete ARN
                        asyncCallback(null);
                    },
                    function (asyncCallback) { //save in aws sns
                        var params = {
                            PlatformApplicationArn: ARN, /* required */
                            Token: regid, /* required */
                            CustomUserData: userId
                        };

                        sns.createPlatformEndpoint(params, function(err, data) {
                            if (err) {
                                console.log(err, err.stack); // an error occurred
                                asyncCallback('cant create EndpointArn');
                            } else {
                                console.log("save in aws sns", "OK");
                                asyncCallback(null, data);
                            }
                        });

                    }, function (data, asyncCallback) { //update customer push_info
                        if (data) {
                            user.push_info = {
                                endpoint_arn: data.EndpointArn,
                                regid: req.body.regid
                            }
                            user.save(function(err, user){
                                if (err) {
                                    console.log(err);
                                    asyncCallback('cant update user info');
                                } else {
                                    console.log("update customer push_info", "OK");
                                    asyncCallback(null, user);
                                }
                            });
                        } else {
                            asyncCallback('invalid parameters');
                        }
                    }
                    ],
                    function(err, user) {

                        if (err) {
                            console.log("final response", "NG", err);
                            return res.status(400).json({status: false, message: err});
                        } else {
                            console.log("final response", "OK");
                            return res.json({status: true, message: 'OK'});
                        }
                    }
                    );
})(req, res, next);
Example #7
0
api.cast = function(req, res, next) {
  var user = res.locals.user,
    targetType = req.query.targetType,
    targetId = req.query.targetId,
    klass = shared.content.spells.special[req.params.spell] ? 'special' : user.stats.class,
    spell = shared.content.spells[klass][req.params.spell];

  if (!spell) return res.json(404, {err: 'Spell "' + req.params.spell + '" not found.'});
  if (spell.mana > user.stats.mp) return res.json(400, {err: 'Not enough mana to cast spell'});

  var done = function(){
    var err = arguments[0];
    var saved = _.size(arguments == 3) ? arguments[2] : arguments[1];
    if (err) return next(err);
    res.json(saved);
    user = targetType = targetId = klass = spell = null;
  }

  switch (targetType) {
    case 'task':
      if (!user.tasks[targetId]) return res.json(404, {err: 'Task "' + targetId + '" not found.'});
      spell.cast(user, user.tasks[targetId]);
      user.save(done);
      break;

    case 'self':
      spell.cast(user);
      user.save(done);
      break;

    case 'party':
    case 'user':
      async.waterfall([
        function(cb){
          Group.findOne({type: 'party', members: {'$in': [user._id]}}).populate('members', 'profile.name stats achievements items.special').exec(cb);
        },
        function(group, cb) {
          // Solo player? let's just create a faux group for simpler code
          var g = group ? group : {members:[user]};
          var series = [], found;
          if (targetType == 'party') {
            spell.cast(user, g.members);
            series = _.transform(g.members, function(m,v,k){
              m.push(function(cb2){v.save(cb2)});
            });
          } else {
            found = _.find(g.members, {_id: targetId})
            spell.cast(user, found);
            series.push(function(cb2){found.save(cb2)});
          }

          if (group) {
            series.push(function(cb2){
              var message = '`'+user.profile.name+' casts '+spell.text() + (targetType=='user' ? ' on '+found.profile.name : ' for the party')+'.`';
              group.sendChat(message);
              group.save(cb2);
            })
          }

          series.push(function(cb2){g = group = series = found = null;cb2();})

          async.series(series, cb);
        },
        function(whatever, cb){
          user.save(cb);
        }
      ], done);
      break;
  }
}
Example #8
0
    /**
     * Function to update a task
     *
     * @param params - route parameters
     * @param payload - route payload
     * @param callback - callback function
     */
    update(params, payload, callback) {

        this.server.log(['debug'], 'START < Tasks.Lib.update >');

        Async.waterfall(
            [
                (cb) => {

                    Joi.validate(params, this.utils.schema.taskRequest, (err) => {

                        if (err) {
                            return cb(Boom.preconditionFailed(err.message));
                        }

                        cb();
                    });
                },
                (cb) => {

                    Joi.validate(payload, this.utils.schema.updateTaskRequest, (err) => {

                        if (err) {
                            return cb(Boom.preconditionFailed(err.message));
                        }

                        cb();
                    });
                },
                (cb) => {

                    // create mongo update operator
                    const operator = {
                      $set: {
                          content: payload.content,
                          status: payload.status,
                          modificationDate: new Date()
                      }
                    };

                    // update task for current id
                    this.db.tasks.readAndUpdate(params.taskId, operator, (err, task) => {

                        if (err) {
                            return cb(Boom.wrap(err));
                        }

                        if (!task) {
                            return cb(Boom.notFound('No task updated for _id `' + params.taskId + '`'));
                        }

                        cb(null, task.response());
                    });
                },
                (task, cb) => {

                    this.utils.getUrl(internals._constants.task, null,
                        [
                            {
                                replace: internals._constants.replaceTaskId,
                                value: task.id
                            }
                        ], (err, url) => {

                            if (err) {
                                return cb(Boom.wrap(err));
                            }

                            // add link in response object
                            Object.assign(task, { link: url });

                            cb(null, task);
                        });
                }
            ],
            (err, response) => {

                if (err) {
                    this.server.log(['debug'], 'END < Tasks.Lib.read > with error');

                    return callback(err);
                }

                this.server.log(['debug'], 'END < Tasks.Lib.read >');

                callback(null, response);
            }
        );
    }
Example #9
0
    /**
     * Function to read all tasks with filter in DB
     *
     * @param params - Filter for search
     * @param callback - Callback method
     */
    readAllWithFilter(params, callback) {

        this.server.log(['debug'], 'START < Tasks.Lib.readAllWithFilter >');

        Async.waterfall(
            [

                (cb) => {

                    Joi.validate(params, this.utils.schema.statusRequest, (err) => {

                        if (err) {
                            return cb(Boom.preconditionFailed(err.message));
                        }

                        cb();
                    });
                },
                (cb) => {

                    const filter = {
                        status: params.statusId
                    };

                    // read all tasks with filter in db
                    this.db.tasks.readAllWithFilter(filter, (err, tasks) => {

                        if (err) {
                            return cb(Boom.wrap(err));
                        }

                        if (!tasks || tasks.length === 0) {
                            this.server.log(['debug'], 'END < Tasks.Lib.readAllWithFilter > without data');

                            return callback();
                        }

                        cb(null, tasks);
                    });
                },
                (tasks, cb) => {

                    // create links array
                    const links = [];

                    // build link for each tasks
                    Async.each(tasks, (task, c) => {

                        this.utils.getUrl(internals._constants.task, null,
                            [
                                {
                                    replace: internals._constants.replaceTaskId,
                                    value: task._id.toString()
                                }
                            ], (err, url) => {

                                if (err) {
                                    return c(Boom.wrap(err));
                                }

                                // push url in links array
                                links.push(url);

                                c();
                            });
                    }, (err) => {

                        if (err) {
                            return cb(Boom.wrap(err));
                        }

                        cb(null, links);
                    });
                }
            ],
            (err, response) => {

                if (err) {
                    this.server.log(['debug'], 'END < Tasks.Lib.readAllWithFilter > with error');

                    return callback(err);
                }

                this.server.log(['debug'], 'END < Tasks.Lib.readAllWithFilter >');

                callback(null, response);
            }
        );
    }
Example #10
0
    /**
     * Function to read all tasks in DB
     *
     * @param callback - Callback method
     */
    readAll(callback) {

        this.server.log(['debug'], 'START < Tasks.Lib.readAll >');

        Async.waterfall(
            [
                (cb) => {

                    // read all tasks in db
                    this.db.tasks.readAll((err, tasks) => {

                        if (err) {
                            return cb(Boom.wrap(err));
                        }

                        if (!tasks || tasks.length === 0) {
                            this.server.log(['debug'], 'END < Tasks.Lib.readAll > without data');

                            return callback();
                        }

                        cb(null, tasks);
                    });
                },
                (tasks, cb) => {

                    // create links array
                    const links = [];

                    // build link for each tasks
                    Async.each(tasks, (task, c) => {

                        this.utils.getUrl(internals._constants.task, null,
                            [
                                {
                                    replace: internals._constants.replaceTaskId,
                                    value: task._id.toString()
                                }
                            ], (err, url) => {

                                if (err) {
                                    return c(Boom.wrap(err));
                                }

                                // push url in links array
                                links.push(url);

                                c();
                            });
                    }, (err) => {

                        if (err) {
                            return cb(Boom.wrap(err));
                        }

                        cb(null, links);
                    });
                }
            ],
            (err, response) => {

                if (err) {
                    this.server.log(['debug'], 'END < Tasks.Lib.readAll > with error');

                    return callback(err);
                }

                this.server.log(['debug'], 'END < Tasks.Lib.readAll >');

                callback(null, response);
            }
        );
    }
Example #11
0
    /**
     * Function to find a task
     *
     * @param params - route parameters
     * @param callback - callback function
     */
    read(params, callback) {

        this.server.log(['debug'], 'START < Tasks.Lib.read >');

        Async.waterfall(
            [
                (cb) => {

                    Joi.validate(params, this.utils.schema.taskRequest, (err) => {

                        if (err) {
                            return cb(Boom.preconditionFailed(err.message));
                        }

                        cb();
                    });
                },
                (cb) => {

                    // get task for current id
                    this.db.tasks.read(params.taskId, (err, task) => {

                        if (err) {
                            return cb(Boom.wrap(err));
                        }

                        if (!task) {
                            return cb(Boom.notFound('No task found for _id `' + params.taskId + '`'));
                        }

                        cb(null, task.response());
                    });
                },
                (task, cb) => {

                    this.utils.getUrl(internals._constants.task, null,
                        [
                            {
                                replace: internals._constants.replaceTaskId,
                                value: task.id
                            }
                        ], (err, url) => {

                            if (err) {
                                return cb(Boom.wrap(err));
                            }

                            // add link in response object
                            Object.assign(task, { link: url });

                            cb(null, task);
                        });
                }
            ],
            (err, response) => {

                if (err) {
                    this.server.log(['debug'], 'END < Tasks.Lib.read > with error');

                    return callback(err);
                }

                this.server.log(['debug'], 'END < Tasks.Lib.read >');

                callback(null, response);
            }
        );
    }
Example #12
0
  id.post('/start', (req, res) => {
    let username = req.user.username;
    let entity   = req.body.id;

    if(!entity) {
      return res.error(405, 'INVALID_INPUT');
    }

    debug('user finished assignments', req.user.assignments);

    if(!entity) {
      return res.error('INVALID_NO_ASSINGMENT');
    }

    let container = null;
    async.waterfall([
      // verify the assignment is real.
      (next) => {
        assignment.isValid(entity)
        .then(a => {
          debug('start', 'assignment name is:', a.name);

          return next();
        })
        .catch(err => {
          debug('start:assignmentValidCheck', 'error: ', err);
          return next(err);
        })
      },

      (next) => {
        if(!req.user.assignments) {
          return next();
        }

        if(typeof req.user.assignments !== 'object') {
          return next();
        }

        if(req.user.assignments[entity].status === 'finished') {
          return next('ASSIGNMENT_FINISHED');
        }
      },

      (next) => {
        // delegate to a workspace container
        let workspace_ip = 'http://'+CONFIG.workspace.ip;
        if(CONFIG.workspace.ip == '<env>') {

          let WORKSPACE = process.env.WORKSPACE_1_PORT || process.env.WORKSPACE_PORT;
          if(WORKSPACE) {
            let Workspace = url.parse(WORKSPACE);

            debug('init', 'using DNS resolving');
            workspace_ip = 'http://'+Workspace.hostname+':'+Workspace.port;
          } else {
            debug('init', 'told to use docker but failed to determine IP');
            return next('INTERNAL_SYS_WORKSPACE_EVAL_ERR');
          }
        }

        debug('workspace', 'POST', workspace_ip)
        request({
          method: 'POST',
          uri: workspace_ip.replace(/\/$/g, '')+'/start',
          body: {
            username: username,
            assignment: entity
          },
          json: true
        }, (err, res, body) => {
          if(err) return next('FAILED_TO_LAUNCH_WORKSPACE');

          debug('worksapce', 'GOT', body)

          if(body === 'FAIL') {
            return next('INTERNAL_SYS_WORKSPACE_LAUNCH');
          }

          return next(false, {
            username: username,
            assignment: entity
          });
        })
      }
    ], (err, info) => {
      debug('workspaces', 'done')
      if(err) {
        return res.error(500, err);
      }

      return res.success({
        status:     'init',
        username:   info.username,
        assignment: info.assignment
      });
    });
  });
Example #13
0
router.get("/files", function(req, res, next) {
  console.log("--- processing files query ---", req.query);
  var hit = queryCache.hit(req.query);
  if (hit) {
    console.log("result is cached");
    res.send(hit);
    return;
  }
  
  var query = constructMongoQuery(req);

  // result paging
  var page = parseInt(req.query.page) || 1;
  var pageSize = 20;

  async.waterfall([
    connect,
    function(db, cb) {
      async.parallel({
        filteredFiles: function(cb) {
          console.time("filteredFiles");
          db.collection("files")
            .find(query)
            .skip(pageSize * (page-1))
            .limit(pageSize)
            .toArray(function(err, filteredFiles) {
              console.timeEnd("filteredFiles");
              cb(err, filteredFiles);
            });
        },
        numResults: function(cb) {
          console.time("numResults");
          var fileCursor = db.collection("files").find(query).batchSize(10000);
          fileCursor.count(function(err, numResults) {
            console.timeEnd("numResults");
            cb(err, numResults);
          });
        },
        lowDate: function(cb) {
          db.collection("files").find(query).sort({date:1}).limit(1).toArray(function(err, files) {
            var date = files.length > 0 ? files[0].date : null;
            cb(err, date);
          });
        },
        highDate: function(cb) {
          db.collection("files").find(query).sort({date:-1}).limit(1).toArray(function(err, files) {
            var date = files.length > 0 ? files[0].date : null;
            cb(err, date);
          });
        },
        counts: function(cb) {
          console.time("processing");

          var stationMap = {};

          db.collection("files").find(query).batchSize(10000).each(function(err, file) {
            if (file === null) {
              console.timeEnd("processing");
              cb(err, { stationMap: stationMap });
            } else {
              if (!(file.stationId in stationMap)) {
                stationMap[file.stationId] = 0;
              }
              stationMap[file.stationId]++;
            }
          });
        }
      },
      function(err, results) {
        cb(err, db, results);
      });
    },
    function(db, results, cb) {
      var payload = {
        stations: results.counts.stationMap,
        lowDate: results.lowDate,
        highDate: results.highDate,
        numResults: results.numResults,
        files: results.filteredFiles
      };

      queryCache.put(req.query, payload);
      res.send(payload);
      db.close();
      cb(null);
    }
  ], function(err) {
    if (err) next(err);
  });
});
  }
});

var sql;
var values=[];
var LastValue=0;
var LastOrder=0;
var LastProduct=0;

async.waterfall([
  parallelFunction,
  insertOrderItem,
  insertLineItem,
], function(err,results){
  if(err){
    console.log(err);
  }
  else{
    console.log("yepee finish!!!!!!!");
  }

  conn.end();
});

function parallelFunction(callback){
  async.parallel([
      function(callback1){
        //insert values for User database
        sql="insert into Users(userId,userName,address,phone,email,alternateEmail) values ?";
        for(i=0;i<1000;i++){
          var a=[];
          a[0]=(1+i);
Example #15
0
router.post('/todaysWrite', function (req, res) {
    var memberId = req.session.user_id;
    var todaysCareTitle = req.body.todaysCareTitle;
    var todaysCareContent = req.body.todaysCareContent;
    var todaysCarePicture1 = 'todays_' + req.files.todaysCarePicture1.name;
    var files = [req.files.todaysCarePicture1.name];
    var idx = todaysCarePicture1.lastIndexOf('.');
    var prefixName = todaysCarePicture1.substring(0, idx);
    var extension = req.files.todaysCarePicture1.extension;
    var todaysCareThumbnail = prefixName + '-thumbnail.' + extension;
    if (req.files.todaysCarePicture2) {
        var todaysCarePicture2 = 'todays_' + req.files.todaysCarePicture2.name;
        files.push(req.files.todaysCarePicture2.name);
    }
    if (req.files.todaysCarePicture3) {
        var todaysCarePicture3 = 'todays_' + req.files.todaysCarePicture3.name;
        files.push(req.files.todaysCarePicture3.name);
    }
    if (req.files.todaysCarePicture4) {
        var todaysCarePicture4 = 'todays_' + req.files.todaysCarePicture4.name;
        files.push(req.files.todaysCarePicture4.name);
    }
    if (req.files.todaysCarePicture5) {
        var todaysCarePicture5 = 'todays_' + req.files.todaysCarePicture5.name;
        files.push(req.files.todaysCarePicture5.name);
    }
    if (req.files.todaysCarePicture6) {
        var todaysCarePicture6 = 'todays_' + req.files.todaysCarePicture6.name;
        files.push(req.files.todaysCarePicture6.name);
    }
    if (req.files.todaysCarePicture7) {
        var todaysCarePicture7 = 'todays_' + req.files.todaysCarePicture7.name;
        files.push(req.files.todaysCarePicture7.name);
    }
    if (req.files.todaysCarePicture8) {
        var todaysCarePicture8 = 'todays_' + req.files.todaysCarePicture8.name;
        files.push(req.files.todaysCarePicture8.name);
    }
    if (req.files.todaysCarePicture9) {
        var todaysCarePicture9 = 'todays_' + req.files.todaysCarePicture9.name;
        files.push(req.files.todaysCarePicture9.name);
    }
    if (req.files.todaysCarePicture10) {
        var todaysCarePicture10 = 'todays_' + req.files.todaysCarePicture10.name;
        files.push(req.files.todaysCarePicture10.name);
    }
    var todaysCareCategory = req.body.todaysCareCategory;

    if (todaysCareTitle == '') {
        res.json({"success": 0, "result": {"message": "오늘의 육아 제목 없음, 오늘의 육아 쓰기 실패"}});
    } else if (todaysCareContent == '') {
        res.json({"success": 0, "result": {"message": "오늘의 육아 내용 없음, 오늘의 육아 쓰기 실패"}});
    } else if (!memberId) {
        res.json({"success": 0, "result": {"message": "로그인 안됨, 오늘의 육아 쓰기 실패"}});
    } else if (memberId != 'admin') {
        res.json({"success": 0, "result": {"message": "관리자 아님, 오늘의 육아 쓰기 실패"}});
    } else {
        async.waterfall([
            function (callback) {
                picture.todays(req.files.todaysCarePicture1, files, function (err) {
                    if (err) {
                        callback(err);
                    } else {
                        callback(null);
                    }
                })
            },
            function (callback) {
                var datas = [memberId, todaysCareTitle, todaysCareContent, todaysCareThumbnail, todaysCarePicture1, todaysCarePicture2,
                    todaysCarePicture3, todaysCarePicture4, todaysCarePicture5, todaysCarePicture6,
                    todaysCarePicture7, todaysCarePicture8, todaysCarePicture9, todaysCarePicture10, todaysCareCategory];
                logger.debug('datas', datas);
                db_admin.todaysWrite(datas, function (err, success) {
                    if (err) {
                        callback(err);
                    } else {
                        if (success) {
                            callback(null);
                        } else {
                            callback('err');
                        }
                    }
                })
            }
        ], function (err) {
            if (err) {
                res.send('<head><meta charset="utf-8"><script>alert("에러가 발생하여 되돌아갑니다!!");' +
                'history.back();</script></head>')
            } else {
                res.redirect('/admin/todays/1');
            }
        })
    }
})
Example #16
0
    /**
     * Function to create new task in DB
     *
     * @param payload - Data to insert in DB
     * @param callback - Callback method
     */
    create(payload, callback) {

        this.server.log(['debug'], 'START < Tasks.Lib.create >');

        Async.waterfall(
            [
                (cb) => {

                    Joi.validate(payload, this.utils.schema.createTaskRequest, (err) => {

                        if (err) {
                            return cb(Boom.preconditionFailed(err.message));
                        }

                        cb();
                    });
                },
                (cb) => {

                    // assign new variables
                    const Data = {
                        content: payload.content,
                        creationDate : new Date(),
                        modificationDate : new Date()
                    };

                    if (payload.status) {
                        Object.assign(Data, { status: payload.status });
                    } else {
                        const aucun = {
                            status: 'Aucun'
                        }
                        Object.assign(Data, { status: aucun.status });
                    }

                    this.server.log(['debug'], '< Tasks.Lib.create > Data to insert in DB => ' + JSON.stringify(Data));

                    // create task in db
                    this.db.tasks.create(Data, (err, task) => {

                        if (err) {
                            return cb(Boom.wrap(err));
                        }

                        if (!task) {
                            return cb(Boom.badData('Task can\'t be created'));
                        }

                        cb(null, task.response());
                    });
                },
                (task, cb) => {

                    this.utils.getUrl(internals._constants.task, null,
                        [
                            {
                                replace: internals._constants.replaceTaskId,
                                value: task.id
                            }
                        ], (err, url) => {

                            if (err) {
                                return cb(Boom.wrap(err));
                            }

                            // add link in response object
                            Object.assign(task, { link: url });

                            cb(null, task);
                        });
                }
            ],
            (err, response) => {

                if (err) {
                    this.server.log(['debug'], 'END < Tasks.Lib.create > with error');

                    return callback(err);
                }

                this.server.log(['debug'], 'END < Tasks.Lib.create >');

                callback(null, response);
            }
        );
    }
Example #17
0
/**
 * Prepares and uploads a file
 *
 * @param {string} fileExt - The extension of the filename
 * @param {string} bucket - The S3 Bucket
 * @param {string} keyPrefix - The prefix for the S3 key
 * @param {string} contentType - The content type (MIME type) of the file
 * @param {requestCallback} cb
 */
function uploadFile(fileExt, bucket, keyPrefix, contentType, cb) {
	console.log('Uploading', contentType);

	var filename = path.join(tempDir, 'out.' + fileExt);
	var rmFiles = [filename];
	var readStream = fs.createReadStream(filename);

	var params = {
		Bucket: bucket,
		Key: keyPrefix + '.' + fileExt,
		ContentType: contentType,
		CacheControl: 'max-age=31536000' // 1 year (60 * 60 * 24 * 365)
	};

	async.waterfall([
		function(cb) {
			if (!config.gzip)
				return cb(null, readStream, filename);

			var gzipFilename = filename + '.gzip';

			rmFiles.push(gzipFilename);
			params.ContentEncoding = 'gzip';

			var gzipWriteStream = fs.createWriteStream(gzipFilename);

			gzipWriteStream.on('finish', function() {
				cb(null, fs.createReadStream(filename), gzipFilename);
			});

			readStream
				.pipe(zlib.createGzip({level: zlib.Z_BEST_COMPRESSION}))
				.pipe(gzipWriteStream);
		},
		function(fstream, uploadFilename, cb) {
			console.log('Begin hashing', uploadFilename);

			var hash = crypto.createHash('sha256');

			fstream.on('data', function(d) {
				hash.update(d);
			});

			fstream.on('end', function() {
				cb(null, fs.createReadStream(uploadFilename), hash.digest('hex'));
			});
		},
		function(fstream, hashdigest, cb) {
			console.log(filename, 'hashDigest:', hashdigest);
			params.Body = fstream;

			if (hashdigest)
				params.Metadata = {'sha256': hashdigest};

			s3upload(params, filename, cb);
		},
		function(data, cb) {
			console.log(filename, 'complete. Deleting now.');
			async.each(rmFiles, fs.unlink, cb);
		}
	], cb);
}
Example #18
0
app.post('/auth/live', function(req, res) {
  async.waterfall([
    // Step 1. Exchange authorization code for access token.
    function(done) {
      var accessTokenUrl = 'https://login.live.com/oauth20_token.srf';
      var params = {
        code: req.body.code,
        client_id: req.body.clientId,
        client_secret: config.WINDOWS_LIVE_SECRET,
        redirect_uri: req.body.redirectUri,
        grant_type: 'authorization_code'
      };
      request.post(accessTokenUrl, { form: params, json: true }, function(err, response, accessToken) {
        done(null, accessToken);
      });
    },
    // Step 2. Retrieve profile information about the current user.
    function(accessToken, done) {
      var profileUrl = 'https://apis.live.net/v5.0/me?access_token=' + accessToken.access_token;
      request.get({ url: profileUrl, json: true }, function(err, response, profile) {
        done(err, profile);
      });
    },
    function(profile) {
      // Step 3a. Link user accounts.
      if (req.headers.authorization) {
        User.findOne({ live: profile.id }, function(err, user) {
          if (user) {
            return res.status(409).send({ message: 'There is already a Windows Live account that belongs to you' });
          }
          var token = req.headers.authorization.split(' ')[1];
          var payload = jwt.decode(token, config.TOKEN_SECRET);
          User.findById(payload.sub, function(err, existingUser) {
            if (!existingUser) {
              return res.status(400).send({ message: 'User not found' });
            }
            existingUser.live = profile.id;
            existingUser.displayName = existingUser.displayName || profile.name;
            existingUser.save(function() {
              var token = createJWT(existingUser);
              res.send({ token: token });
            });
          });
        });
      } else {
        // Step 3b. Create a new user or return an existing account.
        User.findOne({ live: profile.id }, function(err, user) {
          if (user) {
            return res.send({ token: createJWT(user) });
          }
          var newUser = new User();
          newUser.live = profile.id;
          newUser.displayName = profile.name;
          newUser.save(function() {
            var token = createJWT(newUser);
            res.send({ token: token });
          });
        });
      }
    }
  ]);
});
Example #19
0
app.post('/open-api/table_token/:store_id', cors(), function (req, res) {
    var responseJson = function (status, json, message, code) {
        if (!code) {
            if (status)
                code = 200;
            else
                code = 400;
        }

        return res.status(code).json({
            status: status,
            data: json,
            code: code,
            message: message
        });
    };

    async.waterfall([function (asyncCallback) {
        globalSchema.Store.findById(req.params.store_id)
        .populate('user')
        .exec(function (err, store) {
            if (store) {
                asyncCallback(null, store)
            } else {
                asyncCallback("store not found")
            }
        });

    }, function (store, asyncCallback) {
        globalSchema.Customer
        .findOne({service_token: req.body.service_token}, function (err, customer) {
            if (err)
                return asyncCallback("internal error");

            if (customer) {
                asyncCallback(null, store, customer);
            } else {
                asyncCallback("user not found");
            }
        });
    }, function (store, customer, asyncCallback) { //generate request token and save
        globalSchema.CheckInRequest.findOne({customer: customer._id, store: store._id, table: req.body.table_id})
        .exec(function(err, checkInRequest) {

            if (err) {
                return asyncCallback(err);
            }

            console.log(customer);
            if (!checkInRequest) {
                console.log("new checkInRequest");
                checkInRequest               = new globalSchema.CheckInRequest();
                checkInRequest.table         = req.body.table_id;
                checkInRequest.store         = store._id;
                checkInRequest.customer      = customer._id;
                checkInRequest.request_token = checkInRequest.generateRequestToken();
            } else {
                console.log("has checkInRequest");
                checkInRequest.request_count++;
            }

            checkInRequest.save(function (err, checkInRequest) {
                if (err)
                    return asyncCallback(err);
                asyncCallback(null, store, customer, checkInRequest);
            });

        });
    }], function (err, store, customer, checkInRequest) {
            if (err) {
                console.log("err1" , err);
                return responseJson(false, {}, err, 400);
            }

            var serverHash = store.user.serverHash;
            if (serverHash && req.body.table_id) {
                if (connectedUsers[serverHash]) {
                    var sendData = {
                        table_id: req.body.table_id,
                        send_time: Date.now()
                    };

                    if (customer) {
                        sendData.customer = {
                            id: customer._id,
                            name: customer.name,
                            image_url: customer.image_url
                        };
                    }

                    if (checkInRequest) {
                        sendData.checkInRequest = checkInRequest;
                    }

                    connectedUsers[serverHash].emit("request_check_in", sendData, function (data) {
                        if (data.status) {
                            return responseJson(true, data, "OK");
                        } else {
                            return responseJson(false, data, data.err);
                        }
                    });

                } else {
                    console.log("err2" , "server is off");
                    return responseJson(false, {}, "server is off", 400);
                }
            } else {
                console.log("err3" , "invalid parameters", serverHash, req.body.table_id);
                return responseJson(false, {}, "invalid parameters", 400);
            }
        });
    });
Example #20
0
    client.connect(function(err) {
      if (err) {
        log.fatal('Fatal database error', err);
        process.exit(1);
      }

      var Model = require('model')
        , model = new Model(client, dogecoin);

      var TXFEE = argv.txfee;

      function confirmWithUser(inputs, outputs, total, next) {
        log.info('inputs', inputs);
        log.info('outputs', outputs);
        log.info('total', total, 'fee', TXFEE, 'net', total - TXFEE);
        log.info('send to', targetAddress);
        read({
          prompt: 'Is this ok? [all/yes/no]',
          default: 'yes'
        }, function(err, response) {
          if (response === 'yes' || response === 'all') {
            confirm = response !== 'all';
            next(null, inputs, outputs);
          } else {
            next(new Error('aborted'));
          }
        });
      }

      function spendTransactions(txs, callback) {
        var total = _.reduce(txs, function(sum, tx) {
          return sum + Number(tx.amount);
        }, 0);

        var inputs = _.map(txs, function(tx) {
          return {
            txid: tx.txid,
            vout: Number(tx.vout),
            public_address: tx.public_address
          };
        });

        var outputs = {};
        outputs[targetAddress] = total - TXFEE;

        async.waterfall([
          function(next) {
            if (confirm) {
              confirmWithUser(inputs, outputs, total, next);
            } else {
              next(null, inputs, outputs);
            }
          },
          function(inputs, outputs, next) {
            model.sendRawTransaction(inputs, outputs, next);
          },
          function(sent_txid, inputs, outputs, next) {
            log.info('Sent txid', sent_txid);
            async.eachSeries(inputs, function(tx, next_each) {
              log.info('Updating', tx, 'to spent.');
              model.spendTransaction(tx.public_address, tx.txid, tx.vout, sent_txid, next_each);
            }, next);
          }
        ], callback);
      }

      async.waterfall([
        function(next) {
          model.getTransactionsInState(model.CREDITED, next);
        },
        function(credited, next) {
          async.whilst(
            function() { return credited.length > 0; },
            function(next_whilst) {
              var txs = credited.splice(0, 64);
              spendTransactions(txs, next_whilst);
            }, next);
        }
      ], function(err) {
        if (err) {
          log.fatal(err.message);
          process.exit(1);
        } else {
          process.exit(0);
        }
      });
    });
Example #21
0
api.batchUpdate = function(req, res, next) {
  if (_.isEmpty(req.body)) req.body = []; // cases of {} or null
  if (req.body[0] && req.body[0].data)
    return res.json(501, {err: "API has been updated, please refresh your browser or upgrade your mobile app."})

  var user = res.locals.user;
  var oldSend = res.send;
  var oldJson = res.json;

  // Stash user.save, we'll queue the save op till the end (so we don't overload the server)
  var oldSave = user.save;
  user.save = function(cb){cb(null,user)}

  // Setup the array of functions we're going to call in parallel with async
  res.locals.ops = [];
  var ops = _.transform(req.body, function(m,_req){
    if (_.isEmpty(_req)) return;
    _req.language = req.language;

    m.push(function() {
      var cb = arguments[arguments.length-1];
      res.locals.ops.push(_req);
      res.send = res.json = function(code, data) {
        if (_.isNumber(code) && code >= 500)
          return cb(code+": "+ (data.message ? data.message : data.err ? data.err : JSON.stringify(data)));
        return cb();
      };
      api[_req.op](_req, res, cb);
    });
  })
  // Finally, save user at the end
  .concat(function(){
    user.save = oldSave;
    user.save(arguments[arguments.length-1]);
  });

  // call all the operations, then return the user object to the requester
  async.waterfall(ops, function(err,_user) {
    res.json = oldJson;
    res.send = oldSend;
    if (err) return next(err);

    var response = _user.toJSON();
    response.wasModified = res.locals.wasModified;

    user.fns.nullify();
    user = res.locals.user = oldSend = oldJson = oldSave = null;

    // return only drops & streaks
    if (response._tmp && response._tmp.drop){
      res.json(200, {_tmp: {drop: response._tmp.drop}, _v: response._v});

    // Fetch full user object
    }else if(response.wasModified){
      // Preen 3-day past-completed To-Dos from Angular & mobile app
      response.todos = _.where(response.todos, function(t) {
        return !t.completed || (t.challenge && t.challenge.id) || moment(t.dateCompleted).isAfter(moment().subtract({days:3}));
      });
      res.json(200, response);

    // return only the version number
    }else{
      res.json(200, {_v: response._v});
    }
  });
};
exports.reset = function(req, res, next) {
	// Init Variables
	var passwordDetails = req.body;

	async.waterfall([

		function(done) {
			User.findOne({
				resetPasswordToken: req.params.token,
				resetPasswordExpires: {
					$gt: Date.now()
				}
			}, function(err, user) {
				if (!err && user) {
					if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
						user.password = passwordDetails.newPassword;
						user.resetPasswordToken = undefined;
						user.resetPasswordExpires = undefined;

						user.save(function(err) {
							if (err) {
								return res.status(400).send({
									message: errorHandler.getErrorMessage(err)
								});
							} else {
								req.login(user, function(err) {
									if (err) {
										res.status(400).send(err);
									} else {
										// Return authenticated user 
										res.json(user);

										done(err, user);
									}
								});
							}
						});
					} else {
						return res.status(400).send({
							message: 'Passwords do not match'
						});
					}
				} else {
					return res.status(400).send({
						message: 'Password reset token is invalid or has expired.'
					});
				}
			});
		},
		function(user, done) {
			res.render('templates/reset-password-confirm-email', {
				name: user.displayName,
				appName: 'ePartsBD'
			}, function(err, emailHTML) {
				done(err, emailHTML, user);
			});
		},
		// If valid email, send reset email using service
		function(emailHTML, user, done) {
			var smtpTransport = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: '******',
        pass: '******'
    }
});
			var mailOptions = {
				to: user.email,
				from: 'ePartsBD',
				subject: 'Your password has been changed',
				html: emailHTML
			};

			smtpTransport.sendMail(mailOptions, function(err) {
				done(err, 'done');
			});
		}
	], function(err) {
		if (err) return next(err);
	});
};
var handle = function(id, cb)
{
    var sTable = dc.main.get("schemezh");
    var oTable = dc.main.get("torder");
    var tTable = dc.main.get("tticket");
    async.waterfall([
        //find scheme
        function(cb)
        {
            var cond = {id:id};
            var cols = {
                finishedOrderCount:1, cancelOrderCount:1, orderCount:1, status:1, curTermCode:1
            };
            sTable.findOne(cond, cols, [], function(err, data){
                cb(err, data);
            });
        },
        //check status
        function(scheme, cb)
        {
            /*log.info(scheme);
            if(scheme.finishedOrderCount + scheme.cancelOrderCount >= scheme.orderCount)
            {
                scheme.status = schemeStatus.FINISHED;
            }
            else
            {
                scheme.finishedOrderCount++;
                scheme.curTermCode = nextTermCode;
            }
            var cond = {id:id};
            var data = {
                $set:{
                    status:scheme.status, finishedOrderCount:scheme.finishedOrderCount,
                    curTermCode:scheme.curTermCode
                }
            }
            sTable.update(cond, data, [], function(err, data){
                cb(err, scheme);
            });*/
            cb(null, scheme);
        },
        //check scheme status
        function(scheme, cb)
        {
            if(scheme.status == schemeStatus.FINISHED)
            {
                cb("方案已经完结................");
            }
            else
            {
                cb(null, scheme);
            }
        },
        //find the order
        function(scheme, cb)
        {
            var cond = {schemeId:scheme.id, termCode:termCode};
            oTable.findOne(cond, {}, [], function(err, data){
                if(err)
                {
                    cb(err, data);
                }
                else
                {
                    if(data)
                    {
                        cb(err, scheme, data);
                    }
                    else
                    {
                        cb("找不到上一期的订单");
                    }
                }
            });
        },
        //find the new term order
        function(scheme, oldTermOrder, cb)
        {
            var cond = {schemeId:scheme.id, termCode:nextTermCode};
            oTable.findOne(cond, {}, [], function(err, data){
                if(err)
                {
                    cb(err, data);
                }
                else
                {
                    if(data)
                    {
                        cb(err, scheme, oldTermOrder, data);
                    }
                    else
                    {
                        cb("找不到上一期的订单");
                    }
                }
            });
        },
        //find the tickets
        function(scheme, oldTermOrder, newTermOrder, cb)
        {
            var cond = {orderId:oldTermOrder.id};
            var cursor = tTable.find(cond, {}, []);
            cursor.toArray(function(err, data){
                cb(err, scheme, newTermOrder, data);
            });
        },
        //create the new order and tickets
        function(scheme, order, tickets, cb)
        {
            var now = new Date();

            for(var key in tickets)
            {
                var ticket = tickets[key];
                ticket.id = digestUtil.createUUID();
                ticket.termCode = nextTermCode;
                ticket.bonus = 0;
                ticket.bonusBeforeTax = 0;
                ticket.orderId = order.id;
                ticket.acceptTime = now;
                ticket.createTime = now;
                ticket.status = ticketStatus.waiting_print;
                ticket.receiptStatus = receiptStatus.NOT_TAKE_AWAY;
                ticket.version = 0;
                ticket.stubInfo = '';
                ticket.terminalId = '';
                ticket.finishedCount = 0;
                delete ticket.printTime;
                delete ticket.sysTakeTime;
                delete ticket.termIndexDeadline;
            }
            cb(null, scheme, order, tickets);
        },
        //save the order
        function(scheme, order, tickets, cb)
        {
            cb(null, scheme, order, tickets);
        },
        //save the tickets
        function(scheme, order, tickets, cb)
        {
            async.eachSeries(tickets, function(ticket, callback) {
                tTable.save(ticket, [], function(err, data){
                    callback(err);
                });
            }, function(err){
                cb(err, scheme, order, tickets);
            });
        },
        //find the pstation
        function(scheme, order, tickets, cb)
        {
            var stationTable = dc.main.get("station");
            stationTable.find({id:order.printStationId}, {code:1}).toArray(function(err, data){
                cb(null, scheme, order, tickets, data[0]);
            });
        },
        //send the print notify
        function(scheme, order, tickets, pstation, cb)
        {
            var printQueen = dc.mg.pool.getConn().conn.collection("print_queen_" + pstation.code);
            mgKvService.getPrintSeqId(function(err, data){
                printQueen.save({_id:data.value, orderId:order.id,
                    gameCode:order.gameCode, termCode:order.termCode}, [], function(err, data){
                    cb(err);
                });
            });
        }
    ], function (err, rst) {
        log.info(id + ",处理结果:");
        log.info(err);
        log.info(rst);
        cb(null, "ok-------------------");
    });
}
exports.forgot = function(req, res, next) {
	async.waterfall([
		// Generate random token
		function(done) {
			crypto.randomBytes(20, function(err, buffer) {
				var token = buffer.toString('hex');
				done(err, token);
			});
		},
		// Lookup user by username
		function(token, done) {
			if (req.body.username) {
				User.findOne({
					username: req.body.username
				}, '-salt -password', function(err, user) {
					if (!user) {
						return res.status(400).send({
							message: 'No account with that username has been found'
						});
					} else if (user.provider !== 'local') {
						return res.status(400).send({
							message: 'It seems like you signed up using your ' + user.provider + ' account'
						});
					} else {
						user.resetPasswordToken = token;
						user.resetPasswordExpires = Date.now() + 3600000; // 1 hour

						user.save(function(err) {
							done(err, token, user);
						});
					}
				});
			} else {
				return res.status(400).send({
					message: 'Username field must not be blank'
				});
			}
		},
		function(token, user, done) {
			res.render('templates/reset-password-email', {
				name: user.displayName,
				appName: 'ePartsBD',
				url: 'http://' + req.headers.host + '/auth/reset/' + token
			}, function(err, emailHTML) {
				done(err, emailHTML, user);
			});
		},
		// If valid email, send reset email using service
		function(emailHTML, user, done) {
			var smtpTransport = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: '******',
        pass: '******'
    }
});
			var mailOptions = {
				to: user.email,
				from: 'ePartsBD',
				subject: 'Password Reset',
				html: emailHTML
			};
			smtpTransport.sendMail(mailOptions, function(err) {
				if (!err) {
					res.send({
						message: 'An email has been sent to ' + user.email + ' with further instructions.'
					});
				}

				done(err);
			});
		}
	], function(err) {
		if (err) return next(err);
	});
};
Example #25
0
		categories: function(next) {
			async.waterfall([
				async.apply(db.getSortedSetRange, 'categories:cid', 0, -1),
				async.apply(categories.getCategoriesData),
			], next);
		}
var shareLiveStream2GroupsJob = function(userId ,url, sharesAmount, timeShareLimit , note, callback){
    var groups = [];
    var accounts = [];
    var sharePerAccount = [1, 3];
    var messages = [];
    var groupMemberRequire = 10000;
    var user = {};
    async.waterfall([
        function(callbackWaterfall){
                Settings.findOne({
                    key : 'sharePerAccount'
                  }).exec(function (err, finn){
                    if (!err && finn ) {
                        sharePerAccount = JSON.parse(finn.value);
                    }
                    callbackWaterfall()
                });
        },
        function(callbackWaterfall){
                Settings.findOne({
                    key : 'groupMemberRequire'
                  }).exec(function (err, finn){
                    if (!err && finn ) {
                        groupMemberRequire = finn.value;
                    }
                    callbackWaterfall()
                });
        },
        function(callbackWaterfall){
             loadAccounts(sharePerAccount, function(err, data){
                if(err) return callbackWaterfall(err);
                accounts = data;
                //console.log('[shareLiveStream2GroupsJob] loadAccounts: ', accounts);
                if(accounts.length < sharesAmount )
                    return callbackWaterfall('accounts not available')
                callbackWaterfall();
             });
        },
        function(callbackWaterfall){
            loadGroups(groupMemberRequire,accounts,function(err, data){
                if(err) 
                    return callbackWaterfall(err);
                accounts = data;
               // console.log('[shareLiveStream2GroupsJob] loadGroups: ', accounts);
                if(accounts.length < sharesAmount)
                     return callbackWaterfall('groups not available')
                callbackWaterfall();
            })
        },
        function(callbackWaterfall){
            loadMessages(accounts,function(err, data){
                if(err) 
                    return callbackWaterfall(err);
                accounts = data;
                callbackWaterfall();
            })
        },
        
        function(callbackWaterfall){
            User.find({id : userId}).populate('roles').exec(function(err, users){
                if(err|| users[0]) return callbackWaterfall(err);
                user = users[0];
                callbackWaterfall();
            });
        },
        function(callbackWaterfall){
            StreamVideo.create({url : url,sharesAmount : sharesAmount, timeShareLimit : timeShareLimit, status : 'Init' , note : note, createdBy : user.id}).exec(function createCB(err, created){
                if(err)
                    return callbackWaterfall(err);
                else callbackWaterfall(null, created.id);
            });   
        },
        function(streamVideoId, callbackWaterfall){
            var accountsLength = accounts.length;
            for (var i = 0; i < accountsLength - sharesAmount ; i++) {
                var index  = Math.floor(Math.random()*accounts.length);
                accounts.splice(index, 1);
            }
            async.eachOfSeries(accounts, (item, key, cbEachOfSeries) => {
                var account = item;
                var group = {};
                Groups.findOne({
                    groupId : account.shareGroupId
                  }).exec(function (err, finn){
                    if (!err && finn ) {
                        group = finn;
                        //console.log('group :', group)
                        var shareDetail = {account : account.id, group : group.id, streamvideo : streamVideoId,shareGroupId : account.shareGroupId , messageShare :  account.messageShare, status : 'Init' };
                        ShareDetail.create(shareDetail).exec(function createCB(err1, created){
                            if(err1)
                                console.log(err1);
                        });           
                    }
                    cbEachOfSeries();
                    
                });
                
               
            }, err =>{
                callbackWaterfall();
            })
        }
    ], err => {
        if(err)
        {
            console.log('[shareLiveStream2GroupsJob] err:', err );
            return callback(err);
        }
        callback();
    });
}
Example #27
0
      metavar: 'LEVEL'
    }
  }).parse();

  /**
   * Set the log level.
   * @type {string}
   */
  log.level = options.loglevel;

  // read the config, run the main function, and write the output file
  async.waterfall([
    readConfig.bind(null, options.config),
    main,
    fse.outputFile.bind(fse, options.output)
  ], function(err) {
    if (err) {
      log.error(err.message);
      process.exit(1);
    } else {
      process.exit(0);
    }
  });
}


/**
 * Export main function.
 */
module.exports = main;
Example #28
0
router.post('/productWrite', function (req, res) {
    var productBrand = req.body.productBrand;
    var productCategory1 = req.body.productCategory1;
    var productCategory2 = req.body.productCategory2;
    var productName = req.body.productName;
    var productAge = req.body.productAge;
    var productStartAge = [];
    var productEndAge = [];
    var datas = [];
    logger.debug('req.body', req.body);

    async.waterfall([
        function (callback) {
            if(Array.isArray(productAge)){
                for (var i = 0; i < productAge.length; i++) {
                    var temp = productAge[i].split('~');
                    productStartAge.push(temp[0]);
                    productEndAge.push(temp[1]);
                }
            } else {
                var temp = productAge.split('~');
                productStartAge.push(temp[0]);
                productEndAge.push(temp[1]);
            }
            callback(null, productStartAge, productEndAge)
        },
        function (productStartAge, productEndAge, callback) {
            if(Array.isArray(productBrand)){
                for (var j = 0; j < productBrand.length; j++) {
                    var test = [];
                    test.push(productBrand[j]);
                    test.push(productCategory1[j]);
                    test.push(productCategory2[j]);
                    test.push(productName[j]);
                    test.push(productStartAge[j]);
                    test.push(productEndAge[j]);
                    datas.push(test);
                }
                logger.debug('datas', datas);
            } else {
                datas = [productBrand, productCategory1, productCategory2, productName, productStartAge, productEndAge];
            }
            callback(null, datas);

        },
        function (datas, callback) {
            async.eachSeries(datas, function (data, callback) {
                    logger.debug('datas1',data);
                    db_admin.productWrite(data, function (err, success) {
                        if (err) {
                            callback(err);
                        } else {
                            if(success){
                                callback(null);
                            } else {
                                callback('err');
                            }
                        }
                    })
                }, function (err) {
                    if (err) {
                        callback(err);
                    } else {
                        callback(null);
                    }
                }
            )
        }
    ], function (err) {
        if (err) {
            res.send('<head><meta charset="utf-8"><script>alert("에러가 발생하여 되돌아갑니다!!");' +
            'history.back();</script></head>')
        } else {
            res.redirect('/admin/product/1');
        }
    })
})
Example #29
0
var _Flickr = null;
async.waterfall([
  function(next) { 
    tokenHelper.init(next);
  },
  function(token, next) {
    Flickr.authenticate(token, next);
  },
  function(flickr, next) {
    _Flickr = flickr;
  	_Flickr.photos.search({'user_id': flickr.options.user_id}, function(error, result) {
      if (error) {
        return next(error);
      }
      return next(null, result.photos.photo);
    });
  },
  function(photos, next) {
    var ids = [];
    async.each(photos, function(photo, eachCallback) {
      _Flickr.photos.delete({'photo_id': photo.id}, eachCallback);
    }, next);
  }
], function(error, results) {
  if (error) {
    return console.log(error);
  }
  //console.log('Deleted IDs: '+JSON.stringify(results));
  console.log("End good job ");
});
Example #30
0
    router.post('/', (req, res, next) => {
        let name = req.body.name;
        let content = req.body.content;
        let kind = req.body.kind;
        let groupId = req.body.group;
        let templateId = req.body.template;
        let vars = req.body.vars;

        if (!_.isStringParam(req.body, 'name')) {
            return next(new Error('Missing "name" property'));
        }

        if (!(_.isStringParam(req.body, 'content') || _.isStringParam(req.body, 'template'))) {
            return next(new Error('Missing "content" or "template" property'));
        }

        if (!_.isStringParam(req.body, 'group')) {
            return next(new Error('Missing "group" property'));
        }

        if (!_.isNumberParam(req.body, 'kind')) {
            return next(new Error('Missing "kind" property'));
        }

        if (!_.isArrayParam(req.body, 'vars')) {
            return next(new Error('Missing "vars" property'));
        }

        async.waterfall([
            (cb) => {
                moduleDB.NGINXConfigsGroupModel.findOne({_id: mongoose.Types.ObjectId(groupId)}, (err, group) => {
                    if (err) {
                        cb(err);
                    } else if (!group) {
                        err = new Error('Group not found');
                        err.apiError = 'not_found';
                        cb(err);
                    } else {
                        cb(null, group.target_id);
                    }
                });
            },
            (targetId, cb) => {
                const p = {
                    name: name,
                    content: content,
                    vars: vars,
                    groupId: groupId,
                    kind: kind
                };

                if (!content || !content.length) {
                    moduleDB.NGINXTemplateModel.findOne({_id: mongoose.Types.ObjectId(templateId)}, (err, template) => {
                        if (err) {
                            cb(err);
                        } else if (!template) {
                            err = new Error('Template not found');
                            err.apiError = 'not_found';
                            cb(err);
                        } else {
                            p.content = template.content;
                            cb(null, p, targetId);
                        }
                    });
                } else {
                    cb(null, p, targetId);
                }
            },
            (p, targetId, cb) => {
                const task = new db.TaskModel({
                    username: req.currentUser.email,
                    target_id: targetId,
                    module: controller,
                    cmd: 'create-config',

                    params: JSON.stringify(p)
                });

                task.save((err) => {
                    cb(err, task);
                });
            }
        ], (err, task) => {
            if (err) {
                next(err);
            } else {
                res.json({ok: true, data: task._id});
            }
        });
    });