-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreddit_content_manager.py
1365 lines (1097 loc) · 61.8 KB
/
reddit_content_manager.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 sys
from collections import OrderedDict
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
from mainwindow import UIMainWindow
from profilewindow import UIProfileWindow
import os
import praw
import datetime
import shutil
import requests
import json
import textwrap
import webbrowser
import pandas
log_file = f"logs/{datetime.datetime.now().strftime('%m%d%Y - %H%M%S')}.log"
class ThreadDeleteContent(QThread):
remove_comment = Signal(int)
thread_progress = Signal(int)
thread_status = Signal(str)
def __init__(self, parent, profile):
self.stopped = False
self.parent = parent
self.profile = profile
super().__init__()
def run(self):
try:
reddit = praw.Reddit(username=self.profile[0],
password=self.profile[1],
client_id=self.profile[2],
client_secret=self.profile[3],
user_agent="Reddit Content Manager")
reddit.validate_on_submit = True
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
content_deleted = 0
content_already_deleted = 0
total_to_delete = len(self.parent.ui.content_tree.selectedItems())
for index, item in enumerate(reversed(self.parent.ui.content_tree.selectedItems())):
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
if item.statusTip(0) == "Reddit Content":
if self.parent.current_search == "comments":
try:
reddit.comment(item.text(0)).edit("[removed]")
reddit.comment(item.text(0)).delete()
content_deleted += 1
item.setSelected(False)
item.setTextColor(0, QColor(255, 0, 0))
except Exception as e:
log(e)
else:
try:
try:
reddit.submission(item.text(0)).edit("[removed]")
# Tries to edit the text, if it can't (because it isn't a text post), then it just catches
# the exception and passes it.
except:
pass
reddit.submission(item.text(0)).delete()
content_deleted += 1
item.setSelected(False)
item.setTextColor(0, QColor(255, 0, 0))
except Exception as e:
log(e)
else:
content_already_deleted += 1
item.setSelected(False)
self.thread_status.emit(f"Deleting content ({index}/{total_to_delete})")
self.thread_progress.emit((index / total_to_delete) * 100)
self.thread_status.emit(f"Done! {content_deleted} removed. | {content_already_deleted} already removed.")
def stop_thread(self):
self.stopped = True
class ThreadGatherPosts(QThread):
output_post = Signal(list)
thread_progress = Signal(int)
thread_status = Signal(str)
def __init__(self, parent, profile, search_text, filters):
try:
self.stopped = False
self.parent = parent
self.profile = profile
self.search_text = search_text
self.filters = filters
super().__init__()
log("Background thread started!")
except Exception as e:
log(e)
def run(self):
posts = self.get_post_info()
posts = self.filter_posts(posts)
self.output_posts(posts)
num_found = len([post for post in posts.keys() if posts[post]["drop"] is not True])
self.thread_status.emit(f"Process finished! {num_found} posts found!")
self.parent.current_profile = self.parent.ui.profile_list.selectedItems()[0].text()
log("Thread execution finished successfully!")
def get_post_info(self):
log("Getting posts...")
self.thread_status.emit("Getting posts...")
push_link = f"https://api.pushshift.io/reddit/search/submission/?q={self.search_text}" \
f"&sort_type=created_utc" \
f"&author={self.profile[0]}" \
f"&{['after', 'before'][self.filters['Time'][0]]}={self.filters['Time'][1]}" \
f"&limit=1000"
try:
posts = json.loads(requests.get(push_link).content)
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
if not posts["data"]:
self.thread_status.emit("No results found...")
raise Exception("No results found...")
while len(json.loads(requests.get(push_link).content)["data"]) != 0:
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
try:
push_link = f"https://api.pushshift.io/reddit/search/submission/?q={self.search_text}" \
f"&sort_type=created_utc" \
f"&author={self.profile[0]}" \
f"&{['after', 'before'][self.filters['Time'][0]]}={posts['data'][-1]['created_utc']}" \
f"&subreddit={self.filters['Subreddit']}" \
f"&limit=1000"
posts["data"] = posts["data"] + json.loads(requests.get(push_link).content)["data"]
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
try:
reddit = praw.Reddit(username=self.profile[0],
password=self.profile[1],
client_id=self.profile[2],
client_secret=self.profile[3],
user_agent="Reddit Content Manager")
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
posts_by_id = OrderedDict({post["id"]: {"selftext": post["selftext"],
"title": post["title"],
"subreddit": post["subreddit"],
"permalink": post["permalink"],
"created": post["created_utc"],
"score": "Unknown",
"edited": "Unknown",
"awarded": "Unknown",
"removed": "Unknown",
"processed": False, # used to determine if the content was processed
"drop": False # used to determine if content matches filters or not
} for post in posts["data"]})
post_ids = list(posts_by_id.keys())
log("Getting post info...")
self.thread_status.emit(f"Getting post info... (0/{len(post_ids)})")
try:
if len(post_ids) >= 100:
for iteration in range(100, len(post_ids), 100):
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
current_posts = ["t3_" + post_id for post_id in post_ids[iteration - 100:iteration]]
current_post_info = [post_info for post_info in reddit.info(current_posts)]
post_score_info = {post.id: post.score for post in current_post_info}
post_awarded_info = {post_info.id: post_info.distinguished is not None for post_info in
current_post_info}
post_edited_info = {post_info.id: post_info.edited is not False for post_info in
current_post_info}
post_removed_info = {post_info.id: post_info.selftext in ["[removed]", "[deleted]"] for
post_info in current_post_info}
post_selftext_info = {post_info.id: post_info.selftext for post_info in current_post_info}
for post_id in post_ids[iteration - 100:iteration]:
if post_id in post_score_info.keys():
posts_by_id[post_id]["score"] = post_score_info[post_id]
if post_id in post_awarded_info.keys():
posts_by_id[post_id]["awarded"] = post_awarded_info[post_id]
if post_id in post_edited_info.keys():
posts_by_id[post_id]["edited"] = post_edited_info[post_id]
if post_id in post_removed_info.keys():
posts_by_id[post_id]["removed"] = post_removed_info[post_id]
if post_id in post_selftext_info.keys():
if post_selftext_info[post_id] not in ["[removed]", "[deleted]"]:
posts_by_id[post_id]["selftext"] = post_selftext_info[post_id]
posts_by_id[post_id]["processed"] = True
num_complete = len([post_id for post_id in post_ids
if posts_by_id[post_id]["processed"] is True])
self.thread_status.emit(f"Getting post info... ({num_complete}/{len(post_ids)})")
self.thread_progress.emit((num_complete / len(post_ids) * 100))
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
# Code below exists to process remainders or content that falls below the 100 item limit for .info
current_posts = ["t3_" + post_id for post_id in post_ids
if posts_by_id[post_id]["processed"] is False]
current_post_info = [post_info for post_info in reddit.info(current_posts)]
post_score_info = {post_info.id: post_info.score for post_info in current_post_info}
post_awarded_info = {post_info.id: post_info.distinguished for post_info in
current_post_info}
post_edited_info = {post_info.id: post_info.edited is not False for post_info in
current_post_info}
post_removed_info = {post_info.id: post_info.selftext in ["[removed]", "[deleted]"] for
post_info in current_post_info}
post_selftext_info = {post_info.id: post_info.selftext for post_info in current_post_info}
for post_id in current_posts:
post_id = post_id.replace("t3_", "")
if post_id in post_score_info.keys():
posts_by_id[post_id]["score"] = post_score_info[post_id]
if post_id in post_awarded_info.keys():
posts_by_id[post_id]["awarded"] = post_awarded_info[post_id]
if post_id in post_edited_info.keys():
posts_by_id[post_id]["edited"] = post_edited_info[post_id]
if post_id in post_removed_info.keys():
posts_by_id[post_id]["removed"] = post_removed_info[post_id]
if post_id in post_selftext_info.keys():
if post_selftext_info[post_id] not in ["[removed]", "[deleted]"]:
posts_by_id[post_id]["body"] = post_selftext_info[post_id]
posts_by_id[post_id]["processed"] = True
num_complete = len([post_id for post_id in post_ids
if posts_by_id[post_id]["processed"] is True])
self.thread_status.emit(f"Getting post info... ({num_complete}/{len(post_ids)})")
self.thread_progress.emit((num_complete / len(post_ids) * 100))
log("Done getting post info!")
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
return posts_by_id
def filter_posts(self, posts):
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
try:
log("Filtering posts...")
self.thread_status.emit(f"Filtering posts... (0/{len(posts)})")
for index, post_id in enumerate(posts):
score = posts[post_id]["score"]
awarded = posts[post_id]["awarded"]
edited = posts[post_id]["edited"]
removed = posts[post_id]["removed"]
if score != "Unknown":
if score < self.filters["Score"][0] or score > self.filters["Score"][1]:
posts[post_id]["drop"] = True
if awarded != "Unknown":
if self.filters["Awarded"] != 0:
if self.filters["Awarded"] == 1:
posts[post_id]["drop"] = not awarded
else:
posts[post_id]["drop"] = bool(awarded)
else:
if self.filters["Awarded"] != 0:
posts[post_id]["drop"] = True
if edited != "Unknown":
if self.filters["Edited"] != 0:
if self.filters["Edited"] == 1:
posts[post_id]["drop"] = True if edited is False else False
else:
posts[post_id]["drop"] = True if edited is not False else False
else:
if self.filters["Edited"] != 0:
posts[post_id]["drop"] = True
if removed != "Unknown":
if self.filters["Removed"] != 0:
if self.filters["Removed"] == 1:
posts[post_id]["drop"] = True if removed is False else False
else:
posts[post_id]["drop"] = True if removed is not False else False
self.thread_status.emit(f"Filtering posts... ({index}/{len(posts) - 1})")
self.thread_progress.emit((index / len(posts) * 100))
if self.filters["Sort"] == 0:
posts = OrderedDict((sorted((kv for kv in posts.items()), key=lambda kv: kv[1]['created'],
reverse=True)))
else:
posts_score_unknown = OrderedDict(kv for kv in posts.items() if kv[1]['score'] == "Unknown")
posts = OrderedDict(kv for kv in posts.items() if kv[1]['score'] != "Unknown")
posts = OrderedDict((sorted((kv for kv in posts.items()), key=lambda kv: kv[1]['score'],
reverse=True)))
posts = OrderedDict([kv for kv in posts.items()] + [kv for kv in posts_score_unknown.items()])
log("Done filtering posts!")
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
return posts
def output_posts(self, posts):
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
log("Outputting posts...")
self.thread_status.emit(f"Outputting comments... (0/{len(posts)})")
try:
for index, post_id in enumerate(posts):
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
if posts[post_id]["drop"] is False:
self.output_post.emit({"index": index, "id": post_id,
"data": posts[post_id], "num_comments": len(posts)})
self.thread_status.emit(f"Outputting posts... ({index}/{len(posts) - 1})")
self.thread_progress.emit(index / len(posts) * 100)
log("Done outputting posts!")
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
def stop_thread(self):
self.stopped = True
class ThreadGatherComments(QThread):
output_comment = Signal(list)
thread_progress = Signal(int)
thread_status = Signal(str)
def __init__(self, parent, profile, search_text, filters):
try:
self.stopped = False
self.parent = parent
self.profile = profile
self.search_text = search_text
self.filters = filters
super().__init__()
log("Background thread started!")
except Exception as e:
log(e)
def run(self):
comments = self.get_comment_info()
comments = self.filter_comments(comments)
self.output_comments(comments)
if self.stopped:
return
num_found = len([comment for comment in comments.keys() if comments[comment]["drop"] is not True])
self.thread_status.emit(f"Process finished! {num_found} comments found!")
self.parent.current_profile = self.parent.ui.profile_list.selectedItems()[0].text()
log("Thread execution finished successfully!")
def get_comment_info(self):
log("Getting comments...")
self.thread_status.emit("Getting comments...")
push_link = f"https://api.pushshift.io/reddit/search/comment/?q={self.search_text}" \
f"&sort_type=created_utc" \
f"&author={self.profile[0]}" \
f"&{['after', 'before'][self.filters['Time'][0]]}={self.filters['Time'][1]}" \
f"&limit=1000"
try:
comments = json.loads(requests.get(push_link).content)
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
if not comments["data"]:
self.thread_status.emit("No results found...")
raise Exception("No results found...")
while 1:
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
try:
push_link = f"https://api.pushshift.io/reddit/search/comment/?q={self.search_text}" \
f"&sort_type=created_utc" \
f"&author={self.profile[0]}" \
f"&{['after', 'before'][self.filters['Time'][0]]}={comments['data'][-1]['created_utc']}" \
f"&subreddit={self.filters['Subreddit']}" \
f"&limit=1000"
comments["data"] = comments["data"] + json.loads(requests.get(push_link).content)["data"]
if len(json.loads(requests.get(push_link).content)["data"]) == 0:
break
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
try:
reddit = praw.Reddit(username=self.profile[0],
password=self.profile[1],
client_id=self.profile[2],
client_secret=self.profile[3],
user_agent="Reddit Content Manager")
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
comments_by_id = OrderedDict({comment["id"]: {"body": comment["body"],
"subreddit": comment["subreddit"],
"permalink": comment["permalink"],
"created": comment["created_utc"],
"score": "Unknown",
"edited": "Unknown",
"awarded": "Unknown",
"removed": "Unknown",
"processed": False,
"drop": False
} for comment in comments["data"]})
for comment in reddit.redditor(self.profile[0]).comments.new(limit=None):
if comment.id not in comments_by_id.keys():
comments_by_id[comment.id] = {"body": comment.body,
"subreddit": comment.subreddit,
"permalink": comment.permalink,
"created": comment.created_utc,
"score": "Unknown",
"edited": "Unknown",
"awarded": "Unknown",
"removed": "Unknown",
"processed": False,
"drop": False}
comment_ids = list(comments_by_id.keys())
log("Getting comment info...")
self.thread_status.emit(f"Getting comment info... (0/{len(comment_ids)})")
try:
if len(comment_ids) >= 100:
for iteration in range(100, len(comment_ids), 100):
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
current_comments = ["t1_" + comment_id for comment_id in comment_ids[iteration - 100:iteration]]
current_comment_info = [comment_info for comment_info in reddit.info(current_comments)]
comment_score_info = {comment.id: comment.score for comment in current_comment_info}
comment_awarded_info = {comment_info.id: comment_info.distinguished is not None for comment_info in
current_comment_info}
comment_edited_info = {comment_info.id: comment_info.edited is not False for comment_info in
current_comment_info}
comment_removed_info = {comment_info.id: comment_info.body in ["[removed]", "[deleted]"] for
comment_info in current_comment_info}
comment_body_info = {comment_info.id: comment_info.body for comment_info in current_comment_info}
for comment_id in comment_ids[iteration - 100:iteration]:
if comment_id in comment_score_info.keys():
comments_by_id[comment_id]["score"] = comment_score_info[comment_id]
if comment_id in comment_awarded_info.keys():
comments_by_id[comment_id]["awarded"] = comment_awarded_info[comment_id]
if comment_id in comment_edited_info.keys():
comments_by_id[comment_id]["edited"] = comment_edited_info[comment_id]
if comment_id in comment_removed_info.keys():
comments_by_id[comment_id]["removed"] = comment_removed_info[comment_id]
if comment_id in comment_body_info.keys():
if comment_body_info[comment_id] not in ["[removed]", "[deleted]"]:
comments_by_id[comment_id]["body"] = comment_body_info[comment_id]
comments_by_id[comment_id]["processed"] = True
num_complete = len([comment_id for comment_id in comment_ids
if comments_by_id[comment_id]["processed"] is True])
self.thread_status.emit(f"Getting comment info... ({num_complete}/{len(comment_ids)})")
self.thread_progress.emit((num_complete / len(comment_ids) * 100))
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
current_comments = ["t1_" + comment_id for comment_id in comment_ids
if comments_by_id[comment_id]["processed"] is False]
current_comment_info = [comment_info for comment_info in reddit.info(current_comments)]
comment_score_info = {comment.id: comment.score for comment in current_comment_info}
comment_awarded_info = {comment_info.id: comment_info.distinguished for comment_info in
current_comment_info}
comment_edited_info = {comment_info.id: comment_info.edited is not False for comment_info in
current_comment_info}
comment_removed_info = {comment_info.id: comment_info.body in ["[removed]", "[deleted]"] for
comment_info in current_comment_info}
comment_body_info = {comment_info.id: comment_info.body for comment_info in current_comment_info}
for comment_id in current_comments:
comment_id = comment_id.replace("t1_", "")
if comment_id in comment_score_info.keys():
comments_by_id[comment_id]["score"] = comment_score_info[comment_id]
if comment_id in comment_awarded_info.keys():
comments_by_id[comment_id]["awarded"] = comment_awarded_info[comment_id]
if comment_id in comment_edited_info.keys():
comments_by_id[comment_id]["edited"] = comment_edited_info[comment_id]
if comment_id in comment_removed_info.keys():
comments_by_id[comment_id]["removed"] = comment_removed_info[comment_id]
if comment_id in comment_body_info.keys():
if comment_body_info[comment_id] not in ["[removed]", "[deleted]"]:
comments_by_id[comment_id]["body"] = comment_body_info[comment_id]
comments_by_id[comment_id]["processed"] = True
num_complete = len([comment_id for comment_id in comment_ids
if comments_by_id[comment_id]["processed"] is True])
self.thread_status.emit(f"Getting comment info... ({num_complete}/{len(comment_ids)})")
self.thread_progress.emit((num_complete / len(comment_ids) * 100))
log("Done getting comment info!")
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
return comments_by_id
def filter_comments(self, comments):
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
try:
log("Filtering comments...")
self.thread_status.emit(f"Filtering comments... (0/{len(comments)})")
for index, comment_id in enumerate(comments):
score = comments[comment_id]["score"]
awarded = comments[comment_id]["awarded"]
edited = comments[comment_id]["edited"]
removed = comments[comment_id]["removed"]
if score != "Unknown":
if score < self.filters["Score"][0] or score > self.filters["Score"][1]:
comments[comment_id]["drop"] = True
if awarded != "Unknown":
if self.filters["Awarded"] != 0:
if self.filters["Awarded"] == 1:
comments[comment_id]["drop"] = not awarded
else:
comments[comment_id]["drop"] = bool(awarded)
else:
if self.filters["Awarded"] != 0:
comments[comment_id]["drop"] = True
if edited != "Unknown":
if self.filters["Edited"] != 0:
if self.filters["Edited"] == 1:
comments[comment_id]["drop"] = True if edited is False else False
else:
comments[comment_id]["drop"] = True if edited is not False else False
else:
if self.filters["Edited"] != 0:
comments[comment_id]["drop"] = True
if removed != "Unknown":
if self.filters["Removed"] != 0:
if self.filters["Removed"] == 1:
comments[comment_id]["drop"] = True if removed is False else False
else:
comments[comment_id]["drop"] = True if removed is not False else False
self.thread_status.emit(f"Filtering comments... ({index}/{len(comments) - 1})")
self.thread_progress.emit((index / len(comments) * 100))
if self.filters["Sort"] == 0:
comments = OrderedDict((sorted((kv for kv in comments.items()), key=lambda kv: kv[1]['created'],
reverse=True)))
else:
comments_score_unknown = OrderedDict(kv for kv in comments.items() if kv[1]['score'] == "Unknown")
comments = OrderedDict(kv for kv in comments.items() if kv[1]['score'] != "Unknown")
comments = OrderedDict((sorted((kv for kv in comments.items()), key=lambda kv: kv[1]['score'],
reverse=True)))
comments = OrderedDict([kv for kv in comments.items()] + [kv for kv in comments_score_unknown.items()])
log("Done filtering comments!")
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
return comments
def output_comments(self, comments):
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
log("Outputting comments...")
self.thread_status.emit(f"Outputting comments... (0/{len(comments)})")
try:
for index, comment_id in enumerate(comments):
if self.stopped:
self.thread_status.emit("Process stopped by user...")
return
if comments[comment_id]["drop"] is False:
self.output_comment.emit({"index": index, "id": comment_id,
"data": comments[comment_id], "num_comments": len(comments)})
self.thread_status.emit(f"Outputting comments... ({index}/{len(comments) - 1})")
self.thread_progress.emit(index / len(comments) * 100)
log("Done outputting comments!")
except Exception as e:
if not self.stopped:
log(e)
self.thread_status.emit("Process ran into error. Please try again in a few minutes...")
return
def stop_thread(self):
self.stopped = True
class ProfileWindow(QDialog):
def __init__(self, parent, create_profile):
self.parent = parent
log("Setting up profile menu UI...")
try:
super(ProfileWindow, self).__init__()
self.ui = UIProfileWindow()
self.ui.setupUi(self)
log("Profile menu UI set up successfully!")
except Exception as e:
log(e)
log("Setting up menu...")
try:
if create_profile:
self.ui.confirm_btn.clicked.connect(self.do_create_profile)
self.setWindowTitle("Create Profile")
else:
self.setWindowTitle("Modify Profile")
with open(f"profiles/{parent.ui.profile_list.selectedItems()[0].text()}.rpf") as file:
profile_info = [line.replace("\n", "") for line in file.readlines()]
if len(profile_info) < 4:
profile_info = profile_info + ["" for i in range(4 - len(profile_info))]
self.ui.username_edit.setText(profile_info[0])
self.ui.password_edit.setText(profile_info[1])
self.ui.pu_edit.setText(profile_info[2])
self.ui.secret_edit.setText(profile_info[3])
self.ui.confirm_btn.clicked.connect(self.do_modify_profile)
log("Menu set up successfully!")
except Exception as e:
log(e)
if not os.path.isdir("profiles"):
log("Creating profile directory...")
try:
os.mkdir("profiles")
except Exception as e:
log(e)
log("Profile menu opened successfully!")
def do_create_profile(self):
do_create = True
if len(self.ui.username_edit.text()) == 0:
do_create = False
self.ui.username_edit.setStyleSheet("border: 1px solid red;")
else:
self.ui.username_edit.setStyleSheet("border: 1px solid black;")
if len(self.ui.password_edit.text()) == 0:
do_create = False
self.ui.password_edit.setStyleSheet("border: 1px solid red;")
else:
self.ui.password_edit.setStyleSheet("border: 1px solid black;")
if len(self.ui.pu_edit.text()) < 14:
do_create = False
self.ui.pu_edit.setStyleSheet("border: 1px solid red;")
else:
self.ui.pu_edit.setStyleSheet("border: 1px solid black;")
if len(self.ui.secret_edit.text()) < 27:
do_create = False
self.ui.secret_edit.setStyleSheet("border: 1px solid red;")
else:
self.ui.secret_edit.setStyleSheet("border: 1px solid black;")
for user_file in os.listdir("profiles"):
if self.ui.username_edit.text() == user_file.split(".")[0]:
do_create = False
QMessageBox.warning(self, "Profile already exists", "A profile already exists for that user!")
if do_create == True:
log("Creating profile...")
try:
bot = praw.Reddit(username=self.ui.username_edit.text(),
password=self.ui.password_edit.text(),
client_id=self.ui.pu_edit.text(),
client_secret=self.ui.secret_edit.text(),
user_agent='Reddit Content Manager')
_ = bot.user.me() # Verifies connection to Reddit. If not, an exception is raised.
with open(f"profiles/{self.ui.username_edit.text()}.rpf", "w+") as file:
file.writelines([self.ui.username_edit.text() + "\n",
self.ui.password_edit.text() + "\n",
self.ui.pu_edit.text() + "\n",
self.ui.secret_edit.text() + "\n"])
log("Profile created successfully!")
self.close()
except Exception as e:
if "invalid_grant error processing request" in str(e):
QMessageBox.warning(self, "Invalid Login!", "Invalid Username or Password! Please try again!")
elif "error with request HTTPSConnectionPool" in str(e):
QMessageBox.warning(self, "Status Code: 503", "Cannot establish connection!")
elif "received 401 HTTP response" in str(e):
QMessageBox.warning(self, "Status Code: 401", "Invalid PU Script or Secret! Please try again!")
else:
QMessageBox.warning(self, "Unknown Error", "Unknown error! Please check the log for more details!")
log(e)
def do_modify_profile(self):
do_modify = True
if len(self.ui.username_edit.text()) == 0:
do_modify = False
self.ui.username_edit.setStyleSheet("border: 1px solid red;")
else:
self.ui.username_edit.setStyleSheet("border: 1px solid black;")
if len(self.ui.password_edit.text()) == 0:
do_modify = False
self.ui.password_edit.setStyleSheet("border: 1px solid red;")
else:
self.ui.password_edit.setStyleSheet("border: 1px solid black;")
if len(self.ui.pu_edit.text()) < 14:
do_modify = False
self.ui.pu_edit.setStyleSheet("border: 1px solid red;")
else:
self.ui.pu_edit.setStyleSheet("border: 1px solid black;")
if len(self.ui.secret_edit.text()) < 27:
do_modify = False
self.ui.secret_edit.setStyleSheet("border: 1px solid red;")
else:
self.ui.secret_edit.setStyleSheet("border: 1px solid black;")
if do_modify == True:
log("Modifying profile...")
try:
bot = praw.Reddit(username=self.ui.username_edit.text(),
password=self.ui.password_edit.text(),
client_id=self.ui.pu_edit.text(),
client_secret=self.ui.secret_edit.text(),
user_agent='Reddit Content Manager')
_ = bot.user.me()
os.remove(f"profiles/{self.parent.ui.profile_list.selectedItems()[0].text()}.rpf")
with open(f"profiles/{self.ui.username_edit.text()}.rpf", "w+") as file:
file.writelines([self.ui.username_edit.text() + "\n",
self.ui.password_edit.text() + "\n",
self.ui.pu_edit.text() + "\n",
self.ui.secret_edit.text() + "\n"])
log("Profile modified successfully!")
self.close()
except Exception as e:
if "invalid_grant error processing request" in str(e):
QMessageBox.warning(self, "Invalid Login!", "Invalid Username or Password! Please try again!")
elif "error with request HTTPSConnectionPool" in str(e):
QMessageBox.warning(self, "Status Code: 503", "Cannot establish connection!")
elif "received 401 HTTP response" in str(e):
QMessageBox.warning(self, "Status Code: 401", "Invalid PU Script or Secret! Please try again!")
else:
QMessageBox.warning(self, "Unknown Error", "Unknown error! Please check the log for more details!")
log(e)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
log("Setting up UI...")
self.prev_max = 0
self.current_process = None
try:
self.ui = UIMainWindow()
self.ui.setupUi(self)
log("UI Set up successfully!")
except Exception as e:
log(e)
log("Starting timer...")
self.ui.content_tree.itemDoubleClicked.connect(self.open_link)
try:
self.update_timer = QTimer(self)
self.connect_functions()
self.update_timer.start(100)
log("Timer Started!")
except Exception as e:
log(e)
def updater(self):
# This is a function that runs on an interval and continuously updates the UI
profiles = []
for profile_index in range(self.ui.profile_list.count()):
profiles.append(self.ui.profile_list.item(profile_index))
for rpf_file in os.listdir("profiles"):
if rpf_file.split(".")[0] not in [profile.text() for profile in profiles]:
self.ui.profile_list.addItem(rpf_file.split(".")[0])
for profile in profiles:
if (profile.text() + ".rpf") not in os.listdir("profiles"):
if (profile.text() + ".txt") not in os.listdir("profiles"):
self.ui.profile_list.takeItem(self.ui.profile_list.row(profile))
self.ui.modify_profile_action.setDisabled(len(self.ui.profile_list.selectedItems()) == 0)
self.ui.export_profile_action.setDisabled(len(self.ui.profile_list.selectedItems()) == 0)
self.ui.remove_profile_button.setDisabled(len(self.ui.profile_list.selectedItems()) == 0)
self.ui.migrate_profile_button.setDisabled(not len(self.ui.profile_list.selectedItems()) == 2)
self.ui.submission_search_button.setDisabled(not len(self.ui.profile_list.selectedItems()) == 1)
self.ui.submission_dump_button.setDisabled(not len(self.ui.content_tree.selectedItems()))
self.ui.submission_delete_button.setDisabled(not len(self.ui.content_tree.selectedItems()))
self.ui.submission_clear_btn.setDisabled(not len(self.ui.content_tree.selectedItems()))
try:
layouts = [self.ui.profile_layout, self.ui.filter_layout]
for layout in layouts:
layout_widgets = [layout.itemAt(i) for i in range(layout.count())]
for widget in layout_widgets:
if widget.widget() is not None:
widget.widget().setDisabled(self.background_thread.isRunning())
if isinstance(widget, QCheckBox):
widget.setDisabled(self.background_thread.isRunning())
if not self.background_thread.isRunning():
self.ui.submission_progress_bar.setValue(0)
self.ui.content_tree.setDisabled(self.background_thread.isRunning())
self.ui.submission_label.setDisabled(self.background_thread.isRunning())
self.ui.submission_search_bar.setDisabled(self.background_thread.isRunning())
self.ui.profile_menu.setDisabled(self.background_thread.isRunning())
self.ui.autodelete_menu.setDisabled(self.background_thread.isRunning())
if self.background_thread.isRunning() and self.current_process == "Search":
self.ui.submission_search_button.setText("Cancel")
self.ui.submission_search_button.clicked.disconnect()
self.ui.submission_search_button.clicked.connect(lambda: self.background_thread.stop_thread())
self.ui.submission_dump_button.setDisabled(True)
self.ui.submission_delete_button.setDisabled(True)
self.ui.submission_clear_btn.setDisabled(True)
elif self.background_thread.isRunning() and self.current_process == "Delete":
self.ui.submission_delete_button.setText("Cancel")
self.ui.submission_delete_button.clicked.disconnect()
self.ui.submission_delete_button.clicked.connect(lambda: self.background_thread.stop_thread())
self.ui.submission_search_button.setDisabled(True)
self.ui.submission_dump_button.setDisabled(True)
self.ui.submission_clear_btn.setDisabled(True)
else:
self.current_process = None
self.ui.submission_search_button.setText("Search")
self.ui.submission_search_button.clicked.disconnect()
self.ui.submission_search_button.clicked.connect(self.search_content)
self.ui.submission_delete_button.setText("Delete")
self.ui.submission_delete_button.clicked.disconnect()
self.ui.submission_delete_button.clicked.connect(self.delete_content)
except:
pass
def connect_functions(self):
# Connects all of the UI elements to functions at startup
log("Connecting functions...")
try:
self.ui.create_profile_action.triggered.connect(lambda: self.create_modify_profile(True))
self.ui.modify_profile_action.triggered.connect(lambda: self.create_modify_profile(False))
self.ui.remove_profile_button.clicked.connect(self.remove_profile)
self.ui.import_profile_action.triggered.connect(lambda: self.import_export_profile(True))
self.ui.export_profile_action.triggered.connect(lambda: self.import_export_profile(False))
self.update_timer.timeout.connect(self.updater)
self.ui.submission_search_button.clicked.connect(self.search_content)
self.ui.submission_clear_btn.clicked.connect(self.clear_content)
self.ui.submission_delete_button.clicked.connect(self.delete_content)
self.ui.submission_dump_button.clicked.connect(self.dump_content)
self.ui.migrate_profile_button.clicked.connect(self.migrate_content)
log("Functions connected successfully!")
except Exception as e:
log(e)
def create_modify_profile(self, create):
log("Opening profile menu...")
try:
self.profile_window = ProfileWindow(self, create)
self.profile_window.exec_()
except Exception as e:
log(e)