playlists.js 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  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 user's own modifiable user 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 removing
  1226. * @param {Function} cb - gets called with the result
  1227. */
  1228. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1229. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1230. async.waterfall(
  1231. [
  1232. next => {
  1233. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1234. .then(playlist => next(null, playlist))
  1235. .catch(next);
  1236. },
  1237. (playlist, next) => {
  1238. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  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. ],
  1255. async (err, playlist) => {
  1256. if (err) {
  1257. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1258. this.log(
  1259. "ERROR",
  1260. "PLAYLIST_REMOVE",
  1261. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1262. );
  1263. return cb({ status: "error", message: err });
  1264. }
  1265. this.log(
  1266. "SUCCESS",
  1267. "PLAYLIST_REMOVE",
  1268. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1269. );
  1270. CacheModule.runJob("PUB", {
  1271. channel: "playlist.delete",
  1272. value: {
  1273. userId: session.userId,
  1274. playlistId
  1275. }
  1276. });
  1277. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1278. userId: playlist.createdBy,
  1279. type: "playlist__remove",
  1280. payload: {
  1281. message: `Removed playlist ${playlist.displayName}`
  1282. }
  1283. });
  1284. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1285. return cb({
  1286. status: "success",
  1287. message: "Playlist successfully removed"
  1288. });
  1289. }
  1290. );
  1291. }),
  1292. /**
  1293. * Removes a user's modifiable user playlist as an admin
  1294. *
  1295. * @param {object} session - the session object automatically added by the websocket
  1296. * @param {string} playlistId - the id of the playlist we are removing
  1297. * @param {Function} cb - gets called with the result
  1298. */
  1299. removeAdmin: isAdminRequired(async function removeAdmin(session, playlistId, cb) {
  1300. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1301. async.waterfall(
  1302. [
  1303. next => {
  1304. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1305. .then(playlist => next(null, playlist))
  1306. .catch(next);
  1307. },
  1308. (playlist, next) => {
  1309. if (!playlist.isUserModifiable) return next("Playlist cannot be removed.");
  1310. return next(null, playlist);
  1311. },
  1312. (playlist, next) => {
  1313. userModel.updateOne(
  1314. { _id: playlist.createdBy },
  1315. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1316. err => next(err, playlist, playlist.createdBy)
  1317. );
  1318. },
  1319. (playlist, playlistCreator, next) => {
  1320. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1321. .then(() => next(null, playlistCreator))
  1322. .catch(next);
  1323. }
  1324. ],
  1325. async (err, playlistCreator) => {
  1326. if (err) {
  1327. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1328. this.log(
  1329. "ERROR",
  1330. "PLAYLIST_REMOVE_ADMIN",
  1331. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1332. );
  1333. return cb({ status: "error", message: err });
  1334. }
  1335. this.log(
  1336. "SUCCESS",
  1337. "PLAYLIST_REMOVE_ADMIN",
  1338. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1339. );
  1340. CacheModule.runJob("PUB", {
  1341. channel: "playlist.delete",
  1342. value: {
  1343. userId: playlistCreator,
  1344. playlistId
  1345. }
  1346. });
  1347. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1348. return cb({
  1349. status: "success",
  1350. message: "Playlist successfully removed"
  1351. });
  1352. }
  1353. );
  1354. }),
  1355. /**
  1356. * Updates the privacy of a private playlist
  1357. *
  1358. * @param {object} session - the session object automatically added by the websocket
  1359. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1360. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1361. * @param {Function} cb - gets called with the result
  1362. */
  1363. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1364. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1365. async.waterfall(
  1366. [
  1367. next => {
  1368. playlistModel.updateOne(
  1369. { _id: playlistId, createdBy: session.userId },
  1370. { $set: { privacy } },
  1371. { runValidators: true },
  1372. next
  1373. );
  1374. },
  1375. (res, next) => {
  1376. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  1377. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1378. else {
  1379. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1380. .then(playlist => next(null, playlist))
  1381. .catch(next);
  1382. }
  1383. }
  1384. ],
  1385. async (err, playlist) => {
  1386. if (err) {
  1387. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1388. this.log(
  1389. "ERROR",
  1390. "PLAYLIST_UPDATE_PRIVACY",
  1391. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1392. );
  1393. return cb({ status: "error", message: err });
  1394. }
  1395. this.log(
  1396. "SUCCESS",
  1397. "PLAYLIST_UPDATE_PRIVACY",
  1398. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1399. );
  1400. CacheModule.runJob("PUB", {
  1401. channel: "playlist.updatePrivacy",
  1402. value: {
  1403. userId: session.userId,
  1404. playlist
  1405. }
  1406. });
  1407. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1408. userId: session.userId,
  1409. type: "playlist__edit_privacy",
  1410. payload: {
  1411. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1412. playlistId
  1413. }
  1414. });
  1415. return cb({
  1416. status: "success",
  1417. message: "Playlist has been successfully updated"
  1418. });
  1419. }
  1420. );
  1421. }),
  1422. /**
  1423. * Updates the privacy of a playlist
  1424. *
  1425. * @param {object} session - the session object automatically added by the websocket
  1426. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1427. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1428. * @param {Function} cb - gets called with the result
  1429. */
  1430. updatePrivacyAdmin: isAdminRequired(async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  1431. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1432. async.waterfall(
  1433. [
  1434. next => {
  1435. playlistModel.updateOne({ _id: playlistId }, { $set: { privacy } }, { runValidators: true }, next);
  1436. },
  1437. (res, next) => {
  1438. if (res.n === 0) next("No playlist found with that id.");
  1439. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1440. else {
  1441. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1442. .then(playlist => next(null, playlist))
  1443. .catch(next);
  1444. }
  1445. }
  1446. ],
  1447. async (err, playlist) => {
  1448. if (err) {
  1449. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1450. this.log(
  1451. "ERROR",
  1452. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  1453. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1454. );
  1455. return cb({ status: "error", message: err });
  1456. }
  1457. this.log(
  1458. "SUCCESS",
  1459. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  1460. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  1461. );
  1462. if (playlist.type === "user") {
  1463. CacheModule.runJob("PUB", {
  1464. channel: "playlist.updatePrivacy",
  1465. value: {
  1466. userId: playlist.createdBy,
  1467. playlist
  1468. }
  1469. });
  1470. }
  1471. return cb({
  1472. status: "success",
  1473. message: "Playlist has been successfully updated"
  1474. });
  1475. }
  1476. );
  1477. }),
  1478. /**
  1479. * Deletes all orphaned station playlists
  1480. *
  1481. * @param {object} session - the session object automatically added by socket.io
  1482. * @param {Function} cb - gets called with the result
  1483. */
  1484. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1485. async.waterfall(
  1486. [
  1487. next => {
  1488. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1489. .then(() => next())
  1490. .catch(next);
  1491. }
  1492. ],
  1493. async err => {
  1494. if (err) {
  1495. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1496. this.log(
  1497. "ERROR",
  1498. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1499. `Deleting orphaned station playlists failed. "${err}"`
  1500. );
  1501. return cb({ status: "error", message: err });
  1502. }
  1503. this.log(
  1504. "SUCCESS",
  1505. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1506. "Deleting orphaned station playlists successful."
  1507. );
  1508. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1509. }
  1510. );
  1511. }),
  1512. /**
  1513. * Deletes all orphaned genre playlists
  1514. *
  1515. * @param {object} session - the session object automatically added by socket.io
  1516. * @param {Function} cb - gets called with the result
  1517. */
  1518. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1519. async.waterfall(
  1520. [
  1521. next => {
  1522. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1523. .then(() => next())
  1524. .catch(next);
  1525. }
  1526. ],
  1527. async err => {
  1528. if (err) {
  1529. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1530. this.log(
  1531. "ERROR",
  1532. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1533. `Deleting orphaned genre playlists failed. "${err}"`
  1534. );
  1535. return cb({ status: "error", message: err });
  1536. }
  1537. this.log(
  1538. "SUCCESS",
  1539. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1540. "Deleting orphaned genre playlists successful."
  1541. );
  1542. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1543. }
  1544. );
  1545. }),
  1546. /**
  1547. * Requests orpahned playlist songs
  1548. *
  1549. * @param {object} session - the session object automatically added by socket.io
  1550. * @param {Function} cb - gets called with the result
  1551. */
  1552. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1553. async.waterfall(
  1554. [
  1555. next => {
  1556. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1557. .then(() => next())
  1558. .catch(next);
  1559. }
  1560. ],
  1561. async err => {
  1562. if (err) {
  1563. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1564. this.log(
  1565. "ERROR",
  1566. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1567. `Requesting orphaned playlist songs failed. "${err}"`
  1568. );
  1569. return cb({ status: "error", message: err });
  1570. }
  1571. this.log(
  1572. "SUCCESS",
  1573. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1574. "Requesting orphaned playlist songs was successful."
  1575. );
  1576. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  1577. }
  1578. );
  1579. }),
  1580. /**
  1581. * Clears and refills a station playlist
  1582. *
  1583. * @param {object} session - the session object automatically added by socket.io
  1584. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1585. * @param {Function} cb - gets called with the result
  1586. */
  1587. clearAndRefillStationPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1588. async.waterfall(
  1589. [
  1590. next => {
  1591. if (!playlistId) next("Please specify a playlist id");
  1592. else {
  1593. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  1594. .then(() => {
  1595. next();
  1596. })
  1597. .catch(err => {
  1598. next(err);
  1599. });
  1600. }
  1601. }
  1602. ],
  1603. async err => {
  1604. if (err) {
  1605. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1606. this.log(
  1607. "ERROR",
  1608. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1609. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1610. );
  1611. return cb({ status: "error", message: err });
  1612. }
  1613. this.log(
  1614. "SUCCESS",
  1615. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1616. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  1617. );
  1618. return cb({
  1619. status: "success",
  1620. message: "Playlist has been successfully cleared and refilled"
  1621. });
  1622. }
  1623. );
  1624. }),
  1625. /**
  1626. * Clears and refills a genre playlist
  1627. *
  1628. * @param {object} session - the session object automatically added by socket.io
  1629. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1630. * @param {Function} cb - gets called with the result
  1631. */
  1632. clearAndRefillGenrePlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1633. async.waterfall(
  1634. [
  1635. next => {
  1636. if (!playlistId) next("Please specify a playlist id");
  1637. else {
  1638. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  1639. .then(() => {
  1640. next();
  1641. })
  1642. .catch(err => {
  1643. next(err);
  1644. });
  1645. }
  1646. }
  1647. ],
  1648. async err => {
  1649. if (err) {
  1650. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1651. this.log(
  1652. "ERROR",
  1653. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1654. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1655. );
  1656. return cb({ status: "error", message: err });
  1657. }
  1658. this.log(
  1659. "SUCCESS",
  1660. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1661. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  1662. );
  1663. return cb({
  1664. status: "success",
  1665. message: "Playlist has been successfully cleared and refilled"
  1666. });
  1667. }
  1668. );
  1669. }),
  1670. /**
  1671. * Clears and refills all station playlists
  1672. *
  1673. * @param {object} session - the session object automatically added by socket.io
  1674. * @param {Function} cb - gets called with the result
  1675. */
  1676. clearAndRefillAllStationPlaylists: isAdminRequired(async function index(session, cb) {
  1677. async.waterfall(
  1678. [
  1679. next => {
  1680. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  1681. .then(response => {
  1682. next(null, response.playlists);
  1683. })
  1684. .catch(err => {
  1685. next(err);
  1686. });
  1687. },
  1688. (playlists, next) => {
  1689. async.eachLimit(
  1690. playlists,
  1691. 1,
  1692. (playlist, next) => {
  1693. PlaylistsModule.runJob(
  1694. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  1695. { playlistId: playlist._id },
  1696. this
  1697. )
  1698. .then(() => {
  1699. next();
  1700. })
  1701. .catch(err => {
  1702. next(err);
  1703. });
  1704. },
  1705. next
  1706. );
  1707. }
  1708. ],
  1709. async err => {
  1710. if (err) {
  1711. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1712. this.log(
  1713. "ERROR",
  1714. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  1715. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  1716. );
  1717. return cb({ status: "error", message: err });
  1718. }
  1719. this.log(
  1720. "SUCCESS",
  1721. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  1722. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  1723. );
  1724. return cb({
  1725. status: "success",
  1726. message: "Playlists have been successfully cleared and refilled"
  1727. });
  1728. }
  1729. );
  1730. }),
  1731. /**
  1732. * Clears and refills all genre playlists
  1733. *
  1734. * @param {object} session - the session object automatically added by socket.io
  1735. * @param {Function} cb - gets called with the result
  1736. */
  1737. clearAndRefillAllGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1738. async.waterfall(
  1739. [
  1740. next => {
  1741. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  1742. .then(response => {
  1743. next(null, response.playlists);
  1744. })
  1745. .catch(err => {
  1746. next(err);
  1747. });
  1748. },
  1749. (playlists, next) => {
  1750. async.eachLimit(
  1751. playlists,
  1752. 1,
  1753. (playlist, next) => {
  1754. PlaylistsModule.runJob(
  1755. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1756. { playlistId: playlist._id },
  1757. this
  1758. )
  1759. .then(() => {
  1760. next();
  1761. })
  1762. .catch(err => {
  1763. next(err);
  1764. });
  1765. },
  1766. next
  1767. );
  1768. }
  1769. ],
  1770. async err => {
  1771. if (err) {
  1772. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1773. this.log(
  1774. "ERROR",
  1775. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  1776. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  1777. );
  1778. return cb({ status: "error", message: err });
  1779. }
  1780. this.log(
  1781. "SUCCESS",
  1782. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  1783. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  1784. );
  1785. return cb({
  1786. status: "success",
  1787. message: "Playlists have been successfully cleared and refilled"
  1788. });
  1789. }
  1790. );
  1791. })
  1792. };