-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathapp.py
More file actions
3085 lines (2717 loc) · 122 KB
/
app.py
File metadata and controls
3085 lines (2717 loc) · 122 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
# -*- coding: utf-8 -*-
"""
Leaflow Auto Check-in Control Panel
Web-based management interface for the check-in system
"""
import os
import json
import sqlite3
import hashlib
import secrets
import threading
import schedule
import time
import re
import requests
from datetime import datetime, timedelta, timezone
from functools import wraps
from flask import Flask, request, jsonify, render_template_string, make_response
from flask_cors import CORS
import jwt
import logging
from urllib.parse import urlparse, unquote
import random
import pytz
import hmac
import base64
import urllib.parse
import traceback
# Configuration
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('JWT_SECRET_KEY', secrets.token_hex(32))
CORS(app, supports_credentials=True)
# Environment variables
ADMIN_USERNAME = os.getenv('ADMIN_USERNAME', 'admin')
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD', 'admin123')
PORT = int(os.getenv('PORT', '8181'))
MAX_MYSQL_RETRIES = int(os.getenv('MAX_MYSQL_RETRIES', '12'))
# 设置时区为北京时间
TIMEZONE = pytz.timezone('Asia/Shanghai')
# Database configuration
def parse_mysql_dsn(dsn):
"""Parse MySQL DSN string"""
try:
parsed = urlparse(dsn)
if parsed.scheme not in ['mysql', 'mysql+pymysql']:
return None
config = {
'type': 'mysql',
'host': parsed.hostname or 'localhost',
'port': parsed.port or 3306,
'database': parsed.path.lstrip('/') if parsed.path else 'leaflow_checkin',
'password': unquote(parsed.password) if parsed.password else ''
}
username = unquote(parsed.username) if parsed.username else 'root'
if '.' in username:
username = username.split('.')[-1]
config['user'] = username
return config
except Exception as e:
logging.error(f"Error parsing MySQL DSN: {e}")
return None
# Parse database configuration
MYSQL_DSN = os.getenv('MYSQL_DSN', '')
db_config = None
if MYSQL_DSN:
db_config = parse_mysql_dsn(MYSQL_DSN)
if db_config:
DB_TYPE = 'mysql'
DB_HOST = db_config['host']
DB_PORT = db_config['port']
DB_NAME = db_config['database']
DB_USER = db_config['user']
DB_PASSWORD = db_config['password']
else:
DB_TYPE = 'sqlite'
DB_HOST = 'localhost'
DB_PORT = 3306
DB_NAME = 'leaflow_checkin'
DB_USER = 'root'
DB_PASSWORD = ''
# Logging setup
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# 账户缓存
class AccountCache:
def __init__(self):
self.cache = {}
self.last_update = None
self.cache_duration = 300 # 5分钟缓存
self.lock = threading.Lock()
def get_accounts(self, force_refresh=False):
"""获取缓存的账户列表"""
with self.lock:
now = time.time()
if force_refresh or not self.last_update or (now - self.last_update) > self.cache_duration:
return None
return list(self.cache.values()) # 返回列表而不是字典
def update_cache(self, accounts):
"""更新缓存"""
with self.lock:
self.cache = {acc['id']: acc for acc in accounts}
self.last_update = time.time()
def invalidate(self):
"""使缓存失效"""
with self.lock:
self.cache = {}
self.last_update = None
def refresh_from_db(self, db):
"""从数据库刷新缓存"""
try:
accounts_list = db.fetchall('SELECT * FROM accounts WHERE enabled = 1')
if accounts_list:
self.update_cache(accounts_list)
logger.info(f"Account cache refreshed with {len(accounts_list)} accounts")
else:
self.invalidate()
except Exception as e:
logger.error(f"Error refreshing account cache: {e}")
account_cache = AccountCache()
# 通用数据缓存类
class DataCache:
def __init__(self, cache_duration=300):
self.cache = {}
self.cache_duration = cache_duration
self.lock = threading.Lock()
def get(self, key):
"""获取缓存数据"""
with self.lock:
if key in self.cache:
data, timestamp = self.cache[key]
if time.time() - timestamp < self.cache_duration:
return data
else:
del self.cache[key]
return None
def set(self, key, data):
"""设置缓存数据"""
with self.lock:
self.cache[key] = (data, time.time())
def invalidate(self, key=None):
"""使缓存失效"""
with self.lock:
if key:
self.cache.pop(key, None)
else:
self.cache.clear()
def invalidate_pattern(self, pattern):
"""使匹配模式的缓存失效"""
with self.lock:
keys_to_remove = [k for k in self.cache.keys() if pattern in k]
for key in keys_to_remove:
self.cache.pop(key, None)
# 初始化数据缓存
data_cache = DataCache(cache_duration=60) # 1分钟缓存
class Database:
def __init__(self):
self.lock = threading.Lock()
self.conn = None
self.pool = None
self.last_ping = time.time()
self.last_actual_ping = time.time() # 记录上次实际ping的时间
self.ping_check_interval = 300 # 每5分钟检查一次
self.ping_actual_interval = 1800 # 30分钟实际ping间隔
self.db_type = None # 初始化db_type
self.retry_count = 0 # 当前重试次数
self.max_retries = MAX_MYSQL_RETRIES # 最大重试次数
self.connect()
self.init_tables()
# 启动保活线程
self.start_keepalive()
def start_keepalive(self):
"""启动MySQL保活线程"""
if self.db_type == 'mysql':
thread = threading.Thread(target=self._keepalive_worker, daemon=True)
thread.start()
logger.info("MySQL intelligent keepalive thread started")
def _keepalive_worker(self):
"""智能保活工作线程"""
while True:
try:
time.sleep(self.ping_check_interval) # 每5分钟检查一次
with self.lock:
if self.conn and self.db_type == 'mysql':
current_time = time.time()
# 只有在距离上次实际ping超过30分钟时才执行ping
if current_time - self.last_actual_ping >= self.ping_actual_interval:
try:
self.conn.ping(reconnect=True)
self.last_actual_ping = current_time
logger.debug(f"MySQL keepalive ping executed (30min interval)")
except Exception as e:
logger.error(f"MySQL ping failed, reconnecting: {e}")
self.reconnect_with_retry()
self.last_actual_ping = current_time
else:
remaining = self.ping_actual_interval - (current_time - self.last_actual_ping)
logger.debug(f"Keepalive check: Next ping in {remaining:.0f} seconds")
except Exception as e:
logger.error(f"Keepalive worker error: {e}")
def _ensure_connection(self):
"""确保连接可用(智能ping)"""
if self.db_type == 'mysql':
current_time = time.time()
# 如果距离上次ping超过30分钟,执行ping
if current_time - self.last_actual_ping >= self.ping_actual_interval:
try:
self.conn.ping(reconnect=True)
self.last_actual_ping = current_time
logger.debug("Connection ping on query execution")
except Exception as e:
logger.error(f"Connection ping failed: {e}")
self.reconnect_with_retry()
self.last_actual_ping = current_time
def calculate_retry_delay(self, attempt):
"""计算重试延迟(指数退避)"""
base_delay = 3
max_delay = 24
delay = min(base_delay * (2 ** attempt), max_delay)
return delay
def reconnect_with_retry(self):
"""使用指数退避策略重新连接MySQL"""
if self.db_type != 'mysql':
self.reconnect()
return
for attempt in range(self.max_retries):
try:
logger.info(f"MySQL reconnection attempt {attempt + 1}/{self.max_retries}")
if self.conn:
try:
self.conn.close()
except:
pass
import pymysql
self.conn = pymysql.connect(
host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME,
charset='utf8mb4',
autocommit=True,
connect_timeout=10,
read_timeout=30,
write_timeout=30,
max_allowed_packet=64*1024*1024 # 64MB
)
self.last_actual_ping = time.time()
self.retry_count = 0 # 重置重试计数
# 清空所有缓存
data_cache.invalidate()
account_cache.invalidate()
logger.info("MySQL reconnected successfully, cache cleared")
return
except Exception as e:
logger.error(f"MySQL reconnection attempt {attempt + 1} failed: {e}")
if attempt < self.max_retries - 1:
delay = self.calculate_retry_delay(attempt)
logger.info(f"Waiting {delay} seconds before next retry...")
time.sleep(delay)
else:
logger.error(f"All {self.max_retries} MySQL reconnection attempts failed")
raise
def reconnect(self):
"""重新连接数据库(兼容旧代码)"""
try:
if self.db_type == 'mysql':
self.reconnect_with_retry()
else:
if self.conn:
try:
self.conn.close()
except:
pass
self.connect()
# 清空所有缓存
data_cache.invalidate()
account_cache.invalidate()
logger.info("Database reconnected successfully, cache cleared")
except Exception as e:
logger.error(f"Database reconnection failed: {e}")
raise
def connect(self):
"""Establish database connection with retry mechanism"""
if DB_TYPE == 'mysql':
# MySQL使用新的重试机制
import pymysql
for attempt in range(self.max_retries):
try:
logger.info(f"Connecting to MySQL: {DB_HOST}:{DB_PORT}/{DB_NAME} as {DB_USER} (attempt {attempt + 1}/{self.max_retries})")
self.conn = pymysql.connect(
host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME,
charset='utf8mb4',
autocommit=True,
connect_timeout=10,
read_timeout=30,
write_timeout=30,
max_allowed_packet=64*1024*1024 # 64MB
)
self.db_type = 'mysql'
self.last_actual_ping = time.time()
self.retry_count = 0
logger.info("Successfully connected to MySQL database")
return
except Exception as e:
logger.error(f"MySQL connection attempt {attempt + 1} failed: {e}")
if attempt < self.max_retries - 1:
delay = self.calculate_retry_delay(attempt)
logger.info(f"Waiting {delay} seconds before next retry...")
time.sleep(delay)
else:
logger.error("All MySQL connection attempts failed, falling back to SQLite")
# Fallback to SQLite
os.makedirs('/app/data', exist_ok=True)
self.conn = sqlite3.connect('/app/data/leaflow_checkin.db', check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self.db_type = 'sqlite'
logger.info("Successfully connected to SQLite database (fallback)")
else:
# SQLite连接
logger.info("Using SQLite database")
os.makedirs('/app/data', exist_ok=True)
self.conn = sqlite3.connect('/app/data/leaflow_checkin.db', check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self.db_type = 'sqlite'
logger.info("Successfully connected to SQLite database")
def init_tables(self):
"""Initialize database tables"""
with self.lock:
try:
cursor = self.conn.cursor()
if self.db_type == 'mysql':
# MySQL table creation
cursor.execute('''
CREATE TABLE IF NOT EXISTS accounts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) UNIQUE NOT NULL,
token_data TEXT NOT NULL,
enabled BOOLEAN DEFAULT TRUE,
checkin_time_start VARCHAR(5) DEFAULT '06:30',
checkin_time_end VARCHAR(5) DEFAULT '06:40',
check_interval INT DEFAULT 60,
retry_count INT DEFAULT 2,
last_checkin_date DATE DEFAULT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS checkin_history (
id INT AUTO_INCREMENT PRIMARY KEY,
account_id INT NOT NULL,
success BOOLEAN NOT NULL,
message TEXT,
checkin_date DATE NOT NULL,
retry_times INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE,
INDEX idx_checkin_date (checkin_date),
INDEX idx_account_date (account_id, checkin_date)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS notification_settings (
id INT AUTO_INCREMENT PRIMARY KEY,
enabled BOOLEAN DEFAULT FALSE,
telegram_enabled BOOLEAN DEFAULT FALSE,
telegram_bot_token VARCHAR(255) DEFAULT '',
telegram_user_id VARCHAR(255) DEFAULT '',
telegram_host VARCHAR(255) DEFAULT '',
wechat_enabled BOOLEAN DEFAULT FALSE,
wechat_webhook_key VARCHAR(255) DEFAULT '',
wechat_host VARCHAR(255) DEFAULT '',
wxpusher_enabled BOOLEAN DEFAULT FALSE,
wxpusher_app_token VARCHAR(255) DEFAULT '',
wxpusher_uid VARCHAR(255) DEFAULT '',
wxpusher_host VARCHAR(255) DEFAULT '',
dingtalk_enabled BOOLEAN DEFAULT FALSE,
dingtalk_access_token VARCHAR(255) DEFAULT '',
dingtalk_secret VARCHAR(255) DEFAULT '',
dingtalk_host VARCHAR(255) DEFAULT '',
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
''')
# 添加新字段(如果不存在)
new_fields = [
("accounts", "retry_count", "INT DEFAULT 2"),
("checkin_history", "retry_times", "INT DEFAULT 0"),
("notification_settings", "telegram_enabled", "BOOLEAN DEFAULT FALSE"),
("notification_settings", "telegram_host", "VARCHAR(255) DEFAULT ''"),
("notification_settings", "wechat_enabled", "BOOLEAN DEFAULT FALSE"),
("notification_settings", "wechat_host", "VARCHAR(255) DEFAULT ''"),
("notification_settings", "wxpusher_enabled", "BOOLEAN DEFAULT FALSE"),
("notification_settings", "wxpusher_app_token", "VARCHAR(255) DEFAULT ''"),
("notification_settings", "wxpusher_uid", "VARCHAR(255) DEFAULT ''"),
("notification_settings", "wxpusher_host", "VARCHAR(255) DEFAULT ''"),
("notification_settings", "dingtalk_enabled", "BOOLEAN DEFAULT FALSE"),
("notification_settings", "dingtalk_access_token", "VARCHAR(255) DEFAULT ''"),
("notification_settings", "dingtalk_secret", "VARCHAR(255) DEFAULT ''"),
("notification_settings", "dingtalk_host", "VARCHAR(255) DEFAULT ''")
]
for table_name, field_name, field_type in new_fields:
try:
cursor.execute(f"ALTER TABLE {table_name} ADD COLUMN {field_name} {field_type}")
except:
pass
else:
# SQLite table creation
cursor.execute('''
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(255) UNIQUE NOT NULL,
token_data TEXT NOT NULL,
enabled BOOLEAN DEFAULT 1,
checkin_time_start VARCHAR(5) DEFAULT '06:30',
checkin_time_end VARCHAR(5) DEFAULT '06:40',
check_interval INTEGER DEFAULT 60,
retry_count INTEGER DEFAULT 2,
last_checkin_date DATE DEFAULT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS checkin_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id INTEGER NOT NULL,
success BOOLEAN NOT NULL,
message TEXT,
checkin_date DATE NOT NULL,
retry_times INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS notification_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
enabled BOOLEAN DEFAULT 0,
telegram_enabled BOOLEAN DEFAULT 0,
telegram_bot_token TEXT DEFAULT '',
telegram_user_id TEXT DEFAULT '',
telegram_host TEXT DEFAULT '',
wechat_enabled BOOLEAN DEFAULT 0,
wechat_webhook_key TEXT DEFAULT '',
wechat_host TEXT DEFAULT '',
wxpusher_enabled BOOLEAN DEFAULT 0,
wxpusher_app_token TEXT DEFAULT '',
wxpusher_uid TEXT DEFAULT '',
wxpusher_host TEXT DEFAULT '',
dingtalk_enabled BOOLEAN DEFAULT 0,
dingtalk_access_token TEXT DEFAULT '',
dingtalk_secret TEXT DEFAULT '',
dingtalk_host TEXT DEFAULT '',
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 初始化通知设置
cursor.execute('SELECT COUNT(*) as cnt FROM notification_settings')
result = cursor.fetchone()
if self.db_type == 'mysql':
count = result[0] if result else 0
else:
count = result['cnt'] if result else 0
if count == 0:
if self.db_type == 'mysql':
cursor.execute('''
INSERT INTO notification_settings
(enabled) VALUES (FALSE)
''')
else:
cursor.execute('''
INSERT INTO notification_settings
(enabled) VALUES (0)
''')
self.conn.commit()
logger.info("Database tables initialized successfully")
except Exception as e:
logger.error(f"Error initializing tables: {e}")
logger.error(traceback.format_exc())
raise
def execute(self, query, params=None, use_cache=False, cache_key=None):
"""Execute a database query with connection retry and optional caching"""
# 尝试从缓存获取数据(仅用于SELECT查询)
if use_cache and cache_key and query.strip().upper().startswith('SELECT'):
cached_data = data_cache.get(cache_key)
if cached_data is not None:
logger.debug(f"Cache hit for key: {cache_key}")
return cached_data
with self.lock:
max_retries = self.max_retries if self.db_type == 'mysql' else 3
for attempt in range(max_retries):
try:
if self.db_type == 'mysql':
# 智能检查连接
self._ensure_connection()
cursor = self.conn.cursor()
if self.db_type == 'mysql' and query:
query = query.replace('?', '%s')
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
if self.db_type == 'sqlite':
self.conn.commit()
# 如果需要缓存且是SELECT查询,缓存结果
if use_cache and cache_key and query.strip().upper().startswith('SELECT'):
data_cache.set(cache_key, cursor)
# 成功执行,重置重试计数
if self.db_type == 'mysql':
self.retry_count = 0
return cursor
except Exception as e:
logger.error(f"Database execute error (attempt {attempt + 1}): {e}")
if self.db_type == 'mysql' and attempt < max_retries - 1:
delay = self.calculate_retry_delay(attempt)
logger.info(f"Retrying database operation in {delay} seconds...")
time.sleep(delay)
# 尝试重新连接
try:
self.reconnect_with_retry()
except:
pass
elif attempt == max_retries - 1:
raise
def fetchone(self, query, params=None, use_cache=False):
"""Fetch one row from database with optional caching"""
cache_key = None
if use_cache:
# 生成缓存键
cache_key = f"fetchone_{hash(query)}_{hash(str(params))}"
cached_data = data_cache.get(cache_key)
if cached_data is not None:
return cached_data
cursor = self.execute(query, params)
result = cursor.fetchone()
if result:
if self.db_type == 'mysql':
if cursor.description:
columns = [desc[0] for desc in cursor.description]
if isinstance(result, tuple):
result = dict(zip(columns, result))
elif self.db_type == 'sqlite':
result = dict(result) if result else None
# 缓存结果
if use_cache and cache_key:
data_cache.set(cache_key, result)
return result
def fetchall(self, query, params=None, use_cache=False):
"""Fetch all rows from database with optional caching"""
cache_key = None
if use_cache:
# 生成缓存键
cache_key = f"fetchall_{hash(query)}_{hash(str(params))}"
cached_data = data_cache.get(cache_key)
if cached_data is not None:
return cached_data
cursor = self.execute(query, params)
results = cursor.fetchall()
if results:
if self.db_type == 'mysql':
if cursor.description:
columns = [desc[0] for desc in cursor.description]
results = [dict(zip(columns, row)) for row in results]
elif self.db_type == 'sqlite':
results = [dict(row) for row in results]
results = results or []
# 缓存结果
if use_cache and cache_key:
data_cache.set(cache_key, results)
return results
def __del__(self):
"""清理连接"""
try:
if self.conn:
self.conn.close()
except:
pass
# Initialize database
try:
db = Database()
except Exception as e:
logger.error(f"Failed to initialize database: {e}")
raise
# Notification class
class NotificationService:
@staticmethod
def send_notification(title, content, account_name=None):
"""Send notification through configured channels"""
try:
# 不使用缓存,直接从数据库获取最新设置
settings = db.fetchone('SELECT * FROM notification_settings WHERE id = 1')
if not settings or not settings.get('enabled'):
logger.info("Notifications disabled")
return
# Send Telegram notification
if settings.get('telegram_enabled') and settings.get('telegram_bot_token') and settings.get('telegram_user_id'):
NotificationService.send_telegram(
settings['telegram_bot_token'],
settings['telegram_user_id'],
title,
content,
settings.get('telegram_host', '')
)
# Send WeChat Work notification
if settings.get('wechat_enabled') and settings.get('wechat_webhook_key'):
NotificationService.send_wechat(
settings['wechat_webhook_key'],
title,
content,
settings.get('wechat_host', '')
)
# Send WxPusher notification
if settings.get('wxpusher_enabled') and settings.get('wxpusher_app_token') and settings.get('wxpusher_uid'):
NotificationService.send_wxpusher(
settings['wxpusher_app_token'],
settings['wxpusher_uid'],
title,
content,
settings.get('wxpusher_host', '')
)
# Send DingTalk notification
if settings.get('dingtalk_enabled') and settings.get('dingtalk_access_token') and settings.get('dingtalk_secret'):
NotificationService.send_dingtalk(
settings['dingtalk_access_token'],
settings['dingtalk_secret'],
title,
content,
settings.get('dingtalk_host', '')
)
except Exception as e:
logger.error(f"Notification error: {e}")
@staticmethod
def send_telegram(token, chat_id, title, content, custom_host=''):
"""Send Telegram notification"""
try:
base_url = custom_host.rstrip('/') if custom_host else "https://api.telegram.org"
url = f"{base_url}/bot{token}/sendMessage"
data = {
"chat_id": chat_id,
"text": f"📢 {title}\n\n{content}",
"disable_web_page_preview": True
}
response = requests.post(url=url, data=data, timeout=30)
result = response.json()
if result.get("ok"):
logger.info("Telegram notification sent successfully")
else:
logger.error(f"Telegram notification failed: {result.get('description')}")
except Exception as e:
logger.error(f"Telegram notification error: {e}")
@staticmethod
def send_wechat(webhook_key, title, content, custom_host=''):
"""Send WeChat Work notification"""
try:
base_url = custom_host.rstrip('/') if custom_host else "https://qyapi.weixin.qq.com"
url = f"{base_url}/cgi-bin/webhook/send?key={webhook_key}"
headers = {"Content-Type": "application/json;charset=utf-8"}
data = {"msgtype": "text", "text": {"content": f"【{title}】\n\n{content}"}}
response = requests.post(
url=url,
data=json.dumps(data),
headers=headers,
timeout=15
).json()
if response.get("errcode") == 0:
logger.info("WeChat Work notification sent successfully")
else:
logger.error(f"WeChat Work notification failed: {response.get('errmsg')}")
except Exception as e:
logger.error(f"WeChat Work notification error: {e}")
@staticmethod
def send_wxpusher(app_token, uid, title, content, custom_host=''):
"""Send WxPusher notification"""
try:
base_url = custom_host.rstrip('/') if custom_host else "https://wxpusher.zjiecode.com"
url = f"{base_url}/api/send/message"
# 修复HTML模板,使其在深色模式下也能正常显示
html_content = f"""
<div style="padding: 10px; color: #2c3e50; background: #ffffff;">
<h2 style="color: inherit; margin: 0;">{title}</h2>
<div style="margin-top: 10px; padding: 10px; background: #f8f9fa; border-radius: 5px; color: #2c3e50;">
<pre style="white-space: pre-wrap; word-wrap: break-word; margin: 0; color: inherit;">{content}</pre>
</div>
<div style="margin-top: 10px; color: #7f8c8d; font-size: 12px;">
发送时间: {datetime.now(TIMEZONE).strftime('%Y-%m-%d %H:%M:%S')}
</div>
</div>
"""
data = {
"appToken": app_token,
"content": html_content,
"summary": title[:20], # 摘要限制20字符
"contentType": 2, # HTML格式
"uids": [uid],
"verifyPayType": 0
}
response = requests.post(url, json=data, timeout=30)
result = response.json()
if result.get("code") == 1000:
logger.info("WxPusher notification sent successfully")
else:
logger.error(f"WxPusher notification failed: {result.get('msg')}")
except Exception as e:
logger.error(f"WxPusher notification error: {e}")
@staticmethod
def send_dingtalk(access_token, secret, title, content, custom_host=''):
"""Send DingTalk robot notification"""
try:
# 生成签名
timestamp = str(round(time.time() * 1000))
string_to_sign = f'{timestamp}\n{secret}'
hmac_code = hmac.new(
secret.encode('utf-8'),
string_to_sign.encode('utf-8'),
digestmod=hashlib.sha256
).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
# 构建URL
base_url = custom_host.rstrip('/') if custom_host else "https://oapi.dingtalk.com"
url = f'{base_url}/robot/send?access_token={access_token}×tamp={timestamp}&sign={sign}'
# 构建消息体
data = {
"msgtype": "text",
"text": {
"content": f"【{title}】\n{content}"
},
"at": {
"isAtAll": False
}
}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, json=data, headers=headers, timeout=30)
result = response.json()
if result.get("errcode") == 0:
logger.info("DingTalk notification sent successfully")
else:
logger.error(f"DingTalk notification failed: {result.get('errmsg')}")
except Exception as e:
logger.error(f"DingTalk notification error: {e}")
# Leaflow check-in class
class LeafLowCheckin:
def __init__(self):
self.checkin_url = "https://checkin.leaflow.net"
self.main_site = "https://leaflow.net"
self.user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
def create_session(self, token_data):
"""Create session with authentication"""
session = requests.Session()
session.headers.update({
'User-Agent': self.user_agent,
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
})
if 'cookies' in token_data:
for name, value in token_data['cookies'].items():
session.cookies.set(name, value)
if 'headers' in token_data:
session.headers.update(token_data['headers'])
return session
def test_authentication(self, session, account_name):
"""Test if authentication is valid"""
try:
test_urls = [
f"{self.main_site}/dashboard",
f"{self.main_site}/profile",
f"{self.main_site}/user",
self.checkin_url,
]
for url in test_urls:
response = session.get(url, timeout=30)
if response.status_code == 200:
content = response.text.lower()
if any(indicator in content for indicator in ['dashboard', 'profile', 'user', 'logout', 'welcome']):
logger.info(f"✅ [{account_name}] Authentication valid")
return True, "Authentication successful"
elif response.status_code in [301, 302, 303]:
location = response.headers.get('location', '')
if 'login' not in location.lower():
logger.info(f"✅ [{account_name}] Authentication valid (redirect)")
return True, "Authentication successful (redirect)"
return False, "Authentication failed - no valid authenticated pages found"
except Exception as e:
return False, f"Authentication test error: {str(e)}"
def perform_checkin(self, session, account_name):
"""Perform check-in"""
logger.info(f"🎯 [{account_name}] Performing checkin...")
try:
# Try direct check-in page
response = session.get(self.checkin_url, timeout=30)
if response.status_code == 200:
result = self.analyze_and_checkin(session, response.text, self.checkin_url, account_name)
if result[0]:
return result
# Try API endpoints
api_endpoints = [
f"{self.checkin_url}/api/checkin",
f"{self.checkin_url}/checkin",
f"{self.main_site}/api/checkin",
f"{self.main_site}/checkin"
]
for endpoint in api_endpoints:
try:
# GET request
response = session.get(endpoint, timeout=30)
if response.status_code == 200:
success, message = self.check_checkin_response(response.text)
if success:
return True, message
# POST request
response = session.post(endpoint, data={'checkin': '1'}, timeout=30)
if response.status_code == 200:
success, message = self.check_checkin_response(response.text)
if success:
return True, message
except Exception as e:
logger.debug(f"[{account_name}] API endpoint {endpoint} failed: {str(e)}")
continue
return False, "All checkin methods failed"
except Exception as e:
return False, f"Checkin error: {str(e)}"
def analyze_and_checkin(self, session, html_content, page_url, account_name):
"""Analyze page and perform check-in"""
if self.already_checked_in(html_content):
return True, "Already checked in today"
if not self.is_checkin_page(html_content):
return False, "Not a checkin page"
try:
checkin_data = {'checkin': '1', 'action': 'checkin', 'daily': '1'}
csrf_token = self.extract_csrf_token(html_content)
if csrf_token:
checkin_data['_token'] = csrf_token
checkin_data['csrf_token'] = csrf_token
response = session.post(page_url, data=checkin_data, timeout=30)
if response.status_code == 200:
return self.check_checkin_response(response.text)
except Exception as e:
logger.debug(f"[{account_name}] POST checkin failed: {str(e)}")
return False, "Failed to perform checkin"
def already_checked_in(self, html_content):
"""Check if already checked in"""
content_lower = html_content.lower()
indicators = [
'already checked in', '今日已签到', 'checked in today',
'attendance recorded', '已完成签到', 'completed today'
]
return any(indicator in content_lower for indicator in indicators)