summaryrefslogtreecommitdiff
path: root/app/src/main/java/de/danoeh/antennapod/activity/OnlineFeedViewActivity.java
blob: 3b03ed2db5570e8ee10dfae5869d1cedc120d803 (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
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package de.danoeh.antennapod.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import org.apache.commons.lang3.StringUtils;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import de.danoeh.antennapod.BuildConfig;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.feed.Feed;
import de.danoeh.antennapod.core.feed.FeedPreferences;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.service.download.DownloadRequest;
import de.danoeh.antennapod.core.service.download.DownloadStatus;
import de.danoeh.antennapod.core.service.download.Downloader;
import de.danoeh.antennapod.core.service.download.HttpDownloader;
import de.danoeh.antennapod.core.syndication.handler.FeedHandler;
import de.danoeh.antennapod.core.syndication.handler.FeedHandlerResult;
import de.danoeh.antennapod.core.syndication.handler.UnsupportedFeedtypeException;
import de.danoeh.antennapod.core.util.DownloadError;
import de.danoeh.antennapod.core.util.FileNameGenerator;
import de.danoeh.antennapod.core.util.StorageUtils;
import de.danoeh.antennapod.core.util.URLChecker;
import de.danoeh.antennapod.core.util.syndication.FeedDiscoverer;
import de.danoeh.antennapod.dialog.AuthenticationDialog;

/**
 * Downloads a feed from a feed URL and parses it. Subclasses can display the
 * feed object that was parsed. This activity MUST be started with a given URL
 * or an Exception will be thrown.
 * <p/>
 * If the feed cannot be downloaded or parsed, an error dialog will be displayed
 * and the activity will finish as soon as the error dialog is closed.
 */
public abstract class OnlineFeedViewActivity extends ActionBarActivity {
    private static final String TAG = "OnlineFeedViewActivity";
    public static final String ARG_FEEDURL = "arg.feedurl";

    /**
     * Optional argument: specify a title for the actionbar.
     */
    public static final String ARG_TITLE = "title";

    public static final int RESULT_ERROR = 2;

    private Feed feed;
    private Map<String, String> alternateFeedUrls;
    private Downloader downloader;

    private boolean isPaused;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(UserPreferences.getTheme());
        super.onCreate(savedInstanceState);

        if (getIntent() != null && getIntent().hasExtra(ARG_TITLE)) {
            getSupportActionBar().setTitle(getIntent().getStringExtra(ARG_TITLE));
        }

        StorageUtils.checkStorageAvailability(this);

        final String feedUrl;
        if (getIntent().hasExtra(ARG_FEEDURL)) {
            feedUrl = getIntent().getStringExtra(ARG_FEEDURL);
        } else if (StringUtils.equals(getIntent().getAction(), Intent.ACTION_SEND)
                || StringUtils.equals(getIntent().getAction(), Intent.ACTION_VIEW)) {
            feedUrl = (StringUtils.equals(getIntent().getAction(), Intent.ACTION_SEND))
                    ? getIntent().getStringExtra(Intent.EXTRA_TEXT) : getIntent().getDataString();

            getSupportActionBar().setTitle(R.string.add_new_feed_label);
        } else {
            throw new IllegalArgumentException(
                    "Activity must be started with feedurl argument!");
        }

        if (BuildConfig.DEBUG)
            Log.d(TAG, "Activity was started with url " + feedUrl);
        setLoadingLayout();
        if (savedInstanceState == null) {
            startFeedDownload(feedUrl, null, null);
        } else {
            startFeedDownload(feedUrl, savedInstanceState.getString("username"), savedInstanceState.getString("password"));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isPaused = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isPaused = true;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (feed != null && feed.getPreferences() != null) {
            outState.putString("username", feed.getPreferences().getUsername());
            outState.putString("password", feed.getPreferences().getPassword());
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (downloader != null && !downloader.isFinished()) {
            downloader.cancel();
        }
    }

    private void resetIntent(String url, String title) {
        Intent intent = new Intent();
        intent.putExtra(ARG_FEEDURL, url);
        intent.putExtra(ARG_TITLE, title);
        setIntent(intent);
    }


    private void onDownloadCompleted(final Downloader downloader) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (BuildConfig.DEBUG) Log.d(TAG, "Download was completed");
                DownloadStatus status = downloader.getResult();
                if (status != null) {
                    if (!status.isCancelled()) {
                        if (status.isSuccessful()) {
                            parseFeed();
                        } else if (status.getReason() == DownloadError.ERROR_UNAUTHORIZED) {
                            if (!isFinishing() && !isPaused) {
                                Dialog dialog = new FeedViewAuthenticationDialog(OnlineFeedViewActivity.this,
                                        R.string.authentication_notification_title, downloader.getDownloadRequest().getSource());
                                dialog.show();
                            }
                        } else {
                            String errorMsg = status.getReason().getErrorString(
                                    OnlineFeedViewActivity.this);
                            if (errorMsg != null
                                    && status.getReasonDetailed() != null) {
                                errorMsg += " ("
                                        + status.getReasonDetailed() + ")";
                            }
                            showErrorDialog(errorMsg);
                        }
                    }
                } else {
                    Log.wtf(TAG,
                            "DownloadStatus returned by Downloader was null");
                    finish();
                }
            }
        });

    }

    private void startFeedDownload(String url, String username, String password) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Starting feed download");
        url = URLChecker.prepareURL(url);
        feed = new Feed(url, new Date(0));
        if (username != null && password != null) {
            feed.setPreferences(new FeedPreferences(0, false, username, password));
        }
        String fileUrl = new File(getExternalCacheDir(),
                FileNameGenerator.generateFileName(feed.getDownload_url()))
                .toString();
        feed.setFile_url(fileUrl);
        final DownloadRequest request = new DownloadRequest(feed.getFile_url(),
                feed.getDownload_url(), "OnlineFeed", 0, Feed.FEEDFILETYPE_FEED, username, password, true, null);
        downloader = new HttpDownloader(
                request);
        new Thread() {
            @Override
            public void run() {
                loadData();
                downloader.call();
                onDownloadCompleted(downloader);
            }
        }.start();


    }

    /**
     * Displays a progress indicator.
     */
    private void setLoadingLayout() {
        RelativeLayout rl = new RelativeLayout(this);
        RelativeLayout.LayoutParams rlLayoutParams = new RelativeLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);

        ProgressBar pb = new ProgressBar(this);
        pb.setIndeterminate(true);
        RelativeLayout.LayoutParams pbLayoutParams = new RelativeLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        pbLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        rl.addView(pb, pbLayoutParams);
        addContentView(rl, rlLayoutParams);
    }

    private void parseFeed() {
        if (feed == null || feed.getFile_url() == null && feed.isDownloaded()) {
            throw new IllegalStateException(
                    "feed must be non-null and downloaded when parseFeed is called");
        }

        if (BuildConfig.DEBUG)
            Log.d(TAG, "Parsing feed");

        Thread thread = new Thread() {

            @Override
            public void run() {
                String reasonDetailed = "";
                boolean successful = false;
                FeedHandler handler = new FeedHandler();
                try {
                    FeedHandlerResult result = handler.parseFeed(feed);
                    feed = result.feed;
                    alternateFeedUrls = result.alternateFeedUrls;
                    successful = true;
                } catch (SAXException e) {
                    e.printStackTrace();
                    reasonDetailed = e.getMessage();
                } catch (IOException e) {
                    e.printStackTrace();
                    reasonDetailed = e.getMessage();
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                    reasonDetailed = e.getMessage();
                } catch (UnsupportedFeedtypeException e) {
                    if (BuildConfig.DEBUG) Log.d(TAG, "Unsupported feed type detected");
                    if (StringUtils.equalsIgnoreCase("html", e.getRootElement())) {
                        if (showFeedDiscoveryDialog(new File(feed.getFile_url()), feed.getDownload_url())) {
                            return;
                        }
                    } else {
                        e.printStackTrace();
                        reasonDetailed = e.getMessage();
                    }
                } finally {
                    boolean rc = new File(feed.getFile_url()).delete();
                    if (BuildConfig.DEBUG)
                        Log.d(TAG, "Deleted feed source file. Result: " + rc);
                }

                if (successful) {
                    beforeShowFeedInformation(feed, alternateFeedUrls);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showFeedInformation(feed, alternateFeedUrls);
                        }
                    });
                } else {
                    final String errorMsg =
                            DownloadError.ERROR_PARSER_EXCEPTION.getErrorString(
                                    OnlineFeedViewActivity.this)
                                    + " (" + reasonDetailed + ")";
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            showErrorDialog(errorMsg);
                        }
                    });
                }
            }
        };
        thread.start();
    }

    /**
     * Can be used to load data asynchronously.
     */
    protected void loadData() {

    }

    /**
     * Called after the feed has been downloaded and parsed and before showFeedInformation is called.
     * This method is executed on a background thread
     */
    protected void beforeShowFeedInformation(Feed feed, Map<String, String> alternateFeedUrls) {

    }

    /**
     * Called when feed parsed successfully.
     * This method is executed on the GUI thread.
     */
    protected void showFeedInformation(Feed feed, Map<String, String> alternateFeedUrls) {

    }

    private void showErrorDialog(String errorMsg) {
        if (!isFinishing() && !isPaused) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.error_label);
            if (errorMsg != null) {
                builder.setMessage(getString(R.string.error_msg_prefix) + errorMsg);
            } else {
                builder.setMessage(R.string.error_msg_prefix);
            }
            builder.setNeutralButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }
            );
            builder.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    setResult(RESULT_ERROR);
                    finish();
                }
            });
            builder.show();
        }
    }

    private boolean showFeedDiscoveryDialog(File feedFile, String baseUrl) {
        FeedDiscoverer fd = new FeedDiscoverer();
        final Map<String, String> urlsMap;
        try {
            urlsMap = fd.findLinks(feedFile, baseUrl);
            if (urlsMap == null || urlsMap.isEmpty()) {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isPaused || isFinishing()) {
                    return;
                }

                final List<String> titles = new ArrayList<String>();
                final List<String> urls = new ArrayList<String>();

                urls.addAll(urlsMap.keySet());
                for (String url : urls) {
                    titles.add(urlsMap.get(url));
                }

                final ArrayAdapter<String> adapter = new ArrayAdapter<String>(OnlineFeedViewActivity.this, R.layout.ellipsize_start_listitem, R.id.txtvTitle, titles);
                DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String selectedUrl = urls.get(which);
                        dialog.dismiss();
                        resetIntent(selectedUrl, titles.get(which));
                        startFeedDownload(selectedUrl, null, null);
                    }
                };

                AlertDialog.Builder ab = new AlertDialog.Builder(OnlineFeedViewActivity.this)
                        .setTitle(R.string.feeds_label)
                        .setCancelable(true)
                        .setOnCancelListener(new OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                finish();
                            }
                        })
                        .setAdapter(adapter, onClickListener);
                ab.show();
            }
        });


        return true;
    }

    private class FeedViewAuthenticationDialog extends AuthenticationDialog {

        private String feedUrl;

        public FeedViewAuthenticationDialog(Context context, int titleRes, String feedUrl) {
            super(context, titleRes, true, false, null, null);
            this.feedUrl = feedUrl;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            finish();
        }

        @Override
        protected void onConfirmed(String username, String password, boolean saveUsernamePassword) {
            startFeedDownload(feedUrl, username, password);
        }
    }
}