playlists.js 52 KB

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