Welcome to mirror list, hosted at ThFree Co, Russian Federation.

PodcastFragmentActivity.java « owncloudnewsreader « luhmer « de « java « main « src « News-Android-App - github.com/nextcloud/news-android.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d69e7c685e604897e8c68616119410d9999ea251 (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
package de.luhmer.owncloudnewsreader;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.media.session.MediaControllerCompat;
import android.util.Log;
import android.util.TypedValue;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.nextcloud.android.sso.helper.VersionCheckHelper;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;

import de.luhmer.owncloudnewsreader.ListView.SubscriptionExpandableListAdapter;
import de.luhmer.owncloudnewsreader.database.DatabaseConnectionOrm;
import de.luhmer.owncloudnewsreader.database.model.RssItem;
import de.luhmer.owncloudnewsreader.di.ApiProvider;
import de.luhmer.owncloudnewsreader.events.podcast.CollapsePodcastView;
import de.luhmer.owncloudnewsreader.events.podcast.ExpandPodcastView;
import de.luhmer.owncloudnewsreader.events.podcast.PodcastCompletedEvent;
import de.luhmer.owncloudnewsreader.helper.PostDelayHandler;
import de.luhmer.owncloudnewsreader.helper.ThemeChooser;
import de.luhmer.owncloudnewsreader.interfaces.IPlayPausePodcastClicked;
import de.luhmer.owncloudnewsreader.model.MediaItem;
import de.luhmer.owncloudnewsreader.model.PodcastItem;
import de.luhmer.owncloudnewsreader.notification.NextcloudNotificationManager;
import de.luhmer.owncloudnewsreader.services.PodcastDownloadService;
import de.luhmer.owncloudnewsreader.services.PodcastPlaybackService;
import de.luhmer.owncloudnewsreader.ssl.MemorizingTrustManager;
import de.luhmer.owncloudnewsreader.view.PodcastSlidingUpPanelLayout;
import de.luhmer.owncloudnewsreader.widget.WidgetProvider;

import static de.luhmer.owncloudnewsreader.Constants.MIN_NEXTCLOUD_FILES_APP_VERSION_CODE;

public abstract class PodcastFragmentActivity extends AppCompatActivity implements IPlayPausePodcastClicked {

    private static final String TAG = PodcastFragmentActivity.class.getCanonicalName();

    @Inject protected SharedPreferences mPrefs;
    @Inject protected ApiProvider mApi;
    @Inject protected MemorizingTrustManager mMTM;
    @Inject protected PostDelayHandler mPostDelayHandler;

    private EventBus eventBus;
    private PodcastFragment mPodcastFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //Log.v(TAG, "onCreate() called with: savedInstanceState = [" + savedInstanceState + "]");
        ((NewsReaderApplication) getApplication()).getAppComponent().injectActivity(this);

        ThemeChooser.chooseTheme(this);
        super.onCreate(savedInstanceState);
        ThemeChooser.afterOnCreate(this);

        //if (mApi.getAPI() instanceof Proxy) { // doesn't work.. retrofit is also a "proxy"
        boolean useSSO = mPrefs.getBoolean(SettingsActivity.SW_USE_SINGLE_SIGN_ON, false);
        if(useSSO) {
            VersionCheckHelper.verifyMinVersion(this, MIN_NEXTCLOUD_FILES_APP_VERSION_CODE);
        }

        mPostDelayHandler.stopRunningPostDelayHandler();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        //Log.v(TAG, "onPostCreate() called with: savedInstanceState = [" + savedInstanceState + "]");
        super.onPostCreate(savedInstanceState);

        eventBus = EventBus.getDefault();

        updatePodcastView();
    }

    @Override
    protected void onStart() {
        super.onStart();

        mMTM.bindDisplayActivity(this);
    }

    @Override
    protected void onStop() {
        mMTM.unbindDisplayActivity(this);

        super.onStop();
    }


    @Override
    public void onUserLeaveHint() {
        super.onUserLeaveHint();
        mPostDelayHandler.delayOnExitTimer();
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        if (hasWindowFocus) {
            int currentOrientation = getResources().getConfiguration().orientation;
            if (currentOrientation != lastOrientation) {
                getPodcastSlidingUpPanelLayout().setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
                lastOrientation = currentOrientation;
            }
        }

        super.onWindowFocusChanged(hasWindowFocus);
    }


    int lastOrientation = -1;

    @Override
    protected void onResume() {
        eventBus.register(this);

        super.onResume();
    }

    @Override
    protected void onPause() {
        eventBus.unregister(this);

        /*
        isVideoViewVisible = false;
        videoViewInitialized = false;

        eventBus.post(new RegisterVideoOutput(null, null));

        rlVideoPodcastSurfaceWrapper.setVisibility(View.GONE);
        rlVideoPodcastSurfaceWrapper.removeAllViews();
        */

        WidgetProvider.UpdateWidget(this);

        if (NextcloudNotificationManager.isUnreadRssCountNotificationVisible(this)) {
            DatabaseConnectionOrm dbConn = new DatabaseConnectionOrm(this);
            int count = Integer.parseInt(dbConn.getUnreadItemsCountForSpecificFolder(SubscriptionExpandableListAdapter.SPECIAL_FOLDERS.ALL_UNREAD_ITEMS));
            NextcloudNotificationManager.showUnreadRssItemsNotification(this, count, mPrefs);

            if (count == 0) {
                NextcloudNotificationManager.removeRssItemsNotification(this);
            }
        }


        super.onPause();
    }


    /*
    public static boolean isMyServiceRunning(Class<?> serviceClass, Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    */



    /*
    private void buildTransportControls() {
        // Grab the view for the play/pause button

        int pbState = MediaControllerCompat.getMediaController(PodcastFragmentActivity.this).getPlaybackState().getState();
        if (pbState == PlaybackStateCompat.STATE_PLAYING) {
            MediaControllerCompat.getMediaController(PodcastFragmentActivity.this).getTransportControls().pause();
        } else {
            MediaControllerCompat.getMediaController(PodcastFragmentActivity.this).getTransportControls().play();
        }
        MediaControllerCompat mediaController = MediaControllerCompat.getMediaController(PodcastFragmentActivity.this);

        // Display the initial state
        MediaMetadataCompat metadata = mediaController.getMetadata();
        PlaybackStateCompat pbState = mediaController.getPlaybackState();

        // Register a Callback to stay in sync
        mediaController.registerCallback(controllerCallback);
    }
    */

    public PodcastSlidingUpPanelLayout getSlidingLayout() {
        return getPodcastSlidingUpPanelLayout();
    }

    public boolean handlePodcastBackPressed() {
        if(mPodcastFragment != null && getPodcastSlidingUpPanelLayout().getPanelState().equals(SlidingUpPanelLayout.PanelState.EXPANDED)) {
            getPodcastSlidingUpPanelLayout().setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
            return true;
        }
        return false;
    }

    protected void updatePodcastView() {
        if(mPodcastFragment == null) {
            mPodcastFragment = PodcastFragment.newInstance();
        }
        /*
        if(mPodcastFragment != null) {
            getSupportFragmentManager().beginTransaction().remove(mPodcastFragment).commitAllowingStateLoss();
        }
        */

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.podcast_frame, mPodcastFragment)
                .commitAllowingStateLoss();

        collapsePodcastView();
    }


    @Subscribe
    public void onEvent(CollapsePodcastView event) {
        Log.v(TAG, "onEvent(CollapsePodcastView) called with: event = [" + event + "]");
        collapsePodcastView();
    }

    @Subscribe
    public void onEvent(ExpandPodcastView event) {
        Log.v(TAG, "onEvent(ExpandPodcastView) called with: event = [" + event + "]");
        expandPodcastView();
    }


    private void collapsePodcastView() {
        getPodcastSlidingUpPanelLayout().setPanelHeight(0);
    }

    private void expandPodcastView() {
        getPodcastSlidingUpPanelLayout().setPanelHeight((int) dipToPx(68));
    }

    @Subscribe
    public void onEvent(PodcastCompletedEvent podcastCompletedEvent) {
        collapsePodcastView();
        getPodcastSlidingUpPanelLayout().setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
        //currentlyPlaying = false;
    }

    public static int pxToDp(int px) {
        return (int) (px / Resources.getSystem().getDisplayMetrics().density);
    }

    private float dipToPx(float dip) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, getResources().getDisplayMetrics());
    }

    @VisibleForTesting
    public void openMediaItem(final MediaItem mediaItem) {
        Intent intent = new Intent(this, PodcastPlaybackService.class);
        intent.putExtra(PodcastPlaybackService.MEDIA_ITEM, mediaItem);
        startService(intent);

        /*
        if(!mMediaBrowser.isConnected()) {
            mMediaBrowser.connect();
        }
        */


        //bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

    }

    @Override
    public void openPodcast(final RssItem rssItem) {
        final PodcastItem podcastItem = DatabaseConnectionOrm.ParsePodcastItemFromRssItem(this, rssItem);

        File file = new File(PodcastDownloadService.getUrlToPodcastFile(this, podcastItem.link, false));
        if(file.exists()) {
            podcastItem.link = file.getAbsolutePath();
            openMediaItem(podcastItem);
        } else if(!podcastItem.offlineCached) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this)
                    .setNegativeButton("Abort", null)
                    .setTitle("Podcast");

            if("youtube".equals(podcastItem.mimeType)) {
                alertDialog.setPositiveButton("Open Youtube", (dialogInterface, i) -> openYoutube(podcastItem));
            } else {
                alertDialog.setNeutralButton("Download", (dialogInterface, i) -> {
                    PodcastDownloadService.startPodcastDownload(PodcastFragmentActivity.this, podcastItem);
                    Toast.makeText(PodcastFragmentActivity.this, "Starting download of podcast. Please wait..", Toast.LENGTH_SHORT).show();
                });
                alertDialog.setPositiveButton("Stream", (dialogInterface, i) -> openMediaItem(podcastItem));
                alertDialog.setMessage("Choose if you want to download or stream the selected podcast");
            }

            alertDialog.show();
        }
    }


    @Override
    public void pausePodcast() {
        MediaControllerCompat.getMediaController(PodcastFragmentActivity.this).getTransportControls().pause();
    }


    private void openYoutube(PodcastItem podcastItem) {
        Log.e(TAG, podcastItem.link);
        String youtubeVideoID = getVideoIdFromYoutubeUrl(podcastItem.link);
        if(youtubeVideoID == null) {
            Toast.makeText(this, "Failed to extract youtube video id for url: " + podcastItem.link + ". Please report this issue.", Toast.LENGTH_LONG).show();
            return;
        }
        Intent appIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + youtubeVideoID));
        Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + podcastItem.link));
        try {
            startActivity(appIntent);
        } catch (ActivityNotFoundException ex) {
            startActivity(webIntent);
        }
    }

    public String getVideoIdFromYoutubeUrl(String url){
        String videoId = null;
        String regex = "http(?:s)?:\\/\\/(?:m.)?(?:www\\.)?youtu(?:\\.be\\/|be\\.com\\/(?:watch\\?(?:feature=youtu.be\\&)?v=|v\\/|embed\\/|user\\/(?:[\\w#]+\\/)+))([^&#?\\n]+)";
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(url);
        if(matcher.find()){
            videoId = matcher.group(1);
        }
        return videoId;
    }

    protected abstract PodcastSlidingUpPanelLayout getPodcastSlidingUpPanelLayout();
}