playlists.js 55 KB

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