-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathWeb_Actions.py
743 lines (599 loc) · 23.4 KB
/
Web_Actions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
<<<<<<< HEAD
from flask import Flask, request, jsonify, Blueprint, render_template,Response
import sqlite3,os,json,requests,glob,random,string,re,sys,webbrowser,platform,subprocess,chardet,shutil
from datetime import datetime, timedelta
from bs4 import BeautifulSoup
from Ini_sys import *
from Ini_DB import *
web_blueprint = Blueprint('web', __name__)
"""<快捷方式操作网址相关函数>"""
# 插入数据到数据库的函数
def insert_website(WType, UserID, URL, Title, Des, CreDate, UbDate, Utimes):
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("INSERT INTO MyFast (WType, UserID, URL, Title, Des, CreDate, UbDate, Utimes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (WType, UserID, URL, Title, Des, CreDate, UbDate, Utimes))
conn.commit()
except sqlite3.Error as e:
print(f"数据库错误: {e}")
finally:
conn.close()
# 调用函数添加网址到数据库
def add_website():
# 获取JSON数据
data = request.json
url = data.get('url')
title = data.get('title')
description = data.get('description')
# 当前时间
now = datetime.now()
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# 插入数据到数据库
insert_website('website',0,url, title, description, formatted_date, formatted_date, 0)
return {"message": "添加成功"} # 返回一个可以被 jsonify 序列化的字典
# 添加插件到数据库
def add_plugin():
# 获取JSON数据
data = request.json
plugin_id = data.get('plugin_id')
url = data.get('plug_url')
title = data.get('plug_name')
description = data.get('plug_description')
# 检查URL是否已经存在
existing_urls = DB_select_return('MyFast','URL', url)
if existing_urls:
return {"message": "该插件已添加过"}
# 查找插件信息
print(plugin_id)
DB_JSON_List=query_db('MyPlugins', f'ID={plugin_id}')
DB_JSON = DB_JSON_List[0]
print(DB_JSON)
print(DB_JSON['PlugName'])
# 当前时间
now = datetime.now()
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# 插入数据到数据库
insert_website('plugin', 0, url, DB_JSON['PlugName'], DB_JSON['PlugDes'], formatted_date, formatted_date, 0)
return {"message": "添加成功"} # 返回一个可以被 jsonify 序列化的字典
#检测网址,请求TD
def fetch_title_and_description(url):
try:
response = requests.get(url, timeout=10)
response.raise_for_status() # 检查请求是否成功
# 自动检测字符编码
detected_encoding = chardet.detect(response.content)['encoding']
# 如果检测到编码,则使用该编码解码响应内容
if detected_encoding:
response.encoding = detected_encoding
else:
# 默认编码
response.encoding = 'utf-8'
# 解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')
# 尝试获取<title>标签内容作为网页标题
title = soup.find('title').string if soup.find('title') else '获取不到标题'
# 尝试获取<meta name="description">标签的内容
description = soup.find('meta', attrs={'name': 'description'})
description = description['content'] if description else '获取不到描述'
return title, description
except Exception as e:
return '链接失败', '链接失败'
# 删除快捷方式
def del_myfast(id):
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 执行删除操作
cursor.execute("DELETE FROM MyFast WHERE ID = ?", (id,))
conn.commit()
except sqlite3.Error as e:
print(f"数据库操作错误: {e}")
return False
finally:
conn.close()
return True
# 快捷方式记数
def Utimes_myfast(id):
try:
conn = sqlite3.connect(db_path) # 数据库文件路径
cursor = conn.cursor()
# 更新Utimes字段,使其值加1
update_query = "UPDATE MyFast SET Utimes = Utimes + 1 WHERE ID = ?"
cursor.execute(update_query, (id,))
conn.commit() # 提交事务
conn.close() # 关闭连接
return True
except:
return False
"""<读取快捷方式列表相关函数>"""
# 提取7天天数和日期
def get_days_ago(ub_date_str):
ub_date = datetime.strptime(ub_date_str, "%Y-%m-%d %H:%M:%S")
delta = datetime.now() - ub_date
if delta.days <= 7:
return f"{delta.days} 天前"
else:
return ub_date_str
# 提取快捷方式列表
def fetch_myfast():
# 连接到SQLite数据库
# 数据库文件存放路径
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 执行查询
query = "SELECT ID,WType, URL, Title, Des, UbDate, Utimes FROM MyFast ORDER BY UbDate DESC"
cursor.execute(query)
items = cursor.fetchall()
# 关闭数据库连接
conn.close()
# 处理每条记录
formatted_items = []
for item in items:
ID, WType, URL, Title, Des, UbDate, Utimes = item
if WType == "website":
icon_class = "layui-icon-website"
else:
icon_class = "layui-icon-component"
UbDate = get_days_ago(UbDate)
formatted_items.append({
"icon_class": icon_class,
"ID": ID,
"URL": URL,
"Title": Title,
"Des": Des,
"UbDate": UbDate,
"Utimes": Utimes
})
return formatted_items
"""<AI网址大全相关函数>"""
#获取AI网址中的表名
def get_sheet_names():
"""从数据库中读取所有唯一的sheet_name"""
# 连接到SQLite数据库
conn = sqlite3.connect(db_path)
cur = conn.cursor()
# 执行查询操作,选择不重复的sheet_name
cur.execute("SELECT DISTINCT sheet_name FROM AIURL")
# 获取所有结果
sheets = cur.fetchall()
# 关闭游标和连接
cur.close()
conn.close()
# 将结果转换为列表
unique_sheet_names = [sheet[0] for sheet in sheets]
return unique_sheet_names
# 获取所有字段名
def get_table_columns():
"""获取指定表的所有字段名"""
conn = sqlite3.connect(db_path)
cur = conn.cursor()
# 使用PRAGMA table_info()语句获取表的元数据
cur.execute(f"PRAGMA table_info(AIURL)")
# 获取所有字段的信息,每个字段的信息是一个元组,其中第二个元素是字段名
columns_info = cur.fetchall()
# 从每个字段的信息中提取字段名
column_names = [info[1] for info in columns_info if info[1] != 'sheet_name']
cur.close()
conn.close()
return column_names
# 读取表中所有内容
def get_all_records():
"""获取指定表的所有记录"""
# 连接到数据库
conn = sqlite3.connect(db_path)
cur = conn.cursor()
# 构建查询语句,选择所有字段
query = f"SELECT * FROM AIURL"
# 执行查询
cur.execute(query)
# 获取所有记录
records = cur.fetchall()
# 关闭游标和连接
cur.close()
conn.close()
return records
# 临时文件中心表格显示
def file_center_list():
# 连接到SQLite数据库
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 查询数据库
cursor.execute("SELECT PlugName, PlugDir, uploadDir FROM MyPlugins")
plugins = cursor.fetchall()
# 存储结果的列表
result = []
# 遍历每个插件
for plug_name, plug_dir, upload_dir in plugins:
if not upload_dir:
print(f"插件 {plug_name} 的 uploadDir 字段为空")
continue
# 分割uploadDir字段得到子目录
directories = upload_dir.split(',')
for dir in directories:
full_path = os.path.join("plugins", plug_dir, dir)
if not os.path.exists(full_path):
print(f"目录 {full_path} 不存在")
continue
# 计算目录下的文件数和总占用空间
file_count = 0
total_size = 0
for root, dirs, files in os.walk(full_path):
file_count += len(files)
total_size += sum(os.path.getsize(os.path.join(root, name)) for name in files)
# 占用空间转为MB
total_size_mb = round(total_size / (1024 * 1024), 2)
# 将结果加入列表
result.append({
"PlugName": plug_name,
"Directory": full_path,
"FileCount": file_count,
"TotalSizeMB": total_size_mb
})
# 关闭数据库连接
conn.close()
# 转化结果为JSON
#fc_json = result
#fc_json = json.dumps(result)
#return fc_json
return {"code": 0, "msg": "", "count": len(result), "data": result}
# 删除给定的目录列表及其所有内容
def delete_directories(directories):
""" 删除给定的目录列表及其所有内容。 """
try:
for directory in directories:
full_path = os.path.join(directory) # 组合成完整路径
shutil.rmtree(full_path) # 删除目录及其所有内容
return {"code": 0, "msg": "删除成功"}
except Exception as e:
return {"code": 500, "msg": str(e)}
"""<一般web端路由交互执行>"""
@web_blueprint.route('/', methods=['POST'])
def handle_web_Execution():
if request.is_json: # 确保请求包含 JSON 数据
data = request.get_json()
action = data.get('action')
url = data.get('url')
id = data.get('id')
print(f'当前于web路由action状态码:{action}')
print(file_center_list())
match action:
case 'fetch_myfast':# 刷新快捷方式
results = fetch_myfast()
return render_template('add_myfast.html', items=results)
case 'add_website':# 添加网址到快捷方式
response_data = add_website()
return jsonify(response_data)
case 'add_plugin':# 添加插件到快捷方式
response_data = add_plugin()
return jsonify(response_data)
case 'conn_website':# 检测网址
title, description = fetch_title_and_description(url)
return jsonify({'title': title, 'description': description})
case 'del_fast':#删除快捷方式
if del_myfast(id):
return jsonify({"message": "删除成功"})
else:
return jsonify({"error": "删除失败"}), 500
case 'utimes':#快捷方式计数
if Utimes_myfast(id):
return jsonify({'message': 'Utimes_myfast success'})
else:
return jsonify({'status': 'error', 'message': 'Missing id'}), 400
case 'file_center_list': # 临时文件中心表格显示
return file_center_list()
case 'del_upload_file': # 临时文件中心表格显示
directories = data.get('directories', [])
result = delete_directories(directories)
return jsonify(result)
case 'AIURL_list':#读取网址大全列表
unique_sheet_names = get_sheet_names()
unique_column_names = get_table_columns()
unique_all_records = get_all_records()
return render_template('AIURL_List.html',
sheet_names=unique_sheet_names,
column_names=unique_column_names,
all_records=unique_all_records)
case _:
return jsonify({"error": "Invalid action or request method"}), 400
else:
return jsonify({'error': 'Invalid Content-Type'}), 400
=======
from flask import Flask, request, jsonify, Blueprint, render_template,Response
import sqlite3,os,json,requests,glob,random,string,re,sys,webbrowser,platform,subprocess,chardet,shutil
from datetime import datetime, timedelta
from bs4 import BeautifulSoup
from Ini_sys import *
from Ini_DB import *
web_blueprint = Blueprint('web', __name__)
"""<快捷方式操作网址相关函数>"""
# 插入数据到数据库的函数
def insert_website(WType, UserID, URL, Title, Des, CreDate, UbDate, Utimes):
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("INSERT INTO MyFast (WType, UserID, URL, Title, Des, CreDate, UbDate, Utimes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (WType, UserID, URL, Title, Des, CreDate, UbDate, Utimes))
conn.commit()
except sqlite3.Error as e:
print(f"数据库错误: {e}")
finally:
conn.close()
# 调用函数添加网址到数据库
def add_website():
# 获取JSON数据
data = request.json
url = data.get('url')
title = data.get('title')
description = data.get('description')
# 当前时间
now = datetime.now()
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# 插入数据到数据库
insert_website('website',0,url, title, description, formatted_date, formatted_date, 0)
return {"message": "添加成功"} # 返回一个可以被 jsonify 序列化的字典
# 添加插件到数据库
def add_plugin():
# 获取JSON数据
data = request.json
plugin_id = data.get('plugin_id')
url = data.get('plug_url')
title = data.get('plug_name')
description = data.get('plug_description')
# 检查URL是否已经存在
existing_urls = DB_select_return('MyFast','URL', url)
if existing_urls:
return {"message": "该插件已添加过"}
# 查找插件信息
print(plugin_id)
DB_JSON_List=query_db('MyPlugins', f'ID={plugin_id}')
DB_JSON = DB_JSON_List[0]
print(DB_JSON)
print(DB_JSON['PlugName'])
# 当前时间
now = datetime.now()
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# 插入数据到数据库
insert_website('plugin', 0, url, DB_JSON['PlugName'], DB_JSON['PlugDes'], formatted_date, formatted_date, 0)
return {"message": "添加成功"} # 返回一个可以被 jsonify 序列化的字典
#检测网址,请求TD
def fetch_title_and_description(url):
try:
response = requests.get(url, timeout=10)
response.raise_for_status() # 检查请求是否成功
# 自动检测字符编码
detected_encoding = chardet.detect(response.content)['encoding']
# 如果检测到编码,则使用该编码解码响应内容
if detected_encoding:
response.encoding = detected_encoding
else:
# 默认编码
response.encoding = 'utf-8'
# 解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')
# 尝试获取<title>标签内容作为网页标题
title = soup.find('title').string if soup.find('title') else '获取不到标题'
# 尝试获取<meta name="description">标签的内容
description = soup.find('meta', attrs={'name': 'description'})
description = description['content'] if description else '获取不到描述'
return title, description
except Exception as e:
return '链接失败', '链接失败'
# 删除快捷方式
def del_myfast(id):
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 执行删除操作
cursor.execute("DELETE FROM MyFast WHERE ID = ?", (id,))
conn.commit()
except sqlite3.Error as e:
print(f"数据库操作错误: {e}")
return False
finally:
conn.close()
return True
# 快捷方式记数
def Utimes_myfast(id):
try:
conn = sqlite3.connect(db_path) # 数据库文件路径
cursor = conn.cursor()
# 更新Utimes字段,使其值加1
update_query = "UPDATE MyFast SET Utimes = Utimes + 1 WHERE ID = ?"
cursor.execute(update_query, (id,))
conn.commit() # 提交事务
conn.close() # 关闭连接
return True
except:
return False
"""<读取快捷方式列表相关函数>"""
# 提取7天天数和日期
def get_days_ago(ub_date_str):
ub_date = datetime.strptime(ub_date_str, "%Y-%m-%d %H:%M:%S")
delta = datetime.now() - ub_date
if delta.days <= 7:
return f"{delta.days} 天前"
else:
return ub_date_str
# 提取快捷方式列表
def fetch_myfast():
# 连接到SQLite数据库
# 数据库文件存放路径
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 执行查询
query = "SELECT ID,WType, URL, Title, Des, UbDate, Utimes FROM MyFast ORDER BY UbDate DESC"
cursor.execute(query)
items = cursor.fetchall()
# 关闭数据库连接
conn.close()
# 处理每条记录
formatted_items = []
for item in items:
ID, WType, URL, Title, Des, UbDate, Utimes = item
if WType == "website":
icon_class = "layui-icon-website"
else:
icon_class = "layui-icon-component"
UbDate = get_days_ago(UbDate)
formatted_items.append({
"icon_class": icon_class,
"ID": ID,
"URL": URL,
"Title": Title,
"Des": Des,
"UbDate": UbDate,
"Utimes": Utimes
})
return formatted_items
"""<AI网址大全相关函数>"""
#获取AI网址中的表名
def get_sheet_names():
"""从数据库中读取所有唯一的sheet_name"""
# 连接到SQLite数据库
conn = sqlite3.connect(db_path)
cur = conn.cursor()
# 执行查询操作,选择不重复的sheet_name
cur.execute("SELECT DISTINCT sheet_name FROM AIURL")
# 获取所有结果
sheets = cur.fetchall()
# 关闭游标和连接
cur.close()
conn.close()
# 将结果转换为列表
unique_sheet_names = [sheet[0] for sheet in sheets]
return unique_sheet_names
# 获取所有字段名
def get_table_columns():
"""获取指定表的所有字段名"""
conn = sqlite3.connect(db_path)
cur = conn.cursor()
# 使用PRAGMA table_info()语句获取表的元数据
cur.execute(f"PRAGMA table_info(AIURL)")
# 获取所有字段的信息,每个字段的信息是一个元组,其中第二个元素是字段名
columns_info = cur.fetchall()
# 从每个字段的信息中提取字段名
column_names = [info[1] for info in columns_info if info[1] != 'sheet_name']
cur.close()
conn.close()
return column_names
# 读取表中所有内容
def get_all_records():
"""获取指定表的所有记录"""
# 连接到数据库
conn = sqlite3.connect(db_path)
cur = conn.cursor()
# 构建查询语句,选择所有字段
query = f"SELECT * FROM AIURL"
# 执行查询
cur.execute(query)
# 获取所有记录
records = cur.fetchall()
# 关闭游标和连接
cur.close()
conn.close()
return records
# 临时文件中心表格显示
def file_center_list():
# 连接到SQLite数据库
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 查询数据库
cursor.execute("SELECT PlugName, PlugDir, uploadDir FROM MyPlugins")
plugins = cursor.fetchall()
# 存储结果的列表
result = []
# 遍历每个插件
for plug_name, plug_dir, upload_dir in plugins:
if not upload_dir:
print(f"插件 {plug_name} 的 uploadDir 字段为空")
continue
# 分割uploadDir字段得到子目录
directories = upload_dir.split(',')
for dir in directories:
full_path = os.path.join("plugins", plug_dir, dir)
if not os.path.exists(full_path):
print(f"目录 {full_path} 不存在")
continue
# 计算目录下的文件数和总占用空间
file_count = 0
total_size = 0
for root, dirs, files in os.walk(full_path):
file_count += len(files)
total_size += sum(os.path.getsize(os.path.join(root, name)) for name in files)
# 占用空间转为MB
total_size_mb = round(total_size / (1024 * 1024), 2)
# 将结果加入列表
result.append({
"PlugName": plug_name,
"Directory": full_path,
"FileCount": file_count,
"TotalSizeMB": total_size_mb
})
# 关闭数据库连接
conn.close()
# 转化结果为JSON
#fc_json = result
#fc_json = json.dumps(result)
#return fc_json
return {"code": 0, "msg": "", "count": len(result), "data": result}
# 删除给定的目录列表及其所有内容
def delete_directories(directories):
""" 删除给定的目录列表及其所有内容。 """
try:
for directory in directories:
full_path = os.path.join(directory) # 组合成完整路径
shutil.rmtree(full_path) # 删除目录及其所有内容
return {"code": 0, "msg": "删除成功"}
except Exception as e:
return {"code": 500, "msg": str(e)}
"""<一般web端路由交互执行>"""
@web_blueprint.route('/', methods=['POST'])
def handle_web_Execution():
if request.is_json: # 确保请求包含 JSON 数据
data = request.get_json()
action = data.get('action')
url = data.get('url')
id = data.get('id')
print(f'当前于web路由action状态码:{action}')
print(file_center_list())
match action:
case 'fetch_myfast':# 刷新快捷方式
results = fetch_myfast()
return render_template('add_myfast.html', items=results)
case 'add_website':# 添加网址到快捷方式
response_data = add_website()
return jsonify(response_data)
case 'add_plugin':# 添加插件到快捷方式
response_data = add_plugin()
return jsonify(response_data)
case 'conn_website':# 检测网址
title, description = fetch_title_and_description(url)
return jsonify({'title': title, 'description': description})
case 'del_fast':#删除快捷方式
if del_myfast(id):
return jsonify({"message": "删除成功"})
else:
return jsonify({"error": "删除失败"}), 500
case 'utimes':#快捷方式计数
if Utimes_myfast(id):
return jsonify({'message': 'Utimes_myfast success'})
else:
return jsonify({'status': 'error', 'message': 'Missing id'}), 400
case 'file_center_list': # 临时文件中心表格显示
return file_center_list()
case 'del_upload_file': # 临时文件中心表格显示
directories = data.get('directories', [])
result = delete_directories(directories)
return jsonify(result)
case 'AIURL_list':#读取网址大全列表
unique_sheet_names = get_sheet_names()
unique_column_names = get_table_columns()
unique_all_records = get_all_records()
return render_template('AIURL_List.html',
sheet_names=unique_sheet_names,
column_names=unique_column_names,
all_records=unique_all_records)
case _:
return jsonify({"error": "Invalid action or request method"}), 400
else:
return jsonify({'error': 'Invalid Content-Type'}), 400
>>>>>>> 33969d2a895ce8a09fca410185bb3cfa811bfe73