playlists.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919
  1. import async from "async";
  2. import { isAdminRequired, isLoginRequired } from "./hooks";
  3. import moduleManager from "../../index";
  4. const DBModule = moduleManager.modules.db;
  5. const UtilsModule = moduleManager.modules.utils;
  6. const WSModule = moduleManager.modules.ws;
  7. const SongsModule = moduleManager.modules.songs;
  8. const StationsModule = moduleManager.modules.stations;
  9. const CacheModule = moduleManager.modules.cache;
  10. const PlaylistsModule = moduleManager.modules.playlists;
  11. const YouTubeModule = moduleManager.modules.youtube;
  12. const ActivitiesModule = moduleManager.modules.activities;
  13. CacheModule.runJob("SUB", {
  14. channel: "playlist.create",
  15. cb: playlist => {
  16. WSModule.runJob("SOCKETS_FROM_USER", { userId: playlist.createdBy }, this).then(sockets =>
  17. sockets.forEach(socket => socket.dispatch("event:playlist.created", { data: { playlist } }))
  18. );
  19. if (playlist.privacy === "public")
  20. WSModule.runJob("EMIT_TO_ROOM", {
  21. room: `profile-${playlist.createdBy}-playlists`,
  22. args: ["event:playlist.created", { data: { playlist } }]
  23. });
  24. }
  25. });
  26. CacheModule.runJob("SUB", {
  27. channel: "playlist.delete",
  28. cb: res => {
  29. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  30. sockets.forEach(socket => {
  31. socket.dispatch("event:playlist.deleted", { data: { playlistId: res.playlistId } });
  32. });
  33. });
  34. WSModule.runJob("EMIT_TO_ROOM", {
  35. room: `profile-${res.userId}-playlists`,
  36. args: ["event:playlist.deleted", { data: { playlistId: res.playlistId } }]
  37. });
  38. }
  39. });
  40. CacheModule.runJob("SUB", {
  41. channel: "playlist.repositionSong",
  42. cb: res => {
  43. const { userId, playlistId, song } = res;
  44. WSModule.runJob("SOCKETS_FROM_USER", { userId }, this).then(sockets =>
  45. sockets.forEach(socket =>
  46. socket.dispatch("event:playlist.song.repositioned", {
  47. data: { playlistId, song }
  48. })
  49. )
  50. );
  51. }
  52. });
  53. CacheModule.runJob("SUB", {
  54. channel: "playlist.addSong",
  55. cb: res => {
  56. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  57. sockets.forEach(socket => {
  58. socket.dispatch("event:playlist.song.added", {
  59. data: {
  60. playlistId: res.playlistId,
  61. song: res.song
  62. }
  63. });
  64. });
  65. });
  66. if (res.privacy === "public")
  67. WSModule.runJob("EMIT_TO_ROOM", {
  68. room: `profile-${res.userId}-playlists`,
  69. args: [
  70. "event:playlist.song.added",
  71. {
  72. data: {
  73. playlistId: res.playlistId,
  74. song: res.song
  75. }
  76. }
  77. ]
  78. });
  79. }
  80. });
  81. CacheModule.runJob("SUB", {
  82. channel: "playlist.removeSong",
  83. cb: res => {
  84. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  85. sockets.forEach(socket => {
  86. socket.dispatch("event:playlist.song.removed", {
  87. data: {
  88. playlistId: res.playlistId,
  89. youtubeId: res.youtubeId
  90. }
  91. });
  92. });
  93. });
  94. if (res.privacy === "public")
  95. WSModule.runJob("EMIT_TO_ROOM", {
  96. room: `profile-${res.userId}-playlists`,
  97. args: [
  98. "event:playlist.song.removed",
  99. {
  100. data: {
  101. playlistId: res.playlistId,
  102. youtubeId: res.youtubeId
  103. }
  104. }
  105. ]
  106. });
  107. }
  108. });
  109. CacheModule.runJob("SUB", {
  110. channel: "playlist.updateDisplayName",
  111. cb: res => {
  112. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  113. sockets.forEach(socket => {
  114. socket.dispatch("event:playlist.displayName.updated", {
  115. data: {
  116. playlistId: res.playlistId,
  117. displayName: res.displayName
  118. }
  119. });
  120. });
  121. });
  122. if (res.privacy === "public")
  123. WSModule.runJob("EMIT_TO_ROOM", {
  124. room: `profile-${res.userId}-playlists`,
  125. args: [
  126. "event:playlist.displayName.updated",
  127. {
  128. data: {
  129. playlistId: res.playlistId,
  130. displayName: res.displayName
  131. }
  132. }
  133. ]
  134. });
  135. }
  136. });
  137. CacheModule.runJob("SUB", {
  138. channel: "playlist.updatePrivacy",
  139. cb: res => {
  140. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  141. sockets.forEach(socket => {
  142. socket.dispatch("event:playlist.privacy.updated", {
  143. data: {
  144. playlist: res.playlist
  145. }
  146. });
  147. });
  148. });
  149. if (res.playlist.privacy === "public")
  150. return WSModule.runJob("EMIT_TO_ROOM", {
  151. room: `profile-${res.userId}-playlists`,
  152. args: [
  153. "event:playlist.created",
  154. {
  155. data: {
  156. playlist: res.playlist
  157. }
  158. }
  159. ]
  160. });
  161. return WSModule.runJob("EMIT_TO_ROOM", {
  162. room: `profile-${res.userId}-playlists`,
  163. args: [
  164. "event:playlist.deleted",
  165. {
  166. data: {
  167. playlistId: res.playlist._id
  168. }
  169. }
  170. ]
  171. });
  172. }
  173. });
  174. export default {
  175. /**
  176. * Gets all playlists
  177. *
  178. * @param {object} session - the session object automatically added by the websocket
  179. * @param {Function} cb - gets called with the result
  180. */
  181. index: isAdminRequired(async function index(session, cb) {
  182. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  183. async.waterfall(
  184. [
  185. next => {
  186. playlistModel.find({}).sort({ createdAt: "desc" }).exec(next);
  187. }
  188. ],
  189. async (err, playlists) => {
  190. if (err) {
  191. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  192. this.log("ERROR", "PLAYLISTS_INDEX", `Indexing playlists failed. "${err}"`);
  193. return cb({ status: "error", message: err });
  194. }
  195. this.log("SUCCESS", "PLAYLISTS_INDEX", "Indexing playlists successful.");
  196. return cb({ status: "success", data: { playlists } });
  197. }
  198. );
  199. }),
  200. /**
  201. * Searches through all playlists that can be included in a community station
  202. *
  203. * @param {object} session - the session object automatically added by the websocket
  204. * @param {string} query - the query
  205. * @param {string} query - the page
  206. * @param {Function} cb - gets called with the result
  207. */
  208. searchCommunity: isLoginRequired(async function searchCommunity(session, query, page, cb) {
  209. async.waterfall(
  210. [
  211. next => {
  212. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  213. else next();
  214. },
  215. next => {
  216. PlaylistsModule.runJob("SEARCH", {
  217. query,
  218. includeUser: true,
  219. includeGenre: true,
  220. includeOwn: true,
  221. includeSongs: true,
  222. userId: session.userId,
  223. page
  224. })
  225. .then(response => {
  226. next(null, response);
  227. })
  228. .catch(err => {
  229. next(err);
  230. });
  231. }
  232. ],
  233. async (err, data) => {
  234. if (err) {
  235. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  236. this.log("ERROR", "PLAYLISTS_SEARCH_COMMUNITY", `Searching playlists failed. "${err}"`);
  237. return cb({ status: "error", message: err });
  238. }
  239. this.log("SUCCESS", "PLAYLISTS_SEARCH_COMMUNITY", "Searching playlists successful.");
  240. return cb({ status: "success", data });
  241. }
  242. );
  243. }),
  244. /**
  245. * Searches through all playlists that can be included in an official station
  246. *
  247. * @param {object} session - the session object automatically added by the websocket
  248. * @param {string} query - the query
  249. * @param {string} query - the page
  250. * @param {Function} cb - gets called with the result
  251. */
  252. searchOfficial: isAdminRequired(async function searchOfficial(session, query, page, cb) {
  253. async.waterfall(
  254. [
  255. next => {
  256. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  257. else next();
  258. },
  259. next => {
  260. PlaylistsModule.runJob("SEARCH", {
  261. query,
  262. includeGenre: true,
  263. includePrivate: true,
  264. includeSongs: true,
  265. page
  266. })
  267. .then(response => {
  268. next(null, response);
  269. })
  270. .catch(err => {
  271. next(err);
  272. });
  273. }
  274. ],
  275. async (err, data) => {
  276. if (err) {
  277. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  278. this.log("ERROR", "PLAYLISTS_SEARCH_OFFICIAL", `Searching playlists failed. "${err}"`);
  279. return cb({ status: "error", message: err });
  280. }
  281. this.log("SUCCESS", "PLAYLISTS_SEARCH_OFFICIAL", "Searching playlists successful.");
  282. return cb({ status: "success", data });
  283. }
  284. );
  285. }),
  286. /**
  287. * Gets the first song from a private playlist
  288. *
  289. * @param {object} session - the session object automatically added by the websocket
  290. * @param {string} playlistId - the id of the playlist we are getting the first song from
  291. * @param {Function} cb - gets called with the result
  292. */
  293. getFirstSong: isLoginRequired(function getFirstSong(session, playlistId, cb) {
  294. async.waterfall(
  295. [
  296. next => {
  297. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  298. .then(playlist => next(null, playlist))
  299. .catch(next);
  300. },
  301. (playlist, next) => {
  302. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  303. playlist.songs.sort((a, b) => a.position - b.position);
  304. return next(null, playlist.songs[0]);
  305. }
  306. ],
  307. async (err, song) => {
  308. if (err) {
  309. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  310. this.log(
  311. "ERROR",
  312. "PLAYLIST_GET_FIRST_SONG",
  313. `Getting the first song of playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  314. );
  315. return cb({ status: "error", message: err });
  316. }
  317. this.log(
  318. "SUCCESS",
  319. "PLAYLIST_GET_FIRST_SONG",
  320. `Successfully got the first song of playlist "${playlistId}" for user "${session.userId}".`
  321. );
  322. return cb({
  323. status: "success",
  324. data: { song }
  325. });
  326. }
  327. );
  328. }),
  329. /**
  330. * Gets a list of all the playlists for a specific user
  331. *
  332. * @param {object} session - the session object automatically added by the websocket
  333. * @param {string} userId - the user id in question
  334. * @param {Function} cb - gets called with the result
  335. */
  336. indexForUser: async function indexForUser(session, userId, cb) {
  337. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  338. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  339. async.waterfall(
  340. [
  341. next => {
  342. userModel.findById(userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  343. },
  344. ({ preferences }, next) => {
  345. const { orderOfPlaylists } = preferences;
  346. const match = {
  347. createdBy: userId,
  348. type: "user"
  349. };
  350. // if a playlist order exists
  351. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  352. playlistModel
  353. .aggregate()
  354. .match(match)
  355. .addFields({
  356. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  357. })
  358. .sort({ weight: 1 })
  359. .exec(next);
  360. },
  361. (playlists, next) => {
  362. if (session.userId === userId) return next(null, playlists); // user requesting playlists is the owner of the playlists
  363. const filteredPlaylists = [];
  364. return async.each(
  365. playlists,
  366. (playlist, nextPlaylist) => {
  367. if (playlist.privacy === "public") filteredPlaylists.push(playlist);
  368. return nextPlaylist();
  369. },
  370. () => next(null, filteredPlaylists)
  371. );
  372. }
  373. ],
  374. async (err, playlists) => {
  375. if (err) {
  376. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  377. this.log(
  378. "ERROR",
  379. "PLAYLIST_INDEX_FOR_USER",
  380. `Indexing playlists for user "${userId}" failed. "${err}"`
  381. );
  382. return cb({ status: "error", message: err });
  383. }
  384. this.log("SUCCESS", "PLAYLIST_INDEX_FOR_USER", `Successfully indexed playlists for user "${userId}".`);
  385. return cb({
  386. status: "success",
  387. data: { playlists }
  388. });
  389. }
  390. );
  391. },
  392. /**
  393. * Gets all playlists for the user requesting it
  394. *
  395. * @param {object} session - the session object automatically added by the websocket
  396. * @param {boolean} showNonModifiablePlaylists - whether or not to show non modifiable playlists e.g. liked songs
  397. * @param {Function} cb - gets called with the result
  398. */
  399. indexMyPlaylists: isLoginRequired(async function indexMyPlaylists(session, showNonModifiablePlaylists, cb) {
  400. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  401. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  402. async.waterfall(
  403. [
  404. next => {
  405. userModel.findById(session.userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  406. },
  407. ({ preferences }, next) => {
  408. const { orderOfPlaylists } = preferences;
  409. const match = {
  410. createdBy: session.userId,
  411. type: "user"
  412. };
  413. // if non modifiable playlists should be shown as well
  414. if (!showNonModifiablePlaylists) match.isUserModifiable = true;
  415. // if a playlist order exists
  416. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  417. playlistModel
  418. .aggregate()
  419. .match(match)
  420. .addFields({
  421. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  422. })
  423. .sort({ weight: 1 })
  424. .exec(next);
  425. }
  426. ],
  427. async (err, playlists) => {
  428. if (err) {
  429. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  430. this.log(
  431. "ERROR",
  432. "PLAYLIST_INDEX_FOR_ME",
  433. `Indexing playlists for user "${session.userId}" failed. "${err}"`
  434. );
  435. return cb({ status: "error", message: err });
  436. }
  437. this.log(
  438. "SUCCESS",
  439. "PLAYLIST_INDEX_FOR_ME",
  440. `Successfully indexed playlists for user "${session.userId}".`
  441. );
  442. return cb({
  443. status: "success",
  444. data: { playlists }
  445. });
  446. }
  447. );
  448. }),
  449. /**
  450. * Creates a new private playlist
  451. *
  452. * @param {object} session - the session object automatically added by the websocket
  453. * @param {object} data - the data for the new private playlist
  454. * @param {Function} cb - gets called with the result
  455. */
  456. create: isLoginRequired(async function create(session, data, cb) {
  457. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  458. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  459. const blacklist = ["liked songs", "likedsongs", "disliked songs", "dislikedsongs"];
  460. async.waterfall(
  461. [
  462. next => (data ? next() : cb({ status: "error", message: "Invalid data" })),
  463. next => {
  464. const { displayName, songs, privacy } = data;
  465. if (blacklist.indexOf(displayName.toLowerCase()) !== -1)
  466. return next("That playlist name is blacklisted. Please use a different name.");
  467. return playlistModel.create(
  468. {
  469. displayName,
  470. songs,
  471. privacy,
  472. createdBy: session.userId,
  473. createdAt: Date.now(),
  474. createdFor: null,
  475. type: "user"
  476. },
  477. next
  478. );
  479. },
  480. (playlist, next) => {
  481. userModel.updateOne(
  482. { _id: session.userId },
  483. { $push: { "preferences.orderOfPlaylists": playlist._id } },
  484. err => {
  485. if (err) return next(err);
  486. return next(null, playlist);
  487. }
  488. );
  489. }
  490. ],
  491. async (err, playlist) => {
  492. if (err) {
  493. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  494. this.log(
  495. "ERROR",
  496. "PLAYLIST_CREATE",
  497. `Creating private playlist failed for user "${session.userId}". "${err}"`
  498. );
  499. return cb({ status: "error", message: err });
  500. }
  501. CacheModule.runJob("PUB", {
  502. channel: "playlist.create",
  503. value: playlist
  504. });
  505. ActivitiesModule.runJob("ADD_ACTIVITY", {
  506. userId: playlist.createdBy,
  507. type: "playlist__create",
  508. payload: {
  509. message: `Created playlist <playlistId>${playlist.displayName}</playlistId>`,
  510. playlistId: playlist._id
  511. }
  512. });
  513. this.log(
  514. "SUCCESS",
  515. "PLAYLIST_CREATE",
  516. `Successfully created private playlist for user "${session.userId}".`
  517. );
  518. return cb({
  519. status: "success",
  520. message: "Successfully created playlist",
  521. data: {
  522. playlistId: playlist._id
  523. }
  524. });
  525. }
  526. );
  527. }),
  528. /**
  529. * Gets a playlist from id
  530. *
  531. * @param {object} session - the session object automatically added by the websocket
  532. * @param {string} playlistId - the id of the playlist we are getting
  533. * @param {Function} cb - gets called with the result
  534. */
  535. getPlaylist: function getPlaylist(session, playlistId, cb) {
  536. async.waterfall(
  537. [
  538. next => {
  539. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  540. .then(playlist => next(null, playlist))
  541. .catch(next);
  542. },
  543. (playlist, next) => {
  544. if (!playlist) return next("Playlist not found");
  545. if (playlist.privacy !== "public" && playlist.createdBy !== session.userId) {
  546. if (session)
  547. // check if user requested to get a playlist is an admin
  548. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  549. userModel.findOne({ _id: session.userId }, (err, user) => {
  550. if (user && user.role === "admin") return next(null, playlist);
  551. return next("User unauthorised to view playlist.");
  552. });
  553. });
  554. return next("User unauthorised to view playlist.");
  555. }
  556. return next(null, playlist);
  557. }
  558. ],
  559. async (err, playlist) => {
  560. if (err) {
  561. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  562. this.log(
  563. "ERROR",
  564. "PLAYLIST_GET",
  565. `Getting private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  566. );
  567. return cb({ status: "error", message: err });
  568. }
  569. this.log(
  570. "SUCCESS",
  571. "PLAYLIST_GET",
  572. `Successfully got private playlist "${playlistId}" for user "${session.userId}".`
  573. );
  574. return cb({
  575. status: "success",
  576. data: { playlist }
  577. });
  578. }
  579. );
  580. },
  581. /**
  582. * Gets a playlist from station id
  583. *
  584. * @param {object} session - the session object automatically added by the websocket
  585. * @param {string} stationId - the id of the station we are getting
  586. * @param {string} includeSongs - include songs
  587. * @param {Function} cb - gets called with the result
  588. */
  589. getPlaylistForStation: function getPlaylist(session, stationId, includeSongs, cb) {
  590. async.waterfall(
  591. [
  592. next => {
  593. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs }, this)
  594. .then(response => next(null, response.playlist))
  595. .catch(next);
  596. },
  597. (playlist, next) => {
  598. if (!playlist) return next("Playlist not found");
  599. if (playlist.privacy !== "public" && playlist.createdBy !== session.userId) {
  600. if (session)
  601. // check if user requested to get a playlist is an admin
  602. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  603. userModel.findOne({ _id: session.userId }, (err, user) => {
  604. if (user && user.role === "admin") return next(null, playlist);
  605. return next("User unauthorised to view playlist.");
  606. });
  607. });
  608. return next("User unauthorised to view playlist.");
  609. }
  610. return next(null, playlist);
  611. }
  612. ],
  613. async (err, playlist) => {
  614. if (err) {
  615. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  616. this.log(
  617. "ERROR",
  618. "PLAYLIST_GET",
  619. `Getting playlist for station "${stationId}" failed for user "${session.userId}". "${err}"`
  620. );
  621. return cb({ status: "error", message: err });
  622. }
  623. this.log(
  624. "SUCCESS",
  625. "PLAYLIST_GET",
  626. `Successfully got playlist for station "${stationId}" for user "${session.userId}".`
  627. );
  628. return cb({
  629. status: "success",
  630. data: { playlist }
  631. });
  632. }
  633. );
  634. },
  635. /**
  636. * Shuffles songs in a private playlist
  637. *
  638. * @param {object} session - the session object automatically added by the websocket
  639. * @param {string} playlistId - the id of the playlist we are updating
  640. * @param {Function} cb - gets called with the result
  641. */
  642. shuffle: isLoginRequired(async function shuffle(session, playlistId, cb) {
  643. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  644. async.waterfall(
  645. [
  646. next => {
  647. if (!playlistId) return next("No playlist id.");
  648. return playlistModel.findById(playlistId, next);
  649. },
  650. (playlist, next) => {
  651. if (!playlist.isUserModifiable) return next("Playlist cannot be shuffled.");
  652. return UtilsModule.runJob("SHUFFLE_SONG_POSITIONS", { array: playlist.songs }, this)
  653. .then(result => next(null, result.array))
  654. .catch(next);
  655. },
  656. (songs, next) => {
  657. playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, { runValidators: true }, next);
  658. },
  659. (res, next) => {
  660. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  661. .then(playlist => next(null, playlist))
  662. .catch(next);
  663. }
  664. ],
  665. async (err, playlist) => {
  666. if (err) {
  667. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  668. this.log(
  669. "ERROR",
  670. "PLAYLIST_SHUFFLE",
  671. `Updating private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  672. );
  673. return cb({ status: "error", message: err });
  674. }
  675. this.log(
  676. "SUCCESS",
  677. "PLAYLIST_SHUFFLE",
  678. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  679. );
  680. return cb({
  681. status: "success",
  682. message: "Successfully shuffled playlist.",
  683. data: { playlist }
  684. });
  685. }
  686. );
  687. }),
  688. /**
  689. * Changes the order (position) of a song in a playlist
  690. *
  691. * @param {object} session - the session object automatically added by the websocket
  692. * @param {string} playlistId - the id of the playlist we are targeting
  693. * @param {object} song - the song to be repositioned
  694. * @param {string} song.youtubeId - the youtube id of the song being repositioned
  695. * @param {string} song.newIndex - the new position of the song in the playlist
  696. * @param {...any} song.args - any other elements that would be included with a song item in a playlist
  697. * @param {Function} cb - gets called with the result
  698. */
  699. repositionSong: isLoginRequired(async function repositionSong(session, playlistId, song, cb) {
  700. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  701. async.waterfall(
  702. [
  703. next => {
  704. if (!playlistId) return next("Please provide a playlist.");
  705. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  706. return next();
  707. },
  708. // remove song from playlist
  709. next => {
  710. playlistModel.updateOne(
  711. { _id: playlistId },
  712. { $pull: { songs: { youtubeId: song.youtubeId } } },
  713. next
  714. );
  715. },
  716. // add song back to playlist (in new position)
  717. (res, next) => {
  718. playlistModel.updateOne(
  719. { _id: playlistId },
  720. { $push: { songs: { $each: [song], $position: song.newIndex } } },
  721. err => next(err)
  722. );
  723. },
  724. // update the cache with the new songs positioning
  725. next => {
  726. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  727. .then(playlist => next(null, playlist))
  728. .catch(next);
  729. }
  730. ],
  731. async err => {
  732. if (err) {
  733. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  734. this.log(
  735. "ERROR",
  736. "PLAYLIST_REPOSITION_SONG",
  737. `Repositioning song ${song.youtubeId} for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  738. );
  739. return cb({ status: "error", message: err });
  740. }
  741. this.log(
  742. "SUCCESS",
  743. "PLAYLIST_REPOSITION_SONG",
  744. `Successfully repositioned song ${song.youtubeId} for private playlist "${playlistId}" for user "${session.userId}".`
  745. );
  746. CacheModule.runJob("PUB", {
  747. channel: "playlist.repositionSong",
  748. value: {
  749. userId: session.userId,
  750. playlistId,
  751. song
  752. }
  753. });
  754. return cb({
  755. status: "success",
  756. message: "Successfully repositioned song"
  757. });
  758. }
  759. );
  760. }),
  761. /**
  762. * Adds a song to a private playlist
  763. *
  764. * @param {object} session - the session object automatically added by the websocket
  765. * @param {boolean} isSet - is the song part of a set of songs to be added
  766. * @param {string} youtubeId - the youtube id of the song we are trying to add
  767. * @param {string} playlistId - the id of the playlist we are adding the song to
  768. * @param {Function} cb - gets called with the result
  769. */
  770. addSongToPlaylist: isLoginRequired(async function addSongToPlaylist(session, isSet, youtubeId, playlistId, cb) {
  771. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  772. async.waterfall(
  773. [
  774. next => {
  775. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  776. .then(playlist => {
  777. if (!playlist || playlist.createdBy !== session.userId)
  778. return next("Something went wrong when trying to get the playlist");
  779. return async.each(
  780. playlist.songs,
  781. (song, nextSong) => {
  782. if (song.youtubeId === youtubeId)
  783. return next("That song is already in the playlist");
  784. return nextSong();
  785. },
  786. err => next(err)
  787. );
  788. })
  789. .catch(next);
  790. },
  791. next => {
  792. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  793. .then(UserModel => {
  794. UserModel.findOne(
  795. { _id: session.userId },
  796. { "preferences.anonymousSongRequests": 1 },
  797. next
  798. );
  799. })
  800. .catch(next);
  801. },
  802. (user, next) => {
  803. SongsModule.runJob(
  804. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  805. {
  806. youtubeId,
  807. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  808. automaticallyRequested: true
  809. },
  810. this
  811. )
  812. .then(response => {
  813. const { song } = response;
  814. const { _id, title, artists, thumbnail, duration, status } = song;
  815. next(null, {
  816. _id,
  817. youtubeId,
  818. title,
  819. artists,
  820. thumbnail,
  821. duration,
  822. status
  823. });
  824. })
  825. .catch(next);
  826. },
  827. (newSong, next) => {
  828. playlistModel.updateOne(
  829. { _id: playlistId },
  830. { $push: { songs: newSong } },
  831. { runValidators: true },
  832. err => {
  833. if (err) return next(err);
  834. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  835. .then(playlist => next(null, playlist, newSong))
  836. .catch(next);
  837. }
  838. );
  839. }
  840. ],
  841. async (err, playlist, newSong) => {
  842. if (err) {
  843. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  844. this.log(
  845. "ERROR",
  846. "PLAYLIST_ADD_SONG",
  847. `Adding song "${youtubeId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  848. );
  849. return cb({ status: "error", message: err });
  850. }
  851. this.log(
  852. "SUCCESS",
  853. "PLAYLIST_ADD_SONG",
  854. `Successfully added song "${youtubeId}" to private playlist "${playlistId}" for user "${session.userId}".`
  855. );
  856. if (!isSet && playlist.displayName !== "Liked Songs" && playlist.displayName !== "Disliked Songs") {
  857. const songName = newSong.artists
  858. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  859. : newSong.title;
  860. if (playlist.privacy === "public")
  861. ActivitiesModule.runJob("ADD_ACTIVITY", {
  862. userId: session.userId,
  863. type: "playlist__add_song",
  864. payload: {
  865. message: `Added <youtubeId>${songName}</youtubeId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  866. thumbnail: newSong.thumbnail,
  867. playlistId,
  868. youtubeId
  869. }
  870. });
  871. }
  872. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  873. .then(response => {
  874. response.stationIds.forEach(stationId => {
  875. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  876. });
  877. })
  878. .catch();
  879. CacheModule.runJob("PUB", {
  880. channel: "playlist.addSong",
  881. value: {
  882. playlistId: playlist._id,
  883. song: newSong,
  884. userId: session.userId,
  885. privacy: playlist.privacy
  886. }
  887. });
  888. return cb({
  889. status: "success",
  890. message: "Song has been successfully added to the playlist",
  891. data: { songs: playlist.songs }
  892. });
  893. }
  894. );
  895. }),
  896. /**
  897. * Adds a set of songs to a private playlist
  898. *
  899. * @param {object} session - the session object automatically added by the websocket
  900. * @param {string} url - the url of the the YouTube playlist
  901. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  902. * @param {boolean} musicOnly - whether to only add music to the playlist
  903. * @param {Function} cb - gets called with the result
  904. */
  905. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  906. let videosInPlaylistTotal = 0;
  907. let songsInPlaylistTotal = 0;
  908. let addSongsStats = null;
  909. const addedSongs = [];
  910. async.waterfall(
  911. [
  912. next => {
  913. YouTubeModule.runJob("GET_PLAYLIST", { url, musicOnly }, this)
  914. .then(res => {
  915. if (res.filteredSongs) {
  916. videosInPlaylistTotal = res.songs.length;
  917. songsInPlaylistTotal = res.filteredSongs.length;
  918. } else {
  919. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  920. }
  921. next(null, res.songs);
  922. })
  923. .catch(err => {
  924. next(err);
  925. });
  926. },
  927. (youtubeIds, next) => {
  928. let successful = 0;
  929. let failed = 0;
  930. let alreadyInPlaylist = 0;
  931. if (youtubeIds.length === 0) next();
  932. async.eachLimit(
  933. youtubeIds,
  934. 1,
  935. (youtubeId, next) => {
  936. WSModule.runJob(
  937. "RUN_ACTION2",
  938. {
  939. session,
  940. namespace: "playlists",
  941. action: "addSongToPlaylist",
  942. args: [true, youtubeId, playlistId]
  943. },
  944. this
  945. )
  946. .then(res => {
  947. if (res.status === "success") {
  948. successful += 1;
  949. addedSongs.push(youtubeId);
  950. } else failed += 1;
  951. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  952. })
  953. .catch(() => {
  954. failed += 1;
  955. })
  956. .finally(() => next());
  957. },
  958. () => {
  959. addSongsStats = { successful, failed, alreadyInPlaylist };
  960. next(null);
  961. }
  962. );
  963. },
  964. next => {
  965. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  966. .then(playlist => next(null, playlist))
  967. .catch(next);
  968. },
  969. (playlist, next) => {
  970. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  971. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  972. return next(null, playlist);
  973. }
  974. ],
  975. async (err, playlist) => {
  976. if (err) {
  977. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  978. this.log(
  979. "ERROR",
  980. "PLAYLIST_IMPORT",
  981. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  982. );
  983. return cb({ status: "error", message: err });
  984. }
  985. if (playlist.privacy === "public")
  986. ActivitiesModule.runJob("ADD_ACTIVITY", {
  987. userId: session.userId,
  988. type: "playlist__import_playlist",
  989. payload: {
  990. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  991. playlistId
  992. }
  993. });
  994. this.log(
  995. "SUCCESS",
  996. "PLAYLIST_IMPORT",
  997. `Successfully imported a YouTube playlist to private playlist "${playlistId}" for user "${session.userId}". Videos in playlist: ${videosInPlaylistTotal}, songs in playlist: ${songsInPlaylistTotal}, songs successfully added: ${addSongsStats.successful}, songs failed: ${addSongsStats.failed}, already in playlist: ${addSongsStats.alreadyInPlaylist}.`
  998. );
  999. return cb({
  1000. status: "success",
  1001. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1002. data: {
  1003. songs: playlist.songs,
  1004. stats: {
  1005. videosInPlaylistTotal,
  1006. songsInPlaylistTotal
  1007. }
  1008. }
  1009. });
  1010. }
  1011. );
  1012. }),
  1013. /**
  1014. * Removes a song from a private playlist
  1015. *
  1016. * @param {object} session - the session object automatically added by the websocket
  1017. * @param {string} youtubeId - the youtube id of the song we are removing from the private playlist
  1018. * @param {string} playlistId - the id of the playlist we are removing the song from
  1019. * @param {Function} cb - gets called with the result
  1020. */
  1021. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, youtubeId, playlistId, cb) {
  1022. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1023. async.waterfall(
  1024. [
  1025. next => {
  1026. if (!youtubeId || typeof youtubeId !== "string") return next("Invalid song id.");
  1027. if (!playlistId || typeof youtubeId !== "string") return next("Invalid playlist id.");
  1028. return next();
  1029. },
  1030. // remove song from playlist
  1031. next => playlistModel.updateOne({ _id: playlistId }, { $pull: { songs: { youtubeId } } }, next),
  1032. // update cache representation of the playlist
  1033. (res, next) => {
  1034. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1035. .then(playlist => next(null, playlist))
  1036. .catch(next);
  1037. },
  1038. (playlist, next) => {
  1039. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  1040. .then(response => {
  1041. response.stationIds.forEach(stationId => {
  1042. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1043. });
  1044. })
  1045. .catch();
  1046. SongsModule.runJob("GET_SONG_FROM_YOUTUBE_ID", { youtubeId }, this)
  1047. .then(res =>
  1048. next(null, playlist, {
  1049. title: res.song.title,
  1050. thumbnail: res.song.thumbnail,
  1051. artists: res.song.artists
  1052. })
  1053. )
  1054. .catch(() => {
  1055. YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  1056. .then(response => next(null, playlist, response.song))
  1057. .catch(next);
  1058. });
  1059. },
  1060. (playlist, youtubeSong, next) => {
  1061. const songName = youtubeSong.artists
  1062. ? `${youtubeSong.title} by ${youtubeSong.artists.join(", ")}`
  1063. : youtubeSong.title;
  1064. if (
  1065. playlist.displayName !== "Liked Songs" &&
  1066. playlist.displayName !== "Disliked Songs" &&
  1067. playlist.privacy === "public"
  1068. ) {
  1069. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1070. userId: session.userId,
  1071. type: "playlist__remove_song",
  1072. payload: {
  1073. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1074. thumbnail: youtubeSong.thumbnail,
  1075. playlistId,
  1076. youtubeId
  1077. }
  1078. });
  1079. }
  1080. return next(null, playlist);
  1081. }
  1082. ],
  1083. async (err, playlist) => {
  1084. if (err) {
  1085. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1086. this.log(
  1087. "ERROR",
  1088. "PLAYLIST_REMOVE_SONG",
  1089. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1090. );
  1091. return cb({ status: "error", message: err });
  1092. }
  1093. this.log(
  1094. "SUCCESS",
  1095. "PLAYLIST_REMOVE_SONG",
  1096. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1097. );
  1098. CacheModule.runJob("PUB", {
  1099. channel: "playlist.removeSong",
  1100. value: {
  1101. playlistId: playlist._id,
  1102. youtubeId,
  1103. userId: session.userId,
  1104. privacy: playlist.privacy
  1105. }
  1106. });
  1107. return cb({
  1108. status: "success",
  1109. message: "Song has been successfully removed from playlist",
  1110. data: { songs: playlist.songs }
  1111. });
  1112. }
  1113. );
  1114. }),
  1115. /**
  1116. * Updates the displayName of a private playlist
  1117. *
  1118. * @param {object} session - the session object automatically added by the websocket
  1119. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1120. * @param {Function} cb - gets called with the result
  1121. */
  1122. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1123. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1124. async.waterfall(
  1125. [
  1126. next => {
  1127. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1128. .then(playlist => next(null, playlist))
  1129. .catch(next);
  1130. },
  1131. (playlist, next) => {
  1132. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  1133. return next(null);
  1134. },
  1135. next => {
  1136. playlistModel.updateOne(
  1137. { _id: playlistId, createdBy: session.userId },
  1138. { $set: { displayName } },
  1139. { runValidators: true },
  1140. next
  1141. );
  1142. },
  1143. (res, next) => {
  1144. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1145. .then(playlist => next(null, playlist))
  1146. .catch(next);
  1147. }
  1148. ],
  1149. async (err, playlist) => {
  1150. if (err) {
  1151. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1152. this.log(
  1153. "ERROR",
  1154. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1155. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1156. );
  1157. return cb({ status: "error", message: err });
  1158. }
  1159. this.log(
  1160. "SUCCESS",
  1161. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1162. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1163. );
  1164. CacheModule.runJob("PUB", {
  1165. channel: "playlist.updateDisplayName",
  1166. value: {
  1167. playlistId,
  1168. displayName,
  1169. userId: session.userId,
  1170. privacy: playlist.privacy
  1171. }
  1172. });
  1173. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1174. userId: session.userId,
  1175. type: "playlist__edit_display_name",
  1176. payload: {
  1177. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1178. playlistId
  1179. }
  1180. });
  1181. return cb({
  1182. status: "success",
  1183. message: "Playlist has been successfully updated"
  1184. });
  1185. }
  1186. );
  1187. }),
  1188. /**
  1189. * Removes a private playlist
  1190. *
  1191. * @param {object} session - the session object automatically added by the websocket
  1192. * @param {string} playlistId - the id of the playlist we are moving the song to the top from
  1193. * @param {Function} cb - gets called with the result
  1194. */
  1195. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1196. // const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1197. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1198. async.waterfall(
  1199. [
  1200. next => {
  1201. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1202. .then(playlist => next(null, playlist))
  1203. .catch(next);
  1204. },
  1205. (playlist, next) => {
  1206. if (!playlist.isUserModifiable) return next("Playlist cannot be removed.");
  1207. return next(null, playlist);
  1208. },
  1209. (playlist, next) => {
  1210. userModel.updateOne(
  1211. { _id: playlist.createdBy },
  1212. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1213. err => next(err, playlist)
  1214. );
  1215. },
  1216. (playlist, next) => {
  1217. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1218. .then(() => next(null, playlist))
  1219. .catch(next);
  1220. }
  1221. // (playlist, next) => {
  1222. // stationModel.find({ privatePlaylist: playlistId }, (err, res) => {
  1223. // next(err, playlist, res);
  1224. // });
  1225. // },
  1226. // (playlist, stations, next) => {
  1227. // async.each(
  1228. // stations,
  1229. // (station, next) => {
  1230. // async.waterfall(
  1231. // [
  1232. // next => {
  1233. // stationModel.updateOne(
  1234. // { _id: station._id },
  1235. // { $set: { privatePlaylist: null } },
  1236. // { runValidators: true },
  1237. // next
  1238. // );
  1239. // },
  1240. // (res, next) => {
  1241. // if (!station.partyMode) {
  1242. // moduleManager.modules.stations
  1243. // .runJob("UPDATE_STATION", { stationId: station._id }, this)
  1244. // .then(station => next(null, station))
  1245. // .catch(next);
  1246. // CacheModule.runJob("PUB", {
  1247. // channel: "privatePlaylist.selected",
  1248. // value: {
  1249. // playlistId: null,
  1250. // stationId: station._id
  1251. // }
  1252. // });
  1253. // } else next();
  1254. // }
  1255. // ],
  1256. // () => next()
  1257. // );
  1258. // },
  1259. // () => next(null, playlist)
  1260. // );
  1261. // }
  1262. ],
  1263. async (err, playlist) => {
  1264. if (err) {
  1265. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1266. this.log(
  1267. "ERROR",
  1268. "PLAYLIST_REMOVE",
  1269. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1270. );
  1271. return cb({ status: "error", message: err });
  1272. }
  1273. this.log(
  1274. "SUCCESS",
  1275. "PLAYLIST_REMOVE",
  1276. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1277. );
  1278. CacheModule.runJob("PUB", {
  1279. channel: "playlist.delete",
  1280. value: {
  1281. userId: session.userId,
  1282. playlistId
  1283. }
  1284. });
  1285. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1286. userId: playlist.createdBy,
  1287. type: "playlist__remove",
  1288. payload: {
  1289. message: `Removed playlist ${playlist.displayName}`
  1290. }
  1291. });
  1292. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1293. return cb({
  1294. status: "success",
  1295. message: "Playlist successfully removed"
  1296. });
  1297. }
  1298. );
  1299. }),
  1300. /**
  1301. * Updates the privacy of a private playlist
  1302. *
  1303. * @param {object} session - the session object automatically added by the websocket
  1304. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1305. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1306. * @param {Function} cb - gets called with the result
  1307. */
  1308. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1309. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1310. async.waterfall(
  1311. [
  1312. next => {
  1313. playlistModel.updateOne(
  1314. { _id: playlistId, createdBy: session.userId },
  1315. { $set: { privacy } },
  1316. { runValidators: true },
  1317. next
  1318. );
  1319. },
  1320. (res, next) => {
  1321. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  1322. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1323. else {
  1324. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1325. .then(playlist => next(null, playlist))
  1326. .catch(next);
  1327. }
  1328. }
  1329. ],
  1330. async (err, playlist) => {
  1331. if (err) {
  1332. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1333. this.log(
  1334. "ERROR",
  1335. "PLAYLIST_UPDATE_PRIVACY",
  1336. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1337. );
  1338. return cb({ status: "error", message: err });
  1339. }
  1340. this.log(
  1341. "SUCCESS",
  1342. "PLAYLIST_UPDATE_PRIVACY",
  1343. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1344. );
  1345. CacheModule.runJob("PUB", {
  1346. channel: "playlist.updatePrivacy",
  1347. value: {
  1348. userId: session.userId,
  1349. playlist
  1350. }
  1351. });
  1352. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1353. userId: session.userId,
  1354. type: "playlist__edit_privacy",
  1355. payload: {
  1356. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1357. playlistId
  1358. }
  1359. });
  1360. return cb({
  1361. status: "success",
  1362. message: "Playlist has been successfully updated"
  1363. });
  1364. }
  1365. );
  1366. }),
  1367. /**
  1368. * Updates the privacy of a playlist
  1369. *
  1370. * @param {object} session - the session object automatically added by the websocket
  1371. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1372. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1373. * @param {Function} cb - gets called with the result
  1374. */
  1375. updatePrivacyAdmin: isAdminRequired(async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  1376. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1377. async.waterfall(
  1378. [
  1379. next => {
  1380. playlistModel.updateOne({ _id: playlistId }, { $set: { privacy } }, { runValidators: true }, next);
  1381. },
  1382. (res, next) => {
  1383. if (res.n === 0) next("No playlist found with that id.");
  1384. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1385. else {
  1386. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1387. .then(playlist => next(null, playlist))
  1388. .catch(next);
  1389. }
  1390. }
  1391. ],
  1392. async (err, playlist) => {
  1393. if (err) {
  1394. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1395. this.log(
  1396. "ERROR",
  1397. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  1398. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1399. );
  1400. return cb({ status: "error", message: err });
  1401. }
  1402. this.log(
  1403. "SUCCESS",
  1404. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  1405. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  1406. );
  1407. if (playlist.type === "user") {
  1408. CacheModule.runJob("PUB", {
  1409. channel: "playlist.updatePrivacy",
  1410. value: {
  1411. userId: playlist.createdBy,
  1412. playlist
  1413. }
  1414. });
  1415. }
  1416. return cb({
  1417. status: "success",
  1418. message: "Playlist has been successfully updated"
  1419. });
  1420. }
  1421. );
  1422. }),
  1423. /**
  1424. * Deletes all orphaned station playlists
  1425. *
  1426. * @param {object} session - the session object automatically added by socket.io
  1427. * @param {Function} cb - gets called with the result
  1428. */
  1429. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1430. async.waterfall(
  1431. [
  1432. next => {
  1433. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1434. .then(() => next())
  1435. .catch(next);
  1436. }
  1437. ],
  1438. async err => {
  1439. if (err) {
  1440. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1441. this.log(
  1442. "ERROR",
  1443. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1444. `Deleting orphaned station playlists failed. "${err}"`
  1445. );
  1446. return cb({ status: "error", message: err });
  1447. }
  1448. this.log(
  1449. "SUCCESS",
  1450. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1451. "Deleting orphaned station playlists successful."
  1452. );
  1453. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1454. }
  1455. );
  1456. }),
  1457. /**
  1458. * Deletes all orphaned genre playlists
  1459. *
  1460. * @param {object} session - the session object automatically added by socket.io
  1461. * @param {Function} cb - gets called with the result
  1462. */
  1463. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1464. async.waterfall(
  1465. [
  1466. next => {
  1467. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1468. .then(() => next())
  1469. .catch(next);
  1470. }
  1471. ],
  1472. async err => {
  1473. if (err) {
  1474. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1475. this.log(
  1476. "ERROR",
  1477. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1478. `Deleting orphaned genre playlists failed. "${err}"`
  1479. );
  1480. return cb({ status: "error", message: err });
  1481. }
  1482. this.log(
  1483. "SUCCESS",
  1484. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1485. "Deleting orphaned genre playlists successful."
  1486. );
  1487. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1488. }
  1489. );
  1490. }),
  1491. /**
  1492. * Requests orpahned playlist songs
  1493. *
  1494. * @param {object} session - the session object automatically added by socket.io
  1495. * @param {Function} cb - gets called with the result
  1496. */
  1497. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1498. async.waterfall(
  1499. [
  1500. next => {
  1501. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1502. .then(() => next())
  1503. .catch(next);
  1504. }
  1505. ],
  1506. async err => {
  1507. if (err) {
  1508. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1509. this.log(
  1510. "ERROR",
  1511. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1512. `Requesting orphaned playlist songs failed. "${err}"`
  1513. );
  1514. return cb({ status: "error", message: err });
  1515. }
  1516. this.log(
  1517. "SUCCESS",
  1518. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1519. "Requesting orphaned playlist songs was successful."
  1520. );
  1521. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  1522. }
  1523. );
  1524. }),
  1525. /**
  1526. * Clears and refills a station playlist
  1527. *
  1528. * @param {object} session - the session object automatically added by socket.io
  1529. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1530. * @param {Function} cb - gets called with the result
  1531. */
  1532. clearAndRefillStationPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1533. async.waterfall(
  1534. [
  1535. next => {
  1536. if (!playlistId) next("Please specify a playlist id");
  1537. else {
  1538. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  1539. .then(() => {
  1540. next();
  1541. })
  1542. .catch(err => {
  1543. next(err);
  1544. });
  1545. }
  1546. }
  1547. ],
  1548. async err => {
  1549. if (err) {
  1550. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1551. this.log(
  1552. "ERROR",
  1553. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1554. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1555. );
  1556. return cb({ status: "error", message: err });
  1557. }
  1558. this.log(
  1559. "SUCCESS",
  1560. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1561. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  1562. );
  1563. return cb({
  1564. status: "success",
  1565. message: "Playlist has been successfully cleared and refilled"
  1566. });
  1567. }
  1568. );
  1569. }),
  1570. /**
  1571. * Clears and refills a genre playlist
  1572. *
  1573. * @param {object} session - the session object automatically added by socket.io
  1574. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1575. * @param {Function} cb - gets called with the result
  1576. */
  1577. clearAndRefillGenrePlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1578. async.waterfall(
  1579. [
  1580. next => {
  1581. if (!playlistId) next("Please specify a playlist id");
  1582. else {
  1583. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  1584. .then(() => {
  1585. next();
  1586. })
  1587. .catch(err => {
  1588. next(err);
  1589. });
  1590. }
  1591. }
  1592. ],
  1593. async err => {
  1594. if (err) {
  1595. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1596. this.log(
  1597. "ERROR",
  1598. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1599. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1600. );
  1601. return cb({ status: "error", message: err });
  1602. }
  1603. this.log(
  1604. "SUCCESS",
  1605. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1606. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  1607. );
  1608. return cb({
  1609. status: "success",
  1610. message: "Playlist has been successfully cleared and refilled"
  1611. });
  1612. }
  1613. );
  1614. }),
  1615. /**
  1616. * Clears and refills all station playlists
  1617. *
  1618. * @param {object} session - the session object automatically added by socket.io
  1619. * @param {Function} cb - gets called with the result
  1620. */
  1621. clearAndRefillAllStationPlaylists: isAdminRequired(async function index(session, cb) {
  1622. async.waterfall(
  1623. [
  1624. next => {
  1625. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  1626. .then(response => {
  1627. next(null, response.playlists);
  1628. })
  1629. .catch(err => {
  1630. next(err);
  1631. });
  1632. },
  1633. (playlists, next) => {
  1634. async.eachLimit(
  1635. playlists,
  1636. 1,
  1637. (playlist, next) => {
  1638. PlaylistsModule.runJob(
  1639. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  1640. { playlistId: playlist._id },
  1641. this
  1642. )
  1643. .then(() => {
  1644. next();
  1645. })
  1646. .catch(err => {
  1647. next(err);
  1648. });
  1649. },
  1650. next
  1651. );
  1652. }
  1653. ],
  1654. async err => {
  1655. if (err) {
  1656. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1657. this.log(
  1658. "ERROR",
  1659. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  1660. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  1661. );
  1662. return cb({ status: "error", message: err });
  1663. }
  1664. this.log(
  1665. "SUCCESS",
  1666. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  1667. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  1668. );
  1669. return cb({
  1670. status: "success",
  1671. message: "Playlists have been successfully cleared and refilled"
  1672. });
  1673. }
  1674. );
  1675. }),
  1676. /**
  1677. * Clears and refills all genre playlists
  1678. *
  1679. * @param {object} session - the session object automatically added by socket.io
  1680. * @param {Function} cb - gets called with the result
  1681. */
  1682. clearAndRefillAllGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1683. async.waterfall(
  1684. [
  1685. next => {
  1686. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  1687. .then(response => {
  1688. next(null, response.playlists);
  1689. })
  1690. .catch(err => {
  1691. next(err);
  1692. });
  1693. },
  1694. (playlists, next) => {
  1695. async.eachLimit(
  1696. playlists,
  1697. 1,
  1698. (playlist, next) => {
  1699. PlaylistsModule.runJob(
  1700. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1701. { playlistId: playlist._id },
  1702. this
  1703. )
  1704. .then(() => {
  1705. next();
  1706. })
  1707. .catch(err => {
  1708. next(err);
  1709. });
  1710. },
  1711. next
  1712. );
  1713. }
  1714. ],
  1715. async err => {
  1716. if (err) {
  1717. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1718. this.log(
  1719. "ERROR",
  1720. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  1721. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  1722. );
  1723. return cb({ status: "error", message: err });
  1724. }
  1725. this.log(
  1726. "SUCCESS",
  1727. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  1728. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  1729. );
  1730. return cb({
  1731. status: "success",
  1732. message: "Playlists have been successfully cleared and refilled"
  1733. });
  1734. }
  1735. );
  1736. })
  1737. };