-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
653 lines (567 loc) · 21.4 KB
/
app.py
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# *------------------------------------------------------------------------------*
# GroupMe Archiver: A web application to store and display GroupMe group histories
# Copyright (C) 2016 Jordan Buchman
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# *------------------------------------------------------------------------------*
from flask import Flask, request, render_template
import psycopg2
from psycopg2.extras import RealDictCursor
import json
from datetime import datetime, timedelta
import arrow
import groupy
import schedule # mrhwick's fork on github
import threading
import time
import sys
group_jobs = []
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime):
serial = obj.isoformat()
return serial
raise TypeError("Type not serializable")
# http://codereview.stackexchange.com/a/37287
def verbose_timedelta(delta):
d = delta.days
h, s = divmod(delta.seconds, 3600)
m, s = divmod(s, 60)
labels = ['day', 'hour', 'minute', 'second']
dhms = ['%s %s%s' % (i, lbl, 's' if i != 1 else '')
for i, lbl in zip([d, h, m, s], labels)]
for start in range(len(dhms)):
if not dhms[start].startswith('0'):
break
for end in range(len(dhms) - 1, -1, -1):
if not dhms[end].startswith('0'):
break
return ', '.join(dhms[start:end + 1])
app = Flask(__name__, static_url_path='/static')
#app.debug = True
if len(sys.argv) == 4:
conn = psycopg2.connect(
database=sys.argv[1],
user=sys.argv[2],
password=sys.argv[3])
conn_args = {
'database': sys.argv[1],
'user': sys.argv[2],
'password': sys.argv[3]}
elif len(sys.argv) == 3:
conn = psycopg2.connect(database=sys.argv[1], user=sys.argv[2])
conn_args = {'database': sys.argv[1], 'user': sys.argv[2]}
elif len(sys.argv) == 2:
conn = psycopg2.connect(database=sys.argv[1])
conn_args = {'database': sys.argv[1]}
cur = conn.cursor(cursor_factory=RealDictCursor)
cur.execute("""
CREATE TABLE IF NOT EXISTS messages(
id text PRIMARY KEY,
name text,
message text,
attachments text[],
avatar_url text,
created_at timestamp with time zone,
user_id text,
group_id text,
likes text[]
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS members(
user_id text,
nickname text,
avatar text,
group_id text,
UNIQUE (user_id, group_id)
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS groups(
name text,
image_url text,
description text,
id text PRIMARY KEY,
type text
)
""")
def member_avatar(id):
cur.execute("SELECT avatar FROM members WHERE user_id = %s;", (id,))
return cur.fetchone()['avatar']
def member_nickname(id, group_id):
cur.execute(
"SELECT nickname FROM members WHERE user_id = %s AND group_id = %s;", (id, group_id))
return cur.fetchone()['nickname']
app.jinja_env.filters['member_avatar'] = member_avatar
app.jinja_env.filters['member_nickname'] = member_nickname
@app.template_test("image_attachment")
def is_image_attachment(attachment):
return attachment.startswith("Image")
def image_attachment_url(attachment):
return attachment.replace("Image(url='","").replace("')","")
app.jinja_env.filters['image_attachment_url'] = image_attachment_url
def handle_update_group(group_id, type, lock):
with lock:
cur = conn.cursor(cursor_factory=RealDictCursor)
if type == "group":
group = groupy.Group.list().filter(id=group_id).first
cur.execute(
"INSERT INTO groups VALUES (%s, %s, %s, %s, %s) ON CONFLICT (id) DO UPDATE SET name = %s, image_url = %s, description = %s",
(group.name,
group.image_url,
group.description,
group.id,
type,
group.name,
group.image_url,
group.description))
members = group.members()
cur.executemany("INSERT INTO members VALUES (%s, %s, %s, %s) ON CONFLICT (user_id, group_id) DO UPDATE SET nickname = %s, avatar = %s",
[(member.user_id,
member.nickname,
member.image_url,
group.id,
member.nickname,
member.image_url)
for member in members])
elif type == "member":
members = groupy.Member.list()
group = members.filter(user_id=group_id).first
cur.execute(
"INSERT INTO groups VALUES (%s, %s, %s, %s, %s) ON CONFLICT (id) DO UPDATE SET name = %s, image_url = %s, description = %s",
(group.messages().filter(user_id=group.user_id)[0].name,
group.image_url,
'',
group.user_id,
type,
group.messages().filter(user_id=group.user_id)[0].name,
group.image_url,
''))
cur.execute("INSERT INTO members VALUES (%s, %s, %s, %s) ON CONFLICT (user_id, group_id) DO UPDATE SET nickname = %s, avatar = %s",
(group.user_id,
group.messages().filter(
user_id=group.user_id)[0].name,
group.image_url,
group.user_id,
group.messages().filter(
user_id=group.user_id)[0].name,
group.image_url)
)
me = groupy.User.get()
cur.execute("INSERT INTO members VALUES (%s, %s, %s, %s) ON CONFLICT (user_id, group_id) DO UPDATE SET nickname = %s, avatar = %s",
(me.user_id,
me.name,
me.image_url,
group.user_id,
me.name,
me.image_url)
)
messages = group.messages()
cur.execute(
"SELECT id FROM messages WHERE group_id=%s ORDER BY id DESC LIMIT 1;",
(group_id,
))
try:
latest_id = cur.fetchone()['id']
except:
latest_id = None
x = 0
while messages.older():
try:
while messages.iolder():
x += 1
print(group_id, x)
if messages.filter(id=latest_id):
b = True
if b:
break
if b:
break
except:
pass
if type == "group":
cur.executemany("INSERT INTO messages VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING",
[(msg.id,
msg.name,
msg.text or '',
[str(x) for x in msg.attachments],
msg.avatar_url,
msg.created_at,
msg.user_id,
group.id,
msg.favorited_by)
for msg in messages])
elif type == "member":
cur.executemany("INSERT INTO messages VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING",
[(msg.id,
msg.name,
msg.text or '',
[str(x) for x in msg.attachments],
msg.avatar_url,
msg.created_at,
msg.user_id,
group.user_id,
msg.favorited_by)
for msg in messages])
conn.commit()
print("FINISHED ", group_id)
def handle_update_group_async(group_id, type, lock):
thread = threading.Thread(
target=handle_update_group, args=(
group_id, type, lock))
thread.daemon = True
thread.start()
cur.execute("SELECT id, type FROM groups;")
groups = cur.fetchall()
for group in groups:
print(group)
schedule.every(1).minutes.do(
handle_update_group_async,
group_id=group['id'],
type=group['type'],
lock=threading.Lock())
group_jobs.append(group['id'])
schedule.run_all()
schedule.run_continuously()
@app.route("/")
def index():
groups = groupy.Group.list()
members = groupy.Member.list()
return render_template("index.html",
groups=zip(
[g.name for g in groups], [g.id for g in groups]),
members=zip(
[g.nickname for g in members], [g.user_id for g in members])
)
@app.route("/add_group/<group_id>")
def add_group(group_id):
print(group_id)
type = request.args.get('type')
if type == "group":
group = groupy.Group.list().filter(id=group_id).first
elif type == "member":
group = groupy.Member.list().filter(user_id=group_id).first
if not group:
return render_template(
"layout.html", message="Error! Group ID not found."), 404
if group_id in group_jobs:
return render_template(
"layout.html",
message="Error! Group already added.")
schedule.every(1).minutes.do(
handle_update_group_async,
group_id=group_id,
type=type,
lock=threading.Lock())
group_jobs.append(group_id)
schedule.run_all()
if type == "group":
return render_template(
"layout.html",
message="Fetching group history, please wait. <br> Number of messages: {0}. <br> Estimated time for processing: {1}.".format(
group.message_count,
verbose_timedelta(
timedelta(
seconds=group.message_count /
100 *
1.1))))
elif type == "member":
return render_template(
"layout.html",
message="Fetching message history, please wait.")
@app.route("/groups/<group_id>/members/<member_id>")
def member(group_id, member_id):
num = int(request.args.get('num') if 'num' in request.args else 10)
offset = int(request.args.get('offset')) if 'offset' in request.args else 0
query = request.args.get('query') if 'query' in request.args else ''
msg_id = None
date_a = None
if 'date' in request.args:
date_a = arrow.get(request.args.get('date'), 'MM/DD/YYYY')
date = date_a.datetime
cur.execute(
"SELECT id FROM messages WHERE user_id=%s AND group_id=%s AND message ILIKE '%%' || %s || '%%' AND created_at >= %s ORDER BY id ASC LIMIT 1;",
(member_id,
group_id,
query,
date))
msg_id = cur.fetchone()['id']
if 'msg_id' in request.args or msg_id:
if offset < 0:
msg_id = msg_id if msg_id else int(request.args.get('msg_id'))
cur.execute(
"SELECT id FROM messages WHERE user_id=%s AND group_id=%s AND id::bigint >= %s AND message ILIKE '%%' || %s || '%%' ORDER BY id ASC OFFSET %s LIMIT 1;",
(member_id,
group_id,
msg_id,
query,
-offset))
try:
msg_id = cur.fetchone()['id']
except:
pass
offset = 0
msg_id = msg_id if msg_id else int(request.args.get('msg_id'))
cur.execute(
"SELECT * FROM messages WHERE user_id = %s AND group_id = %s AND id::bigint <= %s AND message ILIKE '%%' || %s || '%%' ORDER BY id DESC OFFSET %s LIMIT %s;",
(member_id,
group_id,
msg_id,
query,
offset,
num))
else:
offset = max(offset, 0)
cur.execute(
"SELECT * FROM messages WHERE user_id = %s AND group_id = %s AND message ILIKE '%%' || %s || '%%' ORDER BY id DESC OFFSET %s LIMIT %s;",
(member_id,
group_id,
query,
offset,
num))
data = cur.fetchall()
if not msg_id:
try:
msg_id = data[0]['id']
except:
pass
cur.execute(
"SELECT * FROM members WHERE user_id = %s AND group_id=%s;",
(member_id,
group_id))
print(
cur.mogrify(
"SELECT * FROM members WHERE user_id = %s AND group_id=%s;",
(member_id,
group_id)))
member = cur.fetchall()
cur.execute(
"SELECT created_at, id FROM messages WHERE user_id = %s AND group_id=%s AND message ILIKE '%%' || %s || '%%' ORDER BY created_at DESC LIMIT 1;",
(member_id,
group_id,
query))
end = cur.fetchone()
end_date = arrow.get(end['created_at']).format('MM/DD/YYYY')
end_id = end['id']
cur.execute(
"SELECT created_at, id FROM messages WHERE user_id = %s AND group_id=%s AND message ILIKE '%%' || %s || '%%' ORDER BY created_at ASC LIMIT 1;",
(member_id,
group_id,
query))
start = cur.fetchone()
start_date = arrow.get(start['created_at']).format('MM/DD/YYYY')
start_id = start['id']
return render_template(
"member.html",
messages=data[
::-1],
member=(
member[0] if len(member) > 0 else {}),
id=member_id,
offset=offset,
num=num,
query=query,
group_id=group_id,
msg_id=msg_id,
date=date_a.format('MM/DD/YYYY') if date_a else '',
start_date=start_date,
end_date=end_date,
start_id=start_id,
end_id=end_id)
@app.route("/groups/<group_id>/members")
def members(group_id):
cur.execute("SELECT * FROM members WHERE group_id = %s;", (group_id,))
members = cur.fetchall()
return render_template("members.html", members=members)
@app.route("/groups")
def groups():
cur.execute("SELECT * FROM groups WHERE type = 'group';")
groups = cur.fetchall()
return render_template("groups.html", groups=groups, type="Group")
@app.route("/members")
def p_members():
cur.execute("SELECT * FROM groups WHERE type = 'member';")
groups = cur.fetchall()
return render_template("groups.html", groups=groups, type="Member")
@app.route("/groups/<group_id>")
def group(group_id):
num = int(request.args.get('num') if 'num' in request.args else 10)
offset = int(request.args.get('offset') if 'offset' in request.args else 0)
query = request.args.get('query') if 'query' in request.args else ''
msg_id = None
date_a = None
if 'date' in request.args:
date_a = arrow.get(request.args.get('date'), 'MM/DD/YYYY')
date = date_a.datetime
cur.execute(
"SELECT id FROM messages WHERE group_id=%s AND message ILIKE '%%' || %s || '%%' AND created_at >= %s ORDER BY id ASC LIMIT 1;",
(group_id,
query,
date))
msg_id = cur.fetchone()['id']
if 'msg_id' in request.args or msg_id:
if offset < 0:
msg_id = msg_id if msg_id else int(request.args.get('msg_id'))
cur.execute(
"SELECT id FROM messages WHERE group_id=%s AND id::bigint >= %s AND message ILIKE '%%' || %s || '%%' ORDER BY id ASC OFFSET %s LIMIT 1;",
(group_id,
msg_id,
query,
-offset))
try:
msg_id = cur.fetchone()['id']
except:
pass
offset = 0
msg_id = msg_id if msg_id else int(request.args.get('msg_id'))
cur.execute(
"SELECT * FROM messages WHERE group_id=%s AND id::bigint <= %s AND message ILIKE '%%' || %s || '%%' ORDER BY id DESC OFFSET %s LIMIT %s;",
(group_id,
msg_id,
query,
offset,
num))
else:
offset = max(offset, 0)
cur.execute(
"SELECT * FROM messages WHERE group_id=%s AND message ILIKE '%%' || %s || '%%' ORDER BY id DESC OFFSET %s LIMIT %s;",
(group_id,
query,
offset,
num))
data = cur.fetchall()
if not msg_id:
try:
msg_id = data[0]['id']
except:
pass
cur.execute("SELECT * FROM groups WHERE id = %s;", (group_id,))
group = cur.fetchone()
cur.execute(
"SELECT created_at, id FROM messages WHERE group_id=%s AND message ILIKE '%%' || %s || '%%' ORDER BY created_at DESC LIMIT 1;",
(group_id,
query))
end = cur.fetchone()
end_date = arrow.get(end['created_at']).format('MM/DD/YYYY')
end_id = end['id']
cur.execute(
"SELECT created_at, id FROM messages WHERE group_id=%s AND message ILIKE '%%' || %s || '%%' ORDER BY created_at ASC LIMIT 1;",
(group_id,
query))
start = cur.fetchone()
start_date = arrow.get(start['created_at']).format('MM/DD/YYYY')
start_id = start['id']
return render_template(
"group.html",
messages=data[
::-1],
group=group,
group_id=group_id,
offset=offset,
num=num,
query=query,
msg_id=msg_id,
date=date_a.format('MM/DD/YYYY') if date_a else '',
start_date=start_date,
end_date=end_date,
start_id=start_id,
end_id=end_id)
@app.route("/messages")
def messages():
cur.execute("SELECT * FROM private_members;")
private_members = cur.fetchall()
return render_template("groups.html", groups=private_members)
@app.route("/messages/<group_id>")
def private_messages(group_id):
num = int(request.args.get('num') if 'num' in request.args else 10)
offset = int(request.args.get('offset') if 'offset' in request.args else 0)
query = request.args.get('query') if 'query' in request.args else ''
msg_id = None
date_a = None
if 'date' in request.args:
date_a = arrow.get(request.args.get('date'), 'MM/DD/YYYY')
date = date_a.datetime
cur.execute(
"SELECT id FROM messages WHERE group_id=%s AND message ILIKE '%%' || %s || '%%' AND created_at >= %s ORDER BY id ASC LIMIT 1;",
(group_id,
query,
date))
msg_id = cur.fetchone()['id']
if 'msg_id' in request.args or msg_id:
if offset < 0:
msg_id = msg_id if msg_id else int(request.args.get('msg_id'))
cur.execute(
"SELECT id FROM messages WHERE group_id=%s AND id::bigint >= %s AND message ILIKE '%%' || %s || '%%' ORDER BY id ASC OFFSET %s LIMIT 1;",
(group_id,
msg_id,
query,
-offset))
try:
msg_id = cur.fetchone()['id']
except:
pass
offset = 0
msg_id = msg_id if msg_id else int(request.args.get('msg_id'))
cur.execute(
"SELECT * FROM messages WHERE group_id=%s AND id::bigint <= %s AND message ILIKE '%%' || %s || '%%' ORDER BY id DESC OFFSET %s LIMIT %s;",
(group_id,
msg_id,
query,
offset,
num))
else:
offset = max(offset, 0)
cur.execute(
"SELECT * FROM messages WHERE group_id=%s AND message ILIKE '%%' || %s || '%%' ORDER BY id DESC OFFSET %s LIMIT %s;",
(group_id,
query,
offset,
num))
data = cur.fetchall()
if not msg_id:
try:
msg_id = data[0]['id']
except:
pass
cur.execute("SELECT * FROM groups WHERE id = %s;", (group_id,))
group = cur.fetchone()
cur.execute(
"SELECT created_at, id FROM messages WHERE group_id=%s AND message ILIKE '%%' || %s || '%%' ORDER BY created_at DESC LIMIT 1;",
(group_id,
query))
end = cur.fetchone()
end_date = arrow.get(end['created_at']).format('MM/DD/YYYY')
end_id = end['id']
cur.execute(
"SELECT created_at, id FROM messages WHERE group_id=%s AND message ILIKE '%%' || %s || '%%' ORDER BY created_at ASC LIMIT 1;",
(group_id,
query))
start = cur.fetchone()
start_date = arrow.get(start['created_at']).format('MM/DD/YYYY')
start_id = start['id']
return render_template(
"group.html",
messages=data[
::-1],
group=group,
group_id=group_id,
offset=offset,
num=num,
query=query,
msg_id=msg_id,
date=date_a.format('MM/DD/YYYY') if date_a else '',
start_date=start_date,
end_date=end_date,
start_id=start_id,
end_id=end_id)
if __name__ == "__main__":
app.run()