123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383 |
- import async from "async";
- import CoreClass from "../core";
- let PlaylistsModule;
- let StationsModule;
- let SongsModule;
- let CacheModule;
- let DBModule;
- let UtilsModule;
- class _PlaylistsModule extends CoreClass {
-
- constructor() {
- super("playlists");
- PlaylistsModule = this;
- }
-
- 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();
- }
- }
- )
- );
- }
-
- 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 });
- });
- });
- }
-
- 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);
- }
- );
- });
- }
-
- 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));
- });
- });
- }
-
- 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 });
- });
- });
- }
-
- 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 });
- });
- });
- }
-
- 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 });
- }
- );
- });
- }
-
- 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);
- });
- });
- }
-
- 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);
- });
- });
- }
-
- 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 });
- }
- );
- });
- }
-
- ADD_SONG_TO_PLAYLIST(payload) {
- return new Promise((resolve, reject) => {
- const { _id, youtubeId, title, artists, thumbnail, duration, status } = payload.song;
- const trimmedSong = {
- _id,
- youtubeId,
- title,
- artists,
- thumbnail,
- duration,
- status
- };
- 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));
- });
- }
- }
- );
- });
- }
-
- 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));
- });
- }
- }
- );
- });
- }
-
- 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, status } = song;
- return {
- _id,
- youtubeId,
- title,
- artists,
- thumbnail,
- duration,
- status
- };
- });
- 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({});
- }
- );
- });
- }
-
- 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 });
- }
- );
- }
- });
- });
- }
-
- 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));
- });
- });
- }
-
- 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 });
- }
- );
- }
- });
- });
- }
-
- 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));
- });
- });
- }
-
- 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({});
- }
- );
- });
- }
-
- 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);
- }
- )
- );
- }
-
- GET_DATA(payload) {
- return new Promise((resolve, reject) => {
- async.waterfall(
- [
-
- next => next(null, []),
-
- (pipeline, next) => {
- const { queries, properties } = payload;
-
- const totalLengthFilterExists =
- queries.map(query => query.filter.property).indexOf("totalLength") !== -1;
-
- const totalLengthPropertyExists = properties.indexOf("totalLength") !== -1;
-
- if (!totalLengthFilterExists && !totalLengthPropertyExists) return next(null, pipeline);
-
- pipeline.push({
- $addFields: {
- totalLength: { $sum: "$songs.duration" }
- }
- });
- return next(null, pipeline);
- },
-
- (pipeline, next) => {
- const { queries, properties } = payload;
-
- const songsCountFilterExists =
- queries.map(query => query.filter.property).indexOf("songsCount") !== -1;
-
- const songsCountPropertyExists = properties.indexOf("songsCount") !== -1;
-
- if (!songsCountFilterExists && !songsCountPropertyExists) return next(null, pipeline);
-
- pipeline.push({
- $addFields: {
- songsCount: { $size: "$songs" }
- }
- });
- return next(null, pipeline);
- },
-
- (pipeline, next) => {
- const { queries } = payload;
-
- const createdByFilterExists =
- queries.map(query => query.filter.property).indexOf("createdBy") !== -1;
-
- if (!createdByFilterExists) return next(null, pipeline);
-
- pipeline.push({
- $addFields: {
- createdByOID: {
- $convert: {
- input: "$createdBy",
- to: "objectId",
- onError: "unknown",
- onNull: "unknown"
- }
- }
- }
- });
-
- pipeline.push({
- $lookup: {
- from: "users",
- localField: "createdByOID",
- foreignField: "_id",
- as: "createdByUser"
- }
- });
-
- pipeline.push({
- $unwind: {
- path: "$createdByUser",
- preserveNullAndEmptyArrays: true
- }
- });
-
- pipeline.push({
- $addFields: {
- createdByUsername: {
- $cond: [
- { $eq: ["$createdBy", "Musare"] },
- "Musare",
- { $ifNull: ["$createdByUser.username", "unknown"] }
- ]
- }
- }
- });
-
- pipeline.push({
- $project: {
- createdByOID: 0,
- createdByUser: 0
- }
- });
- return next(null, pipeline);
- },
-
- (pipeline, next) => {
- const { queries, operator } = payload;
- let queryError;
- const newQueries = queries.flatMap(query => {
- const { data, filter, filterType } = query;
- const newQuery = {};
- if (filterType === "regex") {
- newQuery[filter.property] = new RegExp(`${data.slice(1, data.length - 1)}`, "i");
- } else if (filterType === "contains") {
- newQuery[filter.property] = new RegExp(
- `${data.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
- "i"
- );
- } else if (filterType === "exact") {
- newQuery[filter.property] = data.toString();
- } else if (filterType === "datetimeBefore") {
- newQuery[filter.property] = { $lte: new Date(data) };
- } else if (filterType === "datetimeAfter") {
- newQuery[filter.property] = { $gte: new Date(data) };
- } else if (filterType === "numberLesserEqual") {
- newQuery[filter.property] = { $lte: data };
- } else if (filterType === "numberLesser") {
- newQuery[filter.property] = { $lt: data };
- } else if (filterType === "numberGreater") {
- newQuery[filter.property] = { $gt: data };
- } else if (filterType === "numberGreaterEqual") {
- newQuery[filter.property] = { $gte: data };
- } else if (filterType === "numberEquals") {
- newQuery[filter.property] = { $eq: data };
- }
- if (filter.property === "createdBy")
- return { $or: [newQuery, { createdByUsername: newQuery.createdBy }] };
- return newQuery;
- });
- if (queryError) next(queryError);
- const queryObject = {};
- if (newQueries.length > 0) {
- if (operator === "and") queryObject.$and = newQueries;
- else if (operator === "or") queryObject.$or = newQueries;
- else if (operator === "nor") queryObject.$nor = newQueries;
- }
- pipeline.push({ $match: queryObject });
- next(null, pipeline);
- },
-
- (pipeline, next) => {
- const { sort } = payload;
- const newSort = Object.fromEntries(
- Object.entries(sort).map(([property, direction]) => [
- property,
- direction === "ascending" ? 1 : -1
- ])
- );
- if (Object.keys(newSort).length > 0) pipeline.push({ $sort: newSort });
- next(null, pipeline);
- },
-
- (pipeline, next) => {
- const { properties } = payload;
- pipeline.push({ $project: Object.fromEntries(properties.map(property => [property, 1])) });
- next(null, pipeline);
- },
-
- (pipeline, next) => {
- const { page, pageSize } = payload;
- pipeline.push({
- $facet: {
- count: [{ $count: "count" }],
- documents: [{ $skip: pageSize * (page - 1) }, { $limit: pageSize }]
- }
- });
-
- next(null, pipeline);
- },
-
- (pipeline, next) => {
- PlaylistsModule.playlistModel.aggregate(pipeline).exec((err, result) => {
-
-
- if (err) return next(err);
- if (result[0].count.length === 0) return next(null, 0, []);
- const { count } = result[0].count[0];
- const { documents } = result[0];
-
- return next(null, count, documents);
- });
- }
- ],
- (err, count, playlists) => {
- if (err && err !== true) return reject(new Error(err));
- return resolve({ data: playlists, count });
- }
- );
- });
- }
-
- 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);
- }
- )
- );
- }
-
- 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();
- }
- )
- );
- }
-
- 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);
- }
- )
- );
- }
-
- 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();
- }
- );
- });
- }
-
- 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();
|