-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDownloadManager.java
More file actions
390 lines (333 loc) · 12.8 KB
/
Copy pathDownloadManager.java
File metadata and controls
390 lines (333 loc) · 12.8 KB
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
import javax.microedition.lcdui.*;
import java.util.Vector;
public class DownloadManager implements Runnable {
private static DownloadManager instance;
private Vector activeDownloads = new Vector();
private Vector queuedDownloads = new Vector();
private Vector completedDownloads = new Vector();
private Thread downloadThread;
private boolean running = true;
// ✅ NEW: Speed limiting
private int maxSpeedKBps = 0; // 0 = unlimited
private DownloadManager() {
downloadThread = new Thread(this);
downloadThread.start();
loadSpeedLimit();
}
public static synchronized DownloadManager getInstance() {
if (instance == null) {
instance = new DownloadManager();
}
return instance;
}
// ✅ NEW: Load speed limit from settings
private void loadSpeedLimit() {
try {
maxSpeedKBps = SettingsManager.getInstance().getSpeedLimitKBps();
} catch (Exception e) {
maxSpeedKBps = 0; // Unlimited by default
}
}
// ✅ NEW: Update speed limit dynamically
public void setSpeedLimit(int kbps) {
this.maxSpeedKBps = kbps;
}
public void queueDownload(VideoItem item) {
synchronized (queuedDownloads) {
String extension = ".mp4";
String folderName = "videos/";
if (item.fileFormat != null && item.fileFormat.length() > 0) {
extension = "." + item.fileFormat;
if (item.fileFormat.equals("mp3") || item.fileFormat.equals("aac") || item.fileFormat.equals("wav")) {
folderName = "audios/";
} else {
folderName = "videos/";
}
}
String filename = sanitize(item.title) + extension;
String downloadPath = StorageManager.getDownloadPath() + folderName;
try {
javax.microedition.io.file.FileConnection dir =
(javax.microedition.io.file.FileConnection)
javax.microedition.io.Connector.open(downloadPath,
javax.microedition.io.Connector.READ_WRITE);
if (!dir.exists()) dir.mkdir();
dir.close();
} catch (Exception e) {}
String filePath = downloadPath + filename;
DownloadItem dlItem = new DownloadItem(item.videoId, item.title, item.downloadUrl, filePath);
queuedDownloads.addElement(dlItem);
queuedDownloads.notifyAll();
}
}
public void run() {
while (running) {
DownloadItem item = null;
synchronized (queuedDownloads) {
while (queuedDownloads.isEmpty() && running) {
try { queuedDownloads.wait(); } catch (InterruptedException e) { return; }
}
if (!queuedDownloads.isEmpty()) {
item = (DownloadItem) queuedDownloads.elementAt(0);
queuedDownloads.removeElementAt(0);
activeDownloads.addElement(item);
}
}
if (item != null) {
downloadFile(item);
}
}
}
private void downloadFile(DownloadItem item) {
javax.microedition.io.HttpConnection conn = null;
java.io.InputStream is = null;
java.io.OutputStream os = null;
try {
item.setStatus("DOWNLOADING");
conn = (javax.microedition.io.HttpConnection)
javax.microedition.io.Connector.open(item.getDownloadUrl(),
javax.microedition.io.Connector.READ, true);
conn.setRequestMethod(javax.microedition.io.HttpConnection.GET);
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (S60V3; U; en) AppleWebKit/413");
int rc = conn.getResponseCode();
if (rc != javax.microedition.io.HttpConnection.HTTP_OK) {
throw new java.io.IOException("HTTP error: " + rc);
}
long totalSize = conn.getLength();
item.setTotalSize(totalSize);
os = StorageManager.openOutputStream(item.getFilePath(), false);
is = conn.openInputStream();
// ✅ CHANGED: Implement speed limiting
byte[] buffer = new byte[1024];
int len;
long downloaded = 0;
long lastUpdate = System.currentTimeMillis();
long lastSpeedCheck = System.currentTimeMillis();
long bytesInCurrentSecond = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
downloaded += len;
bytesInCurrentSecond += len;
// Update progress display
long now = System.currentTimeMillis();
if (now - lastUpdate > 500) {
long elapsed = now - lastSpeedCheck;
if (elapsed > 0) {
long currentSpeed = (bytesInCurrentSecond * 1000) / elapsed / 1024; // KB/s
item.setSpeed(currentSpeed);
}
item.updateProgress(downloaded, totalSize);
lastUpdate = now;
}
// ✅ NEW: Speed limiting logic
if (maxSpeedKBps > 0) {
long elapsed = now - lastSpeedCheck;
if (elapsed >= 1000) {
// Reset counter every second
lastSpeedCheck = now;
bytesInCurrentSecond = 0;
} else {
// Calculate if we need to throttle
long maxBytesPerSecond = maxSpeedKBps * 1024L;
long expectedTime = (bytesInCurrentSecond * 1000L) / maxBytesPerSecond;
if (elapsed < expectedTime) {
long sleepTime = expectedTime - elapsed;
if (sleepTime > 0 && sleepTime < 5000) { // Safety cap
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
break; // Download cancelled
}
}
}
}
}
}
os.flush();
os.close();
is.close();
conn.close();
item.setStatus("COMPLETED");
synchronized (activeDownloads) {
activeDownloads.removeElement(item);
completedDownloads.addElement(item);
}
notifyUser("Succes", "Telechargement termine: " + item.getVideoTitle());
} catch (Exception e) {
item.setStatus("FAILED");
synchronized (activeDownloads) {
activeDownloads.removeElement(item);
}
notifyUser("Erreur", "Echec: " + e.getMessage());
} finally {
try { if (os != null) os.close(); } catch (Exception e) {}
try { if (is != null) is.close(); } catch (Exception e) {}
try { if (conn != null) conn.close(); } catch (Exception e) {}
}
}
public Vector getActiveDownloads() {
synchronized (activeDownloads) {
Vector clone = new Vector();
for (int i = 0; i < activeDownloads.size(); i++) {
clone.addElement(activeDownloads.elementAt(i));
}
return clone;
}
}
public Vector getQueuedDownloads() {
synchronized (queuedDownloads) {
Vector clone = new Vector();
for (int i = 0; i < queuedDownloads.size(); i++) {
clone.addElement(queuedDownloads.elementAt(i));
}
return clone;
}
}
public Vector getCompletedDownloads() {
synchronized (completedDownloads) {
Vector clone = new Vector();
for (int i = 0; i < completedDownloads.size(); i++) {
clone.addElement(completedDownloads.elementAt(i));
}
return clone;
}
}
public void pauseDownload(DownloadItem item) {
item.setStatus("PAUSED");
}
public void resumeDownload(DownloadItem item) {
if ("PAUSED".equals(item.getStatus())) {
queueDownloadFromItem(item);
}
}
private void queueDownloadFromItem(DownloadItem item) {
synchronized (queuedDownloads) {
queuedDownloads.addElement(item);
queuedDownloads.notifyAll();
}
}
public void cancelDownload(DownloadItem item) {
item.setStatus("CANCELLED");
synchronized (activeDownloads) {
activeDownloads.removeElement(item);
}
synchronized (queuedDownloads) {
queuedDownloads.removeElement(item);
}
try {
javax.microedition.io.file.FileConnection fc =
(javax.microedition.io.file.FileConnection)
javax.microedition.io.Connector.open(item.getFilePath());
if (fc.exists()) fc.delete();
fc.close();
} catch (Exception e) {}
}
private String sanitize(String s) {
StringBuffer clean = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '_' || c == '-' || c == ' ') {
clean.append(c);
} else if (clean.length() > 0 && clean.charAt(clean.length() - 1) != '_') {
clean.append('_');
}
}
if (clean.length() == 0) clean.append("video");
if (clean.length() > 30) clean.setLength(30);
return clean.toString();
}
private void notifyUser(final String title, final String msg) {
Display.getDisplay(VidmateME.instance).callSerially(new Runnable() {
public void run() {
Alert a = new Alert(title, msg, null, AlertType.INFO);
a.setTimeout(3000);
Display.getDisplay(VidmateME.instance).setCurrent(a);
}
});
}
public void shutdown() {
running = false;
synchronized (queuedDownloads) {
queuedDownloads.notifyAll();
}
try { downloadThread.join(); } catch (Exception e) {}
}
}
class DownloadItem {
private String videoId;
private String videoTitle;
private String downloadUrl;
private String filePath;
private String status;
private long totalSize;
private long downloadedSize;
private int progress;
private long speed; // ✅ NEW: KB/s
public DownloadItem(String videoId, String videoTitle, String downloadUrl, String filePath) {
this.videoId = videoId;
this.videoTitle = videoTitle;
this.downloadUrl = downloadUrl;
this.filePath = filePath;
this.status = "QUEUED";
this.totalSize = 0;
this.downloadedSize = 0;
this.progress = 0;
this.speed = 0;
}
public boolean isDownloading() {
return "DOWNLOADING".equals(status);
}
public boolean isPaused() {
return "PAUSED".equals(status);
}
public boolean isCompleted() {
return "COMPLETED".equals(status);
}
public boolean isCancelled() {
return "CANCELLED".equals(status);
}
public void updateProgress(long downloaded, long total) {
this.downloadedSize = downloaded;
this.totalSize = total;
if (total > 0) {
this.progress = (int)((downloaded * 100) / total);
}
}
public String getVideoTitle() {
return videoTitle;
}
public String getFilePath() {
return filePath;
}
public int getProgress() {
return progress;
}
public long getTotalSize() {
return totalSize;
}
public void setTotalSize(long size) {
this.totalSize = size;
}
public long getDownloadedSize() {
return downloadedSize;
}
// ✅ CHANGED: Now actually tracks speed
public long getSpeed() {
return speed;
}
// ✅ NEW
public void setSpeed(long speedKBps) {
this.speed = speedKBps;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
public String getDownloadUrl() {
return downloadUrl;
}
}