Ethscriptions commited on
Commit
9660e2c
·
verified ·
1 Parent(s): ae5d853

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -36
app.py CHANGED
@@ -4,18 +4,58 @@ import os
4
  import threading
5
  import time
6
 
7
- # Session状态初始化
8
- if 'download' not in st.session_state:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  st.session_state.download = {
10
- 'progress': 0,
11
- 'is_downloading': False,
12
- 'complete': False,
13
- 'file_path': None,
14
- 'status': ""
15
  }
16
 
17
  def download_torrent(magnet_link, save_path):
18
  try:
 
 
 
 
 
 
 
 
 
 
19
  ses = lt.session()
20
  params = {
21
  'save_path': save_path,
@@ -25,57 +65,64 @@ def download_torrent(magnet_link, save_path):
25
  handle = lt.add_magnet_uri(ses, magnet_link, params)
26
 
27
  # 获取元数据
28
- st.session_state.download['status'] = "正在获取元数据..."
 
29
  while not handle.has_metadata():
30
  time.sleep(1)
31
 
32
  # 获取文件信息
33
  torrent_info = handle.get_torrent_info()
34
- files = []
35
- for i in range(torrent_info.num_files()):
36
- files.append(torrent_info.file_at(i).path)
37
 
38
  # 开始下载
39
- st.session_state.download['status'] = "开始下载..."
40
- st.session_state.download['is_downloading'] = True
41
 
42
  while handle.status().state != lt.torrent_status.seeding:
43
  status = handle.status()
44
- progress = status.progress * 100
45
- st.session_state.download['progress'] = progress
46
  time.sleep(1)
47
 
48
  # 下载完成
49
- st.session_state.download['is_downloading'] = False
50
- st.session_state.download['complete'] = True
51
- st.session_state.download['file_path'] = save_path
52
- st.session_state.download['status'] = f"下载完成!保存路径:{save_path}"
 
53
 
54
  except Exception as e:
55
- st.session_state.download['status'] = f"错误:{str(e)}"
56
- st.session_state.download['is_downloading'] = False
 
 
 
 
 
 
57
 
58
  # 界面布局
59
  st.title("🎯 磁力链接下载器")
60
  st.write("输入磁力链接开始下载(仅支持单个文件)")
61
 
62
  magnet_link = st.text_input("磁力链接:", placeholder="magnet:?xt=urn:btih:...")
63
- col1, col2 = st.columns([1, 3])
64
 
65
- with col1:
66
- if st.button("🚀 开始下载", disabled=st.session_state.download['is_downloading']):
67
- if not magnet_link.startswith("magnet:"):
68
- st.error("请输入有效的磁力链接!")
69
- else:
70
- save_dir = "./downloads"
71
- os.makedirs(save_dir, exist_ok=True)
72
- threading.Thread(
73
- target=download_torrent,
74
- args=(magnet_link, save_dir),
75
- daemon=True
76
- ).start()
 
 
77
 
78
- # 下载状态显示
79
  if st.session_state.download['is_downloading']:
80
  st.progress(int(st.session_state.download['progress']))
81
  st.write(f"🔍 进度:{st.session_state.download['progress']:.1f}%")
@@ -84,7 +131,7 @@ if st.session_state.download['is_downloading']:
84
  if st.session_state.download['complete']:
85
  st.success("✅ 下载完成!")
86
 
87
- # 显示下载文件
88
  download_dir = st.session_state.download['file_path']
89
  files = [f for f in os.listdir(download_dir) if os.path.isfile(os.path.join(download_dir, f))]
90
 
 
4
  import threading
5
  import time
6
 
7
+ # 线程安全的下载状态管理
8
+ class DownloadState:
9
+ _instance = None
10
+ _lock = threading.Lock()
11
+
12
+ def __new__(cls):
13
+ with cls._lock:
14
+ if cls._instance is None:
15
+ cls._instance = super().__new__(cls)
16
+ cls._instance.progress = 0
17
+ cls._instance.is_downloading = False
18
+ cls._instance.complete = False
19
+ cls._instance.file_path = None
20
+ cls._instance.status = ""
21
+ return cls._instance
22
+
23
+ def init_session_state():
24
+ """初始化session_state"""
25
+ if 'download_initialized' not in st.session_state:
26
+ state = DownloadState()
27
+ st.session_state.download = {
28
+ 'progress': state.progress,
29
+ 'is_downloading': state.is_downloading,
30
+ 'complete': state.complete,
31
+ 'file_path': state.file_path,
32
+ 'status': state.status
33
+ }
34
+ st.session_state.download_initialized = True
35
+
36
+ def sync_session_state():
37
+ """同步状态到session_state"""
38
+ state = DownloadState()
39
  st.session_state.download = {
40
+ 'progress': state.progress,
41
+ 'is_downloading': state.is_downloading,
42
+ 'complete': state.complete,
43
+ 'file_path': state.file_path,
44
+ 'status': state.status
45
  }
46
 
47
  def download_torrent(magnet_link, save_path):
48
  try:
49
+ state = DownloadState()
50
+
51
+ # 初始化下载状态
52
+ with threading.Lock():
53
+ state.progress = 0
54
+ state.is_downloading = True
55
+ state.complete = False
56
+ state.file_path = None
57
+ state.status = "正在初始化..."
58
+
59
  ses = lt.session()
60
  params = {
61
  'save_path': save_path,
 
65
  handle = lt.add_magnet_uri(ses, magnet_link, params)
66
 
67
  # 获取元数据
68
+ with threading.Lock():
69
+ state.status = "正在获取元数据..."
70
  while not handle.has_metadata():
71
  time.sleep(1)
72
 
73
  # 获取文件信息
74
  torrent_info = handle.get_torrent_info()
75
+ files = [torrent_info.file_at(i).path for i in range(torrent_info.num_files())]
 
 
76
 
77
  # 开始下载
78
+ with threading.Lock():
79
+ state.status = "开始下载..."
80
 
81
  while handle.status().state != lt.torrent_status.seeding:
82
  status = handle.status()
83
+ with threading.Lock():
84
+ state.progress = status.progress * 100
85
  time.sleep(1)
86
 
87
  # 下载完成
88
+ with threading.Lock():
89
+ state.is_downloading = False
90
+ state.complete = True
91
+ state.file_path = save_path
92
+ state.status = f"下载完成!保存路径:{save_path}"
93
 
94
  except Exception as e:
95
+ with threading.Lock():
96
+ state.status = f"错误:{str(e)}"
97
+ state.is_downloading = False
98
+ finally:
99
+ sync_session_state()
100
+
101
+ # 初始化session状态
102
+ init_session_state()
103
 
104
  # 界面布局
105
  st.title("🎯 磁力链接下载器")
106
  st.write("输入磁力链接开始下载(仅支持单个文件)")
107
 
108
  magnet_link = st.text_input("磁力链接:", placeholder="magnet:?xt=urn:btih:...")
 
109
 
110
+ if st.button("🚀 开始下载", disabled=st.session_state.download['is_downloading']):
111
+ if not magnet_link.startswith("magnet:"):
112
+ st.error("请输入有效的磁力链接!")
113
+ else:
114
+ save_dir = "./downloads"
115
+ os.makedirs(save_dir, exist_ok=True)
116
+ threading.Thread(
117
+ target=download_torrent,
118
+ args=(magnet_link, save_dir),
119
+ daemon=True
120
+ ).start()
121
+
122
+ # 实时更新状态
123
+ sync_session_state()
124
 
125
+ # 显示下载状态
126
  if st.session_state.download['is_downloading']:
127
  st.progress(int(st.session_state.download['progress']))
128
  st.write(f"🔍 进度:{st.session_state.download['progress']:.1f}%")
 
131
  if st.session_state.download['complete']:
132
  st.success("✅ 下载完成!")
133
 
134
+ # 文件下载部分
135
  download_dir = st.session_state.download['file_path']
136
  files = [f for f in os.listdir(download_dir) if os.path.isfile(os.path.join(download_dir, f))]
137