Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
1202 lines (1057 loc) · 45.2 KB
/
Copy pathdatabase.py
File metadata and controls
1202 lines (1057 loc) · 45.2 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
# database.py
import sqlite3
from typing import List, Dict, Optional, Any
import logging
from datetime import datetime
class Database:
def __init__(self, db_name: str):
self.database_name = db_name
self.conn = sqlite3.connect(db_name)
self.cursor = self.conn.cursor()
self.setup_database()
def setup_database(self):
"""初始化数据库表"""
# 首先检查数据库是否已存在且有数据
import os
import time
import shutil
existing_db = os.path.exists(self.database_name) and os.path.getsize(self.database_name) > 0
# 如果数据库已存在,创建备份
if existing_db:
# 确保备份目录存在
backup_dir = "data/backups"
os.makedirs(backup_dir, exist_ok=True)
# 生成备份文件名
db_filename = os.path.basename(self.database_name)
backup_name = os.path.join(backup_dir, f"{db_filename}.backup_{int(time.time())}")
# 创建备份
shutil.copy2(self.database_name, backup_name)
logging.info(f"已创建数据库备份: {backup_name}")
# 使用 CREATE TABLE IF NOT EXISTS 添加新表
# 这样不会影响现有表和数据
self.cursor.executescript('''
CREATE TABLE IF NOT EXISTS channels (
channel_id INTEGER PRIMARY KEY,
channel_name TEXT,
channel_username TEXT,
channel_type TEXT CHECK(channel_type IN ('MONITOR', 'FORWARD')),
added_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT 1
);
CREATE TABLE IF NOT EXISTS channel_pairs (
monitor_channel_id INTEGER,
forward_channel_id INTEGER,
added_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT 1,
PRIMARY KEY (monitor_channel_id, forward_channel_id),
FOREIGN KEY (monitor_channel_id) REFERENCES channels(channel_id),
FOREIGN KEY (forward_channel_id) REFERENCES channels(channel_id)
);
CREATE TABLE IF NOT EXISTS user_preferences (
user_id INTEGER PRIMARY KEY,
language TEXT DEFAULT 'en',
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 新增过滤规则表
CREATE TABLE IF NOT EXISTS filter_rules (
rule_id INTEGER PRIMARY KEY AUTOINCREMENT,
pair_id TEXT, -- 格式:"monitor_id:forward_id"
rule_type TEXT CHECK(rule_type IN ('WHITELIST', 'BLACKLIST')),
filter_mode TEXT CHECK(filter_mode IN ('KEYWORD', 'REGEX')),
pattern TEXT NOT NULL,
is_active BOOLEAN DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 新增媒体类型过滤表
CREATE TABLE IF NOT EXISTS media_filters (
filter_id INTEGER PRIMARY KEY AUTOINCREMENT,
pair_id TEXT, -- 格式:"monitor_id:forward_id"
media_type TEXT CHECK(media_type IN ('photo', 'video', 'audio', 'document', 'animation', 'sticker', 'text')),
action TEXT CHECK(action IN ('ALLOW', 'BLOCK')) DEFAULT 'ALLOW',
is_active BOOLEAN DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 新增时间段设置表
CREATE TABLE IF NOT EXISTS time_filters (
filter_id INTEGER PRIMARY KEY AUTOINCREMENT,
pair_id TEXT, -- 格式:"monitor_id:forward_id"
start_time TEXT, -- 格式:"HH:MM"
end_time TEXT, -- 格式:"HH:MM"
days_of_week TEXT, -- 格式:"1,2,3,4,5,6,7" (1=周一)
is_active BOOLEAN DEFAULT 1,
mode TEXT CHECK(mode IN ('ALLOW', 'BLOCK')) DEFAULT 'ALLOW',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 新增消息转发关系跟踪表
CREATE TABLE IF NOT EXISTS forwarded_messages (
original_chat_id INTEGER,
original_message_id INTEGER,
forwarded_chat_id INTEGER,
forwarded_message_id INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (original_chat_id, original_message_id, forwarded_chat_id)
);
CREATE INDEX IF NOT EXISTS idx_channels_type
ON channels(channel_type);
CREATE INDEX IF NOT EXISTS idx_channels_active
ON channels(is_active);
CREATE INDEX IF NOT EXISTS idx_pairs_monitor
ON channel_pairs(monitor_channel_id);
CREATE INDEX IF NOT EXISTS idx_pairs_forward
ON channel_pairs(forward_channel_id);
CREATE INDEX IF NOT EXISTS idx_pairs_active
ON channel_pairs(is_active);
-- 新增索引
CREATE INDEX IF NOT EXISTS idx_filter_rules_pair_id
ON filter_rules(pair_id);
CREATE INDEX IF NOT EXISTS idx_filter_rules_active
ON filter_rules(is_active);
CREATE INDEX IF NOT EXISTS idx_time_filters_pair_id
ON time_filters(pair_id);
CREATE INDEX IF NOT EXISTS idx_time_filters_active
ON time_filters(is_active);
CREATE INDEX IF NOT EXISTS idx_media_filters_pair_id
ON media_filters(pair_id);
CREATE INDEX IF NOT EXISTS idx_media_filters_active
ON media_filters(is_active);
CREATE INDEX IF NOT EXISTS idx_media_filters_type
ON media_filters(media_type);
''')
self.conn.commit()
def get_user_language(self, user_id: int) -> str:
"""获取用户语言设置"""
try:
self.cursor.execute('''
SELECT language FROM user_preferences
WHERE user_id = ?
''', (user_id,))
result = self.cursor.fetchone()
return result[0] if result else 'en'
except sqlite3.Error as e:
logging.error(f"Error getting user language: {e}")
return 'en'
def set_user_language(self, user_id: int, language: str) -> bool:
"""设置用户语言偏好"""
try:
self.cursor.execute('''
INSERT OR REPLACE INTO user_preferences (user_id, language, updated_at)
VALUES (?, ?, CURRENT_TIMESTAMP)
''', (user_id, language))
self.conn.commit()
return True
except sqlite3.Error as e:
logging.error(f"Error setting user language: {e}")
return False
def add_channel(self, channel_id: int, channel_name: str,
channel_username: Optional[str], channel_type: str) -> bool:
"""添加新频道"""
try:
# 首先检查频道是否已存在
self.cursor.execute('''
SELECT channel_id, is_active FROM channels
WHERE channel_id = ?
''', (channel_id,))
existing = self.cursor.fetchone()
if existing:
# 如果频道存在但被停用,重新激活它
if not existing[1]:
self.cursor.execute('''
UPDATE channels
SET is_active = 1,
channel_name = ?,
channel_username = ?,
channel_type = ?,
added_date = CURRENT_TIMESTAMP
WHERE channel_id = ?
''', (channel_name, channel_username, channel_type, channel_id))
else:
# 更新现有频道信息
self.cursor.execute('''
UPDATE channels
SET channel_name = ?,
channel_username = ?,
channel_type = ?
WHERE channel_id = ?
''', (channel_name, channel_username, channel_type, channel_id))
else:
# 添加新频道
self.cursor.execute('''
INSERT INTO channels
(channel_id, channel_name, channel_username, channel_type)
VALUES (?, ?, ?, ?)
''', (channel_id, channel_name, channel_username, channel_type))
self.conn.commit()
return True
except sqlite3.Error as e:
logging.error(f"Error in add_channel: {e}")
return False
def remove_channel(self, channel_id: int) -> bool:
"""移除频道及相关数据"""
try:
# 开始事务
self.cursor.execute('BEGIN TRANSACTION')
# 记录详细日志
logging.info(f"开始删除频道: {channel_id}")
# 获取频道类型信息,用于日志记录
self.cursor.execute('''
SELECT channel_name, channel_type FROM channels
WHERE channel_id = ? AND is_active = 1
''', (channel_id,))
channel_info = self.cursor.fetchone()
if not channel_info:
logging.warning(f"要删除的频道不存在或已经停用: {channel_id}")
self.conn.rollback()
return False
channel_name, channel_type = channel_info
logging.info(f"删除频道信息: {channel_name} (ID: {channel_id}, 类型: {channel_type})")
# 1. 停用所有相关的过滤规则
# 生成可能的pair_id模式
if channel_type == 'MONITOR':
# 如果是监控频道,则匹配所有以它为前缀的pair_id
pair_id_pattern = f"{channel_id}:%"
logging.info(f"停用以 {channel_id} 为监控频道的过滤规则")
else:
# 如果是转发频道,则匹配所有以它为后缀的pair_id
pair_id_pattern = f"%:{channel_id}"
logging.info(f"停用以 {channel_id} 为转发频道的过滤规则")
# 停用内容过滤规则
self.cursor.execute('''
UPDATE filter_rules
SET is_active = 0
WHERE pair_id LIKE ?
''', (pair_id_pattern,))
content_filter_count = self.cursor.rowcount
logging.info(f"停用了 {content_filter_count} 条内容过滤规则")
# 停用时间过滤规则
self.cursor.execute('''
UPDATE time_filters
SET is_active = 0
WHERE pair_id LIKE ?
''', (pair_id_pattern,))
time_filter_count = self.cursor.rowcount
logging.info(f"停用了 {time_filter_count} 条时间过滤规则")
# 停用媒体过滤规则
self.cursor.execute('''
UPDATE media_filters
SET is_active = 0
WHERE pair_id LIKE ?
''', (pair_id_pattern,))
media_filter_count = self.cursor.rowcount
logging.info(f"停用了 {media_filter_count} 条媒体过滤规则")
# 2. 停用所有涉及该频道的配对
self.cursor.execute('''
UPDATE channel_pairs
SET is_active = 0
WHERE monitor_channel_id = ? OR forward_channel_id = ?
''', (channel_id, channel_id))
pair_count = self.cursor.rowcount
logging.info(f"停用了 {pair_count} 个频道配对")
# 3. 停用频道本身
self.cursor.execute('''
UPDATE channels
SET is_active = 0
WHERE channel_id = ?
''', (channel_id,))
channel_count = self.cursor.rowcount
logging.info(f"停用了 {channel_count} 个频道")
# 提交事务
self.conn.commit()
logging.info(f"成功删除频道 {channel_name} (ID: {channel_id})")
return True
except sqlite3.Error as e:
# 发生错误时回滚
self.conn.rollback()
logging.error(f"Error in remove_channel: {e}")
logging.error(f"Full error details: {str(e)}")
return False
def get_channels_by_type(self, channel_type: str, page: int = 1, per_page: int = 7) -> Dict[str, Any]:
"""分页获取指定类型的频道"""
try:
# 获取总数
self.cursor.execute('''
SELECT COUNT(*) FROM channels
WHERE channel_type = ? AND is_active = 1
''', (channel_type,))
total = self.cursor.fetchone()[0]
# 计算总页数
total_pages = (total + per_page - 1) // per_page if total > 0 else 1
# 确保页码有效
page = max(1, min(page, total_pages))
# 计算偏移量
offset = (page - 1) * per_page
# 获取当前页的数据
self.cursor.execute('''
SELECT channel_id, channel_name, channel_username, is_active
FROM channels
WHERE channel_type = ? AND is_active = 1
ORDER BY added_date DESC
LIMIT ? OFFSET ?
''', (channel_type, per_page, offset))
channels = [{
'channel_id': row[0],
'channel_name': row[1],
'channel_username': row[2],
'is_active': row[3]
} for row in self.cursor.fetchall()]
return {
'channels': channels,
'total': total,
'current_page': page,
'total_pages': total_pages,
'per_page': per_page
}
except sqlite3.Error as e:
logging.error(f"Error in get_channels_by_type: {e}")
return {
'channels': [],
'total': 0,
'current_page': 1,
'total_pages': 1,
'per_page': per_page
}
def get_channel_pairs(self, page: int = 1, per_page: int = 7) -> Dict[str, Any]:
"""分页获取所有活跃的频道配对"""
try:
# 获取总数
self.cursor.execute('''
SELECT COUNT(*)
FROM channel_pairs cp
JOIN channels m ON cp.monitor_channel_id = m.channel_id
JOIN channels f ON cp.forward_channel_id = f.channel_id
WHERE cp.is_active = 1
AND m.is_active = 1
AND f.is_active = 1
''')
total = self.cursor.fetchone()[0]
# 计算总页数
total_pages = (total + per_page - 1) // per_page if total > 0 else 1
# 确保页码有效
page = max(1, min(page, total_pages))
# 计算偏移量
offset = (page - 1) * per_page
# 获取当前页的数据
self.cursor.execute('''
SELECT
cp.monitor_channel_id,
cp.forward_channel_id,
m.channel_name as monitor_name,
f.channel_name as forward_name,
cp.added_date
FROM channel_pairs cp
JOIN channels m ON cp.monitor_channel_id = m.channel_id
JOIN channels f ON cp.forward_channel_id = f.channel_id
WHERE cp.is_active = 1
AND m.is_active = 1
AND f.is_active = 1
ORDER BY cp.added_date DESC
LIMIT ? OFFSET ?
''', (per_page, offset))
pairs = [{
'monitor_channel_id': row[0],
'forward_channel_id': row[1],
'monitor_name': row[2],
'forward_name': row[3],
'added_date': row[4]
} for row in self.cursor.fetchall()]
return {
'pairs': pairs,
'total': total,
'current_page': page,
'total_pages': total_pages,
'per_page': per_page
}
except sqlite3.Error as e:
logging.error(f"Error in get_channel_pairs: {e}")
return {
'pairs': [],
'total': 0,
'current_page': 1,
'total_pages': 1,
'per_page': per_page
}
def get_unpaired_forward_channels(self, monitor_channel_id: int,
page: int = 1, per_page: int = 7) -> Dict[str, Any]:
"""获取未与指定监控频道配对的转发频道(带分页)"""
try:
# 获取总数
self.cursor.execute('''
SELECT COUNT(*)
FROM channels c
WHERE c.channel_type = 'FORWARD'
AND c.is_active = 1
AND c.channel_id NOT IN (
SELECT forward_channel_id
FROM channel_pairs
WHERE monitor_channel_id = ?
AND is_active = 1
)
''', (monitor_channel_id,))
total = self.cursor.fetchone()[0]
# 计算总页数
total_pages = (total + per_page - 1) // per_page if total > 0 else 1
# 确保页码有效
page = max(1, min(page, total_pages))
# 计算偏移量
offset = (page - 1) * per_page
# 获取数据
self.cursor.execute('''
SELECT c.channel_id, c.channel_name, c.channel_username
FROM channels c
WHERE c.channel_type = 'FORWARD'
AND c.is_active = 1
AND c.channel_id NOT IN (
SELECT forward_channel_id
FROM channel_pairs
WHERE monitor_channel_id = ?
AND is_active = 1
)
ORDER BY c.added_date DESC
LIMIT ? OFFSET ?
''', (monitor_channel_id, per_page, offset))
channels = [{
'channel_id': row[0],
'channel_name': row[1],
'channel_username': row[2]
} for row in self.cursor.fetchall()]
return {
'channels': channels,
'total': total,
'current_page': page,
'total_pages': total_pages,
'per_page': per_page
}
except sqlite3.Error as e:
logging.error(f"Error in get_unpaired_forward_channels: {e}")
return {
'channels': [],
'total': 0,
'current_page': 1,
'total_pages': 1,
'per_page': per_page
}
def get_forward_channels(self, monitor_channel_id: int,
page: int = 1, per_page: int = 7) -> Dict[str, Any]:
"""获取监控频道对应的所有转发频道(带分页)"""
try:
# 获取总数
self.cursor.execute('''
SELECT COUNT(*)
FROM channels c
JOIN channel_pairs cp ON c.channel_id = cp.forward_channel_id
WHERE cp.monitor_channel_id = ?
AND cp.is_active = 1
AND c.is_active = 1
''', (monitor_channel_id,))
total = self.cursor.fetchone()[0]
# 计算总页数
total_pages = (total + per_page - 1) // per_page if total > 0 else 1
# 确保页码有效
page = max(1, min(page, total_pages))
# 计算偏移量
offset = (page - 1) * per_page
# 获取数据
self.cursor.execute('''
SELECT
c.channel_id,
c.channel_name,
c.channel_username,
cp.added_date
FROM channels c
JOIN channel_pairs cp ON c.channel_id = cp.forward_channel_id
WHERE cp.monitor_channel_id = ?
AND cp.is_active = 1
AND c.is_active = 1
ORDER BY cp.added_date DESC
LIMIT ? OFFSET ?
''', (monitor_channel_id, per_page, offset))
channels = [{
'channel_id': row[0],
'channel_name': row[1],
'channel_username': row[2],
'added_date': row[3]
} for row in self.cursor.fetchall()]
return {
'channels': channels,
'total': total,
'current_page': page,
'total_pages': total_pages,
'per_page': per_page
}
except sqlite3.Error as e:
logging.error(f"Error in get_forward_channels: {e}")
return {
'channels': [],
'total': 0,
'current_page': 1,
'total_pages': 1,
'per_page': per_page
}
def get_all_forward_channels(self, monitor_channel_id: int) -> List[Dict[str, Any]]:
"""获取监控频道对应的所有活跃转发频道(不分页,用于消息转发)"""
try:
self.cursor.execute('''
SELECT
c.channel_id,
c.channel_name,
c.channel_username,
cp.added_date
FROM channels c
JOIN channel_pairs cp ON c.channel_id = cp.forward_channel_id
WHERE cp.monitor_channel_id = ?
AND cp.is_active = 1
AND c.is_active = 1
ORDER BY cp.added_date ASC
''', (monitor_channel_id,))
return [{
'channel_id': row[0],
'channel_name': row[1],
'channel_username': row[2],
'added_date': row[3]
} for row in self.cursor.fetchall()]
except sqlite3.Error as e:
logging.error(f"Error in get_all_forward_channels: {e}")
return []
def add_channel_pair(self, monitor_channel_id: int, forward_channel_id: int) -> bool:
"""添加频道配对"""
try:
# 开始事务
self.cursor.execute('BEGIN TRANSACTION')
# 验证两个频道都存在且活跃
self.cursor.execute('''
SELECT COUNT(*) FROM channels
WHERE channel_id IN (?, ?)
AND is_active = 1
''', (monitor_channel_id, forward_channel_id))
if self.cursor.fetchone()[0] != 2:
raise sqlite3.Error("One or both channels are not active")
# 检查配对是否已存在
self.cursor.execute('''
SELECT is_active
FROM channel_pairs
WHERE monitor_channel_id = ?
AND forward_channel_id = ?
''', (monitor_channel_id, forward_channel_id))
existing_pair = self.cursor.fetchone()
if existing_pair:
if not existing_pair[0]:
# 如果配对存在但未激活,重新激活它
self.cursor.execute('''
UPDATE channel_pairs
SET is_active = 1,
added_date = CURRENT_TIMESTAMP
WHERE monitor_channel_id = ?
AND forward_channel_id = ?
''', (monitor_channel_id, forward_channel_id))
else:
# 添加新配对
self.cursor.execute('''
INSERT INTO channel_pairs
(monitor_channel_id, forward_channel_id)
VALUES (?, ?)
''', (monitor_channel_id, forward_channel_id))
# 提交事务
self.conn.commit()
return True
except sqlite3.Error as e:
# 发生错误时回滚
self.conn.rollback()
logging.error(f"Error in add_channel_pair: {e}")
return False
def remove_channel_pair(self, monitor_channel_id: int, forward_channel_id: int) -> bool:
"""移除频道配对"""
try:
self.cursor.execute('''
UPDATE channel_pairs
SET is_active = 0,
added_date = CURRENT_TIMESTAMP
WHERE monitor_channel_id = ?
AND forward_channel_id = ?
AND is_active = 1
''', (monitor_channel_id, forward_channel_id))
self.conn.commit()
return True
except sqlite3.Error as e:
logging.error(f"Error in remove_channel_pair: {e}")
return False
# 过滤规则相关方法
def add_filter_rule(self, pair_id: str, rule_type: str, filter_mode: str, pattern: str) -> bool:
"""添加过滤规则
Args:
pair_id: 频道配对ID,格式为 "monitor_id:forward_id"
rule_type: 规则类型,'WHITELIST' 或 'BLACKLIST'
filter_mode: 过滤模式,'KEYWORD' 或 'REGEX'
pattern: 过滤模式
"""
try:
self.cursor.execute(
"INSERT INTO filter_rules (pair_id, rule_type, filter_mode, pattern) VALUES (?, ?, ?, ?)",
(pair_id, rule_type, filter_mode, pattern)
)
self.conn.commit()
return True
except Exception as e:
logging.error(f"Error adding filter rule: {e}")
return False
def get_filter_rules(self, pair_id: str = None, monitor_id: int = None, forward_id: int = None) -> List[Dict]:
"""获取指定频道配对的过滤规则
可以使用pair_id或者monitor_id+forward_id的组合来查询
"""
try:
# 如果提供了monitor_id和forward_id,生成pair_id
if pair_id is None and monitor_id is not None and forward_id is not None:
pair_id = f"{monitor_id}:{forward_id}"
if pair_id is None:
logging.error("get_filter_rules: 需要提供pair_id或者monitor_id+forward_id")
return []
self.cursor.execute(
"SELECT * FROM filter_rules WHERE pair_id = ? AND is_active = 1",
(pair_id,)
)
rules = self.cursor.fetchall()
result = []
for rule in rules:
result.append({
'rule_id': rule[0],
'pair_id': rule[1],
'rule_type': rule[2],
'filter_mode': rule[3],
'pattern': rule[4],
'is_active': rule[5],
'created_at': rule[6],
'updated_at': rule[7]
})
return result
except Exception as e:
logging.error(f"Error getting filter rules: {e}")
return []
def remove_filter_rule(self, rule_id: int) -> bool:
"""删除过滤规则"""
try:
self.cursor.execute(
"UPDATE filter_rules SET is_active = 0 WHERE rule_id = ?",
(rule_id,)
)
self.conn.commit()
return True
except Exception as e:
logging.error(f"Error removing filter rule: {e}")
return False
# 时间设置相关方法
def add_time_filter(self, pair_id: str, start_time: str, end_time: str, days_of_week: str, mode: str = 'ALLOW') -> bool:
"""添加时间过滤器
Args:
pair_id: 频道配对ID,格式为 "monitor_id:forward_id"
start_time: 开始时间,格式为 "HH:MM"
end_time: 结束时间,格式为 "HH:MM"
days_of_week: 星期,格式为 "1,2,3,4,5,6,7"
mode: 模式,'ALLOW' 或 'BLOCK'
"""
try:
self.cursor.execute(
"INSERT INTO time_filters (pair_id, start_time, end_time, days_of_week, mode) VALUES (?, ?, ?, ?, ?)",
(pair_id, start_time, end_time, days_of_week, mode)
)
self.conn.commit()
return True
except Exception as e:
logging.error(f"Error adding time filter: {e}")
return False
def get_time_filters(self, pair_id: str = None, monitor_id: int = None, forward_id: int = None) -> List[Dict]:
"""获取指定频道配对的时间过滤器
可以使用pair_id或者monitor_id+forward_id的组合来查询
"""
try:
# 如果提供了monitor_id和forward_id,生成pair_id
if pair_id is None and monitor_id is not None and forward_id is not None:
pair_id = f"{monitor_id}:{forward_id}"
if pair_id is None:
logging.error("get_time_filters: 需要提供pair_id或者monitor_id+forward_id")
return []
self.cursor.execute(
"SELECT * FROM time_filters WHERE pair_id = ? AND is_active = 1",
(pair_id,)
)
filters = self.cursor.fetchall()
result = []
for filter in filters:
result.append({
'filter_id': filter[0],
'pair_id': filter[1],
'start_time': filter[2],
'end_time': filter[3],
'days_of_week': filter[4],
'is_active': filter[5],
'mode': filter[6],
'created_at': filter[7],
'updated_at': filter[8]
})
return result
except Exception as e:
logging.error(f"Error getting time filters: {e}")
return []
def remove_time_filter(self, filter_id: int) -> bool:
"""删除时间过滤器"""
try:
self.cursor.execute(
"UPDATE time_filters SET is_active = 0 WHERE filter_id = ?",
(filter_id,)
)
self.conn.commit()
return True
except Exception as e:
logging.error(f"Error removing time filter: {e}")
return False
def get_all_channel_pairs(self) -> List[Dict]:
"""获取所有活跃的频道配对"""
try:
self.cursor.execute(
"""
SELECT cp.monitor_channel_id, cp.forward_channel_id,
m.channel_name as monitor_name, f.channel_name as forward_name
FROM channel_pairs cp
JOIN channels m ON cp.monitor_channel_id = m.channel_id
JOIN channels f ON cp.forward_channel_id = f.channel_id
WHERE cp.is_active = 1
"""
)
pairs = self.cursor.fetchall()
result = []
for pair in pairs:
result.append({
'monitor_id': pair[0],
'forward_id': pair[1],
'monitor_name': pair[2],
'forward_name': pair[3],
'pair_id': f"{pair[0]}:{pair[1]}"
})
return result
except Exception as e:
logging.error(f"Error getting all channel pairs: {e}")
return []
def get_channel_info(self, channel_id: int) -> Optional[Dict[str, Any]]:
"""获取频道信息"""
try:
self.cursor.execute('''
SELECT
channel_id,
channel_name,
channel_username,
channel_type,
added_date,
is_active
FROM channels
WHERE channel_id = ?
''', (channel_id,))
row = self.cursor.fetchone()
if row:
return {
'channel_id': row[0],
'channel_name': row[1],
'channel_username': row[2],
'channel_type': row[3],
'added_date': row[4],
'is_active': row[5]
}
return None
except sqlite3.Error as e:
logging.error(f"Error in get_channel_info: {e}")
return None
def get_channel_stats(self, channel_id: int) -> Dict[str, Any]:
"""获取频道统计信息"""
try:
# 如果是监控频道,获取转发频道数量
self.cursor.execute('''
SELECT COUNT(*)
FROM channel_pairs
WHERE monitor_channel_id = ?
AND is_active = 1
''', (channel_id,))
forward_count = self.cursor.fetchone()[0]
# 如果是转发频道,获取监控频道数量
self.cursor.execute('''
SELECT COUNT(*)
FROM channel_pairs
WHERE forward_channel_id = ?
AND is_active = 1
''', (channel_id,))
monitor_count = self.cursor.fetchone()[0]
return {
'forward_channel_count': forward_count,
'monitor_channel_count': monitor_count
}
except sqlite3.Error as e:
logging.error(f"Error in get_channel_stats: {e}")
return {
'forward_channel_count': 0,
'monitor_channel_count': 0
}
# 过滤规则相关方法
def add_filter_rule(self, monitor_id: int, forward_id: int, rule_type: str, filter_mode: str, pattern: str) -> bool:
"""添加过滤规则"""
try:
pair_id = f"{monitor_id}:{forward_id}"
self.cursor.execute('''
INSERT INTO filter_rules (pair_id, rule_type, filter_mode, pattern)
VALUES (?, ?, ?, ?)
''', (pair_id, rule_type, filter_mode, pattern))
self.conn.commit()
return True
except Exception as e:
logging.error(f"添加过滤规则失败: {e}")
return False
# 已经合并到上面的get_filter_rules方法中
def update_filter_rule(self, rule_id: int, rule_type: str = None, filter_mode: str = None,
pattern: str = None, is_active: bool = None) -> bool:
"""更新过滤规则"""
try:
update_fields = []
params = []
if rule_type is not None:
update_fields.append("rule_type = ?")
params.append(rule_type)
if filter_mode is not None:
update_fields.append("filter_mode = ?")
params.append(filter_mode)
if pattern is not None:
update_fields.append("pattern = ?")
params.append(pattern)
if is_active is not None:
update_fields.append("is_active = ?")
params.append(1 if is_active else 0)
if not update_fields:
return False
update_fields.append("updated_at = CURRENT_TIMESTAMP")
query = f"UPDATE filter_rules SET {', '.join(update_fields)} WHERE rule_id = ?"
params.append(rule_id)
self.cursor.execute(query, params)
self.conn.commit()
return self.cursor.rowcount > 0
except Exception as e:
logging.error(f"更新过滤规则失败: {e}")
return False
def delete_filter_rule(self, rule_id: int) -> bool:
"""删除过滤规则"""
try:
self.cursor.execute("UPDATE filter_rules SET is_active = 0 WHERE rule_id = ?", (rule_id,))
self.conn.commit()
return self.cursor.rowcount > 0
except Exception as e:
logging.error(f"删除过滤规则失败: {e}")
return False
# 媒体过滤相关方法
def add_media_filter(self, pair_id: str, media_type: str, action: str = 'BLOCK') -> bool:
"""添加媒体过滤器
Args:
pair_id: 频道配对ID,格式为 "monitor_id:forward_id"
media_type: 媒体类型,'photo', 'video', 'audio', 'document', 'animation', 'sticker', 'text'
action: 动作,'ALLOW' 或 'BLOCK'
"""
try:
# 检查是否已存在相同的过滤器
self.cursor.execute(
"SELECT filter_id FROM media_filters WHERE pair_id = ? AND media_type = ? AND is_active = 1",
(pair_id, media_type)
)
existing = self.cursor.fetchone()
if existing:
# 如果已存在,更新动作
self.cursor.execute(
"UPDATE media_filters SET action = ?, updated_at = CURRENT_TIMESTAMP WHERE filter_id = ?",
(action, existing[0])
)
else:
# 如果不存在,新增
self.cursor.execute(
"INSERT INTO media_filters (pair_id, media_type, action) VALUES (?, ?, ?)",
(pair_id, media_type, action)
)
self.conn.commit()
return True
except Exception as e:
logging.error(f"Error adding media filter: {e}")
return False
def get_media_filters(self, pair_id: str = None, monitor_id: int = None, forward_id: int = None) -> List[Dict]:
"""获取指定频道配对的媒体过滤器
可以使用pair_id或者monitor_id+forward_id的组合来查询
"""