-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogic.py
1932 lines (1663 loc) · 68.8 KB
/
logic.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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import csv
import hashlib
import json
import re
import time
import uuid
from threading import Thread
from urllib.parse import urlparse
from datetime import datetime, timedelta
import facebook
import praw
import psycopg2
import pymongo
import requests
import tweepy
from decouple import config
import delete_community
from application.Connections import Connection
from application.utils import general
from application.utils import twitter_search_sample_tweets
from crontab_module.crons import facebook_reddit_crontab
# Accessing Twitter API
consumer_key = config("TWITTER_CONSUMER_KEY") # API key
consumer_secret = config("TWITTER_CONSUMER_SECRET") # API secret
access_token = config("TWITTER_ACCESS_TOKEN")
access_secret = config("TWITTER_ACCESS_SECRET")
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
# from http://www.pythoncentral.io/hashing-strings-with-python/
def hash_password(password):
# uuid is used to generate a random number
salt = uuid.uuid4().hex
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
# from http://www.pythoncentral.io/hashing-strings-with-python/
def check_password(hashed_password, user_password):
password, salt = hashed_password.split(':')
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()
def set_current_topic(user_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT topic_id "
"FROM user_topic "
"WHERE user_id = %s"
)
cur.execute(sql, [int(user_id)])
topics = cur.fetchall()
sql = (
"SELECT topic_id "
"FROM user_topic_subscribe "
"WHERE user_id = %s"
)
cur.execute(sql, [int(user_id)])
subscribed_topics = cur.fetchall()
topics = topics + subscribed_topics
sql = (
"SELECT current_topic_id "
"FROM users "
"WHERE user_id = %s"
)
cur.execute(sql, [int(user_id)])
user = cur.fetchall()
if user[0][0] is None and len(topics) != 0:
sql = (
"UPDATE users "
"SET current_topic_id = %s "
"WHERE user_id = %s"
)
cur.execute(sql, [topics[0][0], int(user_id)])
elif len(topics) == 0:
sql = (
"UPDATE users "
"SET current_topic_id = %s "
"WHERE user_id = %s"
)
cur.execute(sql, [None, int(user_id)])
def get_current_location(user_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT current_location "
"FROM users "
"WHERE user_id = %s"
)
cur.execute(sql, [int(user_id)])
user_location = cur.fetchone()
if user_location[0] is None:
sql = (
"UPDATE users "
"SET current_location = %s "
"WHERE user_id = %s"
)
cur.execute(sql, ['italy', int(user_id)])
return 'italy'
return user_location[0]
def save_topic_id(topic_id, user_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"UPDATE users "
"SET current_topic_id = %s "
"WHERE user_id = %s"
)
cur.execute(sql, [int(topic_id), int(user_id)])
def save_location(location, user_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"UPDATE users "
"SET current_location = %s "
"WHERE user_id = %s"
)
cur.execute(sql, [location, int(user_id)])
def get_current_topic(user_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT current_topic_id "
"FROM users "
"WHERE user_id = %s"
)
cur.execute(sql, [int(user_id)])
user = cur.fetchall()
if user[0][0] is not None:
sql = (
"SELECT topic_id, topic_name "
"FROM topics "
"WHERE topic_id = %s"
)
cur.execute(sql, [int(user[0][0])])
topic = cur.fetchall()
return {'topic_id': topic[0][0], 'topic_name': topic[0][1]}
else:
return None
def add_facebook_pages_and_subreddits(topic_id, topic_list):
print(topic_list)
sources = source_selection(topic_list)
with Connection.Instance().get_cursor() as cur:
for facebook_page_id in sources['pages']:
sql = (
"INSERT INTO topic_facebook_page "
"(topic_id, facebook_page_id) "
"VALUES (%s, %s)"
)
cur.execute(sql, [int(topic_id), facebook_page_id['page_id']])
for subreddit in sources['subreddits']:
sql = (
"INSERT INTO topic_subreddit "
"(topic_id, subreddit) "
"VALUES (%s, %s)"
)
cur.execute(sql, [int(topic_id), subreddit])
pages = [facebook_page_id['page_id'] for facebook_page_id in sources['pages']]
subreddits = [subreddit for subreddit in sources['subreddits']]
facebook_reddit_crontab.triggerOneTopic(topic_id, topic_list, list(set(pages)), list(set(subreddits)))
def source_selection(topic_list):
return {'pages': source_selection_from_facebook(topic_list),
'subreddits': source_selection_from_reddit(topic_list)}
def source_selection_from_facebook(topic_list):
my_token = config("FACEBOOK_TOKEN")
graph = facebook.GraphAPI(access_token=my_token, version="2.7")
pages = []
for topic in topic_list:
s = graph.get_object("search?q=" + topic + "&type=page&limit=3")
for search in s["data"]:
pages.append({"page_id": search["id"], "page_name": search["name"]})
s = graph.get_object("search?q=" + topic + "&type=group&limit=3")
for search in s["data"]:
if search["privacy"] == "OPEN":
pages.append({"page_id": search["id"], "page_name": search["name"]})
return [i for n, i in enumerate(pages) if i not in pages[n + 1:]]
def source_selection_from_reddit(topic_list):
keys = {
'client_id': config("REDDIT_CLIENT_ID"),
'client_secret': config("REDDIT_CLIENT_SECRET"),
'user_agent': config("REDDIT_USER_AGENT"),
'api_type': 'json'
}
reddit = praw.Reddit(client_id=keys["client_id"],
client_secret=keys["client_secret"],
user_agent=keys["user_agent"],
api_type=keys["api_type"])
all_subreddits = []
for topic in topic_list:
subreddits = reddit.subreddits.search_by_name(topic)
if " " in topic:
subreddits.extend(reddit.subreddits.search_by_name(topic.replace(" ", "_")))
subreddits.extend(reddit.subreddits.search_by_name(topic.replace(" ", "")))
subreddits = set([sub.display_name for sub in subreddits])
all_subreddits = list(set(all_subreddits + list(subreddits)))
return all_subreddits
def get_topic_limit(user_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT alertlimit "
"FROM users "
"WHERE user_id = %s"
)
cur.execute(sql, [int(user_id)])
fetched = cur.fetchall()
return fetched[0][0]
def register(username, password, country_code):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT EXISTS (SELECT 1 FROM users where username = %s)"
)
cur.execute(sql, [username])
fetched = cur.fetchone()
if fetched[0]:
return {'response': False, 'error_type': 1, 'message': 'Username already taken.'}
sql = (
"SELECT NOT EXISTS (SELECT 1 FROM country_code where country_code = %s)"
)
cur.execute(sql, [country_code])
fetched = cur.fetchone()
if fetched[0]:
return {'response': False, 'error_type': 2, 'message': 'Invalid country code.'}
password = hash_password(password)
sql = (
"INSERT INTO users "
"(username, password, alertlimit, country_code) "
"VALUES (%s, %s, %s, %s)"
)
cur.execute(sql, [username, password, 5, country_code])
sql = (
"SELECT * "
"FROM users "
"WHERE username = %s"
)
cur.execute(sql, [username])
fetched = cur.fetchall()
return {'response': True, 'user_id': fetched[0][0]}
def get_user(user_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT username, country_code "
"FROM users "
"WHERE user_id = %s"
)
cur.execute(sql, [user_id])
fetched = cur.fetchone()
country = ""
if fetched[1] is not None:
country = fetched[1]
return {'username': fetched[0], 'country': country}
def update_twitter_auth(user_id, auth_token, twitter_pin):
with Connection.Instance().get_cursor() as cur:
consumer_key = config("TWITTER_CONSUMER_KEY")
consumer_secret = config("TWITTER_CONSUMER_SECRET")
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.request_token = eval(auth_token)
auth.secure = True
token = auth.get_access_token(verifier=twitter_pin)
if twitter_pin != '' and len(token) == 2:
auth.set_access_token(token[0], token[1])
api = tweepy.API(auth)
user = api.me()._json
profile_image_url = user['profile_image_url_https']
screen_name = user['screen_name']
user_name = user['name']
twitter_id = user['id_str']
sql = (
"SELECT NOT EXISTS (SELECT 1 FROM user_twitter where user_id = %s)"
)
cur.execute(sql, [user_id])
fetched = cur.fetchone()
if fetched[0]:
sql = (
"INSERT INTO user_twitter "
"(user_id, access_token, access_token_secret, profile_image_url, user_name, screen_name, twitter_id) "
"VALUES (%s, %s, %s, %s, %s, %s, %s)"
)
cur.execute(sql, [user_id, token[0], token[1], profile_image_url, user_name, screen_name, twitter_id])
else:
sql = (
"UPDATE user_twitter "
"SET access_token = %s, access_token_secret = %s, profile_image_url = %s, "
"user_name = %s, screen_name = %s, twitter_id = %s "
"WHERE user_id = %s"
)
cur.execute(sql, [token[0], token[1], profile_image_url, user_name, screen_name, twitter_id, user_id])
return {'response': True}
def update_user(user_id, password, country_code, auth_token, twitter_pin):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT NOT EXISTS (SELECT 1 FROM country_code where country_code = %s)"
)
cur.execute(sql, [country_code])
fetched = cur.fetchone()
if fetched[0]:
return {'response': False, 'error_type': 1, 'message': 'Invalid country code.'}
consumer_key = config("TWITTER_CONSUMER_KEY")
consumer_secret = config("TWITTER_CONSUMER_SECRET")
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.request_token = eval(auth_token)
auth.secure = True
token = auth.get_access_token(verifier=twitter_pin)
if twitter_pin != '' and len(token) == 2:
auth.set_access_token(token[0], token[1])
api = tweepy.API(auth)
user = api.me()._json
profile_image_url = user['profile_image_url_https']
screen_name = user['screen_name']
user_name = user['name']
twitter_id = user['id_str']
sql = (
"SELECT NOT EXISTS (SELECT 1 FROM user_twitter where user_id = %s)"
)
cur.execute(sql, [user_id])
fetched = cur.fetchone()
if fetched[0]:
sql = (
"INSERT INTO user_twitter "
"(user_id, access_token, access_token_secret, profile_image_url, user_name, screen_name, twitter_id) "
"VALUES (%s, %s, %s, %s, %s, %s, %s)"
)
cur.execute(sql, [user_id, token[0], token[1], profile_image_url, user_name, screen_name, twitter_id])
else:
sql = (
"UPDATE user_twitter "
"SET access_token = %s, access_token_secret = %s, profile_image_url = %s, "
"user_name = %s, screen_name = %s, twitter_id = %s "
"WHERE user_id = %s"
)
cur.execute(sql, [token[0], token[1], profile_image_url, user_name, screen_name, twitter_id, user_id])
else:
sql = (
"UPDATE users "
"SET password = %s, country_code = %s "
"WHERE user_id = %s"
)
cur.execute(sql, [password, country_code, user_id])
return {'response': True}
def login(username, password):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT * "
"FROM users "
"WHERE username = %s"
)
cur.execute(sql, [username])
fetched = cur.fetchall()
if len(fetched) == 0:
return {'response': False, 'error_type': 1, 'message': 'Invalid username'}
if not check_password(fetched[0][2], str(password)):
return {'response': False, 'error_type': 2, 'message': 'Invalid password'}
return {'response': True, 'user_id': fetched[0][0]}
def get_all_running_topics_list():
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT * "
"FROM topics "
"WHERE is_running = %s"
)
cur.execute(sql, [True])
var = cur.fetchall()
alerts = [
{'alertid': i[0], 'name': i[1], 'description': i[2], 'keywords': sorted(i[3].split(",")),
'lang': sorted(i[4].split(","))}
for i in var]
return sorted(alerts, key=lambda k: k['alertid'])
def get_topic_list(user_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT topic_id FROM user_topic WHERE user_id = %s ;"
)
cur.execute(sql, [user_id])
var = cur.fetchall()
own_topic_ids = [i[0] for i in var]
sql = (
"SELECT topic_id FROM user_topic_subscribe WHERE user_id = %s ;"
)
cur.execute(sql, [user_id])
var = cur.fetchall()
subscribe_topic_ids = [i[0] for i in var]
sql = (
"SELECT topic_id FROM user_topic WHERE user_id != %s ;"
)
cur.execute(sql, [user_id])
var = cur.fetchall()
remaining_topics_topics = []
for i in var:
if i[0] not in subscribe_topic_ids:
remaining_topics_topics.append(i[0])
sql = (
"SELECT * "
"FROM topics;"
)
cur.execute(sql)
var = cur.fetchall()
topics = []
for i in var:
sql = (
"SELECT user_id FROM user_topic WHERE topic_id = %s ;"
)
cur.execute(sql, [i[0]])
var = cur.fetchone()
sql = (
"SELECT username FROM users WHERE user_id = %s ;"
)
cur.execute(sql, [var[0]])
var = cur.fetchone()
temp_topic = {'alertid': i[0], 'name': i[1], 'description': i[2], 'keywords': i[3].split(","),
'lang': i[4].split(","), 'creationTime': i[5], 'updatedTime': i[7], 'status': i[8],
'publish': i[9], 'newsUpdatedTime': i[10], 'created_by': var[0]}
if i[0] in own_topic_ids:
temp_topic['type'] = 'me'
elif i[0] in subscribe_topic_ids:
temp_topic['type'] = 'subscribed'
elif i[0] in remaining_topics_topics:
temp_topic['type'] = 'unsubscribed'
topics.append(temp_topic)
topics = sorted(topics, key=lambda k: k['alertid'])
for topic in topics:
topic['newsCount'] = Connection.Instance().newsPoolDB[str(topic['alertid'])].find().count()
topic['audienceCount'] = Connection.Instance().audienceDB[str(topic['alertid'])].find().count()
topic['eventCount'] = Connection.Instance().events[str(topic['alertid'])].find().count()
topic['tweetCount'] = Connection.Instance().db[str(topic['alertid'])].find().count()
try:
hash_tags = list(Connection.Instance().hashtags[str(topic['alertid'])].find({'name': 'month'},
{'month': 1, 'count': 1,
'_id': 0}))[0]['month']
except:
hash_tags = []
pass
sql = (
"SELECT ARRAY_AGG(hashtag) FROM topic_hashtag WHERE topic_id = %s ;"
)
cur.execute(sql, [topic['alertid']])
var = cur.fetchone()
tags = var[0] if var[0] is not None else []
hash_tags = [
{'hashtag': hash_tag['hashtag'], 'count': hash_tag['count'], 'active': hash_tag['hashtag'] not in tags}
for hash_tag in hash_tags]
topic['hashtags'] = hash_tags
topics.sort(key=lambda topic: (topic['publish'], topic['newsCount']), reverse=True)
return topics
def topic_exist(user_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT topic_id "
"FROM user_topic "
"WHERE user_id = %s"
)
cur.execute(sql, [user_id])
var = cur.fetchone()
if var is not None:
return True
else:
return False
def get_topic(topic_id):
if topic_id is not None:
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT * "
"FROM topics "
"WHERE topic_id = %s"
)
cur.execute(sql, [topic_id])
var = cur.fetchone()
topic = {'alertid': var[0], 'name': var[1], 'description': var[2], 'keywords': var[3],
'lang': var[4].split(","), 'status': var[8],
'keywordlimit': var[6]}
else:
topic = {'alertid': "", 'name': "", 'keywords': "", 'lang': "", 'status': False, 'keywordlimit': 20,
'description': ""}
return topic
def get_topic_all_of_them_list(topic_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT * "
"FROM topics "
"WHERE topic_id = %s"
)
cur.execute(sql, [topic_id])
var = cur.fetchone()
print(var)
topic = {'alertid': var[0], 'name': var[1], 'keywords': var[3].split(","), 'lang': var[4].split(","),
'status': var[8]}
return topic
def set_user_topics_imit(user_id, set_type):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT alertlimit "
"FROM users "
"WHERE user_id = %s"
)
cur.execute(sql, [user_id])
fetched = cur.fetchall()
new_limit = fetched[0][0]
if set_type == 'decrement':
new_limit = fetched[0][0] - 1
elif set_type == 'increment':
new_limit = fetched[0][0] + 1
sql = (
"UPDATE users "
"SET alertlimit = %s "
"WHERE user_id = %s"
)
cur.execute(sql, [new_limit, int(user_id)])
def ban_domain(user_id, topic_id, domain):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT EXISTS (SELECT 1 FROM user_domain where user_id = %s and domain = %s)"
)
cur.execute(sql, [int(user_id), domain])
fetched = cur.fetchone()
if not fetched[0]:
sql = (
"INSERT INTO user_domain "
"(user_id, domain) "
"VALUES (%s, %s)"
)
cur.execute(sql, [user_id, domain])
Connection.Instance().filteredNewsPoolDB[str(topic_id)].update_many(
{},
{'$pull': {
'yesterday': {'domain': domain},
'week': {'domain': domain},
'month': {'domain': domain}
}},
upsert=True
)
def add_topic(topic, user_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"INSERT INTO topics "
"(topic_name, topic_description, keywords, languages, keyword_limit) "
"VALUES (%s, %s, %s, %s, %s)"
)
cur.execute(sql, [topic['name'], topic['description'], topic['keywords'], topic['lang'], topic['keywordlimit']])
sql = (
"SELECT topic_id, topic_name "
"FROM topics "
"ORDER BY topic_id DESC "
"LIMIT 1"
)
cur.execute(sql)
topic_fetched = cur.fetchone()
print(topic_fetched)
if topic['name'] == topic_fetched[1]:
sql = (
"INSERT INTO user_topic "
"(user_id, topic_id) "
"VALUES (%s, %s)"
)
cur.execute(sql, [int(user_id), int(topic_fetched[0])])
topic = get_topic_all_of_them_list(int(topic_fetched[0]))
set_user_topics_imit(user_id, 'decrement')
set_current_topic(user_id)
t = Thread(target=add_facebook_pages_and_subreddits, args=(topic_fetched[1], topic['keywords'],))
t.start()
def delete_topic(topic_id, user_id):
alert = get_topic_all_of_them_list(topic_id)
set_user_topics_imit(user_id, 'increment')
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT * "
"FROM topics "
"WHERE topic_id = %s"
)
cur.execute(sql, [topic_id])
topic = cur.fetchone()
topic = list(topic)
topic.append(int(user_id))
sql = (
"INSERT INTO public.archived_topics "
"(topic_id, topic_name, topic_description, keywords, languages, creation_time, "
"keyword_limit, last_tweet_date, is_running, is_publish, user_id) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);"
)
cur.execute(sql,
[topic[0], topic[1], topic[2], topic[3], topic[4], topic[5], topic[6], topic[7], topic[8], topic[9],
int(user_id)])
sql = (
"DELETE FROM topics "
"WHERE topic_id = %s"
)
cur.execute(sql, [topic_id])
sql = (
"DELETE FROM user_topic "
"WHERE topic_id = %s AND user_id = %s"
)
cur.execute(sql, [topic_id, user_id])
sql = (
"DELETE FROM topic_facebook_page "
"WHERE topic_id = %s"
)
cur.execute(sql, [topic_id])
sql = (
"DELETE FROM topic_subreddit "
"WHERE topic_id = %s"
)
cur.execute(sql, [topic_id])
set_current_topic(user_id)
t = Thread(target=delete_community.main, args=(alert['alertid'],))
t.start()
def update_topic(topic):
with Connection.Instance().get_cursor() as cur:
sql = (
"UPDATE topics "
"SET topic_description = %s, keywords = %s, languages = %s, keyword_limit = %s "
"WHERE topic_id = %s"
)
cur.execute(sql,
[topic['description'], topic['keywords'], topic['lang'], topic['keywordlimit'], topic['alertid']])
topic = get_topic_all_of_them_list(topic['alertid'])
t = Thread(target=add_facebook_pages_and_subreddits, args=(topic['alertid'], topic['keywords'],))
t.start()
def start_topic(topic_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"UPDATE topics "
"SET is_running = %s "
"WHERE topic_id = %s"
)
cur.execute(sql, [True, topic_id])
def stop_topic(topic_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"UPDATE topics "
"SET is_running = %s "
"WHERE topic_id = %s"
)
cur.execute(sql, [False, topic_id])
def publish_topic(topic_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"UPDATE topics "
"SET is_publish = %s "
"WHERE topic_id = %s"
)
cur.execute(sql, [True, topic_id])
def unpublish_topic(topic_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"UPDATE topics "
"SET is_publish = %s "
"WHERE topic_id = %s"
)
cur.execute(sql, [False, topic_id])
def get_bookmarks(user_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT bookmark_link_id "
"FROM user_bookmark "
"WHERE user_id = %s"
)
cur.execute(sql, [user_id])
bookmark_link_ids = [a[0] for a in cur.fetchall()]
if len(bookmark_link_ids) == 0:
bookmark_link_ids = [-1]
sql = (
"SELECT news_id, rating "
"FROM user_news_rating "
"WHERE user_id = %s and news_id IN %s"
)
cur.execute(sql, [int(user_id), tuple(bookmark_link_ids)])
rating_list = cur.fetchall()
ratings = {str(rating[0]): rating[1] for rating in rating_list}
news = []
for alertid in Connection.Instance().newsPoolDB.collection_names():
news = news + list(
Connection.Instance().newsPoolDB[str(alertid)].find({'link_id': {'$in': bookmark_link_ids}}))
for news_item in news:
news_item['bookmark'] = True
news_item['sentiment'] = 0
try:
news_item['sentiment'] = ratings[str(news_item['link_id'])]
except KeyError:
pass
return news
def add_bookmark(user_id, link_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"INSERT INTO user_bookmark "
"(user_id, bookmark_link_id) "
"VALUES (%s, %s)"
)
cur.execute(sql, [int(user_id), int(link_id)])
def remove_bookmark(user_id, link_id):
with Connection.Instance().get_cursor() as cur:
sql = (
"DELETE FROM user_bookmark "
"WHERE user_id = %s AND bookmark_link_id = %s"
)
cur.execute(sql, [int(user_id), int(link_id)])
def sentiment_news(topic_id, user_id, link_id, rating):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT EXISTS (SELECT 1 FROM user_news_rating where user_id = %s and topic_id = %s and news_id = %s)"
)
cur.execute(sql, [int(user_id), int(topic_id), int(link_id)])
fetched = cur.fetchone()
if fetched[0]:
sql = (
"UPDATE user_news_rating "
"SET rating = %s "
"WHERE user_id = %s and news_id = %s and topic_id = %s"
)
cur.execute(sql, [float(rating), int(user_id), int(link_id), int(topic_id)])
else:
sql = (
"INSERT INTO user_news_rating "
"(user_id, news_id, topic_id, rating) "
"VALUES (%s, %s, %s, %s)"
)
cur.execute(sql, [int(user_id), int(link_id), int(topic_id), float(rating)])
def rate_audience(topic_id, user_id, audience_id, rating):
with Connection.Instance().get_cursor() as cur:
sql = (
"SELECT EXISTS "
"(SELECT 1 FROM user_audience_rating where user_id = %s and topic_id = %s and audience_id = %s)"
)
cur.execute(sql, [int(user_id), int(topic_id), int(audience_id)])
fetched = cur.fetchone()
if fetched[0]:
if float(rating) != 0.0:
sql = (
"UPDATE user_audience_rating "
"SET rating = %s "
"WHERE user_id = %s and audience_id = %s and topic_id = %s"
)
cur.execute(sql, [float(rating), int(user_id), int(audience_id), int(topic_id)])
else:
sql = (
"DELETE FROM user_audience_rating "
"WHERE user_id = %s and audience_id = %s and topic_id = %s"
)
cur.execute(sql, [int(user_id), int(audience_id), int(topic_id)])
else:
if float(rating) != 0.0:
sql = (
"INSERT INTO user_audience_rating "
"(user_id, audience_id, topic_id, rating) "
"VALUES (%s, %s, %s, %s)"
)
cur.execute(sql, [int(user_id), int(audience_id), int(topic_id), float(rating)])
def add_local_influencer(topic_id, location, screen_name):
with Connection.Instance().get_cursor() as cur:
sql = (
"INSERT INTO added_influencers "
"(topic_id, country_code, screen_name) "
"VALUES (%s, %s, %s)"
)
cur.execute(sql, [int(topic_id), str(location), str(screen_name), ""])
if Connection.Instance().added_local_influencers_DB['added_influencers'].find_one(
{"screen_name": screen_name}) is None:
new_local_influencer = api.get_user(screen_name)
new_local_influencer['topics'] = topic_id
new_local_influencer['locations'] = location
Connection.Instance().added_local_influencers_DB['added_influencers'].insert_one(new_local_influencer)
else:
Connection.Instance().added_local_influencers_DB['added_influencers'].update(
{"screen_name": screen_name},
{
"$addToSet": {
"topics": topic_id,
"locations": location
}
}
)
def hide_influencer(topic_id, user_id, influencer_id, description, is_hide, location):
# print("in hide influencer:")
# print(influencer_id)
print("In hide influencer")
print("Topic id:" + str(topic_id))
print("Location:" + location)
influencer_id = int(influencer_id)
print(influencer_id)
if is_hide:
print("Hiding influencer with ID:" + str(influencer_id))
with Connection.Instance().get_cursor() as cur:
sql = (
"INSERT INTO hidden_influencers "
"(topic_id, country_code, influencer_id, description) "
"VALUES (%s, %s, %s, %s)"
)
cur.execute(sql, [int(topic_id), str(location), str(influencer_id), ""])
else:
print("Unhiding influencer with ID:" + str(influencer_id))
with Connection.Instance().get_cursor() as cur:
sql = (
"DELETE FROM hidden_influencers "
"WHERE topic_id = %s and country_code = %s and influencer_id = %s "
)
cur.execute(sql, [int(topic_id), str(location), str(influencer_id)])
def hide_event(topic_id, user_id, event_link, description, is_hide):
# print("in hide influencer:")
# print(influencer_id)
print("In hide event")
print("Topic id:" + str(topic_id))
event_link = str(event_link)
print(event_link)
if is_hide:
print("Hiding event with link:" + event_link)
with Connection.Instance().get_cursor() as cur:
sql = (
"INSERT INTO hidden_events "
"(topic_id, event_link, description) "
"VALUES (%s, %s, %s)"
)
cur.execute(sql, [int(topic_id), str(event_link), ""])
else:
print("Unhiding event with link:" + event_link)
with Connection.Instance().get_cursor() as cur:
sql = (
"DELETE FROM hidden_events "
"WHERE topic_id = %s and event_link = %s "
)
cur.execute(sql, [int(topic_id), str(event_link)])
def get_tweets(topic_id):
tweets = Connection.Instance().db[str(topic_id)].find({}, {'tweetDBId': 1, "text": 1, "id": 1, "user": 1,
'created_at': 1, "_id": 0}).sort(
[('tweetDBId', pymongo.DESCENDING)]).limit(25)
tweets = list(tweets)
return tweets
def get_skip_tweets(topic_id, last_tweet_id):
tweets = Connection.Instance().db[str(topic_id)].find({'tweetDBId': {'$lt': int(last_tweet_id)}},
{'tweetDBId': 1, "text": 1, "id": 1, "user": 1,
'created_at': 1, "_id": 0}) \
.sort([('tweetDBId', pymongo.DESCENDING)]).limit(25)
tweets = list(tweets)
return tweets
def check_tweets(topic_id, newest_id):
if int(newest_id) == -1:
tweets = Connection.Instance().db[str(topic_id)].find({}, {'tweetDBId': 1, "text": 1, "id": 1, "user": 1,
'created_at': 1, "_id": 0}).sort(
[('tweetDBId', pymongo.DESCENDING)])
else:
tweets = Connection.Instance().db[str(topic_id)].find({'tweetDBId': {'$gt': int(newest_id)}},
{'tweetDBId': 1, "text": 1, "user": 1, 'created_at': 1,
"_id": 0}).sort([('tweetDBId', pymongo.DESCENDING)])
tweets = list(tweets)
return len(tweets)
def get_new_tweets(topic_id, newest_id):
if int(newest_id) == -1:
tweets = Connection.Instance().db[str(topic_id)].find({}, {'tweetDBId': 1, "text": 1, "id": 1, "user": 1,
'created_at': 1, "_id": 0}).sort(
[('tweetDBId', pymongo.DESCENDING)])
else:
tweets = Connection.Instance().db[str(topic_id)].find({'tweetDBId': {'$gt': int(newest_id)}},
{'tweetDBId': 1, 'id': 1, "text": 1, "user": 1,
'created_at': 1, "_id": 0}) \
.sort([('tweetDBId', pymongo.DESCENDING)])
tweets = list(tweets)
return tweets
def search_news(keywords, languages):
keys = keywords.split(",")
result_keys = []
for key in keys:
if " " in key:
result_keys.append("\"" + key + "\"")
else:
result_keys.append(key)
# ends
keywords = " OR ".join(result_keys)
languages = " OR ".join(languages.split(","))
news = twitter_search_sample_tweets.getNewsFromTweets(keywords, languages)
return news
def get_news(user_id, topic_id, date, cursor):
dates = ['all', 'yesterday', 'week', 'month']