File size: 6,274 Bytes
31d1f71
ae5d853
31d1f71
ae5d853
 
1c8f582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31d1f71
9660e2c
 
 
 
 
 
 
 
1c8f582
9660e2c
1c8f582
 
 
 
 
 
 
 
9660e2c
 
1c8f582
9660e2c
 
 
 
 
 
1c8f582
 
9660e2c
 
 
 
1c8f582
9660e2c
 
 
 
1c8f582
 
 
7d040bf
1c8f582
7d040bf
9660e2c
1c8f582
9660e2c
1c8f582
ae5d853
 
1c8f582
 
ae5d853
7d040bf
1c8f582
 
ae5d853
1c8f582
 
 
 
 
 
 
 
 
 
 
 
 
0582fea
ae5d853
1c8f582
 
 
7d040bf
1c8f582
 
 
ae5d853
1c8f582
 
 
ae5d853
1c8f582
 
 
 
 
 
 
 
 
 
 
7d040bf
ae5d853
 
1c8f582
 
 
 
 
ae5d853
31d1f71
1c8f582
 
 
9660e2c
 
 
1c8f582
9660e2c
1c8f582
0582fea
1c8f582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9660e2c
1c8f582
9660e2c
ae5d853
 
1c8f582
 
 
 
 
ae5d853
0582fea
ae5d853
1c8f582
 
 
0582fea
ae5d853
1c8f582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import libtorrent as lt
import os
import threading
import time
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)

class TorrentSession:
    def __init__(self):
        self.ses = lt.session()
        self.ses.listen_on(6881, 6891)
        self.alerts = []
        self.last_alert_time = time.time()

    def process_alerts(self):
        self.alerts = []
        while (alert := self.ses.wait_for_alert(1000)):
            self.alerts.append(alert)
            self.ses.pop_alert()

class DownloadState:
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance.reset()
            return cls._instance
    
    def reset(self):
        self.progress = 0.0
        self.is_downloading = False
        self.complete = False
        self.file_path = None
        self.status = "等待开始"
        self.info_hash = ""

def init_session_state():
    if 'download' not in st.session_state:
        state = DownloadState()
        st.session_state.download = {
            'progress': state.progress,
            'is_downloading': state.is_downloading,
            'complete': state.complete,
            'file_path': state.file_path,
            'status': state.status,
            'info_hash': state.info_hash
        }

def sync_session_state():
    state = DownloadState()
    st.session_state.download.update({
        'progress': state.progress,
        'is_downloading': state.is_downloading,
        'complete': state.complete,
        'file_path': state.file_path,
        'status': state.status,
        'info_hash': state.info_hash
    })

def download_worker(magnet_link, save_path):
    try:
        state = DownloadState()
        ts = TorrentSession()
        
        # 使用新版API添加磁力链接
        params = {
            'save_path': save_path,
            'storage_mode': lt.storage_mode_t.storage_mode_sparse,
            'flags': lt.torrent_flags.duplicate_is_error | lt.torrent_flags.auto_managed
        }
        
        handle = lt.add_magnet_uri(ts.ses, magnet_link, params)
        state.info_hash = str(handle.info_hash())
        
        # 事件驱动等待元数据
        state.status = "等待元数据..."
        logging.info("等待元数据...")
        
        metadata_received = False
        while not metadata_received:
            ts.process_alerts()
            for alert in ts.alerts:
                if isinstance(alert, lt.metadata_received_alert):
                    if alert.handle == handle:
                        metadata_received = True
                        break
            time.sleep(0.5)
        
        # 获取文件信息
        ti = handle.get_torrent_info()
        state.status = f"开始下载 {ti.name()}"
        logging.info(f"开始下载: {ti.name()}")
        
        # 启动下载
        handle.set_sequential_download(True)
        handle.resume()
        
        # 下载进度监控
        state.is_downloading = True
        while not handle.status().is_seeding:
            status = handle.status()
            state.progress = status.progress * 100
            
            # 检查种子状态
            if status.state == lt.torrent_status.downloading_metadata:
                state.status = "获取元数据..."
            elif status.state == lt.torrent_status.downloading:
                dl = status.download_rate / 1000
                up = status.upload_rate / 1000
                peers = status.num_peers
                state.status = f"下载中: {dl:.1f}kB/s ↑{up:.1f}kB/s ↔{peers} peers"
            
            time.sleep(1)
        
        # 下载完成
        state.is_downloading = False
        state.complete = True
        state.file_path = save_path
        state.status = "下载完成"
        logging.info("下载完成")
        
    except Exception as e:
        logging.error(f"下载错误: {str(e)}")
        state.status = f"错误: {str(e)}"
        state.is_downloading = False
    finally:
        sync_session_state()

# Streamlit界面
init_session_state()
st.title("🚀 磁力链接下载器")

with st.form("magnet_form"):
    magnet = st.text_input("磁力链接", placeholder="magnet:?xt=urn:btih:...")
    submitted = st.form_submit_button("开始下载", 
                    disabled=st.session_state.download['is_downloading'])
    
    if submitted:
        if not magnet.startswith("magnet:"):
            st.error("无效的磁力链接格式")
        else:
            save_dir = "./downloads"
            os.makedirs(save_dir, exist_ok=True)
            
            state = DownloadState()
            state.reset()
            sync_session_state()
            
            threading.Thread(
                target=download_worker,
                args=(magnet, save_dir),
                daemon=True
            ).start()

# 状态显示
sync_session_state()

if st.session_state.download['is_downloading']:
    cols = st.columns([1,3])
    with cols[0]:
        st.metric("进度", f"{st.session_state.download['progress']:.1f}%")
    with cols[1]:
        st.progress(st.session_state.download['progress']/100)
    st.info(st.session_state.download['status'])

if st.session_state.download['complete']:
    st.success("下载完成!")
    files = [f for f in os.listdir(st.session_state.download['file_path']) 
            if os.path.isfile(os.path.join(st.session_state.download['file_path'], f))]
    
    if files:
        with st.expander("下载文件"):
            selected = st.selectbox("选择文件", files)
            with open(os.path.join(st.session_state.download['file_path'], selected), "rb") as f:
                st.download_button(
                    "下载文件",
                    f,
                    file_name=selected,
                    mime="application/octet-stream"
                )

# 状态监控线程
if 'monitor' not in st.session_state:
    def status_monitor():
        while True:
            sync_session_state()
            time.sleep(0.5)
    
    threading.Thread(target=status_monitor, daemon=True).start()
    st.session_state.monitor = True