aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/java/github/daneren2005/dsub/util/compat/RemoteControlClientLP.java
blob: c9f8cab8acf4e4ab0a69d328daa04fef39e2e8da (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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
/*
	This file is part of Subsonic.

	Subsonic is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Subsonic is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Subsonic. If not, see <http://www.gnu.org/licenses/>.

	Copyright 2015 (C) Scott Jackson
*/
package github.daneren2005.dsub.util.compat;

import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.AudioAttributes;
import android.media.MediaDescription;
import android.media.MediaMetadata;
import android.media.RemoteControlClient;
import android.media.session.MediaSession;
import android.media.session.PlaybackState;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.media.MediaRouter;

import java.util.ArrayList;
import java.util.List;

import github.daneren2005.dsub.R;
import github.daneren2005.dsub.activity.SubsonicActivity;
import github.daneren2005.dsub.activity.SubsonicFragmentActivity;
import github.daneren2005.dsub.domain.MusicDirectory;
import github.daneren2005.dsub.domain.Playlist;
import github.daneren2005.dsub.domain.SearchCritera;
import github.daneren2005.dsub.domain.SearchResult;
import github.daneren2005.dsub.service.DownloadFile;
import github.daneren2005.dsub.service.DownloadService;
import github.daneren2005.dsub.service.MusicService;
import github.daneren2005.dsub.util.Constants;
import github.daneren2005.dsub.util.ImageLoader;
import github.daneren2005.dsub.util.SilentServiceTask;
import github.daneren2005.dsub.util.Util;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class RemoteControlClientLP extends RemoteControlClientBase {
	private static final String TAG = RemoteControlClientLP.class.getSimpleName();
	private static final String CUSTOM_ACTION_THUMBS_UP = "github.daneren2005.dsub.THUMBS_UP";
	private static final String CUSTOM_ACTION_THUMBS_DOWN = "github.daneren2005.dsub.THUMBS_DOWN";
	private static final String CUSTOM_ACTION_STAR = "github.daneren2005.dsub.STAR";
	// Copied from MediaControlConstants so I did not have to include the entire Wear SDK just for these constant
	private static final String SHOW_ON_WEAR = "android.support.wearable.media.extra.CUSTOM_ACTION_SHOW_ON_WEAR";
	private static final String WEAR_RESERVE_SKIP_TO_NEXT = "android.support.wearable.media.extra.RESERVE_SLOT_SKIP_TO_NEXT";
	private static final String WEAR_RESERVE_SKIP_TO_PREVIOUS = "android.support.wearable.media.extra.RESERVE_SLOT_SKIP_TO_PREVIOUS";
	private static final String WEAR_BACKGROUND_THEME = "android.support.wearable.media.extra.BACKGROUND_COLOR_FROM_THEME";
	// These constants don't seem to exist anywhere in the SDK.  Grabbed from Google's sample media player app
	private static final String AUTO_RESERVE_SKIP_TO_NEXT = "com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_SKIP_TO_NEXT";
	private static final String AUTO_RESERVE_SKIP_TO_PREVIOUS = "com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_SKIP_TO_PREVIOUS";

	protected MediaSession mediaSession;
	protected DownloadService downloadService;
	protected ImageLoader imageLoader;
	protected List<DownloadFile> currentQueue;
	protected int previousState;

	@Override
	public void register(Context context, ComponentName mediaButtonReceiverComponent) {
		downloadService = (DownloadService) context;
		mediaSession = new MediaSession(downloadService, "DSub MediaSession");

		Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
		mediaButtonIntent.setComponent(mediaButtonReceiverComponent);
		PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, mediaButtonIntent, 0);
		mediaSession.setMediaButtonReceiver(mediaPendingIntent);

		Intent activityIntent = new Intent(context, SubsonicFragmentActivity.class);
		activityIntent.putExtra(Constants.INTENT_EXTRA_NAME_DOWNLOAD, true);
		activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		PendingIntent activityPendingIntent = PendingIntent.getActivity(context, 0, activityIntent, 0);
		mediaSession.setSessionActivity(activityPendingIntent);

		mediaSession.setFlags(MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSession.FLAG_HANDLES_MEDIA_BUTTONS);
		mediaSession.setCallback(new EventCallback());

		AudioAttributes.Builder audioAttributesBuilder = new AudioAttributes.Builder();
		audioAttributesBuilder.setUsage(AudioAttributes.USAGE_MEDIA)
			.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC);
		mediaSession.setPlaybackToLocal(audioAttributesBuilder.build());
		mediaSession.setActive(true);

		Bundle sessionExtras = new Bundle();
		sessionExtras.putBoolean(WEAR_BACKGROUND_THEME, true);
		sessionExtras.putBoolean(WEAR_RESERVE_SKIP_TO_PREVIOUS, true);
		sessionExtras.putBoolean(WEAR_RESERVE_SKIP_TO_NEXT, true);
		sessionExtras.putBoolean(AUTO_RESERVE_SKIP_TO_PREVIOUS, true);
		sessionExtras.putBoolean(AUTO_RESERVE_SKIP_TO_NEXT, true);
		mediaSession.setExtras(sessionExtras);

		imageLoader = SubsonicActivity.getStaticImageLoader(context);
	}

	@Override
	public void unregister(Context context) {
		mediaSession.release();
	}

	@Override
	public void setPlaybackState(int state) {
		PlaybackState.Builder builder = new PlaybackState.Builder();

		int newState = PlaybackState.STATE_NONE;
		switch(state) {
			case RemoteControlClient.PLAYSTATE_PLAYING:
				newState = PlaybackState.STATE_PLAYING;
				break;
			case RemoteControlClient.PLAYSTATE_STOPPED:
				newState = PlaybackState.STATE_STOPPED;
				break;
			case RemoteControlClient.PLAYSTATE_PAUSED:
				newState = PlaybackState.STATE_PAUSED;
				break;
			case RemoteControlClient.PLAYSTATE_BUFFERING:
				newState = PlaybackState.STATE_BUFFERING;
				break;
		}

		long position = -1;
		if(state == RemoteControlClient.PLAYSTATE_PLAYING || state == RemoteControlClient.PLAYSTATE_PAUSED) {
			position = downloadService.getPlayerPosition();
		}
		builder.setState(newState, position, 1.0f);
		builder.setActions(getPlaybackActions());

		DownloadFile downloadFile = downloadService.getCurrentPlaying();
		if(downloadFile != null) {
			MusicDirectory.Entry entry = downloadFile.getSong();
			addCustomActions(entry, builder);
			builder.setActiveQueueItemId(entry.getId().hashCode());
		}

		PlaybackState playbackState = builder.build();
		mediaSession.setPlaybackState(playbackState);
		previousState = state;
	}

	@Override
	public void updateMetadata(Context context, MusicDirectory.Entry currentSong) {
		setMetadata(currentSong, null);

		if(currentSong != null && imageLoader != null) {
			imageLoader.loadImage(context, this, currentSong);
		}
	}

	@Override
	public void metadataChanged(MusicDirectory.Entry currentSong) {
		setPlaybackState(previousState);
	}

	public void setMetadata(MusicDirectory.Entry currentSong, Bitmap bitmap) {
		MediaMetadata.Builder builder = new MediaMetadata.Builder();
		builder.putString(MediaMetadata.METADATA_KEY_ARTIST, (currentSong == null) ? null : currentSong.getArtist())
				.putString(MediaMetadata.METADATA_KEY_ALBUM, (currentSong == null) ? null : currentSong.getAlbum())
				.putString(MediaMetadata.METADATA_KEY_ALBUM_ARTIST, (currentSong == null) ? null : currentSong.getArtist())
				.putString(MediaMetadata.METADATA_KEY_TITLE, (currentSong) == null ? null : currentSong.getTitle())
				.putString(MediaMetadata.METADATA_KEY_GENRE, (currentSong) == null ? null : currentSong.getGenre())
				.putLong(MediaMetadata.METADATA_KEY_TRACK_NUMBER, (currentSong == null) ?
						0 : ((currentSong.getTrack() == null) ? 0 : currentSong.getTrack()))
				.putLong(MediaMetadata.METADATA_KEY_DURATION, (currentSong == null) ?
						0 : ((currentSong.getDuration() == null) ? 0 : (currentSong.getDuration() * 1000)));

		if(bitmap != null) {
			builder.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, bitmap);
		}

		mediaSession.setMetadata(builder.build());
	}

	@Override
	public void updateAlbumArt(MusicDirectory.Entry currentSong, Bitmap bitmap) {
		setMetadata(currentSong, bitmap);
	}

	@Override
	public void registerRoute(MediaRouter router) {
		router.setMediaSession(mediaSession);
	}

	@Override
	public void unregisterRoute(MediaRouter router) {
		router.setMediaSession(null);
	}

	@Override
	public void updatePlaylist(List<DownloadFile> playlist) {
		List<MediaSession.QueueItem> queue = new ArrayList<>();

		for(DownloadFile file: playlist) {
			MusicDirectory.Entry entry = file.getSong();

			MediaDescription description = new MediaDescription.Builder()
					.setMediaId(entry.getId())
					.setTitle(entry.getTitle())
					.setSubtitle(entry.getAlbumDisplay())
					.build();
			MediaSession.QueueItem item = new MediaSession.QueueItem(description, entry.getId().hashCode());
			queue.add(item);
		}

		mediaSession.setQueue(queue);
		currentQueue = playlist;
	}

	public MediaSession getMediaSession() {
		return mediaSession;
	}

	protected long getPlaybackActions() {
		long actions = PlaybackState.ACTION_PLAY |
				PlaybackState.ACTION_PAUSE |
				PlaybackState.ACTION_SEEK_TO |
				PlaybackState.ACTION_SKIP_TO_QUEUE_ITEM;

		int currentIndex = downloadService.getCurrentPlayingIndex();
		int size = downloadService.size();
		if(currentIndex > 0) {
			actions |= PlaybackState.ACTION_SKIP_TO_PREVIOUS;
		}
		if(currentIndex < size - 1) {
			actions |= PlaybackState.ACTION_SKIP_TO_NEXT;
		}

		return actions;
	}
	protected void addCustomActions(MusicDirectory.Entry currentSong, PlaybackState.Builder builder) {
		Bundle showOnWearExtras = new Bundle();
		showOnWearExtras.putBoolean(SHOW_ON_WEAR, true);

		int rating = currentSong.getRating();
		PlaybackState.CustomAction thumbsUp = new PlaybackState.CustomAction.Builder(CUSTOM_ACTION_THUMBS_UP,
					downloadService.getString(R.string.download_thumbs_up),
					rating == 5 ? R.drawable.ic_action_rating_good_selected : R.drawable.ic_action_rating_good)
				.setExtras(showOnWearExtras).build();

		PlaybackState.CustomAction thumbsDown = new PlaybackState.CustomAction.Builder(CUSTOM_ACTION_THUMBS_DOWN,
					downloadService.getString(R.string.download_thumbs_down),
					rating == 1 ? R.drawable.ic_action_rating_bad_selected : R.drawable.ic_action_rating_bad)
				.setExtras(showOnWearExtras).build();

		PlaybackState.CustomAction star = new PlaybackState.CustomAction.Builder(CUSTOM_ACTION_STAR,
					downloadService.getString(R.string.common_star),
					currentSong.isStarred() ? R.drawable.ic_toggle_star : R.drawable.ic_toggle_star_outline)
				.setExtras(showOnWearExtras).build();

		builder.addCustomAction(thumbsDown).addCustomAction(star).addCustomAction(thumbsUp);
	}

	private void searchPlaylist(final String name) {
		new SilentServiceTask<Void>(downloadService) {
			@Override
			protected Void doInBackground(MusicService musicService) throws Throwable {
				List<Playlist> playlists = musicService.getPlaylists(false, downloadService, null);
				for(Playlist playlist: playlists) {
					if(playlist.getName().equals(name)) {
						getPlaylist(playlist);
						return null;
					}
				}

				noResults();
				return null;
			}

			private void getPlaylist(Playlist playlist) throws Exception {
				MusicDirectory musicDirectory = musicService.getPlaylist(false, playlist.getId(), playlist.getName(), downloadService, null);
				playSongs(musicDirectory.getChildren());
			}
		}.execute();
	}
	private void searchCriteria(final SearchCritera searchCritera) {
		new SilentServiceTask<Void>(downloadService) {
			@Override
			protected Void doInBackground(MusicService musicService) throws Throwable {
				SearchResult results = musicService.search(searchCritera, downloadService, null);

				if(results.hasArtists()) {
					playFromParent(new MusicDirectory.Entry(results.getArtists().get(0)));
				} else if(results.hasAlbums()) {
					playFromParent(results.getAlbums().get(0));
				} else if(results.hasSongs()) {
					playSong(results.getSongs().get(0));
				} else {
					noResults();
				}

				return null;
			}
			
			private void playFromParent(MusicDirectory.Entry parent) throws Exception {
				List<MusicDirectory.Entry> songs = new ArrayList<>();
				getSongsRecursively(parent, songs);
				playSongs(songs);
			}
			private void getSongsRecursively(MusicDirectory.Entry parent, List<MusicDirectory.Entry> songs) throws Exception {
				MusicDirectory musicDirectory;
				if(Util.isTagBrowsing(downloadService) && !Util.isOffline(downloadService)) {
					musicDirectory = musicService.getAlbum(parent.getId(), parent.getTitle(), false, downloadService, this);
				} else {
					musicDirectory = musicService.getMusicDirectory(parent.getId(), parent.getTitle(), false, downloadService, this);
				}

				for (MusicDirectory.Entry dir : musicDirectory.getChildren(true, false)) {
					if (dir.getRating() == 1) {
						continue;
					}

					getSongsRecursively(dir, songs);
				}

				for (MusicDirectory.Entry song : musicDirectory.getChildren(false, true)) {
					if (!song.isVideo() && song.getRating() != 1) {
						songs.add(song);
					}
				}
			}
		}.execute();
	}

	private void playSong(MusicDirectory.Entry entry) {
		List<MusicDirectory.Entry> entries = new ArrayList<>();
		entries.add(entry);
		playSongs(entries);
	}
	private void playSongs(List<MusicDirectory.Entry> entries) {
		downloadService.clear();
		downloadService.download(entries, false, true, false, false);
	}

	private void noResults() {

	}

	private class EventCallback extends MediaSession.Callback {
		@Override
		public void onPlay() {
			downloadService.start();
		}

		@Override
		public void onStop() {
			downloadService.pause();
		}

		@Override
		public void onPause() {
			downloadService.pause();
		}

		@Override
		public void onSeekTo(long position) {
			downloadService.seekTo((int) position);
		}

		@Override
		public void onSkipToNext() {
			downloadService.next();
		}
		@Override
		public void onSkipToPrevious() {
			downloadService.previous();
		}

		@Override
		public void onSkipToQueueItem(long queueId) {
			if(currentQueue != null) {
				for(DownloadFile file: currentQueue) {
					if(file.getSong().getId().hashCode() == queueId) {
						downloadService.play(file);
						return;
					}
				}
			}
		}

		@Override
		public void onPlayFromSearch (String query, Bundle extras) {
			// User just asked to playing something
			if("".equals(query)) {
				downloadService.setShufflePlayEnabled(true);
			} else {
				String mediaFocus = extras.getString(MediaStore.EXTRA_MEDIA_FOCUS);


				// Play a specific playlist
				if (MediaStore.Audio.Playlists.ENTRY_CONTENT_TYPE.equals(mediaFocus)) {
					String playlist = extras.getString(MediaStore.EXTRA_MEDIA_PLAYLIST);
					searchPlaylist(playlist);
				}
				// Play a specific genre
				else if (MediaStore.Audio.Genres.ENTRY_CONTENT_TYPE.equals(mediaFocus)) {
					String genre = extras.getString(MediaStore.EXTRA_MEDIA_GENRE);

					SharedPreferences.Editor editor = Util.getPreferences(downloadService).edit();
					editor.putString(Constants.PREFERENCES_KEY_SHUFFLE_START_YEAR, null);
					editor.putString(Constants.PREFERENCES_KEY_SHUFFLE_END_YEAR, null);
					editor.putString(Constants.PREFERENCES_KEY_SHUFFLE_GENRE, genre);
					editor.commit();

					downloadService.setShufflePlayEnabled(true);
				}
				else {
					int artists = 10;
					int albums = 10;
					int songs = 10;

					// Play a specific artist
					if (MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE.equals(mediaFocus)) {
						query = extras.getString(MediaStore.EXTRA_MEDIA_ARTIST);
						albums = 0;
						songs = 0;
					}
					// Play a specific album
					else if (MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE.equals(mediaFocus)) {
						query = extras.getString(MediaStore.EXTRA_MEDIA_ALBUM);
						artists = 0;
						songs = 0 ;
					}
					// Play a specific song
					else if (MediaStore.Audio.Media.ENTRY_CONTENT_TYPE.equals(mediaFocus)) {
						query = extras.getString(MediaStore.EXTRA_MEDIA_TITLE);
						artists = 0;
						albums = 0;
					}

					SearchCritera criteria = new SearchCritera(query, artists, albums, songs);
					searchCriteria(criteria);
				}
			}
		}

		@Override
		public void onCustomAction(String action, Bundle extras) {
			if(CUSTOM_ACTION_THUMBS_UP.equals(action)) {
				downloadService.toggleRating(5);
			} else if(CUSTOM_ACTION_THUMBS_DOWN.equals(action)) {
				downloadService.toggleRating(1);
			} else if(CUSTOM_ACTION_STAR.equals(action)) {
				downloadService.toggleStarred();
			}
		}
	}
}