playlists.js 54 KB

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