/
gpindex_common.js
343 lines (317 loc) · 9.88 KB
/
gpindex_common.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
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
const EventEmitter = require('events');
const r = require('rethinkdb')
const Segment = require('segment')
const config = require('../config.gpindex.json')['gpindex_db']
const event = new EventEmitter();
const segment = new Segment()
var db_conn
var queue = {
public: [],
private: {},
private_update: {}
};
var lock = {}
const sortFunc = {
count_asc: 'member_count',
count_desc: r.desc('member_count'),
id_asc: 'id',
id_desc: r.desc('id'),
title_asc: 'title',
title_desc: r.desc('title')
}
function truncateSearch(term) {
return term.replace(/[-[\]{}()*+?.,\\^$|#]/g, '\\$&')
}
// Flag User
async function setUserFlag(uid, flag, value) {
if (!db_conn) throw new Error('databaseNotConnected');
let user = await r.table('userdata').get(parseInt(uid)).run(db_conn)
let updation = {}
if (Array.isArray(flag) && Array.isArray(value)) {
for (let i of flag) {
updation[i] = value[flag.indexOf(i)]
}
} else {
updation[flag] = value
}
if (user)
return r.table('userdata').get(parseInt(uid)).update(updation).run(db_conn);
else {
updation.id = parseInt(uid)
return r.table('userdata').insert(updation).run(db_conn);
}
}
async function queryUserFlag(uid, flag) {
if (!db_conn) throw new Error('databaseNotConnected');
let result
if (Array.isArray(flag)) {
let flag_obj = await r.table('userdata').get(parseInt(uid)).default({}).run(db_conn)
result = []
for (let i of flag) {
result[flag.indexOf(i)] = flag_obj[i]
}
return result
} else {
let flag_obj = await r.table('userdata').get(parseInt(uid)).default({}).run(db_conn)
return flag_obj[flag] || false
}
}
async function queryUserFlagAll(uid) {
if (!db_conn) throw new Error('databaseNotConnected');
return r.table('userdata').get(parseInt(uid)).default({}).without('id').run(db_conn)
}
async function removeUserFlag(uid, flag) {
let updation = {}
if (Array.isArray(flag)) {
for (let i of flag) {
updation[i] = r.literal()
}
} else {
updation[flag] = r.literal()
}
return r.table('userdata').get(parseInt(uid)).update(updation)
}
// Group Extra Tag
async function setGroupExTag(gid, flag, value) {
if (!db_conn) throw new Error('databaseNotConnected');
let group = await r.table('groupextag').get(parseInt(gid)).run(db_conn)
let updation = {}
if (Array.isArray(flag) && Array.isArray(value)) {
for (let i of flag) {
updation[i] = value[flag.indexOf(i)]
}
} else {
updation[flag] = value
}
if (group)
return r.table('groupextag').get(parseInt(gid)).update(updation).run(db_conn);
else {
updation.id = parseInt(gid)
return r.table('groupextag').insert(updation).run(db_conn);
}
}
async function queryGroupExTag(gid, flag) {
if (!db_conn) throw new Error('databaseNotConnected');
let result
if (Array.isArray(flag)) {
let flag_obj = await r.table('groupextag').get(parseInt(gid)).default({}).run(db_conn)
result = []
for (let i of flag) {
result[flag.indexOf(i)] = flag_obj[i]
}
return result
} else {
let flag_obj = await r.table('groupextag').get(parseInt(gid)).default({}).run(db_conn)
return flag_obj[flag] || false
}
}
async function queryGroupExTagAll(gid) {
if (!db_conn) throw new Error('databaseNotConnected');
return r.table('groupextag').get(parseInt(gid)).default({}).without('id').run(db_conn)
}
function setLock(uid) {
lock[uid] = true;
}
function unsetLock(uid) {
lock[uid] = false;
delete lock[uid];
}
function getLock(uid) {
return !!lock[uid];
}
async function getRecord(group) {
if (!db_conn) throw new Error('databaseNotConnected');
var gid = parseInt(group);
let result = await r.table('groups').get(gid).default({}).merge(function (g) {
return {
"extag": r.table('groupextag').get(g('id')).default({}).without('id')
}
}).run(db_conn)
return result.id ? result : false
}
async function getRecByTag(tag, offset, length, sortfunc) {
if (!db_conn) throw new Error('databaseNotConnected');
let req = r.table('groups')
req = req.getAll(tag, {
index: 'tag'
}).default([]).merge(function (g) {
return {
"extag": r.table('groupextag').get(g('id')).default({}).without('id')
}
})
if (sortfunc) {
req = req.orderBy(sortFunc[sortfunc])
}
if ((offset !== null || offset !== undefined) && length) {
req = req.slice(offset, offset + length)
}
let results = await (await req.run(db_conn)).toArray()
return results
}
async function getRecByCreator(uid) {
if (!db_conn) throw new Error('databaseNotConnected');
let results = await (await r.table('groups').filter({
creator: uid
}).default([]).merge(function (g) {
return {
"extag": r.table('groupextag').get(g('id')).default({}).without('id')
}
}).run(db_conn)).toArray()
return results
}
async function searchByName(term, offset, length, sortfunc, noautosplit, notruncate) {
if (!db_conn) throw new Error('databaseNotConnected');
let search
if (!Array.isArray(term)) {
if (!noautosplit) {
search = segment.doSegment(term, {
simple: true
})
} else {
search = term.split(/[\s,]/)
}
} else {
search = term
}
search = search.map(a => a.normalize())
if (!notruncate) search = search.map(truncateSearch)
let req = r.table('groups')
for (let i of search) {
req = req.filter(function (g) {
return g('title').add(g('desc')).match('(?i)' + i)
})
}
req = req.default([]).merge(function (g) {
return {
"extag": r.table('groupextag').get(g('id')).default({}).without('id')
}
})
if (sortfunc) {
req = req.orderBy(sortFunc[sortfunc])
}
if ((offset !== null || offset !== undefined) && length) {
req = req.slice(offset, offset + length)
}
let results = await (await req.run(db_conn)).toArray()
return results
}
async function doEnrollment(groupinfo) {
if (groupinfo.is_public) {
queue.public.push(groupinfo);
event.emit('new_public_queue', groupinfo);
return 'new_public_queue';
} else {
if (groupinfo.is_update) queue.private_update[groupinfo.id] = groupinfo;
else queue.private[groupinfo.id] = groupinfo;
event.emit('new_private_queue', groupinfo);
return 'new_private_queue';
}
}
async function doRemoval(group) {
try {
var gid = parseInt(group)
event.emit('removed', {id: gid})
return r.table('groups').get(gid).delete().run(db_conn);
} catch (e) {
console.error(e);
}
}
async function commitPublic() {
if (queue.public.length > 0) {
var groupcursor = queue.public.shift();
if (groupcursor.is_update) {
delete groupcursor.is_update
var _is_silent = groupcursor.is_silent
delete groupcursor.is_silent
return r.table('groups').get(parseInt(groupcursor.id)).update(groupcursor).run(db_conn)
.then((ret) => {
if (!_is_silent) event.emit('update_public_data', groupcursor);
return ret;
});
} else {
return r.table('groups').insert(groupcursor).run(db_conn)
.then((ret) => {
event.emit('new_public_commit', groupcursor);
return ret;
});
}
} else {
return false;
}
}
async function doValidate(gid, is_update, is_silent) {
if (!db_conn) throw new Error('databaseNotConnected');
var groupcursor = is_update ? queue.private_update[gid] : queue.private[gid];
if (is_update) {
delete groupcursor.is_update;
return r.table('groups').get(groupcursor.id).update(groupcursor).run(db_conn)
.then((ret) => {
if (!is_silent) event.emit('update_private_data', groupcursor);
return ret;
});
} else {
return r.table('groups').insert(groupcursor).run(db_conn)
.then((ret) => {
if (!is_silent) event.emit('new_private_commit', groupcursor);
return ret;
})
}
}
async function silentInsert(groupinfo) {
if (!db_conn) throw new Error('databaseNotConnected');
return r.table('groups').insert(groupinfo).run(db_conn)
}
async function silentUpdate(id, updation) {
if (!db_conn) throw new Error('databaseNotConnected');
return r.table('groups').get(parseInt(id)).update(updation).run(db_conn)
}
async function init() {
console.log(config);
try {
const conn = await r.connect(config)
db_conn = conn
conn.addListener('close', () => {
// notify admin about connection close
console.error('Reconnecting DB.')
conn.reconnect();
});
console.log('connected')
segment.useDefault()
} catch (e) {
console.error('Unable to connect to DB.')
process.exit(1)
}
setInterval(commitPublic, 1000)
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection \n', reason.stack);
// application specific logging, throwing an error, or other logic here
});
}
module.exports = {
event,
init,
doEnrollment,
getRecord,
getRecByTag,
getRecByCreator,
searchByName,
doValidate,
doRemoval,
commitPublic,
silentInsert,
silentUpdate,
setLock,
getLock,
unsetLock,
UserFlag: {
setUserFlag,
queryUserFlag,
queryUserFlagAll,
removeUserFlag
},
GroupExTag: {
setGroupExTag,
queryGroupExTag,
queryGroupExTagAll
}
}