p2p-transfer 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/INSTALL-LINUX.md +320 -0
  2. package/README.md +192 -114
  3. package/p2p.js +230 -13
  4. package/package.json +2 -1
@@ -0,0 +1,320 @@
1
+ # Linux Installation Guide
2
+
3
+ This guide helps you install P2P Transfer on Linux systems.
4
+
5
+ ## ⚠️ Prerequisites
6
+
7
+ P2P Transfer requires native compilation tools due to its dependency on `node-datachannel`, which is part of WebTorrent.
8
+
9
+ ## 📦 System Requirements
10
+
11
+ - **Node.js**: >= 18.0.0 (LTS recommended)
12
+ - **Build Tools**: C/C++ compiler, make, python3
13
+ - **Disk Space**: ~200 MB
14
+
15
+ ## 🔧 Step-by-Step Installation
16
+
17
+ ### Step 1: Install Build Tools
18
+
19
+ **Ubuntu / Debian:**
20
+ ```bash
21
+ sudo apt update
22
+ sudo apt install -y build-essential python3
23
+ ```
24
+
25
+ **CentOS / RHEL / Fedora:**
26
+ ```bash
27
+ sudo yum groupinstall -y "Development Tools"
28
+ sudo yum install -y python3
29
+ ```
30
+
31
+ **Arch Linux:**
32
+ ```bash
33
+ sudo pacman -S base-devel python3
34
+ ```
35
+
36
+ **openSUSE:**
37
+ ```bash
38
+ sudo zypper install -y -t pattern devel_basis
39
+ sudo zypper install -y python3
40
+ ```
41
+
42
+ ### Step 2: Install Node.js 18 LTS
43
+
44
+ ```bash
45
+ # Using nvm (recommended)
46
+ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
47
+ source ~/.bashrc
48
+ nvm install 18
49
+ nvm use 18
50
+
51
+ # Verify installation
52
+ node -v # Should show v18.x.x
53
+ npm -v # Should show 9.x.x
54
+ ```
55
+
56
+ ### Step 3: Install P2P Transfer
57
+
58
+ ```bash
59
+ npm install -g p2p-transfer
60
+ ```
61
+
62
+ ### Step 4: Verify Installation
63
+
64
+ ```bash
65
+ p2p --help
66
+ ```
67
+
68
+ Expected output:
69
+ ```
70
+ 🌐 P2P 文件传输工具
71
+
72
+ 用法: p2p.js <命令> [参数]
73
+
74
+ Commands:
75
+ p2p.js share 分享文件,生成 magnet 链接
76
+ p2p.js get 下载文件
77
+ p2p.js info 显示帮助信息
78
+
79
+ Options:
80
+ -h, --help 显示帮助
81
+ -v, --version 版本
82
+ ```
83
+
84
+ ## 🐛 Troubleshooting
85
+
86
+ ### Error: prebuild ERR! build TypeError
87
+
88
+ **Cause**: Missing build tools
89
+
90
+ **Solution**:
91
+ ```bash
92
+ sudo apt install -y build-essential python3
93
+ npm cache clean --force
94
+ npm install -g p2p-transfer
95
+ ```
96
+
97
+ ### Error: node-gyp errors
98
+
99
+ **Cause**: Missing Python or build tools
100
+
101
+ **Solution**:
102
+ ```bash
103
+ # Ubuntu/Debian
104
+ sudo apt install -y python3 python3-dev build-essential
105
+
106
+ # CentOS/RHEL
107
+ sudo yum install -y python3 python3-devel gcc gcc-c++
108
+ ```
109
+
110
+ ### Error: EACCES permission denied
111
+
112
+ **Cause**: npm doesn't have write permission
113
+
114
+ **Solution 1**: Fix npm permissions
115
+ ```bash
116
+ mkdir ~/.npm-global
117
+ npm config set prefix '~/.npm-global'
118
+ echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
119
+ source ~/.bashrc
120
+ npm install -g p2p-transfer
121
+ ```
122
+
123
+ **Solution 2**: Use sudo (not recommended)
124
+ ```bash
125
+ sudo npm install -g p2p-transfer
126
+ ```
127
+
128
+ ### Error: ECONNREFUSED or ETIMEDOUT
129
+
130
+ **Cause**: Network issues, likely in China
131
+
132
+ **Solution**: Use npm mirror
133
+ ```bash
134
+ # Temporarily use mirror
135
+ npm install -g p2p-transfer --registry=https://registry.npmmirror.com
136
+
137
+ # Or set permanent mirror
138
+ npm config set registry https://registry.npmmirror.com
139
+ npm install -g p2p-transfer
140
+ ```
141
+
142
+ ### Error: node-datachannel compilation failed
143
+
144
+ **Cause**: Incompatible Node.js version or missing dependencies
145
+
146
+ **Solution 1**: Install specific Node.js version
147
+ ```bash
148
+ nvm install 18.16.0
149
+ nvm use 18.16.0
150
+ npm install -g p2p-transfer
151
+ ```
152
+
153
+ **Solution 2**: Build from source
154
+ ```bash
155
+ git clone https://github.com/yourusername/p2p-transfer.git
156
+ cd p2p-transfer
157
+ npm install --build-from-source
158
+ npm link
159
+ ```
160
+
161
+ ## 🚀 Automated Installation Script
162
+
163
+ Download and run the automated installation script:
164
+
165
+ ```bash
166
+ curl -fsSL https://raw.githubusercontent.com/yourusername/p2p-transfer/main/install-linux.sh | bash
167
+ ```
168
+
169
+ Or manually:
170
+
171
+ ```bash
172
+ # Download script
173
+ wget https://raw.githubusercontent.com/yourusername/p2p-transfer/main/install-linux.sh
174
+
175
+ # Make executable
176
+ chmod +x install-linux.sh
177
+
178
+ # Run
179
+ ./install-linux.sh
180
+ ```
181
+
182
+ ## 🐳 Using Docker
183
+
184
+ Create a `Dockerfile`:
185
+
186
+ ```dockerfile
187
+ FROM node:18-slim
188
+
189
+ RUN apt-get update && apt-get install -y \
190
+ build-essential \
191
+ python3 \
192
+ && rm -rf /var/lib/apt/lists/*
193
+
194
+ WORKDIR /app
195
+
196
+ # Install p2p-transfer globally
197
+ RUN npm install -g p2p-transfer
198
+
199
+ # Create a non-root user
200
+ RUN useradd -m -s /bin/bash appuser && \
201
+ npm set prefix /home/appuser/.npm-global && \
202
+ echo 'export PATH=/home/appuser/.npm-global/bin:$PATH' >> /home/appuser/.bashrc
203
+
204
+ USER appuser
205
+ WORKDIR /home/appuser
206
+
207
+ CMD ["p2p", "--help"]
208
+ ```
209
+
210
+ Build and run:
211
+
212
+ ```bash
213
+ docker build -t p2p-transfer .
214
+ docker run -it p2p-transfer share /path/to/file
215
+ ```
216
+
217
+ ## 📋 Quick Reference
218
+
219
+ | Command | Description |
220
+ |---------|-------------|
221
+ | `apt install build-essential python3` | Install build tools (Ubuntu) |
222
+ | `yum groupinstall "Development Tools"` | Install build tools (CentOS) |
223
+ | `pacman -S base-devel python3` | Install build tools (Arch) |
224
+ | `npm install -g p2p-transfer` | Install P2P Transfer |
225
+ | `p2p --help` | Verify installation |
226
+
227
+ ## 🔍 Check System Info
228
+
229
+ Run these commands to check your system:
230
+
231
+ ```bash
232
+ # Check OS
233
+ cat /etc/os-release
234
+
235
+ # Check Node.js version
236
+ node -v
237
+
238
+ # Check npm version
239
+ npm -v
240
+
241
+ # Check build tools
242
+ gcc --version
243
+ make --version
244
+ python3 --version
245
+
246
+ # Check if build tools are installed
247
+ which gcc make python3
248
+ ```
249
+
250
+ ## 📞 Getting Help
251
+
252
+ If you encounter issues not covered here:
253
+
254
+ 1. Check the [Troubleshooting Guide](#troubleshooting)
255
+ 2. Search [existing issues](https://github.com/yourusername/p2p-transfer/issues)
256
+ 3. Create a new issue with:
257
+ - Your Linux distribution and version
258
+ - Node.js version: `node -v`
259
+ - npm version: `npm -v`
260
+ - Complete error message
261
+ - Output of: `sudo apt list --installed | grep -E "(build-essential|python3|gcc)"`
262
+
263
+ ## ✅ Verification
264
+
265
+ After successful installation, verify:
266
+
267
+ ```bash
268
+ # Check p2p-transfer version
269
+ p2p --version
270
+
271
+ # Test share command
272
+ echo "test" > test.txt
273
+ p2p share test.txt
274
+ # Should show: "🚀 初始化 P2P 分享..."
275
+
276
+ # Clean up
277
+ rm test.txt
278
+ ```
279
+
280
+ ## 🎉 Success!
281
+
282
+ Once installed successfully, you can use P2P Transfer:
283
+
284
+ ```bash
285
+ # Share a file
286
+ p2p share ~/movies/vacation.mp4
287
+
288
+ # Download a file
289
+ p2p get "magnet:?xt=urn:btih:abc123..."
290
+
291
+ # Get help
292
+ p2p info
293
+ ```
294
+
295
+ ## 🔄 Update
296
+
297
+ To update to the latest version:
298
+
299
+ ```bash
300
+ npm update -g p2p-transfer
301
+ ```
302
+
303
+ ## 🗑️ Uninstall
304
+
305
+ To remove P2P Transfer:
306
+
307
+ ```bash
308
+ npm uninstall -g p2p-transfer
309
+ ```
310
+
311
+ To also remove build tools (if not needed):
312
+
313
+ ```bash
314
+ # Ubuntu/Debian
315
+ sudo apt remove build-essential python3
316
+ ```
317
+
318
+ ---
319
+
320
+ **Last Updated**: 2024-06-01
package/README.md CHANGED
@@ -1,247 +1,325 @@
1
- # P2P Transfer
1
+ # P2P Transfer - 点对点文件传输工具
2
2
 
3
- 🚀 A pure CLI tool for peer-to-peer file transfer between different networks, powered by WebTorrent and BitTorrent DHT.
3
+ 🚀 基于 WebTorrent BitTorrent DHT 的纯命令行点对点文件传输工具,支持跨局域网直传。
4
4
 
5
- ## ✨ Features
5
+ ## ✨ 功能特性
6
6
 
7
- - 🌐 **Pure CLI** - No web UI or browser required, operate directly in terminal
8
- - 🔧 **Zero Configuration** - One command to send, one command to receive
9
- - 👶 **Beginner Friendly** - Intuitive commands with progress bar and speed display
10
- - ⚡ **Maximum Speed** - DHT + configurable Tracker subscription for optimal peer discovery
11
- - 🔒 **Cross-Network** - Transfer between different LANs without requiring public IP
12
- - 📦 **Large File Support** - Handles files of any size with automatic chunking
7
+ - 🌐 **纯命令行** - 无需 Web UI 或浏览器,终端直接操作
8
+ - 🔧 **零配置** - 一条命令发送,一条命令接收
9
+ - 👶 **小白友好** - 语义化命令,带进度条和速度显示
10
+ - ⚡ **速度最大化** - DHT + 可配置 Tracker 订阅,最大化节点发现
11
+ - 🔒 **跨网络传输** - 不同局域网之间传输,无需公网 IP
12
+ - 📦 **大文件支持** - 自动分块处理任意大小文件
13
+ - ⚙️ **灵活配置** - 支持自定义 Tracker 列表和远程订阅更新
13
14
 
14
- ## 🚀 Quick Start
15
+ ## 🚀 快速开始
15
16
 
16
- ### Installation
17
+ ### 安装
17
18
 
18
19
  ```bash
19
- # Install via npm (after publishing)
20
+ # 通过 npm 全局安装
20
21
  npm install -g p2p-transfer
21
22
 
22
- # Or use npx directly
23
+ # 或者使用 npx 直接运行
23
24
  npx p2p-transfer share <file>
24
25
  ```
25
26
 
26
- ### Basic Usage
27
+ ### 基础用法
27
28
 
28
- **Share a file (on sender's machine):**
29
+ **发送文件(在发送方机器上):**
29
30
  ```bash
30
31
  p2p share ~/movies/vacation.mp4
31
32
  ```
32
33
 
33
- **Download a file (on receiver's machine):**
34
+ **接收文件(在接收方机器上):**
34
35
  ```bash
35
36
  p2p get "magnet:?xt=urn:btih:abc123..."
36
37
  ```
37
38
 
38
- ## 📖 Detailed Usage
39
+ ## 📖 详细用法
39
40
 
40
- ### Share Command
41
+ ### share 命令 - 分享文件
41
42
 
42
43
  ```bash
43
- p2p share <file> [options]
44
+ p2p share <文件路径> [选项]
44
45
 
45
- Options:
46
- -v, --verbose Show detailed logs
46
+ 选项:
47
+ -v, --verbose 显示详细日志
47
48
  ```
48
49
 
49
- **Example:**
50
+ **示例:**
50
51
  ```bash
51
52
  p2p share ~/documents/report.pdf
52
53
  p2p share ./large-video.mp4 --verbose
53
54
  ```
54
55
 
55
- **Output:**
56
+ **输出示例:**
56
57
  ```
57
- 🚀 Initializing P2P share...
58
- 📁 File: report.pdf
59
- 📊 Size: 2.5 MB
58
+ 🚀 初始化 P2P 分享...
59
+ 📁 文件: report.pdf
60
+ 📊 大小: 2.5 MB
61
+ 🔗 Trackers: 9 个
60
62
 
61
- Share successful!
63
+ 分享成功!
62
64
 
63
- 🔗 Magnet URI (copy and send to receiver):
65
+ 🔗 Magnet 链接 (复制发送给接收方):
64
66
  magnet:?xt=urn:btih:abc123def456...
65
67
 
66
68
  📋 BTIH Hash: abc123def456
67
69
 
68
- Waiting for connections... (Press Ctrl+C to stop)
70
+ 等待连接中... ( Ctrl+C 停止)
69
71
  ```
70
72
 
71
- ### Download Command
73
+ ### get 命令 - 下载文件
72
74
 
73
75
  ```bash
74
- p2p get <magnet> [path] [options]
76
+ p2p get <magnet链接> [保存目录] [选项]
75
77
 
76
- Arguments:
77
- magnet Magnet URI
78
- path Download directory (default: current directory)
78
+ 参数:
79
+ magnet Magnet 链接
80
+ path 保存目录(默认:当前目录)
79
81
 
80
- Options:
81
- -v, --verbose Show detailed logs
82
+ 选项:
83
+ -v, --verbose 显示详细日志
82
84
  ```
83
85
 
84
- **Example:**
86
+ **示例:**
85
87
  ```bash
86
88
  p2p get "magnet:?xt=urn:btih:abc123..." ~/Downloads
87
89
  p2p get "magnet:?xt=urn:btih:abc123..." ./my-files
88
90
  ```
89
91
 
90
- **Output:**
92
+ **输出示例:**
91
93
  ```
92
- 📥 Initializing P2P download...
94
+ 📥 初始化 P2P 下载...
93
95
 
94
- File found!
96
+ 找到文件!
95
97
 
96
- 📁 Filename: report.pdf
97
- 📊 Total size: 2.5 MB
98
+ 📁 文件名: report.pdf
99
+ 📊 总大小: 2.5 MB
98
100
  📋 Hash: abc123def456
99
- 📁 Save to: ~/Downloads
101
+ 📁 保存到: ~/Downloads
100
102
 
101
- 📥 Download Progress |████████████░░░░| 45% | 1.1 MB/2.5 MB | 5.2 MB/s | ETA: 00:00:03
103
+ 📥 下载进度 |████████████░░░░| 45% | 1.1 MB/2.5 MB | 5.2 MB/s | ETA: 00:00:03
102
104
 
103
- Download complete!
104
- ⏱️ Total time: 2.50 seconds
105
- 📁 Location: ~/Downloads/report.pdf
105
+ 下载完成!
106
+ ⏱️ 总耗时: 2.50
107
+ 📁 保存位置: ~/Downloads/report.pdf
106
108
  ```
107
109
 
108
- ### Help Command
110
+ ### config 命令 - 配置管理
111
+
112
+ ```bash
113
+ p2p config <子命令>
114
+
115
+ 子命令:
116
+ show 显示当前配置
117
+ add <tracker> 添加新的 Tracker
118
+ remove <url> 移除指定 Tracker
119
+ set-url <url> 设置远程订阅地址
120
+ update 从订阅地址更新 Trackers
121
+ reset 重置配置为默认值
122
+ ```
123
+
124
+ **示例:**
125
+ ```bash
126
+ # 查看当前配置
127
+ p2p config show
128
+
129
+ # 添加新的 Tracker
130
+ p2p config add udp://tracker.example.com:8080/announce
131
+
132
+ # 移除 Tracker
133
+ p2p config remove udp://tracker.example.com:8080/announce
134
+
135
+ # 更新远程订阅地址
136
+ p2p config set-url https://example.com/trackers.txt
137
+
138
+ # 从远程订阅更新 Trackers
139
+ p2p config update
140
+
141
+ # 重置配置
142
+ p2p config reset
143
+ ```
144
+
145
+ **配置文件位置:** `~/.p2p-transfer/config.json`
146
+
147
+ ### info 命令 - 显示帮助信息
109
148
 
110
149
  ```bash
111
150
  p2p info
112
151
  ```
113
152
 
114
- ## 🎯 How It Works
153
+ ## 🎯 工作原理
115
154
 
116
155
  ```
117
156
  ┌─────────────────┐ ┌─────────────────┐
118
- Sender │ P2P │ Receiver
157
+ 发送方 │ P2P │ 接收方
119
158
  │ │◄───────►│ │
120
- │ 1. Seed file │ DHT │ 2. Download
121
- │ 3. Get Magnet │ │ 4. Parse Magnet
122
- │ 4. Share Link │ │ 5. Start D/L
159
+ │ 1. 播种文件 │ DHT │ 2. 下载文件
160
+ │ 3. 生成链接 │ │ 4. 解析链接
161
+ │ 4. 分享链接 │ │ 5. 开始下载
123
162
  └─────────────────┘ └─────────────────┘
124
163
  ```
125
164
 
126
- 1. **Sender** runs `p2p share <file>` to start seeding
127
- 2. Generates unique **Magnet URI** containing file hash and Tracker addresses
128
- 3. **Receiver** runs `p2p get <magnet>` with the received URI
129
- 4. **DHT + Trackers** discover peers automatically
130
- 5. **P2P connection** established for direct transfer
165
+ 1. **发送方**运行 `p2p share <file>` 开始播种文件
166
+ 2. 生成包含文件哈希和 Tracker 地址的唯一 **Magnet URI**
167
+ 3. **接收方**使用收到的链接运行 `p2p get <magnet>`
168
+ 4. **DHT + Trackers** 自动发现节点
169
+ 5. 建立 **P2P 连接**进行直接传输
131
170
 
132
- ## 🔧 Technical Details
171
+ ## 🔧 技术细节
133
172
 
134
- - **Protocol**: BitTorrent
135
- - **Peer Discovery**: DHT (Distributed Hash Table)
136
- - **Trackers**: 7 public trackers for maximum connectivity
137
- - **No Public IP Required**: Works behind NAT and firewalls
173
+ - **协议**: BitTorrent
174
+ - **节点发现**: DHT (分布式哈希表)
175
+ - **Trackers**: 9 个公共 Tracker,支持远程订阅更新
176
+ - **无需公网 IP**: 支持 NAT 和防火墙穿透
138
177
 
139
- ### Default Trackers
178
+ ### 默认 Trackers
140
179
 
141
180
  ```
142
181
  - udp://tracker.opentrackr.org:1337/announce
143
182
  - udp://tracker.openbittorrent.com:6969/announce
144
- - udp://exodus.desync.com:6969/announce
145
183
  - udp://tracker.coppersurfer.tk:6969/announce
184
+ - udp://tracker.publicbt.com:80/announce
185
+ - udp://tracker.bitsearch.to:1337/announce
146
186
  - wss://tracker.btorrent.xyz
147
187
  - wss://tracker.openwebtorrent.com
148
188
  - wss://tracker.webtorrent.io
189
+ - wss://tracker.files.fm:7073/announce
149
190
  ```
150
191
 
151
- ## 💡 Use Cases
192
+ ### 远程订阅地址
193
+
194
+ 默认订阅地址:`https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_best.txt`
195
+
196
+ 运行 `p2p config update` 可从该地址自动更新 Tracker 列表。
152
197
 
153
- - **NAS to Local**: Transfer files from NAS to your computer
154
- - **Cross-Network**: Share files between different networks (home ↔ office)
155
- - **Quick Sharing**: No need to upload to cloud first
156
- - **Large Files**: Perfect for big files without size limits
157
- - **Offline Sharing**: Works without internet servers (via DHT)
198
+ ## 💡 使用场景
158
199
 
159
- ## ⚙️ Requirements
200
+ - **NAS 到本地**: 从 NAS 传输文件到电脑
201
+ - **跨网络传输**: 不同网络之间共享文件(家用 ↔ 办公室)
202
+ - **快速分享**: 无需先上传到云端
203
+ - **大文件传输**: 适合无大小限制的大文件
204
+ - **离线分享**: 无需服务器支持(通过 DHT)
205
+ - **远程协作**: 团队成员之间直接传输文件
206
+
207
+ ## ⚙️ 系统要求
160
208
 
161
209
  - Node.js >= 18.0.0
162
210
  - npm >= 8.0.0
211
+ - 支持的系统:macOS / Linux / Windows (WSL)
163
212
 
164
- ## 📦 Installation from Source
213
+ ## 📦 从源码安装
165
214
 
166
215
  ```bash
167
216
  git clone https://gitcode.com/yunqiang_wu/p2p-transfer.git
168
217
  cd p2p-transfer
169
218
  npm install
219
+
220
+ # 运行
221
+ node p2p.js share <file>
222
+
223
+ # 或者链接到全局
224
+ npm link
225
+ p2p share <file>
170
226
  ```
171
227
 
172
- ## 🌟 Advanced Usage
228
+ ## 🌟 高级用法
229
+
230
+ ### Linux 环境安装
173
231
 
174
- ### Global Installation
232
+ 对于 Linux 用户,可能需要安装编译工具:
175
233
 
176
234
  ```bash
235
+ # Ubuntu/Debian
236
+ sudo apt update && sudo apt install -y build-essential python3
237
+
238
+ # CentOS/RHEL
239
+ sudo yum groupinstall -y "Development Tools" && sudo yum install -y python3
240
+
241
+ # 然后安装
177
242
  npm install -g p2p-transfer
243
+ ```
244
+
245
+ 或者使用自动安装脚本:
178
246
 
179
- # Now you can use it anywhere
180
- p2p share ~/file.txt
247
+ ```bash
248
+ curl -fsSL https://raw.githubusercontent.com/yunqiang_wu/p2p-transfer/main/install-linux.sh | bash
181
249
  ```
182
250
 
183
- ### Use as Project Dependency
251
+ ### 作为项目依赖使用
184
252
 
185
253
  ```bash
186
254
  npm install p2p-transfer
187
255
  ```
188
256
 
189
- Then in your code:
257
+ 然后在代码中使用:
258
+
190
259
  ```javascript
191
- import { share, get } from 'p2p-transfer';
260
+ import { shareFile, getFile } from 'p2p-transfer';
192
261
 
193
- await share('/path/to/file');
194
- await get('magnet:?xt=urn:btih:...');
262
+ await shareFile('/path/to/file');
263
+ await getFile('magnet:?xt=urn:btih:...', './downloads');
195
264
  ```
196
265
 
197
- ## 🐛 Troubleshooting
266
+ ## 🐛 故障排除
267
+
268
+ ### 无法连接到节点?
269
+
270
+ 1. **检查防火墙**: 确保允许 UDP/TCP 出站连接
271
+ 2. **稍等片刻**: DHT 节点发现可能需要 1-2 分钟
272
+ 3. **使用详细模式**: `p2p share <file> -v`
273
+ 4. **更新 Trackers**: `p2p config update`
198
274
 
199
- ### No peers connecting?
275
+ ### 下载速度慢?
200
276
 
201
- 1. **Check firewall**: Ensure outbound UDP/TCP is allowed
202
- 2. **Wait longer**: DHT peer discovery may take 1-2 minutes
203
- 3. **Try verbose mode**: `p2p share <file> -v`
204
- 4. **Use more trackers**: Add additional trackers in code
277
+ 1. **等待更多节点**: 速度随种子数增加而提升
278
+ 2. **检查网络**: 某些网络有限制
279
+ 3. **尝试其他网络**: 某些 ISP 限制 BitTorrent
205
280
 
206
- ### Download speed is slow?
281
+ ### 连接问题?
207
282
 
208
- 1. **Wait for more peers**: Speed increases with more seeders
209
- 2. **Check NAT**: Some networks have bandwidth limits
210
- 3. **Try different network**: Some ISPs throttle BitTorrent
283
+ - 确保双方都有互联网访问
284
+ - 检查 Magnet 链接是否完整(无截断)
285
+ - 尝试重启发送方和接收方
211
286
 
212
- ### Connection issues?
287
+ ### Linux 安装失败?
213
288
 
214
- - Ensure both sides have internet access
215
- - Check if magnet link is complete (no truncation)
216
- - Try restarting both sender and receiver
289
+ ```bash
290
+ # 安装编译依赖
291
+ sudo apt install build-essential python3
292
+ npm install -g p2p-transfer
293
+ ```
217
294
 
218
- ## 🤝 Contributing
295
+ ## 🤝 贡献指南
219
296
 
220
- Contributions are welcome! Please feel free to submit a Pull Request.
297
+ 欢迎贡献代码!请查看 [CONTRIBUTING.md](CONTRIBUTING.md) 了解详细信息。
221
298
 
222
- ## 📄 License
299
+ ## 📄 许可证
223
300
 
224
- MIT License - see [LICENSE](LICENSE) file for details.
301
+ MIT License - 详见 [LICENSE](LICENSE) 文件。
225
302
 
226
- ## 🙏 Acknowledgments
303
+ ## 🙏 致谢
227
304
 
228
- - [WebTorrent](https://webtorrent.io/) - BitTorrent implementation for Node.js
229
- - [BitTorrent DHT](https://en.wikipedia.org/wiki/Mainline_DHT) - Distributed hash table
230
- - All the public tracker operators
305
+ - [WebTorrent](https://webtorrent.io/) - Node.js BitTorrent 实现
306
+ - [BitTorrent DHT](https://en.wikipedia.org/wiki/Mainline_DHT) - 分布式哈希表
307
+ - [ngosang/trackerslist](https://github.com/ngosang/trackerslist) - 公共 Tracker 列表
308
+ - 所有公共 Tracker 运营者
231
309
 
232
- ## 📈 Roadmap
310
+ ## 📈 开发路线图
233
311
 
234
- - [ ] Add WebRTC support for browser-based sharing
235
- - [ ] Implement pause/resume functionality
236
- - [ ] Add multiple file sharing support
237
- - [ ] Implement bandwidth limiting
238
- - [ ] Add encryption option
239
- - [ ] Create GUI version
312
+ - [ ] 添加 WebRTC 支持,支持浏览器端分享
313
+ - [ ] 实现暂停/续传功能
314
+ - [ ] 添加多文件分享支持
315
+ - [ ] 实现带宽限制
316
+ - [ ] 添加加密选项
317
+ - [ ] 创建 GUI 版本
240
318
 
241
- ## 📞 Support
319
+ ## 📞 支持
242
320
 
243
- - 🐛 Issues: [GitHub Issues](https://gitcode.com/yunqiang_wu/p2p-transfer/issues)
244
- - 💬 Discussions: [GitHub Discussions](https://gitcode.com/yunqiang_wu/p2p-transfer/discussions)
321
+ - 🐛 问题报告: [GitCode Issues](https://gitcode.com/yunqiang_wu/p2p-transfer/issues)
322
+ - 💬 讨论交流: [GitCode Discussions](https://gitcode.com/yunqiang_wu/p2p-transfer/discussions)
245
323
 
246
324
  ---
247
325
 
package/p2p.js CHANGED
@@ -9,19 +9,56 @@ import fs from 'fs';
9
9
  import path from 'path';
10
10
  import os from 'os';
11
11
  import { fileURLToPath } from 'url';
12
+ import https from 'https';
13
+ import http from 'http';
12
14
 
13
15
  const __filename = fileURLToPath(import.meta.url);
14
16
  const __dirname = path.dirname(__filename);
15
17
 
16
- const DEFAULT_TRACKERS = [
17
- 'udp://tracker.opentrackr.org:1337/announce',
18
- 'udp://tracker.openbittorrent.com:6969/announce',
19
- 'udp://exodus.desync.com:6969/announce',
20
- 'udp://tracker.coppersurfer.tk:6969/announce',
21
- 'wss://tracker.btorrent.xyz',
22
- 'wss://tracker.openwebtorrent.com',
23
- 'wss://tracker.webtorrent.io',
24
- ];
18
+ const CONFIG_DIR = path.join(os.homedir(), '.p2p-transfer');
19
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
20
+
21
+ const DEFAULT_CONFIG = {
22
+ trackers: [
23
+ 'udp://tracker.opentrackr.org:1337/announce',
24
+ 'udp://tracker.openbittorrent.com:6969/announce',
25
+ 'udp://tracker.coppersurfer.tk:6969/announce',
26
+ 'udp://tracker.publicbt.com:80/announce',
27
+ 'udp://tracker.bitsearch.to:1337/announce',
28
+ 'wss://tracker.btorrent.xyz',
29
+ 'wss://tracker.openwebtorrent.com',
30
+ 'wss://tracker.webtorrent.io',
31
+ 'wss://tracker.files.fm:7073/announce',
32
+ ],
33
+ subUrl: 'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_best.txt',
34
+ autoUpdate: true,
35
+ updateInterval: 24,
36
+ };
37
+
38
+ function getConfig() {
39
+ try {
40
+ if (fs.existsSync(CONFIG_FILE)) {
41
+ const content = fs.readFileSync(CONFIG_FILE, 'utf8');
42
+ return { ...DEFAULT_CONFIG, ...JSON.parse(content) };
43
+ }
44
+ } catch (err) {
45
+ console.warn(chalk.yellow('⚠️ 读取配置文件失败,使用默认配置'));
46
+ }
47
+ return { ...DEFAULT_CONFIG };
48
+ }
49
+
50
+ function saveConfig(config) {
51
+ try {
52
+ if (!fs.existsSync(CONFIG_DIR)) {
53
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
54
+ }
55
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
56
+ return true;
57
+ } catch (err) {
58
+ console.error(chalk.red('❌ 保存配置失败:'), err.message);
59
+ return false;
60
+ }
61
+ }
25
62
 
26
63
  function formatSize(bytes) {
27
64
  if (bytes === 0) return '0 B';
@@ -43,7 +80,50 @@ function formatTime(seconds) {
43
80
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
44
81
  }
45
82
 
83
+ async function fetchUrl(url) {
84
+ return new Promise((resolve, reject) => {
85
+ const protocol = url.startsWith('https') ? https : http;
86
+ protocol.get(url, (res) => {
87
+ if (res.statusCode !== 200) {
88
+ reject(new Error(`HTTP error! status: ${res.statusCode}`));
89
+ return;
90
+ }
91
+ let data = '';
92
+ res.on('data', (chunk) => {
93
+ data += chunk;
94
+ });
95
+ res.on('end', () => {
96
+ resolve(data);
97
+ });
98
+ }).on('error', (err) => {
99
+ reject(err);
100
+ });
101
+ });
102
+ }
103
+
104
+ async function updateTrackersFromUrl(url) {
105
+ console.log(chalk.blue(`🔄 正在从 ${url} 更新 trackers...`));
106
+ try {
107
+ const data = await fetchUrl(url);
108
+ const lines = data.split('\n')
109
+ .map(line => line.trim())
110
+ .filter(line => line && !line.startsWith('#'));
111
+
112
+ if (lines.length > 0) {
113
+ console.log(chalk.green(`✅ 成功获取 ${lines.length} 个 trackers`));
114
+ return lines;
115
+ } else {
116
+ console.warn(chalk.yellow('⚠️ 获取到的 trackers 列表为空'));
117
+ return null;
118
+ }
119
+ } catch (err) {
120
+ console.error(chalk.red('❌ 获取 trackers 失败:'), err.message);
121
+ return null;
122
+ }
123
+ }
124
+
46
125
  async function shareFile(filePath, options) {
126
+ const config = getConfig();
47
127
  console.log(chalk.blue('🚀 初始化 P2P 分享...'));
48
128
 
49
129
  const client = new WebTorrent({
@@ -68,10 +148,11 @@ async function shareFile(filePath, options) {
68
148
 
69
149
  console.log(chalk.cyan('📁 文件: ') + fileName);
70
150
  console.log(chalk.cyan('📊 大小: ') + formatSize(stats.size));
151
+ console.log(chalk.cyan('🔗 Trackers: ') + config.trackers.length + ' 个');
71
152
 
72
153
  return new Promise((resolve, reject) => {
73
154
  client.seed(absolutePath, {
74
- announceList: [DEFAULT_TRACKERS],
155
+ announceList: [config.trackers],
75
156
  name: fileName,
76
157
  }, (torrent) => {
77
158
  console.log(chalk.green('\n✅ 分享成功!\n'));
@@ -105,6 +186,7 @@ async function shareFile(filePath, options) {
105
186
  }
106
187
 
107
188
  async function getFile(magnetUri, downloadPath, options) {
189
+ const config = getConfig();
108
190
  console.log(chalk.blue('📥 初始化 P2P 下载...'));
109
191
 
110
192
  const client = new WebTorrent({
@@ -125,7 +207,7 @@ async function getFile(magnetUri, downloadPath, options) {
125
207
  return new Promise((resolve, reject) => {
126
208
  const torrent = client.add(magnetUri, {
127
209
  path: savePath,
128
- announceList: [DEFAULT_TRACKERS],
210
+ announceList: [config.trackers],
129
211
  });
130
212
 
131
213
  const progressBar = new cliProgress.SingleBar({
@@ -136,7 +218,6 @@ async function getFile(magnetUri, downloadPath, options) {
136
218
  });
137
219
 
138
220
  let startTime = Date.now();
139
- let lastDownloaded = 0;
140
221
  let updateInterval;
141
222
 
142
223
  torrent.on('metadata', () => {
@@ -212,6 +293,76 @@ async function getFile(magnetUri, downloadPath, options) {
212
293
  });
213
294
  }
214
295
 
296
+ function showConfig() {
297
+ const config = getConfig();
298
+ console.log(chalk.bold('\n⚙️ P2P 传输配置\n'));
299
+ console.log(chalk.cyan('📁 配置文件位置: ') + CONFIG_FILE);
300
+ console.log('');
301
+ console.log(chalk.yellow('📋 Trackers (' + config.trackers.length + ' 个):'));
302
+ config.trackers.forEach((tracker, index) => {
303
+ console.log(chalk.white(` ${index + 1}. ${tracker}`));
304
+ });
305
+ console.log('');
306
+ console.log(chalk.yellow('🔗 订阅地址:'));
307
+ console.log(chalk.white(' subUrl: ') + config.subUrl);
308
+ console.log('');
309
+ console.log(chalk.yellow('⚙️ 其他配置:'));
310
+ console.log(chalk.white(' autoUpdate: ') + (config.autoUpdate ? 'true' : 'false'));
311
+ console.log(chalk.white(' updateInterval: ') + config.updateInterval + ' 小时');
312
+ console.log('');
313
+ }
314
+
315
+ function setTracker(url) {
316
+ const config = getConfig();
317
+ if (config.trackers.includes(url)) {
318
+ console.log(chalk.yellow('⚠️ Tracker 已存在: ' + url));
319
+ return;
320
+ }
321
+ config.trackers.push(url);
322
+ if (saveConfig(config)) {
323
+ console.log(chalk.green('✅ 添加 tracker 成功: ' + url));
324
+ }
325
+ }
326
+
327
+ function removeTracker(url) {
328
+ const config = getConfig();
329
+ const index = config.trackers.indexOf(url);
330
+ if (index === -1) {
331
+ console.log(chalk.yellow('⚠️ Tracker 不存在: ' + url));
332
+ return;
333
+ }
334
+ config.trackers.splice(index, 1);
335
+ if (saveConfig(config)) {
336
+ console.log(chalk.green('✅ 移除 tracker 成功: ' + url));
337
+ }
338
+ }
339
+
340
+ function setSubUrl(url) {
341
+ const config = getConfig();
342
+ config.subUrl = url;
343
+ if (saveConfig(config)) {
344
+ console.log(chalk.green('✅ 设置订阅地址成功: ' + url));
345
+ }
346
+ }
347
+
348
+ async function updateTrackers() {
349
+ const config = getConfig();
350
+ const newTrackers = await updateTrackersFromUrl(config.subUrl);
351
+ if (newTrackers) {
352
+ config.trackers = newTrackers;
353
+ if (saveConfig(config)) {
354
+ console.log(chalk.green('✅ Trackers 已更新!'));
355
+ console.log(chalk.cyan('📊 更新后共 ' + config.trackers.length + ' 个 trackers'));
356
+ }
357
+ }
358
+ }
359
+
360
+ function resetConfig() {
361
+ if (saveConfig(DEFAULT_CONFIG)) {
362
+ console.log(chalk.green('✅ 配置已重置为默认值'));
363
+ }
364
+ }
365
+
215
366
  function showInfo() {
216
367
  console.log(chalk.bold('\n🌐 P2P 文件传输工具\n'));
217
368
  console.log(chalk.cyan('使用方法:'));
@@ -221,6 +372,13 @@ function showInfo() {
221
372
  console.log(' 接收文件:');
222
373
  console.log(chalk.white(' p2p get <magnet链接> [保存目录]'));
223
374
  console.log(' 例如: p2p get "magnet:?xt=..." ~/Downloads\n');
375
+ console.log(' 配置管理:');
376
+ console.log(chalk.white(' p2p config show - 显示当前配置'));
377
+ console.log(chalk.white(' p2p config add <tracker> - 添加 tracker'));
378
+ console.log(chalk.white(' p2p config remove <url> - 移除 tracker'));
379
+ console.log(chalk.white(' p2p config set-url <url> - 设置订阅地址'));
380
+ console.log(chalk.white(' p2p config update - 从订阅地址更新 trackers'));
381
+ console.log(chalk.white(' p2p config reset - 重置配置\n'));
224
382
  console.log(chalk.cyan('原理:'));
225
383
  console.log(' - 使用 BitTorrent 协议进行 P2P 传输');
226
384
  console.log(' - 通过 DHT 网络发现节点,无需公网 IP');
@@ -275,10 +433,68 @@ const argv = yargs(hideBin(process.argv))
275
433
  }
276
434
  await getFile(magnet, savePath, argv);
277
435
  })
436
+ .command('config', '配置管理', (yargs) => {
437
+ return yargs
438
+ .command('show', '显示当前配置', {}, () => {
439
+ showConfig();
440
+ })
441
+ .command('add', '添加 tracker', (yargs) => {
442
+ return yargs
443
+ .positional('tracker', {
444
+ describe: 'Tracker URL',
445
+ type: 'string',
446
+ });
447
+ }, (argv) => {
448
+ const tracker = argv._[2];
449
+ if (!tracker) {
450
+ console.error(chalk.red('❌ 请提供 tracker URL'));
451
+ process.exit(1);
452
+ }
453
+ setTracker(tracker);
454
+ })
455
+ .command('remove', '移除 tracker', (yargs) => {
456
+ return yargs
457
+ .positional('url', {
458
+ describe: '要移除的 tracker URL',
459
+ type: 'string',
460
+ });
461
+ }, (argv) => {
462
+ const url = argv._[2];
463
+ if (!url) {
464
+ console.error(chalk.red('❌ 请提供要移除的 tracker URL'));
465
+ process.exit(1);
466
+ }
467
+ removeTracker(url);
468
+ })
469
+ .command('set-url', '设置订阅地址', (yargs) => {
470
+ return yargs
471
+ .positional('url', {
472
+ describe: '订阅地址 URL',
473
+ type: 'string',
474
+ });
475
+ }, (argv) => {
476
+ const url = argv._[2];
477
+ if (!url) {
478
+ console.error(chalk.red('❌ 请提供订阅地址'));
479
+ process.exit(1);
480
+ }
481
+ setSubUrl(url);
482
+ })
483
+ .command('update', '从订阅地址更新 trackers', {}, async () => {
484
+ await updateTrackers();
485
+ })
486
+ .command('reset', '重置配置为默认值', {}, () => {
487
+ resetConfig();
488
+ })
489
+ .demandCommand(1, chalk.red('❌ 请指定配置子命令: show, add, remove, set-url, update, reset'));
490
+ }, () => {
491
+ console.log(chalk.yellow('📋 使用 p2p config <subcommand> 查看配置子命令'));
492
+ console.log(chalk.white(' 例如: p2p config show'));
493
+ })
278
494
  .command('info', '显示帮助信息', {}, () => {
279
495
  showInfo();
280
496
  })
281
- .demandCommand(1, chalk.red('❌ 请指定命令: share get'))
497
+ .demandCommand(1, chalk.red('❌ 请指定命令: share, get, config, info'))
282
498
  .help('h', '显示帮助')
283
499
  .alias('h', 'help')
284
500
  .version('v', '版本', '1.0.0')
@@ -286,4 +502,5 @@ const argv = yargs(hideBin(process.argv))
286
502
  .epilog(chalk.cyan('\n💡 提示:'))
287
503
  .epilog(chalk.cyan(' 发送方运行: p2p share <文件>'))
288
504
  .epilog(chalk.cyan(' 接收方运行: p2p get <magnet链接>'))
505
+ .epilog(chalk.cyan(' 管理配置: p2p config show'))
289
506
  .parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "p2p-transfer",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "🚀 Pure CLI P2P file transfer tool using WebTorrent and BitTorrent DHT. Transfer files between different networks without public IP.",
5
5
  "keywords": [
6
6
  "p2p",
@@ -54,6 +54,7 @@
54
54
  "files": [
55
55
  "p2p.js",
56
56
  "README.md",
57
+ "INSTALL-LINUX.md",
57
58
  "LICENSE"
58
59
  ]
59
60
  }