forked from cnodejs/nodeclub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.js
106 lines (101 loc) · 2.84 KB
/
message.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
var Message = require('../proxy').Message;
var EventProxy = require('eventproxy');
exports.index = function (req, res, next) {
if (!req.session.user) {
res.redirect('home');
return;
}
var message_ids = [];
var user_id = req.session.user._id;
Message.getMessagesByUserId(user_id, function (err, docs) {
if (err) {
return next(err);
}
for (var i = 0; i < docs.length; i++) {
message_ids.push(docs[i]._id);
}
var messages = [];
if (message_ids.length === 0) {
res.render('message/index', {has_read_messages: [], hasnot_read_messages: []});
return;
}
var proxy = new EventProxy();
var render = function () {
var has_read_messages = [];
var hasnot_read_messages = [];
for (var i = 0; i < messages.length; i++) {
if (messages[i].is_invalid) {
messages[i].remove();
} else {
if (messages[i].has_read) {
has_read_messages.push(messages[i]);
} else {
hasnot_read_messages.push(messages[i]);
}
}
}
res.render('message/index', {has_read_messages: has_read_messages, hasnot_read_messages: hasnot_read_messages});
return;
};
proxy.after('message_ready', message_ids.length, render);
message_ids.forEach(function (id, i) {
Message.getMessageById(id, function (err, message) {
if (err) {
return next(err);
}
messages[i] = message;
proxy.emit('message_ready');
});
});
});
};
exports.mark_read = function (req, res, next) {
if (!req.session || !req.session.user) {
res.send('forbidden!');
return;
}
var message_id = req.body.message_id;
Message.getMessageById(message_id, function (err, message) {
if (err) {
return next(err);
}
if (!message) {
res.json({status: 'failed'});
return;
}
if (message.master_id.toString() !== req.session.user._id.toString()) {
res.json({status: 'failed'});
return;
}
message.has_read = true;
message.save(function (err) {
if (err) {
return next(err);
}
res.json({status: 'success'});
});
});
};
exports.mark_all_read = function (req, res, next) {
if (!req.session || !req.session.user) {
res.send('forbidden!');
return;
}
// TODO: 直接做update,无需查找然后再逐个修改。
Message.getUnreadMessageByUserId(req.session.user._id, function (err, messages) {
if (messages.length === 0) {
res.json({'status': 'success'});
return;
}
var proxy = new EventProxy();
proxy.after('marked', messages.length, function () {
res.json({'status': 'success'});
});
proxy.fail(next);
for (var i = 0; i < messages.length; i++) {
var message = messages[i];
message.has_read = true;
message.save(proxy.done('marked'));
}
});
};