-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
231 lines (202 loc) · 7.49 KB
/
server.js
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
const express = require('express');
const cors = require('cors');
const axios = require('axios');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const qbittorrentUrl = process.env.QBITTORRENT_URL || 'http://localhost:8080';
const axiosInstance = axios.create({
baseURL: qbittorrentUrl,
withCredentials: true
});
axiosInstance.interceptors.request.use(async (config) => {
if (!qBittorrentCookie) {
await loginToQBittorrent();
}
if (qBittorrentCookie) {
config.headers['Cookie'] = qBittorrentCookie;
}
return config;
});
let qBittorrentCookie = null;
async function loginToQBittorrent() {
try {
const response = await axios.post(`${qbittorrentUrl}/api/v2/auth/login`, null, {
params: {
username: process.env.QBITTORRENT_USERNAME,
password: process.env.QBITTORRENT_PASSWORD
}
});
if (response.data === 'Ok.') {
console.log('Successfully logged in to qBittorrent');
qBittorrentCookie = response.headers['set-cookie'];
return true;
} else {
console.error('Login failed');
return false;
}
} catch (error) {
console.error('Error logging in to qBittorrent:', error.message);
return false;
}
}
const path = require('path');
app.post('/api/login', async (req, res) => {
try {
const { username, password } = req.body;
const response = await axios.post(`${qbittorrentUrl}/api/v2/auth/login`, null, {
params: { username, password },
withCredentials: true
});
// Set the session cookie
if (response.headers['set-cookie']) {
res.setHeader('Set-Cookie', response.headers['set-cookie']);
}
res.json({ success: true, message: 'Login successful' });
} catch (error) {
res.status(401).json({ success: false, message: 'Login failed' });
}
});
app.get('/api/torrents', async (req, res) => {
try {
const response = await axios.get(`${qbittorrentUrl}/api/v2/torrents/info`);
const torrents = response.data;
// Fetch categories
const categoriesResponse = await axios.get(`${qbittorrentUrl}/api/v2/torrents/categories`);
const categories = categoriesResponse.data;
// Add category information to each torrent
const torrentsWithCategories = torrents.map(torrent => ({
...torrent,
categoryName: categories[torrent.category] ? categories[torrent.category].name : 'Uncategorized'
}));
res.json(torrentsWithCategories);
} catch (error) {
console.error('Failed to fetch torrents:', error);
res.status(500).json({ success: false, message: 'Failed to fetch torrents' });
}
});
app.get('/api/torrents/:hash/files', async (req, res) => {
try {
const response = await axios.get(`${qbittorrentUrl}/api/v2/torrents/files`, {
params: {
hash: req.params.hash
}
});
res.json(response.data);
} catch (error) {
console.error('Error fetching torrent files:', error);
res.status(500).json({ error: 'Failed to fetch torrent files' });
}
});
app.post('/api/torrents/:hash/open-in-explorer', async (req, res) => {
const { hash } = req.params;
try {
const propertiesResponse = await axiosInstance.get('/api/v2/torrents/properties', { params: { hash } });
const filesResponse = await axiosInstance.get('/api/v2/torrents/files', { params: { hash } });
const savePath = propertiesResponse.data.save_path;
const torrentName = filesResponse.data[0].name.split('/')[0]; // Get the first folder name
const fullPath = path.join(savePath, torrentName);
let command;
switch (process.platform) {
case 'win32':
command = `explorer "${fullPath}"`;
break;
case 'darwin':
command = `open "${fullPath}"`;
break;
default:
command = `xdg-open "${fullPath}"`;
}
const { exec } = require('child_process');
exec(command, (error, stdout, stderr) => {
if (error) {
console.error('Error opening explorer:', error);
res.status(500).json({ error: 'Failed to open in explorer', details: error.message });
} else if (stderr) {
console.error('Error opening explorer:', stderr);
res.status(500).json({ error: 'Failed to open in explorer', details: stderr });
} else {
res.status(200).json({ message: 'Opened in explorer' });
}
});
} catch (error) {
console.error('Error getting torrent info:', error);
res.status(500).json({ error: 'Failed to get torrent info', details: error.message });
}
});
app.post('/api/logout', async (req, res) => {
try {
await axios.post(`${qbittorrentUrl}/api/v2/auth/logout`);
res.json({ success: true, message: 'Logout successful' });
} catch (error) {
res.status(500).json({ success: false, message: 'Logout failed' });
}
});
app.post('/api/torrents/:hash/remove', async (req, res) => {
const { hash } = req.params;
const { deleteFiles } = req.body;
try {
const response = await axiosInstance.post('/api/v2/torrents/delete', `hashes=${hash}&deleteFiles=${deleteFiles ? 'true' : 'false'}`, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
if (response.status === 200) {
res.status(200).json({ message: 'Torrent removed successfully' });
} else {
res.status(response.status).json({ error: 'Failed to remove torrent', details: response.data });
}
} catch (error) {
console.error('Error removing torrent:', error.response ? error.response.data : error.message);
res.status(500).json({ error: 'Failed to remove torrent', details: error.response ? error.response.data : error.message });
}
});
app.post('/api/torrents/:hash/stop', async (req, res) => {
const { hash } = req.params;
try {
console.log(`Attempting to stop torrent with hash: ${hash}`);
const response = await axiosInstance.post('/api/v2/torrents/pause', `hashes=${hash}`, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
console.log('qBittorrent API response status:', response.status);
console.log('qBittorrent API response data:', response.data);
if (response.status === 200) {
res.status(200).json({ message: 'Torrent stopped successfully' });
} else {
console.error('Unexpected response status:', response.status);
res.status(response.status).json({ error: 'Failed to stop torrent', details: response.data });
}
} catch (error) {
console.error('Error stopping torrent:', error.message);
if (error.response) {
console.error('Error response status:', error.response.status);
console.error('Error response data:', error.response.data);
}
res.status(error.response ? error.response.status : 500).json({ error: 'Failed to stop torrent', details: error.response ? error.response.data : error.message });
}
});
app.get('/api/torrents/:hash', async (req, res) => {
const { hash } = req.params;
try {
const response = await axiosInstance.get('/api/v2/torrents/info', {
params: { hashes: hash }
});
console.log('Torrent info response:', response.data);
if (response.data.length > 0) {
res.status(200).json(response.data[0]);
} else {
res.status(404).json({ error: 'Torrent not found' });
}
} catch (error) {
console.error('Error fetching torrent info:', error.message);
res.status(500).json({ error: 'Failed to fetch torrent info', details: error.message });
}
});
app.listen(port, async () => {
console.log(`Server is running on port ${port}`);
await loginToQBittorrent();
});