summaryrefslogtreecommitdiff
path: root/lib/history.js
blob: 2723422c23575b06d6e090e6efec35c6c5362b57 (plain)
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
//history
//external modules
var async = require('async');
var moment = require('moment');

//core
var config = require("./config.js");
var logger = require("./logger.js");
var response = require("./response.js");
var models = require("./models");

//public
var History = {
    historyGet: historyGet,
    historyPost: historyPost,
    historyDelete: historyDelete,
    isReady: isReady,
    updateHistory: updateHistory
};

var caches = {};
//update when the history is dirty
var updater = setInterval(function () {
    var deleted = [];
    async.each(Object.keys(caches), function (key, callback) {
        var cache = caches[key];
        if (cache.isDirty) {
            if (config.debug) logger.info("history updater found dirty history: " + key);
            var history = parseHistoryToArray(cache.history);
            cache.isDirty = false;
            finishUpdateHistory(key, history, function (err, count) {
                if (err) return callback(err, null);
                if (!count) return callback(null, null);
                cache.updateAt = Date.now();
                return callback(null, null);
            });
        } else {
            if (moment().isAfter(moment(cache.updateAt).add(5, 'minutes'))) {
                deleted.push(key);
            }
            return callback(null, null);
        }
    }, function (err) {
        if (err) return logger.error('history updater error', err);
    });
    // delete specified caches
    for (var i = 0, l = deleted.length; i < l; i++) {
        caches[deleted[i]].history = {};
        delete caches[deleted[i]];
    }
}, 1000);

function finishUpdateHistory(userid, history, callback) {
    models.User.update({
        history: JSON.stringify(history)
    }, {
        where: {
            id: userid
        }
    }).then(function (count) {
        return callback(null, count);
    }).catch(function (err) {
        return callback(err, null);
    });
}

function isReady() {
    var dirtyCount = 0;
    async.each(Object.keys(caches), function (key, callback) {
        if (caches[key].isDirty) dirtyCount++;
        return callback(null, null);
    }, function (err) {
        if (err) return logger.error('history ready check error', err);
    });
    return dirtyCount > 0 ? false : true;
}

function getHistory(userid, callback) {
    if (caches[userid]) {
        return callback(null, caches[userid].history);
    } else {
        models.User.findOne({
            where: {
                id: userid
            }
        }).then(function (user) {
            if (!user)
                return callback(null, null);
            var history = [];
            if (user.history)
                history = JSON.parse(user.history);
            if (config.debug)
                logger.info('read history success: ' + user.id);
            setHistory(userid, history);
            return callback(null, history);
        }).catch(function (err) {
            logger.error('read history failed: ' + err);
            return callback(err, null);
        });   
    }
}

function setHistory(userid, history) {
    if (Array.isArray(history)) history = parseHistoryToObject(history);
    if (!caches[userid]) {
        caches[userid] = {
            history: {},
            isDirty: false,
            updateAt: Date.now()
        };
    }
    caches[userid].history = history;
}

function updateHistory(userid, noteId, document) {
    if (userid && noteId && typeof document !== 'undefined') {
        getHistory(userid, function (err, history) {
            if (err || !history) return;
            if (!caches[userid].history[noteId]) {
                caches[userid].history[noteId] = {};
            }
            var noteHistory = caches[userid].history[noteId];
            var noteInfo = models.Note.parseNoteInfo(document);
            noteHistory.id = noteId;
            noteHistory.text = noteInfo.title;
            noteHistory.time = moment().valueOf();
            noteHistory.tags = noteInfo.tags;
            caches[userid].isDirty = true;
        });
    }
}

function parseHistoryToArray(history) {
    var _history = [];
    Object.keys(history).forEach(function (key) {
        var item = history[key];
        _history.push(item);
    });
    return _history;
}

function parseHistoryToObject(history) {
    var _history = {};
    for (var i = 0, l = history.length; i < l; i++) {
        var item = history[i];
        _history[item.id] = item;
    }
    return _history;
}

function historyGet(req, res) {
    if (req.isAuthenticated()) {
        getHistory(req.user.id, function (err, history) {
            if (err) return response.errorInternalError(res);
            if (!history) return response.errorNotFound(res);
            res.send({
                history: parseHistoryToArray(history)
            });
        });
    } else {
        return response.errorForbidden(res);
    }
}

function historyPost(req, res) {
    if (req.isAuthenticated()) {
        var noteId = req.params.noteId;
        if (!noteId) {
            if (typeof req.body['history'] === 'undefined') return response.errorBadRequest(res);
            if (config.debug)
                logger.info('SERVER received history from [' + req.user.id + ']: ' + req.body.history);
            try {
                var history = JSON.parse(req.body.history);
            } catch (err) {
                return response.errorBadRequest(res);
            }
            if (Array.isArray(history)) {
                setHistory(req.user.id, history);
                caches[req.user.id].isDirty = true;
                res.end();
            } else {
                return response.errorBadRequest(res);
            }
        } else {
            if (typeof req.body['pinned'] === 'undefined') return response.errorBadRequest(res);
            getHistory(req.user.id, function (err, history) {
                if (err) return response.errorInternalError(res);
                if (!history) return response.errorNotFound(res);
                if (!caches[req.user.id].history[noteId]) return response.errorNotFound(res);
                if (req.body.pinned === 'true' || req.body.pinned === 'false') {
                    caches[req.user.id].history[noteId].pinned = (req.body.pinned === 'true');
                    caches[req.user.id].isDirty = true;
                    res.end();
                } else {
                    return response.errorBadRequest(res);
                }
            });
        }
    } else {
        return response.errorForbidden(res);
    }
}

function historyDelete(req, res) {
    if (req.isAuthenticated()) {
        var noteId = req.params.noteId;
        if (!noteId) {
            setHistory(req.user.id, []);
            caches[req.user.id].isDirty = true;
            res.end();
        } else {
            getHistory(req.user.id, function (err, history) {
                if (err) return response.errorInternalError(res);
                if (!history) return response.errorNotFound(res);
                delete caches[req.user.id].history[noteId];
                caches[req.user.id].isDirty = true;
                res.end();
            });
        }
    } else {
        return response.errorForbidden(res);
    }
}

module.exports = History;