-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathFileDownloadMessenger.java
More file actions
407 lines (337 loc) · 13.9 KB
/
FileDownloadMessenger.java
File metadata and controls
407 lines (337 loc) · 13.9 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/*
* Copyright (c) 2015 LingoChamp Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liulishuo.filedownloader;
import com.liulishuo.filedownloader.message.BlockCompleteMessage;
import com.liulishuo.filedownloader.message.MessageSnapshot;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.filedownloader.util.FileDownloadLog;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* The messenger for sending messages to {@link FileDownloadListener}.
*
* @see IFileDownloadMessenger
*/
class FileDownloadMessenger implements IFileDownloadMessenger {
private BaseDownloadTask.IRunningTask mTask;
private BaseDownloadTask.LifeCycleCallback mLifeCycleCallback;
private Queue<MessageSnapshot> parcelQueue;
private boolean mIsDiscard = false;
FileDownloadMessenger(final BaseDownloadTask.IRunningTask task,
final BaseDownloadTask.LifeCycleCallback callback) {
init(task, callback);
}
private void init(final BaseDownloadTask.IRunningTask task,
BaseDownloadTask.LifeCycleCallback callback) {
this.mTask = task;
this.mLifeCycleCallback = callback;
parcelQueue = new LinkedBlockingQueue<>();
}
@Override
public boolean notifyBegin() {
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "notify begin %s", mTask);
}
if (mTask == null) {
FileDownloadLog.w(this, "can't begin the task, the holder fo the messenger is nil, %d",
parcelQueue.size());
return false;
}
mLifeCycleCallback.onBegin();
return true;
}
@Override
public void notifyPending(MessageSnapshot snapshot) {
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "notify pending %s", mTask);
}
mLifeCycleCallback.onIng();
process(snapshot);
}
@Override
public void notifyStarted(MessageSnapshot snapshot) {
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "notify started %s", mTask);
}
mLifeCycleCallback.onIng();
process(snapshot);
}
@Override
public void notifyConnected(MessageSnapshot snapshot) {
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "notify connected %s", mTask);
}
mLifeCycleCallback.onIng();
process(snapshot);
}
@Override
public void notifyProgress(MessageSnapshot snapshot) {
final BaseDownloadTask originTask = mTask.getOrigin();
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "notify progress %s %d %d",
originTask, originTask.getLargeFileSoFarBytes(),
originTask.getLargeFileTotalBytes());
}
if (originTask.getCallbackProgressTimes() <= 0) {
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "notify progress but client not request notify %s", mTask);
}
return;
}
mLifeCycleCallback.onIng();
process(snapshot);
}
/**
* sync
*/
@Override
public void notifyBlockComplete(MessageSnapshot snapshot) {
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "notify block completed %s %s", mTask,
Thread.currentThread().getName());
}
mLifeCycleCallback.onIng();
process(snapshot);
}
@Override
public void notifyRetry(MessageSnapshot snapshot) {
if (FileDownloadLog.NEED_LOG) {
final BaseDownloadTask originTask = mTask.getOrigin();
FileDownloadLog.d(this, "notify retry %s %d %d %s", mTask,
originTask.getAutoRetryTimes(), originTask.getRetryingTimes(),
originTask.getErrorCause());
}
mLifeCycleCallback.onIng();
process(snapshot);
}
// Over state, from FileDownloadList, to user -----------------------------
@Override
public void notifyWarn(MessageSnapshot snapshot) {
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "notify warn %s", mTask);
}
mLifeCycleCallback.onOver();
process(snapshot);
}
@Override
public void notifyError(MessageSnapshot snapshot) {
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "notify error %s %s", mTask, mTask.getOrigin().getErrorCause());
}
mLifeCycleCallback.onOver();
process(snapshot);
}
@Override
public void notifyPaused(MessageSnapshot snapshot) {
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "notify paused %s", mTask);
}
mLifeCycleCallback.onOver();
process(snapshot);
}
@Override
public void notifyCompleted(MessageSnapshot snapshot) {
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "notify completed %s", mTask);
}
mLifeCycleCallback.onOver();
process(snapshot);
}
private void process(MessageSnapshot snapshot) {
if (mTask == null) {
if (FileDownloadLog.NEED_LOG) {
// the most possible of occurring this case is the thread for flowing the paused
// message is different with others.
FileDownloadLog.d(this, "occur this case, it would be the host task of this "
+ "messenger has been over(paused/warn/completed/error) on the "
+ "other thread before receiving the snapshot(id[%d], status[%d])",
snapshot.getId(), snapshot.getStatus());
}
return;
}
if (mIsDiscard || mTask.getOrigin().getListener() == null) {
if ((FileDownloadMonitor.isValid() || mTask.isContainFinishListener())
&& snapshot.getStatus() == FileDownloadStatus.blockComplete) {
// there is a FileDownloadMonitor, so we have to ensure the 'BaseDownloadTask#over'
// can be invoked.
mLifeCycleCallback.onOver();
}
inspectAndHandleOverStatus(snapshot.getStatus());
} else {
parcelQueue.offer(snapshot);
FileDownloadMessageStation.getImpl().requestEnqueue(this);
}
}
private void inspectAndHandleOverStatus(int status) {
// If this task is in the over state, try to retire this messenger.
if (FileDownloadStatus.isOver(status)) {
if (!parcelQueue.isEmpty()) {
final MessageSnapshot queueTopTask = parcelQueue.peek();
FileDownloadLog.w(this,
"the messenger[%s](with id[%d]) has already "
+ "accomplished all his job, but there still are some messages in"
+ " parcel queue[%d] queue-top-status[%d]",
this, queueTopTask.getId(), parcelQueue.size(), queueTopTask.getStatus());
}
mTask = null;
}
}
@Override
public void handoverMessage() {
if (mIsDiscard) {
return;
}
final MessageSnapshot message = parcelQueue.poll();
final int currentStatus = message.getStatus();
final BaseDownloadTask.IRunningTask task = mTask;
if (task == null) {
throw new IllegalArgumentException(FileDownloadUtils.formatString(
"can't handover the message, no master to receive this "
+ "message(status[%d]) size[%d]",
currentStatus, parcelQueue.size()));
}
final BaseDownloadTask originTask = task.getOrigin();
final FileDownloadListener listener = originTask.getListener();
final ITaskHunter.IMessageHandler messageHandler = task.getMessageHandler();
inspectAndHandleOverStatus(currentStatus);
if (listener == null || listener.isInvalid()) {
return;
}
if (currentStatus == FileDownloadStatus.blockComplete) {
try {
listener.blockComplete(originTask);
notifyCompleted(((BlockCompleteMessage) message).transmitToCompleted());
} catch (Throwable throwable) {
notifyError(messageHandler.prepareErrorMessage(throwable));
}
} else {
FileDownloadLargeFileListener largeFileListener = null;
if (listener instanceof FileDownloadLargeFileListener) {
largeFileListener = (FileDownloadLargeFileListener) listener;
}
switch (currentStatus) {
case FileDownloadStatus.pending:
if (largeFileListener != null) {
largeFileListener.pending(originTask,
message.getLargeSofarBytes(),
message.getLargeTotalBytes());
} else {
listener.pending(originTask,
message.getSmallSofarBytes(),
message.getSmallTotalBytes());
}
break;
case FileDownloadStatus.started:
listener.started(originTask);
break;
case FileDownloadStatus.connected:
if (largeFileListener != null) {
largeFileListener.connected(originTask,
message.getEtag(),
message.isResuming(),
originTask.getLargeFileSoFarBytes(),
message.getLargeTotalBytes());
} else {
listener.connected(originTask,
message.getEtag(),
message.isResuming(),
originTask.getSmallFileSoFarBytes(),
message.getSmallTotalBytes());
}
break;
case FileDownloadStatus.progress:
if (largeFileListener != null) {
largeFileListener.progress(originTask,
message.getLargeSofarBytes(),
originTask.getLargeFileTotalBytes());
} else {
listener.progress(originTask,
message.getSmallSofarBytes(),
originTask.getSmallFileTotalBytes());
}
break;
case FileDownloadStatus.retry:
if (largeFileListener != null) {
largeFileListener.retry(originTask,
message.getThrowable(),
message.getRetryingTimes(),
message.getLargeSofarBytes());
} else {
listener.retry(originTask,
message.getThrowable(),
message.getRetryingTimes(),
message.getSmallSofarBytes());
}
break;
case FileDownloadStatus.completed:
listener.completed(originTask);
break;
case FileDownloadStatus.error:
listener.error(originTask,
message.getThrowable());
break;
case FileDownloadStatus.paused:
if (largeFileListener != null) {
largeFileListener.paused(originTask,
message.getLargeSofarBytes(),
message.getLargeTotalBytes());
} else {
listener.paused(originTask,
message.getSmallSofarBytes(),
message.getSmallTotalBytes());
}
break;
case FileDownloadStatus.warn:
// already same url & path in pending/running list
listener.warn(originTask);
break;
default:
// ignored
}
}
}
@Override
public boolean handoverDirectly() {
return mTask.getOrigin().isSyncCallback();
}
@Override
public void reAppointment(BaseDownloadTask.IRunningTask task,
BaseDownloadTask.LifeCycleCallback callback) {
if (this.mTask != null) {
throw new IllegalStateException(
FileDownloadUtils.formatString("the messenger is working, can't "
+ "re-appointment for %s", task));
}
init(task, callback);
}
@Override
public boolean isBlockingCompleted() {
return parcelQueue.peek().getStatus() == FileDownloadStatus.blockComplete;
}
@Override
public void discard() {
mIsDiscard = true;
}
@Override
public String toString() {
return FileDownloadUtils.formatString("%d:%s",
mTask == null ? -1 : mTask.getOrigin().getId(), super.toString());
}
public boolean hasTask() {
return mTask != null;
}
}