capacitor-plugin-playlist 0.10.10 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +74 -17
  2. package/android/build.gradle +21 -0
  3. package/android/src/main/AndroidManifest.xml +11 -2
  4. package/android/src/main/java/org/dwbn/plugins/playlist/App.kt +2 -15
  5. package/android/src/main/java/org/dwbn/plugins/playlist/PlaylistPlugin.kt +60 -6
  6. package/android/src/main/java/org/dwbn/plugins/playlist/PlaylistRuntime.kt +16 -0
  7. package/android/src/main/java/org/dwbn/plugins/playlist/RmxAudioPlayer.java +7 -9
  8. package/android/src/main/java/org/dwbn/plugins/playlist/RmxAudioStatusMessage.java +2 -0
  9. package/android/src/main/java/org/dwbn/plugins/playlist/manager/PlaylistManager.kt +105 -3
  10. package/android/src/main/java/org/dwbn/plugins/playlist/service/MediaService.kt +2 -2
  11. package/android/src/test/java/org/dwbn/plugins/playlist/manager/PlaylistManagerMoveTest.kt +76 -0
  12. package/android/src/test/java/org/dwbn/plugins/playlist/manager/PlaylistManagerReplaceTest.kt +57 -0
  13. package/dist/docs.json +111 -1
  14. package/dist/esm/Constants.d.ts +10 -0
  15. package/dist/esm/Constants.js +10 -0
  16. package/dist/esm/Constants.js.map +1 -1
  17. package/dist/esm/RmxAudioPlayer.d.ts +16 -2
  18. package/dist/esm/RmxAudioPlayer.js +28 -3
  19. package/dist/esm/RmxAudioPlayer.js.map +1 -1
  20. package/dist/esm/definitions.d.ts +28 -1
  21. package/dist/esm/web.d.ts +3 -1
  22. package/dist/esm/web.js +54 -2
  23. package/dist/esm/web.js.map +1 -1
  24. package/dist/plugin.cjs.js +92 -5
  25. package/dist/plugin.cjs.js.map +1 -1
  26. package/dist/plugin.js +92 -5
  27. package/dist/plugin.js.map +1 -1
  28. package/ios/Sources/PlaylistPlugin/Constants.swift +2 -0
  29. package/ios/Sources/PlaylistPlugin/Plugin.swift +52 -5
  30. package/ios/Sources/PlaylistPlugin/RmxAudioPlayer.swift +123 -1
  31. package/ios/Tests/PlaylistPluginTests/PlaylistMutationTests.swift +168 -0
  32. package/package.json +10 -4
  33. package/android/.gradle/8.14.3/checksums/checksums.lock +0 -0
  34. package/android/.gradle/8.14.3/checksums/md5-checksums.bin +0 -0
  35. package/android/.gradle/8.14.3/checksums/sha1-checksums.bin +0 -0
  36. package/android/.gradle/8.14.3/executionHistory/executionHistory.bin +0 -0
  37. package/android/.gradle/8.14.3/executionHistory/executionHistory.lock +0 -0
  38. package/android/.gradle/8.14.3/fileChanges/last-build.bin +0 -0
  39. package/android/.gradle/8.14.3/fileHashes/fileHashes.bin +0 -0
  40. package/android/.gradle/8.14.3/fileHashes/fileHashes.lock +0 -0
  41. package/android/.gradle/8.14.3/fileHashes/resourceHashesCache.bin +0 -0
  42. package/android/.gradle/8.14.3/gc.properties +0 -0
  43. package/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock +0 -0
  44. package/android/.gradle/buildOutputCleanup/cache.properties +0 -2
  45. package/android/.gradle/buildOutputCleanup/outputFiles.bin +0 -0
  46. package/android/.gradle/file-system.probe +0 -0
  47. package/android/.gradle/vcs-1/gc.properties +0 -0
package/README.md CHANGED
@@ -24,7 +24,9 @@ Requires **Capacitor 8+** (peer dependency `@capacitor/core >= 8.0.0`).
24
24
  ### Playlist management
25
25
 
26
26
  - `setPlaylistItems` — replace entire playlist (optional position retention)
27
- - `addItem` / `addAllItems` — append tracks
27
+ - `addItem` / `addAllItems` — append tracks; `addItem` accepts optional insert index (“play next”)
28
+ - `moveItem` — reorder without disrupting current playback
29
+ - `replaceItem` — swap track metadata/URL in place (e.g. stream → offline file)
28
30
  - `removeItem` / `removeItems` / `clearAllItems` — remove tracks
29
31
  - `getPlaylist` — snapshot of current items
30
32
  - `setLoop` — loop entire playlist when the last track completes
@@ -49,7 +51,7 @@ Requires **Capacitor 8+** (peer dependency `@capacitor/core >= 8.0.0`).
49
51
 
50
52
  ### Background audio
51
53
 
52
- - Android: foreground media service with `WAKE_LOCK` and `FOREGROUND_SERVICE_MEDIA_PLAYBACK` (Android 14+)
54
+ - Android: foreground media service with `WAKE_LOCK`, `FOREGROUND_SERVICE`, and `FOREGROUND_SERVICE_MEDIA_PLAYBACK` (Android 14+)
53
55
  - iOS: `UIBackgroundModes` → `audio`
54
56
  - Position events throttled while WebView is backgrounded; one live snapshot emitted on foreground resume (0.9.1+)
55
57
 
@@ -83,7 +85,7 @@ See [Video handoff](#video-handoff).
83
85
  ### Not supported
84
86
 
85
87
  - Shuffle
86
- - Reorder API
88
+ - Audio ads / IMA integration ([#71](https://github.com/phiamo/capacitor-plugin-playlist/issues/71))
87
89
  - Mixable / low-latency game audio (use [cordova-plugin-nativeaudio](https://github.com/floatinghotpot/cordova-plugin-nativeaudio) instead)
88
90
  - Simultaneous audio mixing (lock-screen controls require exclusive audio focus)
89
91
 
@@ -132,16 +134,16 @@ Add to `angular.json` → architect → build → options → scripts:
132
134
 
133
135
  #### AndroidManifest.xml
134
136
 
135
- ```xml
136
- <uses-permission android:name="android.permission.WAKE_LOCK" />
137
- <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
138
- <application android:name="org.dwbn.plugins.playlist.App">
139
- <service android:enabled="true" android:exported="false"
140
- android:foregroundServiceType="mediaPlayback"
141
- android:name="org.dwbn.plugins.playlist.service.MediaService">
142
- </service>
143
- </application>
144
- ```
137
+ From **0.11.0**, the plugin library manifest merges the media playback service and required permissions into your app automatically:
138
+
139
+ - `android.permission.WAKE_LOCK`
140
+ - `android.permission.FOREGROUND_SERVICE`
141
+ - `android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK`
142
+ - `org.dwbn.plugins.playlist.service.MediaService` (`exported="false"`, `foregroundServiceType="mediaPlayback"`)
143
+
144
+ After upgrading, run `npx cap sync android`. You do **not** need to copy these entries into your host `AndroidManifest.xml` unless you want to override plugin defaults.
145
+
146
+ Keep your application's existing Android `Application` class. The legacy `org.dwbn.plugins.playlist.App` class remains available for compatibility, but it is no longer required — remove `android:name="org.dwbn.plugins.playlist.App"` from `<application>` when upgrading from older setups.
145
147
 
146
148
  #### Gradle 9+
147
149
 
@@ -443,6 +445,8 @@ See [CHANGELOG.md](./CHANGELOG.md) for version-specific fixes (0.8.8–0.10.3).
443
445
  * [`release()`](#release)
444
446
  * [`setPlaylistItems(...)`](#setplaylistitems)
445
447
  * [`addItem(...)`](#additem)
448
+ * [`moveItem(...)`](#moveitem)
449
+ * [`replaceItem(...)`](#replaceitem)
446
450
  * [`addAllItems(...)`](#addallitems)
447
451
  * [`removeItem(...)`](#removeitem)
448
452
  * [`removeItems(...)`](#removeitems)
@@ -552,7 +556,9 @@ Use `options.retainPosition` to keep the current track and playback position.
552
556
  addItem(options: AddItemOptions) => Promise<void>
553
557
  ```
554
558
 
555
- Append a single track to the end of the playlist.
559
+ Append a single track to the end of the playlist, or insert at a 0-based index.
560
+ When `index` is omitted the track is appended. Insertion does not interrupt playback
561
+ of the current track.
556
562
 
557
563
  | Param | Type |
558
564
  | ------------- | --------------------------------------------------------- |
@@ -561,6 +567,37 @@ Append a single track to the end of the playlist.
561
567
  --------------------
562
568
 
563
569
 
570
+ ### moveItem(...)
571
+
572
+ ```typescript
573
+ moveItem(options: MoveItemOptions) => Promise<void>
574
+ ```
575
+
576
+ Move a track from one index to another without restarting the current track.
577
+
578
+ | Param | Type |
579
+ | ------------- | ----------------------------------------------------------- |
580
+ | **`options`** | <code><a href="#moveitemoptions">MoveItemOptions</a></code> |
581
+
582
+ --------------------
583
+
584
+
585
+ ### replaceItem(...)
586
+
587
+ ```typescript
588
+ replaceItem(options: ReplaceItemOptions) => Promise<void>
589
+ ```
590
+
591
+ Replace a track's metadata and source URL in place (e.g. stream URL → local file).
592
+ When replacing the currently playing track, playback position and play/pause state are preserved.
593
+
594
+ | Param | Type |
595
+ | ------------- | ----------------------------------------------------------------- |
596
+ | **`options`** | <code><a href="#replaceitemoptions">ReplaceItemOptions</a></code> |
597
+
598
+ --------------------
599
+
600
+
564
601
  ### addAllItems(...)
565
602
 
566
603
  ```typescript
@@ -1035,9 +1072,27 @@ that were in the previous list.
1035
1072
 
1036
1073
  #### AddItemOptions
1037
1074
 
1038
- | Prop | Type |
1039
- | ---------- | ------------------------------------------------- |
1040
- | **`item`** | <code><a href="#audiotrack">AudioTrack</a></code> |
1075
+ | Prop | Type | Description |
1076
+ | ----------- | ------------------------------------------------- | ------------------------------------------- |
1077
+ | **`item`** | <code><a href="#audiotrack">AudioTrack</a></code> | |
1078
+ | **`index`** | <code>number</code> | 0-based index to insert at. Omit to append. |
1079
+
1080
+
1081
+ #### MoveItemOptions
1082
+
1083
+ | Prop | Type | Description |
1084
+ | ---------- | ------------------- | ------------------------------------------ |
1085
+ | **`from`** | <code>number</code> | Source index (0-based). |
1086
+ | **`to`** | <code>number</code> | Destination index (0-based) after removal. |
1087
+
1088
+
1089
+ #### ReplaceItemOptions
1090
+
1091
+ | Prop | Type | Description |
1092
+ | ----------- | ------------------------------------------------- | -------------------------------------------------------------------------- |
1093
+ | **`item`** | <code><a href="#audiotrack">AudioTrack</a></code> | Replacement track data. When `trackId` is omitted the existing id is kept. |
1094
+ | **`index`** | <code>number</code> | Index of the track to replace (preferred over `id`). |
1095
+ | **`id`** | <code>string</code> | Id of the track to replace. |
1041
1096
 
1042
1097
 
1043
1098
  #### AddAllItemOptions
@@ -1189,6 +1244,8 @@ that were in the previous list.
1189
1244
  | **`RMXSTATUS_PLAYLIST_COMPLETED`** | <code>105</code> | The entire playlist has completed playback. After this event has been raised, the current item is set to null and the current index to -1. |
1190
1245
  | **`RMXSTATUS_ITEM_ADDED`** | <code>110</code> | An item has been added to the playlist. For the setPlaylistItems and addAllItems methods, this status is raised once for every track in the collection. |
1191
1246
  | **`RMXSTATUS_ITEM_REMOVED`** | <code>115</code> | An item has been removed from the playlist. For the removeItems and clearAllItems methods, this status is raised once for every track that was removed. |
1247
+ | **`RMXSTATUS_ITEM_MOVED`** | <code>112</code> | An item has been moved within the playlist. |
1248
+ | **`RMXSTATUS_ITEM_REPLACED`** | <code>113</code> | An item in the playlist has been replaced in place. |
1192
1249
  | **`RMXSTATUS_PLAYLIST_CLEARED`** | <code>120</code> | All items have been removed from the playlist |
1193
1250
  | **`RMXSTATUS_VIEWDISAPPEAR`** | <code>200</code> | Just for testing.. you don't need this and in fact can never receive it, the plugin is destroyed before it can be raised. |
1194
1251
 
@@ -1,9 +1,27 @@
1
+ // Consuming Capacitor apps normally supply the Android/Kotlin Gradle plugin classpath from
2
+ // their own root build.gradle. This buildscript block is only needed to run `./gradlew test`
3
+ // standalone from this module (e.g. `npm run verify:android`); it is additive to this
4
+ // subproject's own build-script classpath and does not affect a parent app's configuration.
5
+ buildscript {
6
+ repositories {
7
+ google()
8
+ mavenCentral()
9
+ }
10
+ dependencies {
11
+ classpath 'com.android.tools.build:gradle:8.13.0'
12
+ classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.0'
13
+ }
14
+ }
15
+
1
16
  import org.jetbrains.kotlin.gradle.dsl.JvmTarget
2
17
 
3
18
  ext {
4
19
  junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'
5
20
  androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.3.0'
6
21
  androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.7.0'
22
+ // Only used when this module is built standalone (e.g. `npm run verify:android`); when
23
+ // embedded, the consuming app's root build.gradle already sets rootProject.ext.kotlin_version.
24
+ kotlin_version = project.hasProperty('kotlinVersion') ? rootProject.ext.kotlinVersion : '2.1.0'
7
25
  }
8
26
 
9
27
  apply plugin: 'com.android.library'
@@ -50,6 +68,9 @@ dependencies {
50
68
  implementation fileTree(dir: 'libs', include: ['*.jar'])
51
69
  implementation project(':capacitor-android')
52
70
  testImplementation "junit:junit:$junitVersion"
71
+ // Real org.json implementation for plain JVM unit tests: the android.jar stub used for
72
+ // compilation throws "Stub!" for org.json.* at runtime outside instrumented/Robolectric tests.
73
+ testImplementation "org.json:json:20231013"
53
74
  androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
54
75
  androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
55
76
  implementation "androidx.core:core-ktx:1.17.0"
@@ -1,4 +1,13 @@
1
1
 
2
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3
- >
2
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
3
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
4
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
5
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
6
+
7
+ <application>
8
+ <service
9
+ android:name="org.dwbn.plugins.playlist.service.MediaService"
10
+ android:exported="false"
11
+ android:foregroundServiceType="mediaPlayback" />
12
+ </application>
4
13
  </manifest>
@@ -1,19 +1,6 @@
1
1
  package org.dwbn.plugins.playlist
2
2
 
3
3
  import android.app.Application
4
- import org.dwbn.plugins.playlist.manager.PlaylistManager
5
4
 
6
- class App : Application() {
7
- private lateinit var _playlistManager: PlaylistManager;
8
- val playlistManager get() = _playlistManager
9
-
10
- fun resetPlaylistManager() {
11
- _playlistManager = PlaylistManager(this)
12
- }
13
-
14
- override fun onCreate() {
15
- resetPlaylistManager()
16
- super.onCreate()
17
-
18
- }
19
- }
5
+ @Deprecated("No longer required; use your app's existing Application class")
6
+ class App : Application()
@@ -22,7 +22,7 @@ public class PlaylistPlugin : Plugin(), OnStatusReportListener {
22
22
  private var isWebViewActive = true
23
23
 
24
24
  override fun load() {
25
- audioPlayerImpl = RmxAudioPlayer(this, (this.context.applicationContext as App))
25
+ audioPlayerImpl = RmxAudioPlayer(this, context.applicationContext)
26
26
  }
27
27
 
28
28
  @PluginMethod
@@ -97,15 +97,19 @@ public class PlaylistPlugin : Plugin(), OnStatusReportListener {
97
97
  fun addItem(call: PluginCall) {
98
98
  Handler(Looper.getMainLooper()).post {
99
99
  val item: JSONObject = call.getObject("item")
100
+ val index: Int = call.getInt("index", -1)!!
100
101
  val playerItem: AudioTrack? = getTrackItem(item)
101
- audioPlayerImpl!!.getPlaylistManager().addItem(playerItem)
102
-
102
+ audioPlayerImpl!!.getPlaylistManager().addItem(playerItem, index)
103
103
 
104
104
  if (playerItem?.trackId != null) {
105
+ val payload = playerItem.toDict()
106
+ if (index >= 0) {
107
+ payload.put("index", index.coerceIn(0, audioPlayerImpl!!.playlistManager.getAllItems().size - 1))
108
+ }
105
109
  onStatus(
106
110
  RmxAudioStatusMessage.RMXSTATUS_ITEM_ADDED,
107
111
  playerItem.trackId,
108
- playerItem.toDict()
112
+ payload
109
113
  )
110
114
  }
111
115
  call.resolve()
@@ -113,6 +117,56 @@ public class PlaylistPlugin : Plugin(), OnStatusReportListener {
113
117
  }
114
118
  }
115
119
 
120
+ @PluginMethod
121
+ fun moveItem(call: PluginCall) {
122
+ Handler(Looper.getMainLooper()).post {
123
+ val from: Int = call.getInt("from", -1)!!
124
+ val to: Int = call.getInt("to", -1)!!
125
+ val moved = audioPlayerImpl!!.playlistManager.moveItem(from, to)
126
+ if (!moved) {
127
+ call.reject("Index out of bounds")
128
+ return@post
129
+ }
130
+
131
+ val payload = JSONObject()
132
+ payload.put("from", from)
133
+ payload.put("to", to)
134
+ payload.put("currentIndex", audioPlayerImpl!!.playlistManager.currentPosition)
135
+ onStatus(
136
+ RmxAudioStatusMessage.RMXSTATUS_ITEM_MOVED,
137
+ audioPlayerImpl!!.playlistManager.currentItem?.trackId ?: "INVALID",
138
+ payload
139
+ )
140
+ call.resolve()
141
+ Log.i(TAG, "moveItem from=$from to=$to")
142
+ }
143
+ }
144
+
145
+ @PluginMethod
146
+ fun replaceItem(call: PluginCall) {
147
+ Handler(Looper.getMainLooper()).post {
148
+ val trackIndex: Int = call.getInt("index", -1)!!
149
+ val trackId: String = call.getString("id", "")!!
150
+ val item: JSONObject = call.getObject("item")
151
+ // An omitted trackId in the payload intentionally means "keep the existing id",
152
+ // so this must not be rejected the way a brand-new addItem() track would be.
153
+ val replacement: AudioTrack? = getTrackItem(item, requireTrackId = false)
154
+ val replaced = audioPlayerImpl!!.playlistManager.replaceItem(trackIndex, trackId, replacement)
155
+
156
+ if (replaced != null) {
157
+ onStatus(
158
+ RmxAudioStatusMessage.RMXSTATUS_ITEM_REPLACED,
159
+ replaced.trackId,
160
+ replaced.toDict()
161
+ )
162
+ call.resolve()
163
+ } else {
164
+ call.reject("Could not find item!")
165
+ }
166
+ Log.i(TAG, "replaceItem")
167
+ }
168
+ }
169
+
116
170
  @PluginMethod
117
171
  fun addAllItems(call: PluginCall) {
118
172
  Handler(Looper.getMainLooper()).post {
@@ -475,10 +529,10 @@ public class PlaylistPlugin : Plugin(), OnStatusReportListener {
475
529
  audioPlayerImpl!!.playlistManager.clearItems()
476
530
  }
477
531
 
478
- private fun getTrackItem(item: JSONObject?): AudioTrack? {
532
+ private fun getTrackItem(item: JSONObject?, requireTrackId: Boolean = true): AudioTrack? {
479
533
  if (item != null) {
480
534
  val track = AudioTrack(item)
481
- return if (track.trackId != null) {
535
+ return if (!requireTrackId || track.trackId != null) {
482
536
  track
483
537
  } else null
484
538
  }
@@ -0,0 +1,16 @@
1
+ package org.dwbn.plugins.playlist
2
+
3
+ import android.app.Application
4
+ import android.content.Context
5
+ import org.dwbn.plugins.playlist.manager.PlaylistManager
6
+
7
+ object PlaylistRuntime {
8
+ private var playlistManager: PlaylistManager? = null
9
+
10
+ @JvmStatic
11
+ fun getPlaylistManager(context: Context): PlaylistManager = synchronized(this) {
12
+ playlistManager ?: PlaylistManager(context.applicationContext as Application).also {
13
+ playlistManager = it
14
+ }
15
+ }
16
+ }
@@ -1,5 +1,6 @@
1
1
  package org.dwbn.plugins.playlist;
2
2
 
3
+ import android.content.Context;
3
4
  import android.util.Log;
4
5
 
5
6
  import androidx.annotation.NonNull;
@@ -39,16 +40,16 @@ public class RmxAudioPlayer implements PlaybackStatusListener<AudioTrack>,
39
40
  // It would be used to switch between playlists. I guess we could
40
41
  // support that in the future, might be cool.
41
42
  private static final int PLAYLIST_ID = 32;
42
- private PlaylistManager playlistManager;
43
+ private final PlaylistManager playlistManager;
43
44
  private final OnStatusReportListener statusListener;
44
45
 
45
46
  private int lastBufferPercent = 0;
46
47
  private long lastDuration = 0;
47
48
  private boolean trackLoaded = false;
48
49
  private boolean resetStreamOnPause = true;
49
- private final App app;
50
+ private final Context context;
50
51
 
51
- public RmxAudioPlayer(@NonNull OnStatusReportListener statusListener, App context) {
52
+ public RmxAudioPlayer(@NonNull OnStatusReportListener statusListener, @NonNull Context context) {
52
53
  // AudioPlayerPlugin and RmxAudioPlayer are separate classes in order to increase
53
54
  // the portability of this code.
54
55
  // Because AudioPlayerPlugin itself holds a strong reference to this class,
@@ -56,10 +57,9 @@ public class RmxAudioPlayer implements PlaybackStatusListener<AudioTrack>,
56
57
  // but these two objects will always live together (And the plugin couldn't function
57
58
  // at all if this one gets garbage collected).
58
59
  this.statusListener = statusListener;
59
- this.app = context;
60
+ this.context = context.getApplicationContext();
61
+ this.playlistManager = PlaylistRuntime.getPlaylistManager(this.context);
60
62
 
61
- app.resetPlaylistManager();
62
- getPlaylistManager();
63
63
  playlistManager.setId(PLAYLIST_ID);
64
64
  playlistManager.setPlaybackStatusListener(this);
65
65
  playlistManager.setOnErrorListener(this);
@@ -67,7 +67,6 @@ public class RmxAudioPlayer implements PlaybackStatusListener<AudioTrack>,
67
67
  }
68
68
 
69
69
  public PlaylistManager getPlaylistManager() {
70
- playlistManager = app.getPlaylistManager();
71
70
  return playlistManager;
72
71
  }
73
72
 
@@ -81,7 +80,7 @@ public class RmxAudioPlayer implements PlaybackStatusListener<AudioTrack>,
81
80
  }
82
81
 
83
82
  public void setOptions(JSONObject val) {
84
- Options options = new Options(app, val);
83
+ Options options = new Options(context, val);
85
84
  getPlaylistManager().setOptions(options);
86
85
  }
87
86
 
@@ -412,7 +411,6 @@ public class RmxAudioPlayer implements PlaybackStatusListener<AudioTrack>,
412
411
 
413
412
  public void resume() {
414
413
  Log.i(TAG, "Resumed, wiring up event listeners");
415
- getPlaylistManager();
416
414
  registerPlaylistListeners();
417
415
  //Makes sure to retrieve the current playback information
418
416
  updateCurrentPlaybackInformation();
@@ -24,6 +24,8 @@ public enum RmxAudioStatusMessage {
24
24
  RMXSTATUS_TRACK_CHANGED(100),
25
25
  RMXSTATUS_PLAYLIST_COMPLETED(105),
26
26
  RMXSTATUS_ITEM_ADDED(110),
27
+ RMXSTATUS_ITEM_MOVED(112),
28
+ RMXSTATUS_ITEM_REPLACED(113),
27
29
  RMXSTATUS_ITEM_REMOVED(115),
28
30
  RMXSTATUS_PLAYLIST_CLEARED(120),
29
31
 
@@ -135,22 +135,89 @@ class PlaylistManager(application: Application) :
135
135
  beginPlayback(seekStart, options.startPaused)
136
136
  }
137
137
 
138
- fun addItem(item: AudioTrack?) {
138
+ fun addItem(item: AudioTrack?, index: Int = -1) {
139
139
  if (item == null) {
140
140
  return
141
141
  }
142
- val countBefore = audioTracks.size;
143
- audioTracks.add(item)
142
+ val countBefore = audioTracks.size
143
+ val insertIndex = if (index >= 0) {
144
+ index.coerceIn(0, audioTracks.size)
145
+ } else {
146
+ audioTracks.size
147
+ }
148
+
149
+ if (insertIndex >= audioTracks.size) {
150
+ audioTracks.add(item)
151
+ } else {
152
+ audioTracks.add(insertIndex, item)
153
+ if (currentPosition >= insertIndex && currentPosition != INVALID_POSITION) {
154
+ currentPosition++
155
+ }
156
+ }
144
157
  items = audioTracks
158
+
145
159
  if (countBefore == 0) {
146
160
  currentPosition = 0
147
161
  beginPlayback(1, true)
162
+ } else if (this.playlistHandler != null) {
163
+ this.playlistHandler!!.updateMediaControls()
164
+ }
165
+ }
166
+
167
+ fun moveItem(from: Int, to: Int): Boolean {
168
+ if (from < 0 || from >= audioTracks.size || to < 0 || to >= audioTracks.size) {
169
+ return false
148
170
  }
171
+ if (from == to) {
172
+ return true
173
+ }
174
+
175
+ val item = audioTracks.removeAt(from)
176
+ audioTracks.add(to, item)
177
+ items = audioTracks
178
+
179
+ currentPosition = adjustCurrentIndexForMove(currentPosition, from, to, INVALID_POSITION)
180
+
149
181
  if (this.playlistHandler != null) {
150
182
  this.playlistHandler!!.updateMediaControls()
151
183
  }
184
+ return true
185
+ }
186
+
187
+ fun replaceItem(index: Int, itemId: String, replacement: AudioTrack?): AudioTrack? {
188
+ if (replacement == null) {
189
+ return null
190
+ }
191
+ val resolvedIndex = resolveItemPosition(index, itemId)
192
+ if (resolvedIndex < 0 || resolvedIndex >= audioTracks.size) {
193
+ return null
194
+ }
195
+
196
+ val existing = audioTracks[resolvedIndex]
197
+ val resolvedReplacement = mergeReplacementTrackId(existing, replacement)
198
+
199
+ val isCurrent = existing == currentItem
200
+ val wasPlaying = isPlaying
201
+ val progress = currentProgress
202
+ val seekPosition: Long = if (progress != null) progress.position else 0
203
+
204
+ if (isCurrent && playlistHandler != null) {
205
+ playlistHandler!!.pause(true)
206
+ }
207
+
208
+ audioTracks[resolvedIndex] = resolvedReplacement
209
+ items = audioTracks
210
+
211
+ if (isCurrent) {
212
+ beginPlayback(seekPosition, !wasPlaying)
213
+ } else if (this.playlistHandler != null) {
214
+ this.playlistHandler!!.updateMediaControls()
215
+ }
216
+
217
+ return resolvedReplacement
152
218
  }
153
219
 
220
+
154
221
  fun addAllItems(its: List<AudioTrack>?) {
155
222
  val currentItem = currentItem // may be null
156
223
  audioTracks.addAll(its.orEmpty())
@@ -308,6 +375,41 @@ class PlaylistManager(application: Application) :
308
375
 
309
376
  companion object {
310
377
  private const val TAG = "PlaylistManager"
378
+
379
+ /**
380
+ * Computes the new position of the "current" item after moving an item from index
381
+ * [from] to index [to] (post-removal insertion semantics, i.e. matching
382
+ * `MutableList.removeAt(from)` followed by `MutableList.add(to, item)`).
383
+ *
384
+ * Pure function so it can be unit-tested without an Android/Application context.
385
+ */
386
+ @JvmStatic
387
+ fun adjustCurrentIndexForMove(currentIndex: Int, from: Int, to: Int, invalidPosition: Int): Int {
388
+ if (currentIndex == invalidPosition) {
389
+ return currentIndex
390
+ }
391
+ if (from == currentIndex) {
392
+ return to
393
+ }
394
+ val mid = if (from < currentIndex) currentIndex - 1 else currentIndex
395
+ return if (mid >= to) mid + 1 else mid
396
+ }
397
+
398
+ /**
399
+ * Builds the [AudioTrack] that should replace [existing], backfilling `trackId` from
400
+ * [existing] when [replacement] doesn't specify one (an omitted id signals "keep the
401
+ * existing id" rather than "generate a new one").
402
+ *
403
+ * Pure function so it can be unit-tested without an Android/Application context.
404
+ */
405
+ @JvmStatic
406
+ fun mergeReplacementTrackId(existing: AudioTrack, replacement: AudioTrack): AudioTrack {
407
+ val replacementConfig = replacement.toDict()
408
+ if (replacement.trackId.isNullOrEmpty() && existing.trackId != null) {
409
+ replacementConfig.put("trackId", existing.trackId)
410
+ }
411
+ return AudioTrack(replacementConfig)
412
+ }
311
413
  }
312
414
 
313
415
  init {
@@ -8,7 +8,7 @@ import android.os.Build
8
8
  import android.util.Log
9
9
  import com.devbrackets.android.playlistcore.components.playlisthandler.PlaylistHandler
10
10
  import com.devbrackets.android.playlistcore.service.BasePlaylistService
11
- import org.dwbn.plugins.playlist.App
11
+ import org.dwbn.plugins.playlist.PlaylistRuntime
12
12
  import org.dwbn.plugins.playlist.data.AudioTrack
13
13
  import org.dwbn.plugins.playlist.manager.PlaylistManager
14
14
  import org.dwbn.plugins.playlist.playlist.AudioApi
@@ -97,7 +97,7 @@ class MediaService : BasePlaylistService<AudioTrack, PlaylistManager>() {
97
97
  fun isRunningInForeground(): Boolean = inForeground
98
98
 
99
99
  override val playlistManager: PlaylistManager
100
- get() = (applicationContext as App).playlistManager
100
+ get() = PlaylistRuntime.getPlaylistManager(applicationContext)
101
101
 
102
102
  override fun newPlaylistHandler(): PlaylistHandler<AudioTrack> {
103
103
  val imageProvider = MediaImageProvider(applicationContext, object : OnImageUpdatedListener {
@@ -0,0 +1,76 @@
1
+ package org.dwbn.plugins.playlist.manager
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Test
5
+
6
+ /**
7
+ * Regression coverage for the currentPosition arithmetic used by [PlaylistManager.moveItem].
8
+ * Verified against a brute-force ground truth (simulate removeAt(from)+add(to,item) on a real
9
+ * list and look up the moved-tracked item's resulting index) for lists of size 2..6 and every
10
+ * valid (from, to, currentIndex) combination.
11
+ */
12
+ class PlaylistManagerMoveTest {
13
+
14
+ private val invalid = -1
15
+
16
+ @Test
17
+ fun currentItem_isTheOneMoved_returnsDestinationIndex() {
18
+ assertEquals(2, PlaylistManager.adjustCurrentIndexForMove(0, 0, 2, invalid))
19
+ assertEquals(0, PlaylistManager.adjustCurrentIndexForMove(3, 3, 0, invalid))
20
+ }
21
+
22
+ @Test
23
+ fun invalidPosition_isReturnedUnchanged() {
24
+ assertEquals(invalid, PlaylistManager.adjustCurrentIndexForMove(invalid, 0, 2, invalid))
25
+ }
26
+
27
+ @Test
28
+ fun movingItemFromBeforeCurrent_toAtOrBeforeCurrent_shiftsCurrentLeft() {
29
+ // list [a,b,c,d], current = b (index 1), move a(0) -> 1: [b,a,c,d]; b is now at 0.
30
+ assertEquals(0, PlaylistManager.adjustCurrentIndexForMove(1, 0, 1, invalid))
31
+ }
32
+
33
+ @Test
34
+ fun movingItemFromBeforeCurrent_toAfterCurrent_leavesCurrentUnchanged() {
35
+ // list [a,b,c,d], current = b (index 1), move a(0) -> 3: [b,c,d,a]; b stays at 0.
36
+ assertEquals(0, PlaylistManager.adjustCurrentIndexForMove(1, 0, 3, invalid))
37
+ }
38
+
39
+ @Test
40
+ fun movingItemFromAfterCurrent_toAtOrBeforeCurrent_shiftsCurrentRight() {
41
+ // list [a,b,c,d], current = a (index 0), move c(2) -> 0: [c,a,b,d]; a is now at 1.
42
+ assertEquals(1, PlaylistManager.adjustCurrentIndexForMove(0, 2, 0, invalid))
43
+ }
44
+
45
+ @Test
46
+ fun movingItemFromAfterCurrent_toAfterCurrent_leavesCurrentUnchanged() {
47
+ // list [a,b,c,d], current = a (index 0), move c(2) -> 3: [a,b,d,c]; a stays at 0.
48
+ assertEquals(0, PlaylistManager.adjustCurrentIndexForMove(0, 2, 3, invalid))
49
+ }
50
+
51
+ @Test
52
+ fun bruteForce_matchesGroundTruthForAllCombinations() {
53
+ for (n in 2..6) {
54
+ val base = (0 until n).toList()
55
+ for (from in 0 until n) {
56
+ for (to in 0 until n) {
57
+ if (from == to) continue
58
+ val expectedArr = base.toMutableList()
59
+ val moved = expectedArr.removeAt(from)
60
+ expectedArr.add(to, moved)
61
+
62
+ for (currentIndex in 0 until n) {
63
+ val trackedId = base[currentIndex]
64
+ val expectedNewIndex = expectedArr.indexOf(trackedId)
65
+ val got = PlaylistManager.adjustCurrentIndexForMove(currentIndex, from, to, invalid)
66
+ assertEquals(
67
+ "n=$n from=$from to=$to currentIndex=$currentIndex",
68
+ expectedNewIndex,
69
+ got
70
+ )
71
+ }
72
+ }
73
+ }
74
+ }
75
+ }
76
+ }