Example #1
0
exports.index = function (req, res, next) {
  var user_id = req.session.user._id;
  var ep = new eventproxy();
  ep.fail(next);

  ep.all('has_read_messages', 'hasnot_read_messages', function (has_read_messages, hasnot_read_messages) {
    res.render('message/index', {has_read_messages: has_read_messages, hasnot_read_messages: hasnot_read_messages});
  });

  ep.all('has_read', 'unread', function (has_read, unread) {
    [has_read, unread].forEach(function (msgs, idx) {
      var epfill = new eventproxy();
      epfill.fail(next);
      epfill.after('message_ready', msgs.length, function (docs) {
        docs = docs.filter(function (doc) {
          return !doc.is_invalid;
        });
        ep.emit(idx === 0 ? 'has_read_messages' : 'hasnot_read_messages', docs);
      });
      msgs.forEach(function (doc) {
        Message.getMessageById(doc._id, epfill.group('message_ready'));
      });
    });
  });

  Message.getReadMessagesByUserId(user_id, ep.done('has_read'));

  Message.getUnreadMessageByUserId(user_id, ep.done('unread', function (docs) {
    docs.forEach(function (doc) {
      doc.has_read = true;
      doc.save();
    });
    return docs;
  }));
};
Example #2
0
File: qun.js Project: fluagen/ownc
exports.explore = function(req, res, next) {
    var user = req.session.user;
    var ep = new EventProxy();
    ep.fail(next);
    ep.all('topics', function(topics) {
        if (!topics) {
            topics = [];
        }
        res.render('qun/explore', {
            topics: topics
        });
    });

    ep.all('quns', function(quns) {
        var qids = _.map(quns, 'id');
        // Topic.find({'qun_id': {
        //             $in: qids
        //         }}).exec(ep.done('topics'));
        Topic.where('qun_id').in(qids)
            .exec(ep.done(function(topics) {
                topicRepo.affixQunTopics(topics, ep.done('topics'));
            }));
    });



    Qun.find({ 'members.id': user.loginid })
        .select('id')
        .exec(ep.done('quns'));
};
Example #3
0
exports.getByPage = function (req, res, next) {
    var currentPage = parseInt(req.query.currentPage, 10) || 1;
    var pageSize = Number(req.query.pageSize);
    var options = {};
    if (pageSize) {
        options = {skip: (currentPage - 1) * pageSize, limit: pageSize, sort: '-create_at'};
    }
    var query = {};
    // 如下字段进行模糊查询。
    ['name'].forEach(function (v) {
        var value = req.query[v];
        if (value) {
            query[v] = new RegExp(value);
        }
    });
    var ep = new eventProxy();
    ep.all('count', 'results', function (count, results) {
        res.send({
            results: results,
            totalCount: count,
        })
    });
    ep.fail(function (err) {
        res.sendError(err, '获取信息失败!', 422);
    })
    Role.getRolesByQuery(query, options, ep.done('results'));
    Role.getRolesCountByQuery(query, ep.done('count'));
};
Example #4
0
exports.collect = function(req, res, next){
	var id = req.query.id;
	var topic_node = req.query.node;
	var topic_title = req.query.title;
	var topic_id = req.query.id;
	var user_id = req.session.user._id;
	var option = req.query.option;
	var proxy = new EventProxy();
	proxy.all('topic','user', function(){
		return res.json({data:'success'});
	});
	Topic.commitCollect({id:id , user_id:user_id}, option, function(err){
		if(err) return res.json({data:'failure'});
		else proxy.emit('topic');
	});
	User.getUserById(user_id, function(err, user){
		if(err) return res.json({data:'failure'});
		if(option='add'){
			user.concerned_topics.push({topicId:topic_id,topicTitle:topic_title,topicNode:topic_node});
		}else{
			user.concerned_topics.pull({topicId:topic_id,topicTitle:topic_title,topicNode:topic_node});
		}	
		user.save(function(err){
			if(err) return res.json({data:'failure'});
			proxy.emit('user');
		});
	});

}
Example #5
0
var show = function (req, res, next) {
  var topicId  = String(req.params.id);

  var mdrender = req.query.mdrender === 'false' ? false : true;
  var ep       = new eventproxy();

  if (!validator.isMongoId(topicId)) {
    res.status(400);
    return res.send({success: false, error_msg: '不是有效的话题id'});
  }

  ep.fail(next);

  TopicProxy.getFullTopic(topicId, ep.done(function (msg, topic, author, replies) {
    if (!topic) {
      res.status(404);
      return res.send({success: false, error_msg: '话题不存在'});
    }
    topic = _.pick(topic, ['id', 'author_id', 'tab', 'content', 'title', 'last_reply_at',
      'good', 'top', 'reply_count', 'visit_count', 'create_at', 'author']);

    if (mdrender) {
      topic.content = renderHelper.markdown(at.linkUsers(topic.content));
    }
    topic.author = _.pick(author, ['loginname', 'avatar_url']);

    topic.replies = replies.map(function (reply) {
      if (mdrender) {
        reply.content = renderHelper.markdown(at.linkUsers(reply.content));
      }
      reply.author = _.pick(reply.author, ['loginname', 'avatar_url']);
      reply =  _.pick(reply, ['id', 'author', 'content', 'ups', 'create_at', 'reply_id']);
      reply.reply_id = reply.reply_id || null;

      if (reply.ups && req.user && reply.ups.indexOf(req.user.id) != -1) {
        reply.is_uped = true;
      } else {
        reply.is_uped = false;
      }

      return reply;
    });

    ep.emit('full_topic', topic)
  }));


  if (!req.user) {
    ep.emitLater('is_collect', null)
  } else {
    TopicCollect.getTopicCollect(req.user._id, topicId, ep.done('is_collect'))
  }

  ep.all('full_topic', 'is_collect', function (full_topic, is_collect) {
    full_topic.is_collect = !!is_collect;

    res.send({success: true, data: full_topic});
  })

};
Example #6
0
exports.editCode = function(req,res){
    var id = req.params.id;
    var proxy = new eventproxy();
    proxy.all('jsCode','jsCates',function(jsCode,jsCates){
        res.render('admin/editCode',{
            title:"JS代码修改",
            crumbs:[
                {selected:2,value:"管理JS代码"},
                {selected:3,value:"查看所有代码列表 > "+jsCode['title']}
            ],
            jsCode:jsCode,
            jsCates:jsCates,
            adminUser:req.session.user
        })
    });
    jsCate.queryCate(function(err,docs){
        if(err){
            console.log(err);
        }else{
            if(docs){
                proxy.emit('jsCates',docs);
            }
        }
    });
    jsCateCode.getById(id,function(err,docs){
        if(err){
            console.log(err);
        }else{
            if(docs){
                proxy.emit('jsCode',docs);
            }
        }
    });
};
Example #7
0
exports.sitemap = function (req, res, next) {
  var urlset = xmlbuilder.create('urlset',
    {version: '1.0', encoding: 'UTF-8'});
  urlset.att('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');

  var ep = new eventproxy();
  ep.fail(next);

  ep.all('sitemap', function (sitemap) {
    res.type('xml');
    res.send(sitemap);
  });

  cache.get('sitemap', ep.done(function (sitemapData) {
    if (sitemapData) {
      ep.emit('sitemap', sitemapData);
    } else {
      Topic.getLimit5w(function (err, topics) {
        if (err) {
          return next(err);
        }
        topics.forEach(function (topic) {
          urlset.ele('url').ele('loc', 'http://cnodejs.org/topic/' + topic._id);
        });

        var sitemapData = urlset.end();
        // 缓存一天
        cache.set('sitemap', sitemapData, 3600 * 24);
        ep.emit('sitemap', sitemapData);
      });
    }
  }));
};
Example #8
0
function addCallQueuePost(req, res, next) {
  var ep = new EventProxy();
  var result = {};
  ep.all('data', function(data) {
    req.log.info('CallQueueCreate Success');
    result = util.parseJSON(data);

    // PBX成功后把请求参数发往Callqueue
    //if(result.call_queue_password && result.ring_group_number) {
    //  req.body.call_queue_password = result.call_queue_password;
    //  req.body.ring_group_number = result.ring_group_number;
    //  apiCallQueue.callQueueCreateCallQueue(req.body, function(err, data) {
    //    // 这里不考虑成功与否
    //  });
    //}

    result = util.extend({}, [req.body, result]);
    delete result.access_token;

    res.json(result).end();
  });
  ep.fail(function(err,errMsg) {
    req.log.error(errMsg);
    res.json({err_code:'500', msg:err.msg || errMsg }).end();
  });
  apiCallQueue.callQueueCreate(req.body, util.done('data', ep, 'CallQueueCreate ERROR'));
}
Example #9
0
exports.cateList = function(req,res){
    var cateId = req.params.cateid;
    var proxy = new eventproxy();

    proxy.all('lists','cate',function(lists,cate){
        res.render('admin/jsCateList',{
            title:'JS代码列表',
            crumbs:[
                {selected:2,value:"管理JS代码 > 分类【" + cate['name'] +"】代码列表"}
            ],
            lists:lists,
            adminUser:req.session.user
        })
    });

    jsCateCode.getByCateId(cateId,null,function(err,docs){
        if(err){
            console.log(err);
        }else{
            proxy.emit('lists',docs);
        }
    });
    jsCate.getById(cateId,function(err,doc){
        if(err){
            console.log(err);
        }else{
            proxy.emit('cate',doc);
        }
    });
};
Example #10
0
 bindMachineDepartment.all('connection', function (connection) {
     var ep = new EventProxy();
     ep.all('data1', 'data2', 'data3', function (data1, data2, data3) {
         connection.commit(function (err) {
             if (err) {
                 log.error(err);
                 res.send({"success": false, "data": " 数据库出错!!!" + err.message });
                 connection.rollback(function () {
                     D_base.endTransactions(connection);//结束事务
                 });
             }
             log.info(moment().format('YYYY-MM-DD HH:mm:ss.SSS') + ' IP:' + req.ip + 'commit');
             res.send({"success": true, "data": " 增加成功!!!"});
             D_base.endTransactions(connection);//结束事务
         });
     });
     ep.fail(function (err) {
         log.error(err);
         res.send({"success": false, "data": " 数据库出错!!!" + err.message });
         connection.rollback(function () {
             D_base.endTransactions(connection);//结束事务
         });
     });
     D_barcode_type.changeMachineType(connection, machine,
         moment().format('YYYY-MM-DD HH:mm:ss.SSS') + ' IP:' + req.ip + ' ', ep.done('data1'));
     D_barcode_department.changeMachineDepartment(connection, machine,
         moment().format('YYYY-MM-DD HH:mm:ss.SSS') + ' IP:' + req.ip + ' ', ep.done('data2'));
     D_machine.changeMachinemisc(connection, machine,
         moment().format('YYYY-MM-DD HH:mm:ss.SSS') + ' IP:' + req.ip + ' ', ep.done('data3'));
 });
exports.data = function(opt,fn){

    var pageIndex = (opt.hasOwnProperty("pageIndex") && (!isNaN(opt.pageIndex))) ? opt.pageIndex : 1;
    var pageCount = (opt.hasOwnProperty("pageCount") && (!isNaN(opt.pageCount))) ? opt.pageCount : 10;
    var query = opt.hasOwnProperty("query")? opt.query:{};

    var ep = new eventproxy();

    ep.fail(fn);

    ep.all('query','count',function(result,total){

        var _d = {};

        //计算分页
        var totalPage = total % pageCount === 0 ? parseInt(total/pageCount) : parseInt(total/pageCount)+1;

        _d.totalPage = totalPage;
        _d.total=total;
        _d.pageIndex = pageIndex;
        _d.pageCount = pageCount;
        _d.data = result;

        fn(null,_d);
    });

    queryData(query,pageIndex,pageCount,ep.done(function(result){
        ep.emit('query',result);
    }));

    queryCount(query,ep.done(function(count){
        ep.emit('count',count);
    }));
}
Example #12
0
module.exports.content = function(req, res, next) {
    logger.info('get contents params with : %j', req.params);

	var ep = new eventproxy();
	ep.fail(next);

	var page = parseInt(req.params.page) || 1;
    var userId = req.session.user._id;
    var events = ['content', 'total'];
    ep.all(events, function(contents, total) {
		res.render('blog/admin/content/index', {
			title: '分享管理',
			tools: tools,
            page: page,
            total: Math.ceil(total/config.page_limit),
			contents: contents
        });

    });
	Content.getAllContents(page, userId, ep.done(function(contents) {
        ep.emit('content', contents);
	}));
    Content.getTotal(userId, ep.done(function(total) {
        ep.emit('total', total);
    }));
};
Example #13
0
exports.show=function(req,res){
    var id=req.query.id
    var ep =new eventproxy()
    
    ep.all('order','details',function(order,details){
        res.render('order',{
            order:order,
            details:details
        })
    })
    Order.findOne({_id:id})
         .exec(function(err,order){
         //   console.log(order)
        ep.emit('order',order)
    })
    
    Detail.find({order_id:id})
            .populate({
                path:'product_id',
                select:'_id productName'
                })
            .populate({
                path:'differ_id'
                })
            .exec(function(err,details){
             //   console.log(details)
                ep.emit('details',details)
            })


}
Example #14
0
exports.artAlterLoad = function(req, res, next){

	var _id = req.params.id;

	var ep = new eventproxy();

	ep.all('getCate', 'getAuthor', 'getArt', function(getCate, getAuthor, getArt){
		res.render('admin/create_article', {
			config: config,
			authors: getAuthor,
			categories: getCate,
			article: getArt
		});
	});

	// 查找所有分类
	Category.find({}, '_id name', {sort: {name: 1}}, function(err, categories){
		ep.fail(err);
		ep.emit('getCate', categories);
	});
	// 查找所有作者
	Author.find({}, '_id name', {sort: {name: 1}}, function(err, authors){
		ep.fail(err);
		ep.emit('getAuthor', authors);
	});
	// 根据id 查找文章
	Article.findById(_id, function(err, article){
		ep.fail(err);
		ep.emit('getArt', article);
	});
	
};
Example #15
0
exports.artPublishLoad = function(req, res, next){

	var ep = new eventproxy();

	ep.all('getCate', 'getAuthor', function(getCate, getAuthor){
		res.render('admin/create_article', {
			config: config,
			authors: getAuthor,
			categories: getCate,
			article: null
		});
	});

	// 查找所有分类
	Category.find({}, '_id name', {sort: {name: 1}}, function(err, categories){
		ep.fail(err);
		ep.emit('getCate', categories);
	});
	// 查找所有作者
	Author.find({}, '_id name', {sort: {name: 1}}, function(err, authors){
		ep.fail(err);
		ep.emit('getAuthor', authors);
	});

};
Example #16
0
router.get('/create',function(req,res,next){
  var page = req.query.page;
  
  var ep = new EventProxy();
  
  ep.all(['bugtree','userlist'],function(bugtree,userlist){
    
    res.render('bugcreate.html',
               {page:page,bugtree:bugtree,userlist:userlist});
  });
  
  //取项目列表
  var mysqlpro = 'select ZID,ZPRO_ID,ZPID,ZHASCHILD,ZNAME from TB_BUG_TREE where ZPID=-1 order by ZSORT ';
  Db.query(mysqlpro,function(err,rows){
    ep.emit('bugtree',!err && rows ? rows : []);
  });
  
  //取出可用的用户
  var mysqluser = '******';
  Db.query(mysqluser,function(err,rows){
    ep.emit('userlist',!err && rows ? rows : []);
  });
  
   
});
Example #17
0
function homeArchivePagination(req,res,next){
    var ep=new eventProxy();
    var pageNum=parseInt(req.params.pageNum)||1;
    var prePage=pageNum-1;
    var nextPage=pageNum+1;
    var author=req.params.username;
    var date=req.params.date;
    if(req.params.pageNum<1){
        req.params.pageNum=1;
    }
    ep.all('getArticles','archive','getUserInfo','getCategories','getFriendLinks',function(articles,archive,userInfo,categories,friendLinks){
        res.render('home',{'articles':articles,'archive':archive,'userInfo':userInfo,'categories':categories,'friendLinks':friendLinks,'prePaginationUrl':'/'+author+'/archive/'+date+'/page/'+prePage+'/',nextPaginationUrl:'/'+author+'/archive/'+date+'/page/'+nextPage+'/'});
    });
    BlogUtil.archiveByYourself(author,function (err,result) {
        ep.emit('archive',result);
    });
    BlogUtil.paginationByYourselfByDate({'author':author,'date':date,'pageNum':pageNum},function(err,result){
        ep.emit('getArticles',result);
    });
    Post.getCategoryByUsername({user_name:author},function(err,result){
        ep.emit('getCategories',result);
    });
    User.getByName(author,function(err,result){
        ep.emit('getUserInfo',result[0]);
    });
    BlogUtil.getFriendLinksByUserName({userName:author}, function (err,result) {
        ep.emit('getFriendLinks',result);
    });
}
Example #18
0
exports.indexView = (req, res, next) => {
    var themeId = req.params.id;

    var ep = new eventproxy();
    ep.fail(next);

    ep.on('theme', (theme) => {
        Area.findOne({_id : theme.area_id}, ep.done('showArea', (showArea) => { return showArea }));
    });

    ep.all('setting','showArea','theme', (setting, showArea, theme) => {
        res.render('index/theme', {
            title: theme.name,
            setting : setting,
            showArea : showArea,
            theme: theme
        });
    });

    Setting.findOne({setting_type : 0}, ep.done('setting', (setting) => { return setting }));

    Theme.findOne({_id : themeId})
        .populate({path: 'main_activity other_activitys back_up_activitys meals lodges'})
        .exec(ep.done('theme', (theme) =>  theme ));
}
Example #19
0
module.exports.message = function(req, res, next) {
    logger.info('get message params with : %j', req.params);
	var ep = new eventproxy();
	ep.fail(next);

    var page = parseInt(req.params.page) || 1;
    var userId = req.session.user._id;
    var events = ['message', 'total'];
    ep.all(events, function(messages, total) {
		res.render('blog/admin/message/index', {
			title: '图片管理',
			tools: tools,
            page: page,
            total: Math.ceil(total/config.page_limit),
			messages: messages
        });

    });
    Message.getAllMessages(page, userId, ep.done(function(messages) {
        ep.emit('message', messages);
	}));
    Message.getTotal(userId, ep.done(function(total) {
        ep.emit('total', total);
    }));
};
Example #20
0
function addCallQueueGet(req, res, next) {

  var ep = new EventProxy();
  var result = {};
  result['esData'] = {};
  result['rgsData'] = {};
  result['vrsData'] = {};
  result['cqData'] = {};
  ep.all('esData', 'rgsData', 'vrsData', function(esData, rgsData, vrsData) {
    result.esData = util.parseJSON(esData);
    result.rgsData = util.parseJSON(rgsData);
    result.vrsData = util.parseJSON(vrsData);

    req.log.info('ProvidersList SUCCESS');
    req.log.info(JSON.stringify(result));

    res.render('solomon/content/callQueue/addCallQueue', {type: 'add',data: result});
  });
  ep.fail(function(err, msg) {
    req.log.error('ProvidersList ERROR');
    req.log.error(msg);
    res.json({err_code:'500', msg:err.msg || msg });
  });
  if(req.query && !req.query.cursor) {
    req.query.cursor = 1;
  }
  apiExtensions.extensionList(req.query, util.done('esData', ep, 'ExtensionList ERROR'));
  apiRingGroups.ringGroupsList(req.query, util.done('rgsData', ep, 'RingGroupsList ERROR'));
  apiVirtualReceptionist.virtualReceptionistList(req.query, util.done('vrsData', ep, 'VirtualReceptionistList ERROR'));


}
Example #21
0
exports.index = function(req,res){
    var page = parseInt(req.query.page) || 1;
    page = page > 0 ? page : 1 ;
    var tab = req.query.tab || "all";
    var query = {};
    if(tab != "all"){
        query.tab = tab ;
    }
    var count = 40;
    var option = {skip:(page-1)*count,limit:count,sort:'-insertTime'};

    var ep = new eventproxy();
    ep.all('index_success','page_success','user_success',function(topics,pageCount,userInfo){
        res.render('index',{topics:topics,page:page,pageCount:pageCount,tab:tab,userInfo:userInfo});
    });

    TopicModel.getTopics(query,option,function(err,topics){
       topics =  _.map(topics,function(topic){
            topic.timeStr = topic.insertTime.toLocaleDateString()+' '+topic.insertTime.toTimeString().replace(/\sGm.*$/,'');
            return topic;
        });
       ep.emit('index_success',topics);
    });
    TopicModel.pageCount(query,function(err,allCount){
       var pageCount = Math.ceil(allCount/count);
        ep.emit('page_success',pageCount);
    });
    var username = req.session.user ? req.session.user.username : '';
    UserModel.getUserInfo(username,function(err,userInfo){
       ep.emit('user_success',userInfo);
    });
}
Example #22
0
File: user.js Project: Johnqing/stg
exports.userViews = function(req, res, next){
	if(!req.session.user || !req.session.user.isAdmin){
		res.render('error', {
			error: '对不起,你没有权限这么做!'
		});
		return;
	}

	var limit = 10;
	var currentPage = parseInt(req.query.page, 10) || 1;
	var pathname = url.parse(req.url).pathname;

	var render = function(users, pages){
		res.render('user_views',{
			users: users,
			current_page: currentPage,
			pages: pages,
			base_url: pathname
		});
	}

	var proxy = new EventProxy();
	proxy.all('users', 'pages', render);
	User.getAll({}, {
		skip: (currentPage - 1) * limit,
		limit: limit
	}, function(err, users){
		if(err)
			return next(err);

		var done = function(userRow){
			proxy.emit('users', userRow);
		}
		proxy.after('usersRow', users.length, done);
		// 提取编辑人用户名/格式化时间
		for(var i= 0, len=users.length; i<len; i++){
			(function(i){
				User.get({
					_id: users[i].edit_id
				}, function(err, editer){
					if(err)
						return next(err);
					users[i].edit = editer;
					users[i].createTime = Util.format_date(users[i].create_time);
					users[i].updateTime = Util.format_date(users[i].update_at);
					proxy.emit('usersRow', users[i]);
				})
			})(i);
		}

	});

	User.getCounts({}, function(err, cont){
		if(err)
			return next(err);

		proxy.emit('pages', cont);
	});

}
Example #23
0
exports.sitemap = function (req, res, next) {
  var urlset = xmlbuilder.create('urlset',
    {version: '1.0', encoding: 'UTF-8'});
  urlset.att('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');

  var ep = new eventproxy();
  ep.fail(next);

  ep.all('sitemap', function (sitemap) {
    res.type('xml');
    res.send(sitemap);
  });

  cache.get('sitemap', ep.done(function (sitemapData) {
    if (sitemapData) {
      ep.emit('sitemap', sitemapData);
    } else {
      Post.getLimit5w(function (err, posts) {
        if (err) {
          return next(err);
        }
        posts.forEach(function (post) {
          urlset.ele('url').ele('loc', 'http://blog.gaoqixhb.com/p/' + post._id);
        });

        var sitemapData = urlset.end();
        // 缓存一天
        cache.set('sitemap', sitemapData, 1000 * 3600 * 2);
        ep.emit('sitemap', sitemapData);
      });
    }
  }));
};
Example #24
0
function addInboundRuleGet(req, res, next) {

  var ep = new EventProxy();
  var result = {};
  result['psData'] = {};
  result['esData'] = {};
  result['vrsData'] = {};
  ep.all('psData', 'esData', 'vrsData', 'rgsData', function(psData, esData, vrsData, rgsData) {
    result.psData = util.parseJSON(psData);
    result.esData = util.parseJSON(esData);
    //页码
    var pageData = result.esData;
    if(pageData.start_position && pageData.end_position && pageData.remaining_extensions >= 0) {
      var start = pageData.start_position;
      var end = pageData.end_position;
      var sum = pageData.remaining_extensions;
      result.esData.page = Math.ceil(end / (end - start + 1)); //当前页
      result.esData.page_sum = result.esData.page + Math.ceil(sum / (end - start + 1)); //总页
    }
    result.vrsData = util.parseJSON(vrsData);
    result.rgsData = util.parseJSON(rgsData);
    console.log(result);
    res.render('solomon/content/inboundRules/addInboundRule', {type: 'add', data: result});
  });
  ep.fail(function(err, errMsg) {
    res.json({err_code:'500', msg:err.msg || errMsg }).end();
  });
  req.query.cursor = 1;
  apiProviders.providersList(req.query, util.done('psData', ep, 'ProvidersList ERROR'));
  apiExtensions.extensionList(req.query, util.done('esData', ep, 'extensions ERROR'));
  apiVirtualReceptionist.virtualReceptionistList(req.query, util.done('vrsData', ep, 'virtualReceptionistList ERROR'));
  apiRingGroup.ringGroupsList(req.query, util.done('rgsData', ep, 'ringGroupsList ERROR'));

}
Example #25
0
exports.addCode = function(req,res){
    var proxy = new eventproxy();
    proxy.all('jsCates',function(jsCates){
        console.log(jsCates);
        res.render('admin/addCode',{
            title:'添加代码',
            crumbs:[
                {selected:2,value:"管理JS代码"},
                {selected:2,value:"添加JS代码"}
            ],
            jsCates:jsCates,
            adminUser:req.session.user
        });
    });

    jsCate.queryCate(function(err,docs){
        if(err){
            console.log(err);
        }else{
            if(docs){
                proxy.emit('jsCates',docs);
            }
        }
    });
};
Example #26
0
exports.index = function (req, res, next) {
    var proxy = new EventProxy();
    proxy.fail(next);

      //最新加入
    UserProxy.getUsersByQuery(
        {'$or': [
          {is_block: {'$exists': false}},
          {is_block: false}
        ]},
        { limit: 10, sort: '-create_at'},
        proxy.done('lasts', function (lasts) {
          return lasts;
        })
      );
        //积分排行榜
    UserProxy.getUsersByQuery(
        {'$or': [
          {is_block: {'$exists': false}},
          {is_block: false}
        ]},
        { limit: 10, sort: '-score'},
        proxy.done('tops', function (tops) {
          return tops;
        })
      );
    proxy.all('lasts','tops',function (lasts,tops) {
      res.locals.current_page='index';
      res.render('index', {
        lasts: lasts,
        tops: tops,
        pageTitle:'首页'
      });
    });
}
Example #27
0
exports.auth_user = function (req, res, next) {
  var ep = new eventproxy();
  ep.fail(next);

  ep.all('get_user', function (user) {
    if (!user) {
      return next();
    }
    res.locals.current_user = req.session.user = user;
    req.session.user.avatar_url = User.getGravatar(user.email);

    if (config.admins.hasOwnProperty(user.name)) {
      user.is_admin = true;
    }
    Message.getMessagesCount(user._id, ep.done(function (count) {
      user.messages_count = count;
      next();
    }));

  });

  if (req.session.user) {
    ep.emit('get_user', req.session.user);
  } else {
    var cookie = req.cookies[config.auth_cookie_name];
    if (!cookie) {
      return next();
    }

    var auth_token = decrypt(cookie, config.session_secret);
    var auth = auth_token.split('\t');
    var user_id = auth[0];
    User.getUserById(user_id, ep.done('get_user'));
  }
};
Example #28
0
module.exports.show = (req, res, next) => {
  const ep = new Eventproxy()
  ep.fail(next)

  ep.all('records', 'devices', 'apks', (records, devices, apks) => {
    records.forEach((record) => {
      if (record.setup.length !== 0) {
        const actions = _.join(record.setup, '\n')
        record.setup = actions
      }

      ApkModel.findOne({ _id: record.apk_id }).exec(ep.done((apk) => {
        record.apk_name = apk.name
        record.package_name = apk.package_name
        record.activity_name = apk.activity_name

        if (apk.blacklist.length !== 0) {
          const resources = _.join(apk.blacklist, '\n')
          record.blacklist = resources
        }
        ep.emit('apk')
      }))
    })

    ep.after('apk', records.length, () => {
      return res.render('records/records', { title: '自动遍历任务', records, devices, apks })
    })
  })

  RecordModel.find({}).sort({ create_at: -1 }).exec(ep.done('records'))
  DeviceModel.find({}).sort({ create_at: -1 }).exec(ep.done('devices'))
  ApkModel.find({}).sort({ create_at: -1 }).exec(ep.done('apks'))
}
Example #29
0
  TopicProxy.newAndSave(title, content, tab, req.user.id, function (err, topic) {
    if (err) {
      return next(err);
    }

    var proxy = new eventproxy();
    proxy.fail(next);

    proxy.all('score_saved', function () {
      res.send({
        success: true,
        topic_id: topic.id
      });
    });
    UserProxy.getUserById(req.user.id, proxy.done(function (user) {
      user.score += 5;
      user.topic_count += 1;
      user.save();
      req.user = user;
      proxy.emit('score_saved');
    }));

    //发送at消息
    at.sendMessageToMentionUsers(content, topic.id, req.user.id);
  });
Example #30
0
router.get('/good1', function (req, res) {

    var ep = new EventProxy();
    ep.on('done', function (a, b, c) {
        console.log(`${a} ${b} ${c}`);
        res.json({a, b, c});
    });

    ep.all('get-a', 'get-b', function (a, b) {
        // 发起add操作
        rest.post("http://localhost:3000/api/add", {data: {a, b}}).on("success", function (result) {
            console.log("result is ", result);
            let c = result.result;
            console.log(`got result: ${c}`);
            ep.emit('done', a, b, c);
        });
    });

    // 发起 geta
    rest.get("http://localhost:3000/api/get_a").on("success", function (result) {
        console.log("got a:", result.a);
        ep.emit("get-a", result.a);
    });

    // 发起getb
    rest.get("http://localhost:3000/api/get_b").on("success", function (result) {
        console.log("got b:", result.b);
        ep.emit("get-b", result.b);
    });

});