summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/storage/DownloadRequester.java
blob: 0eae52137a7af8542a289e6cb9e2771a1cb85a28 (plain)
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
package de.danoeh.antennapod.storage;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.webkit.URLUtil;
import de.danoeh.antennapod.BuildConfig;
import de.danoeh.antennapod.feed.*;
import de.danoeh.antennapod.preferences.UserPreferences;
import de.danoeh.antennapod.service.download.DownloadRequest;
import de.danoeh.antennapod.service.download.DownloadService;
import de.danoeh.antennapod.util.FileNameGenerator;
import de.danoeh.antennapod.util.URLChecker;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * Sends download requests to the DownloadService. This class should always be used for starting downloads,
 * otherwise they won't work correctly.
 */
public class DownloadRequester {
    private static final String TAG = "DownloadRequester";

    public static final String IMAGE_DOWNLOADPATH = "images/";
    public static final String FEED_DOWNLOADPATH = "cache/";
    public static final String MEDIA_DOWNLOADPATH = "media/";

    private static DownloadRequester downloader;

    private Map<String, DownloadRequest> downloads;

    private DownloadRequester() {
        downloads = new ConcurrentHashMap<String, DownloadRequest>();
    }

    public static synchronized DownloadRequester getInstance() {
        if (downloader == null) {
            downloader = new DownloadRequester();
        }
        return downloader;
    }

    /**
     * Starts a new download with the given DownloadRequest. This method should only
     * be used from outside classes if the DownloadRequest was created by the DownloadService to
     * ensure that the data is valid. Use downloadFeed(), downloadImage() or downloadMedia() instead.
     *
     * @param context Context object for starting the DownloadService
     * @param request The DownloadRequest. If another DownloadRequest with the same source URL is already stored, this method
     *                call will return false.
     * @return True if the download request was accepted, false otherwise.
     */
    public synchronized boolean download(Context context, DownloadRequest request) {
        Validate.notNull(context);
        Validate.notNull(request);

        if (downloads.containsKey(request.getSource())) {
            if (BuildConfig.DEBUG) Log.i(TAG, "DownloadRequest is already stored.");
            return false;
        }
        downloads.put(request.getSource(), request);

        Intent launchIntent = new Intent(context, DownloadService.class);
        launchIntent.putExtra(DownloadService.EXTRA_REQUEST, request);
        context.startService(launchIntent);
        EventDistributor.getInstance().sendDownloadQueuedBroadcast();
        return true;
    }

    private void download(Context context, FeedFile item, File dest,
                          boolean overwriteIfExists, String username, String password, boolean deleteOnFailure) {
        if (!isDownloadingFile(item)) {
            if (!isFilenameAvailable(dest.toString()) || (deleteOnFailure && dest.exists())) {
                if (BuildConfig.DEBUG)
                    Log.d(TAG, "Filename already used.");
                if (isFilenameAvailable(dest.toString()) && overwriteIfExists) {
                    boolean result = dest.delete();
                    if (BuildConfig.DEBUG)
                        Log.d(TAG, "Deleting file. Result: " + result);
                } else {
                    // find different name
                    File newDest = null;
                    for (int i = 1; i < Integer.MAX_VALUE; i++) {
                        String newName = FilenameUtils.getBaseName(dest
                                .getName())
                                + "-"
                                + i
                                + FilenameUtils.EXTENSION_SEPARATOR
                                + FilenameUtils.getExtension(dest.getName());
                        if (BuildConfig.DEBUG)
                            Log.d(TAG, "Testing filename " + newName);
                        newDest = new File(dest.getParent(), newName);
                        if (!newDest.exists()
                                && isFilenameAvailable(newDest.toString())) {
                            if (BuildConfig.DEBUG)
                                Log.d(TAG, "File doesn't exist yet. Using "
                                        + newName);
                            break;
                        }
                    }
                    if (newDest != null) {
                        dest = newDest;
                    }
                }
            }
            if (BuildConfig.DEBUG)
                Log.d(TAG,
                        "Requesting download of url " + item.getDownload_url());
            item.setDownload_url(URLChecker.prepareURL(item.getDownload_url()));

            DownloadRequest request = new DownloadRequest(dest.toString(),
                    URLChecker.prepareURL(item.getDownload_url()), item.getHumanReadableIdentifier(),
                    item.getId(), item.getTypeAsInt(), username, password, deleteOnFailure);

            download(context, request);
        } else {
            Log.e(TAG, "URL " + item.getDownload_url()
                    + " is already being downloaded");
        }
    }

    /**
     * Returns true if a filename is available and false if it has already been
     * taken by another requested download.
     */
    private boolean isFilenameAvailable(String path) {
        for (String key : downloads.keySet()) {
            DownloadRequest r = downloads.get(key);
            if (StringUtils.equals(r.getDestination(), path)) {
                if (BuildConfig.DEBUG)
                    Log.d(TAG, path
                            + " is already used by another requested download");
                return false;
            }
        }
        if (BuildConfig.DEBUG)
            Log.d(TAG, path + " is available as a download destination");
        return true;
    }

    public synchronized void downloadFeed(Context context, Feed feed)
            throws DownloadRequestException {
        if (feedFileValid(feed)) {
            String username = (feed.getPreferences() != null) ? feed.getPreferences().getUsername() : null;
            String password = (feed.getPreferences() != null) ? feed.getPreferences().getPassword() : null;

            download(context, feed, new File(getFeedfilePath(context),
                    getFeedfileName(feed)), true, username, password, true);
        }
    }

    public synchronized void downloadImage(Context context, FeedImage image)
            throws DownloadRequestException {
        if (feedFileValid(image)) {
            download(context, image, new File(getImagefilePath(context),
                    getImagefileName(image)), false, null, null, false);
        }
    }

    public synchronized void downloadMedia(Context context, FeedMedia feedmedia)
            throws DownloadRequestException {
        if (feedFileValid(feedmedia)) {
            Feed feed = feedmedia.getItem().getFeed();
            String username;
            String password;
            if (feed != null && feed.getPreferences() != null) {
                username = feed.getPreferences().getUsername();
                password = feed.getPreferences().getPassword();
            } else {
                username = null;
                password = null;
            }

            File dest;
            if (feedmedia.getFile_url() != null) {
                dest = new File(feedmedia.getFile_url());
            } else {
                dest = new File(getMediafilePath(context, feedmedia),
                        getMediafilename(feedmedia));
            }
            download(context, feedmedia,
                    dest, false, username, password, false
            );
        }
    }

    /**
     * Throws a DownloadRequestException if the feedfile or the download url of
     * the feedfile is null.
     *
     * @throws DownloadRequestException
     */
    private boolean feedFileValid(FeedFile f) throws DownloadRequestException {
        if (f == null) {
            throw new DownloadRequestException("Feedfile was null");
        } else if (f.getDownload_url() == null) {
            throw new DownloadRequestException("File has no download URL");
        } else {
            return true;
        }
    }

    /**
     * Cancels a running download.
     */
    public synchronized void cancelDownload(final Context context, final FeedFile f) {
        cancelDownload(context, f.getDownload_url());
    }

    /**
     * Cancels a running download.
     */
    public synchronized void cancelDownload(final Context context, final String downloadUrl) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Cancelling download with url " + downloadUrl);
        Intent cancelIntent = new Intent(DownloadService.ACTION_CANCEL_DOWNLOAD);
        cancelIntent.putExtra(DownloadService.EXTRA_DOWNLOAD_URL, downloadUrl);
        context.sendBroadcast(cancelIntent);
    }

    /**
     * Cancels all running downloads
     */
    public synchronized void cancelAllDownloads(Context context) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Cancelling all running downloads");
        context.sendBroadcast(new Intent(
                DownloadService.ACTION_CANCEL_ALL_DOWNLOADS));
    }

    /**
     * Returns true if there is at least one Feed in the downloads queue.
     */
    public synchronized boolean isDownloadingFeeds() {
        for (DownloadRequest r : downloads.values()) {
            if (r.getFeedfileType() == Feed.FEEDFILETYPE_FEED) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks if feedfile is in the downloads list
     */
    public synchronized boolean isDownloadingFile(FeedFile item) {
        if (item.getDownload_url() != null) {
            return downloads.containsKey(item.getDownload_url());
        }
        return false;
    }

    public synchronized DownloadRequest getDownload(String downloadUrl) {
        return downloads.get(downloadUrl);
    }

    /**
     * Checks if feedfile with the given download url is in the downloads list
     */
    public synchronized boolean isDownloadingFile(String downloadUrl) {
        return downloads.get(downloadUrl) != null;
    }

    public synchronized boolean hasNoDownloads() {
        return downloads.isEmpty();
    }

    /**
     * Remove an object from the downloads-list of the requester.
     */
    public synchronized void removeDownload(DownloadRequest r) {
        if (downloads.remove(r.getSource()) == null) {
            Log.e(TAG,
                    "Could not remove object with url " + r.getSource());
        }
    }

    /**
     * Get the number of uncompleted Downloads
     */
    public synchronized int getNumberOfDownloads() {
        return downloads.size();
    }

    public synchronized String getFeedfilePath(Context context)
            throws DownloadRequestException {
        return getExternalFilesDirOrThrowException(context, FEED_DOWNLOADPATH)
                .toString() + "/";
    }

    public synchronized String getFeedfileName(Feed feed) {
        String filename = feed.getDownload_url();
        if (feed.getTitle() != null && !feed.getTitle().isEmpty()) {
            filename = feed.getTitle();
        }
        return "feed-" + FileNameGenerator.generateFileName(filename);
    }

    public synchronized String getImagefilePath(Context context)
            throws DownloadRequestException {
        return getExternalFilesDirOrThrowException(context, IMAGE_DOWNLOADPATH)
                .toString() + "/";
    }

    public synchronized String getImagefileName(FeedImage image) {
        String filename = image.getDownload_url();
        if (image.getOwner() != null && image.getOwner().getHumanReadableIdentifier() != null) {
            filename = image.getOwner().getHumanReadableIdentifier();
        }
        return "image-" + FileNameGenerator.generateFileName(filename);
    }

    public synchronized String getMediafilePath(Context context, FeedMedia media)
            throws DownloadRequestException {
        File externalStorage = getExternalFilesDirOrThrowException(
                context,
                MEDIA_DOWNLOADPATH
                        + FileNameGenerator.generateFileName(media.getItem()
                        .getFeed().getTitle()) + "/"
        );
        return externalStorage.toString();
    }

    private File getExternalFilesDirOrThrowException(Context context,
                                                     String type) throws DownloadRequestException {
        File result = UserPreferences.getDataFolder(context, type);
        if (result == null) {
            throw new DownloadRequestException(
                    "Failed to access external storage");
        }
        return result;
    }

    private String getMediafilename(FeedMedia media) {
        String filename;
        String titleBaseFilename = "";

        // Try to generate the filename by the item title
        if (media.getItem() != null && media.getItem().getTitle() != null) {
            String title = media.getItem().getTitle();
            // Delete reserved characters
            titleBaseFilename = title.replaceAll("[\\\\/%\\?\\*:|<>\"\\p{Cntrl}]", "");
            titleBaseFilename = titleBaseFilename.trim();
        }

        String URLBaseFilename = URLUtil.guessFileName(media.getDownload_url(),
                null, media.getMime_type());
        ;

        if (titleBaseFilename != "") {
            // Append extension
            filename = titleBaseFilename + FilenameUtils.EXTENSION_SEPARATOR +
                    FilenameUtils.getExtension(URLBaseFilename);
        } else {
            // Fall back on URL file name
            filename = URLBaseFilename;
        }
        return filename;
    }
}