Skip to content

Commit

Permalink
playlists: stricter checks when moving playlist items (#399)
Browse files Browse the repository at this point in the history
  • Loading branch information
goto-bus-stop authored Aug 7, 2020
1 parent 1e96748 commit f9e1f33
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
7 changes: 6 additions & 1 deletion src/models/Playlist.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ function playlistModel() {
},
shared: { type: Boolean, default: false },
nsfw: { type: Boolean, default: false },
media: [{ type: Types.ObjectId, ref: 'PlaylistItem', index: true }],
media: [{
type: Types.ObjectId,
ref: 'PlaylistItem',
required: true,
index: true,
}],
}, {
collection: 'playlists',
timestamps: true,
Expand Down
12 changes: 8 additions & 4 deletions src/plugins/playlists.js
Original file line number Diff line number Diff line change
Expand Up @@ -453,12 +453,16 @@ class PlaylistsRepository {
async movePlaylistItems(playlistOrID, itemIDs, { afterID }) {
const playlist = await this.getPlaylist(playlistOrID);

// Create a plain array instead of a mongoose array because it crashes on splice()
// otherwise.
const newMedia = [...playlist.media].filter((item) => !itemIDs.includes(`${item}`));
// Use a plain array instead of a mongoose array because we need `splice()`.
const itemsInPlaylist = [...playlist.media];
const itemIDsInPlaylist = new Set(itemsInPlaylist.map((item) => `${item}`));
// Only attempt to move items that are actually in the playlist.
const itemIDsToInsert = itemIDs.filter((id) => itemIDsInPlaylist.has(`${id}`));

const newMedia = itemsInPlaylist.filter((item) => !itemIDsToInsert.includes(`${item}`));
// Reinsert items at their new position.
const insertIndex = newMedia.findIndex((item) => `${item}` === afterID);
newMedia.splice(insertIndex + 1, 0, ...itemIDs);
newMedia.splice(insertIndex + 1, 0, ...itemIDsToInsert);
playlist.media = newMedia;

await playlist.save();
Expand Down

0 comments on commit f9e1f33

Please sign in to comment.