| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142 | import async from "async";import CoreClass from "../core";let PlaylistsModule;let StationsModule;let SongsModule;let CacheModule;let DBModule;let UtilsModule;class _PlaylistsModule extends CoreClass {	// eslint-disable-next-line require-jsdoc	constructor() {		super("playlists");		PlaylistsModule = this;	}	/**	 * Initialises the playlists module	 *	 * @returns {Promise} - returns promise (reject, resolve)	 */	async initialize() {		this.setStage(1);		StationsModule = this.moduleManager.modules.stations;		CacheModule = this.moduleManager.modules.cache;		DBModule = this.moduleManager.modules.db;		UtilsModule = this.moduleManager.modules.utils;		SongsModule = this.moduleManager.modules.songs;		this.playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" });		this.playlistSchemaCache = await CacheModule.runJob("GET_SCHEMA", { schemaName: "playlist" });		this.setStage(2);		return new Promise((resolve, reject) => {			async.waterfall(				[					next => {						this.setStage(3);						CacheModule.runJob("HGETALL", { table: "playlists" })							.then(playlists => {								next(null, playlists);							})							.catch(next);					},					(playlists, next) => {						this.setStage(4);						if (!playlists) return next();						const playlistIds = Object.keys(playlists);						return async.each(							playlistIds,							(playlistId, next) => {								PlaylistsModule.playlistModel.findOne({ _id: playlistId }, (err, playlist) => {									if (err) next(err);									else if (!playlist) {										CacheModule.runJob("HDEL", {											table: "playlists",											key: playlistId										})											.then(() => next())											.catch(next);									} else next();								});							},							next						);					},					next => {						this.setStage(5);						PlaylistsModule.playlistModel.find({}, next);					},					(playlists, next) => {						this.setStage(6);						async.each(							playlists,							(playlist, cb) => {								CacheModule.runJob("HSET", {									table: "playlists",									key: playlist._id,									value: PlaylistsModule.playlistSchemaCache(playlist)								})									.then(() => cb())									.catch(next);							},							next						);					}				],				async err => {					if (err) {						const formattedErr = await UtilsModule.runJob("GET_ERROR", {							error: err						});						reject(new Error(formattedErr));					} else {						resolve();					}				}			);		});	}	/**	 * Returns a list of playlists that include a specific song	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.songId - the song id	 * @param {string} payload.includeSongs - include the songs	 * @returns {Promise} - returns promise (reject, resolve)	 */	GET_PLAYLISTS_WITH_SONG(payload) {		return new Promise((resolve, reject) => {			const includeObject = payload.includeSongs ? null : { songs: false };			PlaylistsModule.playlistModel.find({ "songs._id": payload.songId }, includeObject, (err, playlists) => {				if (err) reject(err);				else resolve({ playlists });			});		});	}	/**	 * Creates a playlist owned by a user	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.userId - the id of the user to create the playlist for	 * @param {string} payload.displayName - the display name of the playlist	 * @param {string} payload.type - the type of the playlist	 * @returns {Promise} - returns promise (reject, resolve)	 */	CREATE_USER_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			PlaylistsModule.playlistModel.create(				{					displayName: payload.displayName,					songs: [],					createdBy: payload.userId,					createdAt: Date.now(),					createdFor: null,					type: payload.type				},				(err, playlist) => {					if (err) return reject(new Error(err));					return resolve(playlist._id);				}			);		});	}	/**	 * Creates a playlist that contains all songs of a specific genre	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.genre - the genre	 * @returns {Promise} - returns promise (reject, resolve)	 */	CREATE_GENRE_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre: payload.genre.toLowerCase() }, this)				.then(() => {					reject(new Error("Playlist already exists"));				})				.catch(err => {					if (err.message === "Playlist not found") {						PlaylistsModule.playlistModel.create(							{								displayName: `Genre - ${payload.genre}`,								songs: [],								createdBy: "Musare",								createdFor: `${payload.genre.toLowerCase()}`,								createdAt: Date.now(),								type: "genre"							},							(err, playlist) => {								if (err) return reject(new Error(err));								return resolve(playlist._id);							}						);					} else reject(new Error(err));				});		});	}	/**	 * Gets all genre playlists	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.includeSongs - include the songs	 * @returns {Promise} - returns promise (reject, resolve)	 */	GET_ALL_GENRE_PLAYLISTS(payload) {		return new Promise((resolve, reject) => {			const includeObject = payload.includeSongs ? null : { songs: false };			PlaylistsModule.playlistModel.find({ type: "genre" }, includeObject, (err, playlists) => {				if (err) reject(new Error(err));				else resolve({ playlists });			});		});	}	/**	 * Gets all station playlists	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.includeSongs - include the songs	 * @returns {Promise} - returns promise (reject, resolve)	 */	GET_ALL_STATION_PLAYLISTS(payload) {		return new Promise((resolve, reject) => {			const includeObject = payload.includeSongs ? null : { songs: false };			PlaylistsModule.playlistModel.find({ type: "station" }, includeObject, (err, playlists) => {				if (err) reject(new Error(err));				else resolve({ playlists });			});		});	}	/**	 * Gets a genre playlist	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.genre - the genre	 * @param {string} payload.includeSongs - include the songs	 * @returns {Promise} - returns promise (reject, resolve)	 */	GET_GENRE_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			const includeObject = payload.includeSongs ? null : { songs: false };			PlaylistsModule.playlistModel.findOne(				{ type: "genre", createdFor: payload.genre },				includeObject,				(err, playlist) => {					if (err) reject(new Error(err));					else if (!playlist) reject(new Error("Playlist not found"));					else resolve({ playlist });				}			);		});	}	/**	 * Gets all missing genre playlists	 *	 * @returns {Promise} - returns promise (reject, resolve)	 */	GET_MISSING_GENRE_PLAYLISTS() {		return new Promise((resolve, reject) => {			SongsModule.runJob("GET_ALL_GENRES", {}, this)				.then(response => {					const { genres } = response;					const missingGenres = [];					async.eachLimit(						genres,						1,						(genre, next) => {							PlaylistsModule.runJob(								"GET_GENRE_PLAYLIST",								{ genre: genre.toLowerCase(), includeSongs: false },								this							)								.then(() => {									next();								})								.catch(err => {									if (err.message === "Playlist not found") {										missingGenres.push(genre);										next();									} else next(err);								});						},						err => {							if (err) reject(err);							else resolve({ genres: missingGenres });						}					);				})				.catch(err => {					reject(err);				});		});	}	/**	 * Creates all missing genre playlists	 *	 * @returns {Promise} - returns promise (reject, resolve)	 */	CREATE_MISSING_GENRE_PLAYLISTS() {		return new Promise((resolve, reject) => {			PlaylistsModule.runJob("GET_MISSING_GENRE_PLAYLISTS", {}, this)				.then(response => {					const { genres } = response;					async.eachLimit(						genres,						1,						(genre, next) => {							PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre }, this)								.then(() => {									next();								})								.catch(err => {									next(err);								});						},						err => {							if (err) reject(err);							else resolve();						}					);				})				.catch(err => {					reject(err);				});		});	}	/**	 * Gets a station playlist	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.staationId - the station id	 * @param {string} payload.includeSongs - include the songs	 * @returns {Promise} - returns promise (reject, resolve)	 */	GET_STATION_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			const includeObject = payload.includeSongs ? null : { songs: false };			PlaylistsModule.playlistModel.findOne(				{ type: "station", createdFor: payload.stationId },				includeObject,				(err, playlist) => {					if (err) reject(new Error(err));					else if (!playlist) reject(new Error("Playlist not found"));					else resolve({ playlist });				}			);		});	}	/**	 * Adds a song to a playlist	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.playlistId - the playlist id	 * @param {string} payload.song - the song	 * @returns {Promise} - returns promise (reject, resolve)	 */	ADD_SONG_TO_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			const { _id, youtubeId, title, artists, thumbnail, duration, verified } = payload.song;			const trimmedSong = {				_id,				youtubeId,				title,				artists,				thumbnail,				duration,				verified			};			PlaylistsModule.playlistModel.updateOne(				{ _id: payload.playlistId },				{ $push: { songs: trimmedSong } },				{ runValidators: true },				err => {					if (err) reject(new Error(err));					else {						PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)							.then(() => resolve())							.catch(err => {								reject(new Error(err));							});					}				}			);		});	}	/**	 * Deletes a song from a playlist based on the youtube id	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.playlistId - the playlist id	 * @param {string} payload.youtubeId - the youtube id	 * @returns {Promise} - returns promise (reject, resolve)	 */	DELETE_SONG_FROM_PLAYLIST_BY_YOUTUBE_ID(payload) {		return new Promise((resolve, reject) => {			PlaylistsModule.playlistModel.updateOne(				{ _id: payload.playlistId },				{ $pull: { songs: { youtubeId: payload.youtubeId } } },				err => {					if (err) reject(new Error(err));					else {						PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: payload.playlistId }, this)							.then(() => resolve())							.catch(err => {								reject(new Error(err));							});					}				}			);		});	}	/**	 * Fills a genre playlist with songs	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.genre - the genre	 * @returns {Promise} - returns promise (reject, resolve)	 */	AUTOFILL_GENRE_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			async.waterfall(				[					next => {						PlaylistsModule.runJob(							"GET_GENRE_PLAYLIST",							{ genre: payload.genre.toLowerCase(), includeSongs: true },							this						)							.then(response => {								next(null, response.playlist._id);							})							.catch(err => {								if (err.message === "Playlist not found") {									PlaylistsModule.runJob("CREATE_GENRE_PLAYLIST", { genre: payload.genre }, this)										.then(playlistId => {											next(null, playlistId);										})										.catch(err => {											next(err);										});								} else next(err);							});					},					(playlistId, next) => {						SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: payload.genre }, this)							.then(response => {								next(null, playlistId, response.songs);							})							.catch(err => {								console.log(err);								next(err);							});					},					(playlistId, _songs, next) => {						const songs = _songs.map(song => {							const { _id, youtubeId, title, artists, thumbnail, duration, verified } = song;							return {								_id,								youtubeId,								title,								artists,								thumbnail,								duration,								verified							};						});						PlaylistsModule.playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, err => {							next(err, playlistId);						});					},					(playlistId, next) => {						PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)							.then(() => {								next(null, playlistId);							})							.catch(next);					},					(playlistId, next) => {						StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId }, this)							.then(response => {								async.eachLimit(									response.stationIds,									1,									(stationId, next) => {										PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)											.then(() => {												next();											})											.catch(err => {												next(err);											});									},									err => {										if (err) next(err);										else next();									}								);							})							.catch(err => {								next(err);							});					}				],				err => {					if (err && err !== true) return reject(new Error(err));					return resolve({});				}			);		});	}	/**	 * Gets orphaned genre playlists	 *	 * @returns {Promise} - returns promise (reject, resolve)	 */	GET_ORPHANED_GENRE_PLAYLISTS() {		return new Promise((resolve, reject) => {			PlaylistsModule.playlistModel.find({ type: "genre" }, { songs: false }, (err, playlists) => {				if (err) reject(new Error(err));				else {					const orphanedPlaylists = [];					async.eachLimit(						playlists,						1,						(playlist, next) => {							SongsModule.runJob("GET_ALL_SONGS_WITH_GENRE", { genre: playlist.createdFor }, this)								.then(response => {									if (response.songs.length === 0) {										StationsModule.runJob(											"GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST",											{ playlistId: playlist._id },											this										)											.then(response => {												if (response.stationIds.length === 0) orphanedPlaylists.push(playlist);												next();											})											.catch(next);									} else next();								})								.catch(next);						},						err => {							if (err) reject(new Error(err));							else resolve({ playlists: orphanedPlaylists });						}					);				}			});		});	}	/**	 * Deletes all orphaned genre playlists	 *	 * @returns {Promise} - returns promise (reject, resolve)	 */	DELETE_ORPHANED_GENRE_PLAYLISTS() {		return new Promise((resolve, reject) => {			PlaylistsModule.runJob("GET_ORPHANED_GENRE_PLAYLISTS", {}, this)				.then(response => {					async.eachLimit(						response.playlists,						1,						(playlist, next) => {							PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)								.then(() => {									this.log("INFO", "Deleting orphaned genre playlist");									next();								})								.catch(err => {									next(err);								});						},						err => {							if (err) reject(new Error(err));							else resolve({});						}					);				})				.catch(err => {					reject(new Error(err));				});		});	}	/**	 * Gets a orphaned station playlists	 *	 * @returns {Promise} - returns promise (reject, resolve)	 */	GET_ORPHANED_STATION_PLAYLISTS() {		return new Promise((resolve, reject) => {			PlaylistsModule.playlistModel.find({ type: "station" }, { songs: false }, (err, playlists) => {				if (err) reject(new Error(err));				else {					const orphanedPlaylists = [];					async.eachLimit(						playlists,						1,						(playlist, next) => {							StationsModule.runJob("GET_STATION", { stationId: playlist.createdFor }, this)								.then(station => {									if (station.playlist !== playlist._id.toString()) {										orphanedPlaylists.push(playlist);									}									next();								})								.catch(err => {									if (err.message === "Station not found") {										orphanedPlaylists.push(playlist);										next();									} else next(err);								});						},						err => {							if (err) reject(new Error(err));							else resolve({ playlists: orphanedPlaylists });						}					);				}			});		});	}	/**	 * Deletes all orphaned station playlists	 *	 * @returns {Promise} - returns promise (reject, resolve)	 */	DELETE_ORPHANED_STATION_PLAYLISTS() {		return new Promise((resolve, reject) => {			PlaylistsModule.runJob("GET_ORPHANED_STATION_PLAYLISTS", {}, this)				.then(response => {					async.eachLimit(						response.playlists,						1,						(playlist, next) => {							PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: playlist._id }, this)								.then(() => {									this.log("INFO", "Deleting orphaned station playlist");									next();								})								.catch(err => {									next(err);								});						},						err => {							if (err) reject(new Error(err));							else resolve({});						}					);				})				.catch(err => {					reject(new Error(err));				});		});	}	/**	 * Fills a station playlist with songs	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.stationId - the station id	 * @returns {Promise} - returns promise (reject, resolve)	 */	AUTOFILL_STATION_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			let originalPlaylist = null;			async.waterfall(				[					next => {						if (!payload.stationId) next("Please specify a station id");						else next();					},					next => {						StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)							.then(station => {								next(null, station);							})							.catch(next);					},					(station, next) => {						PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: station.playlist }, this)							.then(playlist => {								originalPlaylist = playlist;								next(null, station);							})							.catch(err => {								next(err);							});					},					(station, next) => {						const includedPlaylists = [];						async.eachLimit(							station.includedPlaylists,							1,							(playlistId, next) => {								PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)									.then(playlist => {										includedPlaylists.push(playlist);										next();									})									.catch(next);							},							err => {								next(err, station, includedPlaylists);							}						);					},					(station, includedPlaylists, next) => {						const excludedPlaylists = [];						async.eachLimit(							station.excludedPlaylists,							1,							(playlistId, next) => {								PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)									.then(playlist => {										excludedPlaylists.push(playlist);										next();									})									.catch(next);							},							err => {								next(err, station, includedPlaylists, excludedPlaylists);							}						);					},					(station, includedPlaylists, excludedPlaylists, next) => {						const excludedSongs = excludedPlaylists							.flatMap(excludedPlaylist => excludedPlaylist.songs)							.reduce(								(items, item) =>									items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],								[]							);						const includedSongs = includedPlaylists							.flatMap(includedPlaylist => includedPlaylist.songs)							.reduce(								(songs, song) =>									songs.find(x => x.youtubeId === song.youtubeId) ? [...songs] : [...songs, song],								[]							)							.filter(song => !excludedSongs.find(x => x.youtubeId === song.youtubeId));						next(null, station, includedSongs);					},					(station, includedSongs, next) => {						PlaylistsModule.playlistModel.updateOne(							{ _id: station.playlist },							{ $set: { songs: includedSongs } },							err => {								next(err, includedSongs);							}						);					},					(includedSongs, next) => {						PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId: originalPlaylist._id }, this)							.then(() => {								next(null, includedSongs);							})							.catch(next);					},					(includedSongs, next) => {						if (originalPlaylist.songs.length === 0 && includedSongs.length > 0)							StationsModule.runJob("SKIP_STATION", { stationId: payload.stationId, natural: false });						next();					}				],				err => {					if (err && err !== true) return reject(new Error(err));					return resolve({});				}			);		});	}	/**	 * Gets a playlist by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.playlistId - the id of the playlist we are trying to get	 * @returns {Promise} - returns promise (reject, resolve)	 */	GET_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			async.waterfall(				[					next => {						CacheModule.runJob(							"HGET",							{								table: "playlists",								key: payload.playlistId							},							this						)							.then(playlist => next(null, playlist))							.catch(next);					},					(playlist, next) => {						if (playlist)							PlaylistsModule.playlistModel.exists({ _id: payload.playlistId }, (err, exists) => {								if (err) next(err);								else if (exists) next(null, playlist);								else {									CacheModule.runJob(										"HDEL",										{											table: "playlists",											key: payload.playlistId										},										this									)										.then(() => next())										.catch(next);								}							});						else PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);					},					(playlist, next) => {						if (playlist) {							CacheModule.runJob(								"HSET",								{									table: "playlists",									key: payload.playlistId,									value: playlist								},								this							)								.then(playlist => {									next(null, playlist);								})								.catch(next);						} else next("Playlist not found");					}				],				(err, playlist) => {					if (err && err !== true) return reject(new Error(err));					return resolve(playlist);				}			);		});	}	/**	 * Gets a playlist from id from Mongo and updates the cache with it	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.playlistId - the id of the playlist we are trying to update	 * @returns {Promise} - returns promise (reject, resolve)	 */	UPDATE_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			async.waterfall(				[					next => {						PlaylistsModule.playlistModel.findOne({ _id: payload.playlistId }, next);					},					(playlist, next) => {						if (!playlist) {							CacheModule.runJob("HDEL", {								table: "playlists",								key: payload.playlistId							});							return next("Playlist not found");						}						return CacheModule.runJob(							"HSET",							{								table: "playlists",								key: payload.playlistId,								value: playlist							},							this						)							.then(playlist => {								next(null, playlist);							})							.catch(next);					}				],				(err, playlist) => {					if (err && err !== true) return reject(new Error(err));					return resolve(playlist);				}			);		});	}	/**	 * Deletes playlist from id from Mongo and cache	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.playlistId - the id of the playlist we are trying to delete	 * @returns {Promise} - returns promise (reject, resolve)	 */	DELETE_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			async.waterfall(				[					next => {						PlaylistsModule.playlistModel.deleteOne({ _id: payload.playlistId }, next);					},					(res, next) => {						CacheModule.runJob(							"HDEL",							{								table: "playlists",								key: payload.playlistId							},							this						)							.then(() => next())							.catch(next);					},					next => {						StationsModule.runJob(							"REMOVE_INCLUDED_OR_EXCLUDED_PLAYLIST_FROM_STATIONS",							{ playlistId: payload.playlistId },							this						)							.then(() => {								next();							})							.catch(err => next(err));					}				],				err => {					if (err && err !== true) return reject(new Error(err));					return resolve();				}			);		});	}	/**	 * Searches through playlists	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.query - the query	 * @param {string} payload.includePrivate - include private playlists	 * @param {string} payload.includeStation - include station playlists	 * @param {string} payload.includeUser - include user playlists	 * @param {string} payload.includeGenre - include genre playlists	 * @param {string} payload.includeOwn - include own user playlists	 * @param {string} payload.userId - the user id of the person requesting	 * @param {string} payload.includeSongs - include songs	 * @param {string} payload.page - page (default 1)	 * @returns {Promise} - returns promise (reject, resolve)	 */	SEARCH(payload) {		return new Promise((resolve, reject) => {			async.waterfall(				[					next => {						const types = [];						if (payload.includeStation) types.push("station");						if (payload.includeUser) types.push("user");						if (payload.includeGenre) types.push("genre");						if (types.length === 0 && !payload.includeOwn) return next("No types have been included.");						const privacies = ["public"];						if (payload.includePrivate) privacies.push("private");						const includeObject = payload.includeSongs ? null : { songs: false };						const filterArray = [							{								displayName: new RegExp(`${payload.query}`, "i"),								privacy: { $in: privacies },								type: { $in: types }							}						];						if (payload.includeOwn && payload.userId)							filterArray.push({								displayName: new RegExp(`${payload.query}`, "i"),								type: "user",								createdBy: payload.userId							});						return next(null, filterArray, includeObject);					},					(filterArray, includeObject, next) => {						const page = payload.page ? payload.page : 1;						const pageSize = 15;						const skipAmount = pageSize * (page - 1);						PlaylistsModule.playlistModel.find({ $or: filterArray }).count((err, count) => {							if (err) next(err);							else {								PlaylistsModule.playlistModel									.find({ $or: filterArray }, includeObject)									.skip(skipAmount)									.limit(pageSize)									.exec((err, playlists) => {										if (err) next(err);										else {											next(null, {												playlists,												page,												pageSize,												skipAmount,												count											});										}									});							}						});					},					(data, next) => {						if (data.playlists.length > 0) next(null, data);						else next("No playlists found");					}				],				(err, data) => {					if (err && err !== true) return reject(new Error(err));					return resolve(data);				}			);		});	}	/**	 * Clears and refills a station playlist	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill	 * @returns {Promise} - returns promise (reject, resolve)	 */	CLEAR_AND_REFILL_STATION_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			const { playlistId } = payload;			async.waterfall(				[					next => {						PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)							.then(playlist => {								next(null, playlist);							})							.catch(err => {								next(err);							});					},					(playlist, next) => {						if (playlist.type !== "station") next("This playlist is not a station playlist.");						else next(null, playlist.createdFor);					},					(stationId, next) => {						PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }, this)							.then(() => {								next();							})							.catch(err => {								next(err);							});					}				],				err => {					if (err && err !== true) return reject(new Error(err));					return resolve();				}			);		});	}	/**	 * Clears and refills a genre playlist	 *	 * @param {object} payload - object that contains the payload	 * @param {string} payload.playlistId - the id of the playlist we are trying to clear and refill	 * @returns {Promise} - returns promise (reject, resolve)	 */	CLEAR_AND_REFILL_GENRE_PLAYLIST(payload) {		return new Promise((resolve, reject) => {			const { playlistId } = payload;			async.waterfall(				[					next => {						PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)							.then(playlist => {								next(null, playlist);							})							.catch(err => {								next(err);							});					},					(playlist, next) => {						if (playlist.type !== "genre") next("This playlist is not a genre playlist.");						else next(null, playlist.createdFor);					},					(genre, next) => {						PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }, this)							.then(() => {								next();							})							.catch(err => {								next(err);							});					}				],				err => {					if (err && err !== true) return reject(new Error(err));					return resolve();				}			);		});	}}export default new _PlaylistsModule();
 |