-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodlog_wiki_publisher.py
More file actions
1724 lines (1396 loc) · 69.9 KB
/
modlog_wiki_publisher.py
File metadata and controls
1724 lines (1396 loc) · 69.9 KB
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
#!/usr/bin/env python3
"""
Reddit Modlog Wiki Publisher
Scrapes moderation logs and publishes them to a subreddit wiki page
"""
import argparse
import hashlib
import json
import logging
import os
import re
import sqlite3
import sys
import time
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
import praw
DB_PATH = os.getenv("DATABASE_PATH", "modlog.db")
LOGS_DIR = os.getenv("LOGS_DIR", "logs")
BASE_BACKOFF_WAIT = 30
MAX_BACKOFF_WAIT = 300
logger = logging.getLogger(__name__)
# Action type configurations
REMOVAL_ACTIONS = ["removelink", "removecomment", "spamlink", "spamcomment"]
APPROVAL_ACTIONS = ["approvelink", "approvecomment"]
REASON_ACTIONS = ["addremovalreason"]
DEFAULT_WIKI_ACTIONS = REMOVAL_ACTIONS + REASON_ACTIONS + APPROVAL_ACTIONS
# Valid Reddit modlog actions (hardcoded for validation)
VALID_MODLOG_ACTIONS = [
# Content removal
"removelink",
"removecomment",
"spamlink",
"spamcomment",
# Content approval
"approvelink",
"approvecomment",
# Moderation reasons and notes
"addremovalreason",
"addnote",
"deletenote",
# User actions
"banuser",
"unbanuser",
"muteuser",
"unmuteuser",
"invitemoderator",
"acceptmoderatorinvite",
# Post management
"distinguish",
"undistinguish",
"sticky",
"unsticky",
"lock",
"unlock",
"marknsfw",
"unmarknsfw",
# Wiki actions
"wikirevise",
"wikipagelisted",
"wikipermlevel",
"wikibanned",
"wikicontributor",
# Settings and rules
"editsettings",
"editflair",
"createrule",
"editrule",
"deleterule",
"reorderrules",
# Reports and modmail
"ignorereports",
"unignorereports",
"request_assistance",
# Community features
"community_widgets",
"community_welcome_page",
"edit_post_requirements",
"edit_comment_requirements",
# Saved responses
"edit_saved_response",
# Collections
"addtocollection",
"removefromcollection",
]
# Configuration limits and defaults
CONFIG_LIMITS = {
"retention_days": {"min": 1, "max": 365, "default": 90},
"batch_size": {"min": 10, "max": 500, "default": 50},
"update_interval": {"min": 60, "max": 3600, "default": 600},
"max_wiki_entries_per_page": {"min": 100, "max": 2000, "default": 1000},
"max_continuous_errors": {"min": 1, "max": 50, "default": 5},
"rate_limit_buffer": {"min": 30, "max": 300, "default": 60},
"max_batch_retries": {"min": 1, "max": 10, "default": 3},
"archive_threshold_days": {"min": 1, "max": 30, "default": 7},
}
# Database schema version
CURRENT_DB_VERSION = 5
def get_db_version():
"""Get current database schema version"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Check if version table exists
cursor.execute("""
SELECT name FROM sqlite_master
WHERE type='table' AND name='schema_version'
""")
if not cursor.fetchone():
conn.close()
return 0
cursor.execute("SELECT version FROM schema_version ORDER BY id DESC LIMIT 1")
result = cursor.fetchone()
conn.close()
return result[0] if result else 0
except Exception as e:
logger.warning(f"Could not determine database version: {e}")
return 0
def set_db_version(version):
"""Set database schema version"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS schema_version (
id INTEGER PRIMARY KEY AUTOINCREMENT,
version INTEGER NOT NULL,
applied_at INTEGER DEFAULT (strftime('%s', 'now'))
)
""")
cursor.execute("INSERT INTO schema_version (version) VALUES (?)", (version,))
conn.commit()
conn.close()
logger.info(f"Database schema version set to {version}")
except Exception as e:
logger.error(f"Failed to set database version: {e}")
raise
def validate_config_value(key, value, config_limits):
"""Validate and enforce configuration limits"""
if key not in config_limits:
return value
limits = config_limits[key]
if value < limits["min"]:
logger.warning(f"{key} value {value} below minimum {limits['min']}, using minimum")
return limits["min"]
elif value > limits["max"]:
logger.warning(f"{key} value {value} above maximum {limits['max']}, using maximum")
return limits["max"]
return value
def validate_wiki_actions(wiki_actions):
"""Validate wiki_actions against known Reddit modlog actions"""
if not isinstance(wiki_actions, list):
raise ValueError("wiki_actions must be a list")
if not wiki_actions:
logger.info("Empty wiki_actions, using defaults")
return DEFAULT_WIKI_ACTIONS
invalid_actions = [action for action in wiki_actions if action not in VALID_MODLOG_ACTIONS]
if invalid_actions:
raise ValueError(f"Invalid modlog actions: {invalid_actions}. Valid actions: {sorted(VALID_MODLOG_ACTIONS)}")
logger.info(f"Validated {len(wiki_actions)} wiki_actions: {wiki_actions}")
return wiki_actions
def apply_config_defaults_and_limits(config):
"""Apply default values and enforce limits on configuration"""
for key, limits in CONFIG_LIMITS.items():
if key not in config:
config[key] = limits["default"]
logger.info(f"Using default value for {key}: {limits['default']}")
else:
config[key] = validate_config_value(key, config[key], CONFIG_LIMITS)
# Set default wiki actions if not specified
if "wiki_actions" not in config:
config["wiki_actions"] = DEFAULT_WIKI_ACTIONS
logger.info("Using default wiki_actions: removals, removal reasons, and approvals")
else:
config["wiki_actions"] = validate_wiki_actions(config["wiki_actions"])
# Validate required fields
required_fields = ["reddit", "source_subreddit"]
for field in required_fields:
if field not in config:
raise ValueError(f"Missing required configuration field: {field}")
# Validate reddit credentials
reddit_config = config.get("reddit", {})
required_reddit_fields = ["client_id", "client_secret", "username", "password"]
for field in required_reddit_fields:
if field not in reddit_config or not reddit_config[field]:
raise ValueError(f"Missing required reddit configuration field: {field}")
# CRITICAL SECURITY CHECK: Never allow moderator de-anonymization on live Reddit
if not config.get("anonymize_moderators", True):
raise ValueError("SECURITY: anonymize_moderators=false is not allowed. This would expose moderator identities publicly.")
return config
def migrate_database():
"""Run database migrations to current version"""
current_version = get_db_version()
target_version = CURRENT_DB_VERSION
if current_version >= target_version:
logger.info(f"Database already at version {current_version}, no migration needed")
return
logger.info(f"Migrating database from version {current_version} to {target_version}")
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Migration from version 0 to 1: Initial schema
if current_version < 1:
logger.info("Applying migration: Initial schema (v0 -> v1)")
cursor.execute("""
CREATE TABLE IF NOT EXISTS processed_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
action_id TEXT UNIQUE NOT NULL,
created_at INTEGER NOT NULL,
processed_at INTEGER DEFAULT (strftime('%s', 'now'))
)
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_action_id ON processed_actions(action_id)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_created_at ON processed_actions(created_at)")
set_db_version(1)
# Migration from version 1 to 2: Add tracking columns
if current_version < 2:
logger.info("Applying migration: Add tracking columns (v1 -> v2)")
# Check if columns already exist to handle partial migrations
cursor.execute("PRAGMA table_info(processed_actions)")
existing_columns = [row[1] for row in cursor.fetchall()]
columns_to_add = [
("action_type", "TEXT"),
("moderator", "TEXT"),
("target_id", "TEXT"),
("target_type", "TEXT"),
("display_id", "TEXT"),
("target_permalink", "TEXT"),
]
for column_name, column_type in columns_to_add:
if column_name not in existing_columns:
try:
cursor.execute(f"ALTER TABLE processed_actions ADD COLUMN {column_name} {column_type}")
logger.info(f"Added column: {column_name}")
except sqlite3.OperationalError as e:
if "duplicate column name" not in str(e):
raise
# Add new indexes
cursor.execute("CREATE INDEX IF NOT EXISTS idx_display_id ON processed_actions(display_id)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_target_id ON processed_actions(target_id)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_target_type ON processed_actions(target_type)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_moderator ON processed_actions(moderator)")
set_db_version(2)
# Migration from version 2 to 3: Add removal reason column
if current_version < 3:
logger.info("Applying migration: Add removal reason column (v2 -> v3)")
# Check if column already exists
cursor.execute("PRAGMA table_info(processed_actions)")
existing_columns = [row[1] for row in cursor.fetchall()]
if "removal_reason" not in existing_columns:
try:
cursor.execute("ALTER TABLE processed_actions ADD COLUMN removal_reason TEXT")
logger.info("Added column: removal_reason")
except sqlite3.OperationalError as e:
if "duplicate column name" not in str(e):
raise
set_db_version(3)
# Migration from version 3 to 4: Add wiki hash caching table
if current_version < 4:
logger.info("Applying migration: Add wiki hash caching table (v3 -> v4)")
cursor.execute("""
CREATE TABLE IF NOT EXISTS wiki_hash_cache (
id INTEGER PRIMARY KEY AUTOINCREMENT,
subreddit TEXT NOT NULL,
wiki_page TEXT NOT NULL,
content_hash TEXT NOT NULL,
last_updated INTEGER DEFAULT (strftime('%s', 'now')),
UNIQUE(subreddit, wiki_page)
)
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_subreddit_page ON wiki_hash_cache(subreddit, wiki_page)")
logger.info("Created wiki_hash_cache table")
set_db_version(4)
# Migration from version 4 to 5: Add subreddit column
if current_version < 5:
logger.info("Applying migration: Add subreddit column (v4 -> v5)")
# Check if column already exists
cursor.execute("PRAGMA table_info(processed_actions)")
existing_columns = [row[1] for row in cursor.fetchall()]
if "subreddit" not in existing_columns:
try:
cursor.execute("ALTER TABLE processed_actions ADD COLUMN subreddit TEXT")
logger.info("Added column: subreddit")
except sqlite3.OperationalError as e:
if "duplicate column name" not in str(e):
raise
cursor.execute("CREATE INDEX IF NOT EXISTS idx_subreddit ON processed_actions(subreddit)")
set_db_version(5)
conn.commit()
conn.close()
logger.info(f"Database migration completed successfully to version {target_version}")
except Exception as e:
logger.error(f"Database migration failed: {e}")
raise
def setup_database():
"""Initialize and migrate database"""
try:
migrate_database()
update_missing_subreddits()
logger.info("Database setup completed successfully")
except Exception as e:
logger.error(f"Database setup failed: {e}")
raise
def get_content_hash(content: str) -> str:
"""Calculate SHA-256 hash of content"""
return hashlib.sha256(content.encode("utf-8")).hexdigest()
def get_cached_wiki_hash(subreddit: str, wiki_page: str) -> Optional[str]:
"""Get cached wiki content hash for subreddit/page"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT content_hash FROM wiki_hash_cache WHERE subreddit = ? AND wiki_page = ?", (subreddit, wiki_page))
result = cursor.fetchone()
conn.close()
return result[0] if result else None
except Exception as e:
logger.warning(f"Failed to get cached wiki hash: {e}")
return None
def update_cached_wiki_hash(subreddit: str, wiki_page: str, content_hash: str):
"""Update cached wiki content hash for subreddit/page"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"""
INSERT OR REPLACE INTO wiki_hash_cache (subreddit, wiki_page, content_hash, last_updated)
VALUES (?, ?, ?, strftime('%s', 'now'))
""",
(subreddit, wiki_page, content_hash),
)
conn.commit()
conn.close()
logger.debug(f"Updated cached hash for /r/{subreddit}/wiki/{wiki_page}")
except Exception as e:
logger.warning(f"Failed to update cached wiki hash: {e}")
def censor_email_addresses(text):
"""Censor email addresses in removal reasons"""
if not text:
return text
import re
# Replace email addresses with [EMAIL]
return re.sub(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", "[EMAIL]", text)
def sanitize_for_markdown(text: str) -> str:
"""Sanitize text for use in markdown tables by escaping pipe characters"""
if text is None:
return ""
return str(text).replace("|", " ")
def get_config_with_default(config: Dict[str, Any], key: str) -> Any:
"""Get config value with fallback to CONFIG_LIMITS default"""
if key not in CONFIG_LIMITS:
raise ValueError(f"Unknown config key: {key}")
return config.get(key, CONFIG_LIMITS[key]["default"])
def get_action_datetime(action):
"""Convert action.created_utc to datetime object regardless of input type"""
if isinstance(action.created_utc, (int, float)):
return datetime.fromtimestamp(action.created_utc, tz=timezone.utc)
else:
return action.created_utc
def get_moderator_name(action, anonymize=True):
"""Get moderator name with optional anonymization for human moderators"""
if not action.mod:
return None
# Extract the actual moderator name
if isinstance(action.mod, str):
mod_name = action.mod
else:
mod_name = action.mod.name
# Handle special cases - don't censor these, match main branch exactly
if mod_name.lower() in ["automoderator", "reddit"]:
if mod_name.lower() == "automoderator":
return "AutoModerator" # Match main branch exactly
else:
return "Reddit"
# For human moderators, show generic label or actual name based on config
if anonymize:
return "HumanModerator"
else:
return mod_name
def extract_target_id(action):
"""Extract Reddit ID from action target - NEVER return user ID"""
# Priority order: get actual post/comment ID first
if hasattr(action, "target_submission") and action.target_submission:
if hasattr(action.target_submission, "id"):
return action.target_submission.id
else:
# Extract ID from submission object string representation
target_str = str(action.target_submission)
if target_str.startswith("t3_"):
return target_str[3:] # Remove t3_ prefix
return target_str
elif hasattr(action, "target_comment") and action.target_comment:
if hasattr(action.target_comment, "id"):
return action.target_comment.id
else:
# Extract ID from comment object string representation
target_str = str(action.target_comment)
if target_str.startswith("t1_"):
return target_str[3:] # Remove t1_ prefix
return target_str
else:
# For user-related actions, use action ID instead of user ID
return action.id
def get_target_type(action):
"""Determine target type for ID prefix"""
if hasattr(action, "target_submission") and action.target_submission:
return "post"
elif hasattr(action, "target_comment") and action.target_comment:
return "comment"
elif hasattr(action, "target_author"):
return "user"
else:
return "action"
def generate_display_id(action):
"""Generate human-readable display ID - NEVER use user ID"""
target_id = extract_target_id(action)
target_type = get_target_type(action)
# Prefix mapping: P=post, C=comment, U=user, A=action
prefixes = {"post": "P", "comment": "C", "user": "U", "action": "A"}
prefix = prefixes.get(target_type, "ZZU")
# Shorten long IDs for display
if len(str(target_id)) > 8 and target_type in ["post", "comment"]:
short_id = str(target_id)[:6]
return f"{prefix}{short_id}"
else:
return f"{prefix}{target_id}"
def get_target_permalink(action):
"""Get permalink for the target content - prioritize actual content over user profiles"""
# Check if we have a cached permalink from database
if hasattr(action, "target_permalink_cached") and action.target_permalink_cached:
return action.target_permalink_cached
try:
# Priority 1: get actual post/comment permalinks from Reddit API
if hasattr(action, "target_submission") and action.target_submission:
if hasattr(action.target_submission, "permalink"):
return f"https://reddit.com{action.target_submission.permalink}"
elif hasattr(action.target_submission, "id"):
# Construct permalink from submission ID
return f"https://reddit.com/comments/{action.target_submission.id}/"
elif hasattr(action, "target_comment") and action.target_comment:
if hasattr(action.target_comment, "permalink"):
return f"https://reddit.com{action.target_comment.permalink}"
elif hasattr(action.target_comment, "id") and hasattr(action.target_comment, "submission"):
# For comments, construct proper permalink with submission ID
return f"https://reddit.com/comments/{action.target_comment.submission.id}/_/{action.target_comment.id}/"
elif hasattr(action.target_comment, "id"):
# Fallback for comment without submission info
return f"https://reddit.com/comments/{action.target_comment.id}/"
# Priority 2: Try to get content permalink from action.target_permalink if it's not a user profile
if hasattr(action, "target_permalink") and action.target_permalink:
permalink = action.target_permalink
# Only use if it's actual content (contains /comments/) not user profile (/u/)
if "/comments/" in permalink and "/u/" not in permalink:
return f"https://reddit.com{permalink}" if not permalink.startswith("http") else permalink
# NEVER fall back to user profiles - only link to actual content
except:
pass
return None
def is_duplicate_action(action_id: str) -> bool:
"""Check if action has already been processed"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT 1 FROM processed_actions WHERE action_id = ? LIMIT 1", (action_id,))
result = cursor.fetchone() is not None
conn.close()
return result
except Exception as e:
logger.error(f"Error checking duplicate action: {e}")
return False
def extract_subreddit_from_permalink(permalink):
"""Extract subreddit name from Reddit permalink URL"""
if not permalink:
return None
import re
# Match patterns like /r/subreddit/ or https://reddit.com/r/subreddit/
match = re.search(r"/r/([^/]+)/", permalink)
return match.group(1) if match else None
def store_processed_action(action, subreddit_name=None):
"""Store processed action to prevent duplicates"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Process removal reason properly - ALWAYS prefer actual text over numeric details
removal_reason = None
# For addremovalreason actions, use description field (contains actual text)
if action.action == "addremovalreason" and hasattr(action, "description") and action.description:
removal_reason = censor_email_addresses(str(action.description).strip())
# First priority: mod_note (actual removal reason text)
elif hasattr(action, "mod_note") and action.mod_note:
removal_reason = censor_email_addresses(str(action.mod_note).strip())
# Second priority: details (accept ALL details text, including numbers)
elif hasattr(action, "details") and action.details:
details_str = str(action.details).strip()
removal_reason = censor_email_addresses(details_str)
# Extract subreddit from URL if not provided
target_permalink = get_target_permalink(action)
if not subreddit_name and target_permalink:
subreddit_name = extract_subreddit_from_permalink(target_permalink)
# Add subreddit column if it doesn't exist
cursor.execute("PRAGMA table_info(processed_actions)")
columns = [row[1] for row in cursor.fetchall()]
if "subreddit" not in columns:
cursor.execute("ALTER TABLE processed_actions ADD COLUMN subreddit TEXT")
# Add target_author column if it doesn't exist
if "target_author" not in columns:
cursor.execute("ALTER TABLE processed_actions ADD COLUMN target_author TEXT")
# Extract target author
target_author = None
if hasattr(action, "target_author") and action.target_author:
if hasattr(action.target_author, "name"):
target_author = action.target_author.name
else:
target_author = str(action.target_author)
cursor.execute(
"""
INSERT OR REPLACE INTO processed_actions
(action_id, action_type, moderator, target_id, target_type,
display_id, target_permalink, removal_reason, target_author, created_at, subreddit) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
action.id,
action.action,
get_moderator_name(action, False), # Store actual name in database
extract_target_id(action),
get_target_type(action),
generate_display_id(action),
target_permalink,
sanitize_for_markdown(removal_reason), # Store properly processed removal reason
target_author,
int(action.created_utc) if isinstance(action.created_utc, (int, float)) else int(action.created_utc.timestamp()),
subreddit_name or "unknown",
),
)
conn.commit()
conn.close()
except Exception as e:
logger.error(f"Error storing processed action: {e}")
raise
def update_missing_subreddits():
"""Update NULL subreddit entries by extracting from permalinks"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Get entries with NULL subreddit but valid permalink
cursor.execute("""
SELECT id, target_permalink FROM processed_actions
WHERE subreddit IS NULL AND target_permalink IS NOT NULL
""")
updates = []
for row_id, permalink in cursor.fetchall():
subreddit = extract_subreddit_from_permalink(permalink)
if subreddit:
updates.append((subreddit, row_id))
# Update entries in batches
if updates:
cursor.executemany("UPDATE processed_actions SET subreddit = ? WHERE id = ?", updates)
logger.info(f"Updated {len(updates)} entries with extracted subreddit names")
conn.commit()
conn.close()
except Exception as e:
logger.error(f"Error updating missing subreddits: {e}")
def cleanup_old_entries(retention_days: int):
"""Remove entries older than retention_days"""
if retention_days <= 0:
retention_days = CONFIG_LIMITS["retention_days"]["default"] # No config object available here
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cutoff_timestamp = int((datetime.now() - datetime.fromtimestamp(0)).total_seconds()) - (retention_days * 86400)
cursor.execute("DELETE FROM processed_actions WHERE created_at < ?", (cutoff_timestamp,))
deleted_count = cursor.rowcount
conn.commit()
conn.close()
if deleted_count > 0:
logger.info(f"Cleaned up {deleted_count} old entries")
except Exception as e:
logger.error(f"Error during cleanup: {e}")
def get_recent_actions_from_db(config: Dict[str, Any], force_all_actions: bool = False, show_only_removals: bool = True) -> List:
"""Fetch recent actions from database for force refresh"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# For force refresh, get ALL actions, not just wiki_actions filter
if force_all_actions:
# Get all unique action types in database
cursor.execute("SELECT DISTINCT action_type FROM processed_actions WHERE action_type IS NOT NULL")
wiki_actions = set(row[0] for row in cursor.fetchall())
logger.info(f"Force refresh: including all action types: {wiki_actions}")
elif show_only_removals:
wiki_actions = set(DEFAULT_WIKI_ACTIONS)
else:
# Get configurable list of actions to show in wiki
wiki_actions = set(config.get("wiki_actions", DEFAULT_WIKI_ACTIONS))
# Get recent actions within retention period
retention_days = get_config_with_default(config, "retention_days")
cutoff_timestamp = int((datetime.now() - datetime.fromtimestamp(0)).total_seconds()) - (retention_days * 86400)
# Limit to max wiki entries
max_entries = get_config_with_default(config, "max_wiki_entries_per_page")
placeholders = ",".join(["?"] * len(wiki_actions))
# STRICT subreddit filtering - only exact matches, no nulls
subreddit_name = config.get("source_subreddit", "")
logger.debug(f"Query parameters - cutoff: {cutoff_timestamp}, wiki_actions: {wiki_actions}, subreddit: '{subreddit_name}', max_entries: {max_entries}")
# Check if actions exist for the requested subreddit
cursor.execute(
"""
SELECT COUNT(*) FROM processed_actions
WHERE created_at >= ? AND action_type IN ({})
AND LOWER(subreddit) = LOWER(?)
""".format(placeholders),
[cutoff_timestamp] + list(wiki_actions) + [subreddit_name],
)
action_count = cursor.fetchone()[0]
# If no actions exist for this subreddit, return empty list
if action_count == 0:
logger.info(f"No actions found for subreddit '{subreddit_name}' in the specified time range")
conn.close()
return []
logger.debug(f"Found {action_count} actions for subreddit '{subreddit_name}'")
# Get list of all subreddits for informational purposes
cursor.execute(
"""
SELECT DISTINCT LOWER(subreddit) FROM processed_actions
WHERE created_at >= ? AND subreddit IS NOT NULL
""",
[cutoff_timestamp],
)
all_subreddits = [row[0] for row in cursor.fetchall() if row[0]]
if len(all_subreddits) > 1:
logger.info(f"Multi-subreddit database contains data for: {sorted(all_subreddits)}")
logger.info(f"Retrieving actions for subreddit: '{subreddit_name}'")
query = f"""
SELECT action_id, action_type, moderator, target_id, target_type,
display_id, target_permalink, removal_reason, target_author, created_at
FROM processed_actions
WHERE created_at >= ? AND action_type IN ({placeholders})
AND LOWER(subreddit) = LOWER(?)
ORDER BY created_at DESC
LIMIT ?
"""
cursor.execute(query, [cutoff_timestamp] + list(wiki_actions) + [subreddit_name, max_entries])
rows = cursor.fetchall()
conn.close()
logger.debug(f"Database query returned {len(rows)} rows")
# Convert database rows to mock action objects for compatibility with existing functions
mock_actions = []
for row in rows:
action_id, action_type, moderator, target_id, target_type, display_id, target_permalink, removal_reason, target_author, created_at = row
logger.debug(f"Processing cached action: {action_type} by {moderator} at {created_at}")
# Create a mock action object with the data we have
class MockAction:
def __init__(self, action_id, action_type, moderator, target_id, target_type, display_id, target_permalink, removal_reason, target_author, created_at):
self.id = action_id
self.action = action_type
self.mod = moderator
# Use the created_at directly
self.created_utc = created_at
self.details = removal_reason
self.display_id = display_id
self.target_permalink = (
target_permalink.replace("https://reddit.com", "") if target_permalink and target_permalink.startswith("https://reddit.com") else target_permalink
)
self.target_permalink_cached = target_permalink
# Use actual target_author from database
self.target_title = None
self.target_author = target_author # Use actual target_author from database
mock_actions.append(MockAction(action_id, action_type, moderator, target_id, target_type, display_id, target_permalink, removal_reason, target_author, created_at))
logger.info(f"Retrieved {len(mock_actions)} actions from database for force refresh")
return mock_actions
except Exception as e:
logger.error(f"Error fetching actions from database: {e}")
return []
def format_content_link(action) -> str:
"""Format content link for wiki table - matches main branch approach exactly"""
# Use actual Reddit API data like main branch does
formatted_link = ""
if hasattr(action, "target_permalink") and action.target_permalink:
formatted_link = f"https://www.reddit.com{action.target_permalink}"
elif hasattr(action, "target_permalink_cached") and action.target_permalink_cached:
formatted_link = action.target_permalink_cached
# Check if comment using main branch logic
is_comment = bool(hasattr(action, "target_permalink") and action.target_permalink and "/comments/" in action.target_permalink and action.target_permalink.count("/") > 6)
# Determine title using main branch approach
formatted_title = ""
if is_comment and hasattr(action, "target_title") and action.target_title:
formatted_title = action.target_title
elif is_comment and (not hasattr(action, "target_title") or not action.target_title):
target_author = action.target_author if hasattr(action, "target_author") and action.target_author else "[deleted]"
formatted_title = f"Comment by u/{target_author}"
elif not is_comment and hasattr(action, "target_title") and action.target_title:
formatted_title = action.target_title
elif not is_comment and (not hasattr(action, "target_title") or not action.target_title):
target_author = action.target_author if hasattr(action, "target_author") and action.target_author else "[deleted]"
formatted_title = f"Post by u/{target_author}"
else:
formatted_title = "Unknown content"
# Format with link like main branch
if formatted_link:
formatted_title = f"[{formatted_title}]({formatted_link})"
return sanitize_for_markdown(formatted_title)
def extract_content_id_from_permalink(permalink):
"""Extract the actual post/comment ID from Reddit permalink URL"""
if not permalink:
return None
import re
# Check for comment ID first - URLs like /comments/abc123/title/def456/
comment_match = re.search(r"/comments/[a-zA-Z0-9]+/[^/]*/([a-zA-Z0-9]+)/?", permalink)
if comment_match:
return f"t1_{comment_match.group(1)}"
# Extract post ID from URLs like /comments/abc123/ (only if no comment ID found)
post_match = re.search(r"/comments/([a-zA-Z0-9]+)/", permalink)
if post_match:
return f"t3_{post_match.group(1)}"
return None
def format_modlog_entry(action, config: Dict[str, Any]) -> Dict[str, str]:
"""Format modlog entry - matches main branch approach exactly"""
reason_text = "-"
if hasattr(action, "combined_reason") and action.combined_reason:
reason_text = str(action.combined_reason).strip()
elif hasattr(action, "approval_context") and action.approval_context:
reason_text = str(action.approval_context).strip()
else:
parsed_mod_note = ""
if hasattr(action, "mod_note") and action.mod_note:
parsed_mod_note = str(action.mod_note).strip()
elif hasattr(action, "details") and action.details:
parsed_mod_note = str(action.details).strip()
if hasattr(action, "details") and action.details:
reason_text = str(action.details).strip()
if action.action in ["addremovalreason"]:
reason_text = parsed_mod_note if parsed_mod_note else reason_text
elif parsed_mod_note:
reason_text = parsed_mod_note
content_id = "-"
if hasattr(action, "target_permalink") and action.target_permalink:
extracted_id = extract_content_id_from_permalink(action.target_permalink)
if extracted_id:
content_id = extracted_id.replace("t3_", "").replace("t1_", "")[:8]
display_action = action.action
if action.action in REMOVAL_ACTIONS and get_moderator_name(action, False) == "AutoModerator":
display_action = f"filter-{action.action}"
return {
"time": get_action_datetime(action).strftime("%H:%M:%S UTC"),
"action": display_action,
"id": content_id,
"moderator": get_moderator_name(action, config.get("anonymize_moderators", True)) or "Unknown",
"content": format_content_link(action),
"reason": sanitize_for_markdown(str(reason_text)),
"inquire": generate_modmail_link(config["source_subreddit"], action),
}
def generate_modmail_link(subreddit: str, action) -> str:
"""Generate modmail link for user inquiries with content ID for tracking"""
from urllib.parse import quote
# Determine removal type like main branch
type_map = {
"removelink": "Post",
"removepost": "Post",
"removecomment": "Comment",
"spamlink": "Spam Post",
"spamcomment": "Spam Comment",
"removecontent": "Content",
"addremovalreason": "Removal Reason",
}
removal_type = type_map.get(action.action, "Content")
# Get content ID for tracking
content_id = "-"
if hasattr(action, "target_permalink") and action.target_permalink:
extracted_id = extract_content_id_from_permalink(action.target_permalink)
if extracted_id:
content_id = extracted_id.replace("t3_", "").replace("t1_", "")[:8]
# Get title and truncate if needed
if hasattr(action, "target_title") and action.target_title:
title = action.target_title
else:
title = f"Content by u/{action.target_author}" if hasattr(action, "target_author") and action.target_author else "Unknown content"
# Truncate title if too long
max_title_length = 50
if len(title) > max_title_length:
title = title[: max_title_length - 3] + "..."
# Get URL
url = ""
if hasattr(action, "target_permalink_cached") and action.target_permalink_cached:
url = action.target_permalink_cached
elif hasattr(action, "target_permalink") and action.target_permalink:
url = f"https://www.reddit.com{action.target_permalink}" if not action.target_permalink.startswith("http") else action.target_permalink
# Create subject line with content ID for tracking
subject = f"{removal_type} Removal Inquiry - {title} [ID: {content_id}]"
# Create body with content ID for easier modmail tracking
body = (
f"Hello Moderators of /r/{subreddit},\n\n"
f"I would like to inquire about the recent removal of the following {removal_type.lower()}:\n\n"
f"**Content ID:** {content_id}\n\n"
f"**Title:** {title}\n\n"
f"**Action Type:** {action.action}\n\n"
f"**Link:** {url}\n\n"
"Please provide details regarding this action.\n\n"
"Thank you!"
)
modmail_url = f"https://www.reddit.com/message/compose?to=/r/{subreddit}&subject={quote(subject)}&message={quote(body)}"
return f"[Contact Mods]({modmail_url})"
def build_wiki_content(actions: List, config: Dict[str, Any]) -> str:
"""Build wiki page content from actions"""
# Add timestamp header at the top
current_time = datetime.now(timezone.utc)
timestamp_header = f"**Last Updated:** {current_time.strftime('%Y-%m-%d %H:%M:%S UTC')}\n\n---\n\n"
if not actions:
return timestamp_header + "No recent moderation actions found."
# CRITICAL: Validate all actions belong to the same subreddit before building content
target_subreddit = config.get("source_subreddit", "")
mixed_subreddits = set()
for action in actions:
# Check if action has subreddit info and if it matches (case-insensitive)
if hasattr(action, "subreddit") and action.subreddit:
if action.subreddit.lower() != target_subreddit.lower():
mixed_subreddits.add(action.subreddit)