playlists.js 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187
  1. import async from "async";
  2. import config from "config";
  3. import isLoginRequired from "../hooks/loginRequired";
  4. import { hasPermission, useHasPermission } from "../hooks/hasPermission";
  5. // eslint-disable-next-line
  6. import moduleManager from "../../index";
  7. const DBModule = moduleManager.modules.db;
  8. const UtilsModule = moduleManager.modules.utils;
  9. const WSModule = moduleManager.modules.ws;
  10. const SongsModule = moduleManager.modules.songs;
  11. const CacheModule = moduleManager.modules.cache;
  12. const PlaylistsModule = moduleManager.modules.playlists;
  13. const YouTubeModule = moduleManager.modules.youtube;
  14. const SoundcloudModule = moduleManager.modules.soundcloud;
  15. const ActivitiesModule = moduleManager.modules.activities;
  16. const MediaModule = moduleManager.modules.media;
  17. CacheModule.runJob("SUB", {
  18. channel: "playlist.create",
  19. cb: playlist => {
  20. if (playlist.createdBy !== "Musare") {
  21. WSModule.runJob("SOCKETS_FROM_USER", { userId: playlist.createdBy }, this).then(sockets =>
  22. sockets.forEach(socket => socket.dispatch("event:playlist.created", { data: { playlist } }))
  23. );
  24. if (playlist.privacy === "public")
  25. WSModule.runJob("EMIT_TO_ROOM", {
  26. room: `profile.${playlist.createdBy}.playlists`,
  27. args: ["event:playlist.created", { data: { playlist } }]
  28. });
  29. }
  30. WSModule.runJob("EMIT_TO_ROOM", {
  31. room: "admin.playlists",
  32. args: ["event:admin.playlist.created", { data: { playlist } }]
  33. });
  34. }
  35. });
  36. CacheModule.runJob("SUB", {
  37. channel: "playlist.delete",
  38. cb: res => {
  39. if (res.createdBy !== "Musare") {
  40. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.createdBy }, this).then(sockets => {
  41. sockets.forEach(socket => {
  42. socket.dispatch("event:playlist.deleted", { data: { playlistId: res.playlistId } });
  43. });
  44. });
  45. WSModule.runJob("EMIT_TO_ROOM", {
  46. room: `profile.${res.createdBy}.playlists`,
  47. args: ["event:playlist.deleted", { data: { playlistId: res.playlistId } }]
  48. });
  49. }
  50. WSModule.runJob("EMIT_TO_ROOM", {
  51. room: "admin.playlists",
  52. args: ["event:admin.playlist.deleted", { data: { playlistId: res.playlistId } }]
  53. });
  54. }
  55. });
  56. CacheModule.runJob("SUB", {
  57. channel: "playlist.repositionSong",
  58. cb: res => {
  59. const { createdBy, playlistId, song } = res;
  60. if (createdBy !== "Musare") {
  61. WSModule.runJob("SOCKETS_FROM_USER", { userId: createdBy }, this).then(sockets =>
  62. sockets.forEach(socket =>
  63. socket.dispatch("event:playlist.song.repositioned", {
  64. data: { playlistId, song }
  65. })
  66. )
  67. );
  68. }
  69. }
  70. });
  71. CacheModule.runJob("SUB", {
  72. channel: "playlist.addSong",
  73. cb: res => {
  74. if (res.createdBy !== "Musare") {
  75. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.createdBy }, this).then(sockets => {
  76. sockets.forEach(socket => {
  77. socket.dispatch("event:playlist.song.added", {
  78. data: {
  79. playlistId: res.playlistId,
  80. song: res.song
  81. }
  82. });
  83. });
  84. });
  85. if (res.privacy === "public")
  86. WSModule.runJob("EMIT_TO_ROOM", {
  87. room: `profile.${res.createdBy}.playlists`,
  88. args: [
  89. "event:playlist.song.added",
  90. {
  91. data: {
  92. playlistId: res.playlistId,
  93. song: res.song
  94. }
  95. }
  96. ]
  97. });
  98. }
  99. WSModule.runJob("EMIT_TO_ROOM", {
  100. room: "admin.playlists",
  101. args: ["event:admin.playlist.song.added", { data: { playlistId: res.playlistId, song: res.song } }]
  102. });
  103. }
  104. });
  105. CacheModule.runJob("SUB", {
  106. channel: "playlist.removeSong",
  107. cb: res => {
  108. if (res.createdBy !== "Musare") {
  109. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.createdBy }, this).then(sockets => {
  110. sockets.forEach(socket => {
  111. socket.dispatch("event:playlist.song.removed", {
  112. data: {
  113. playlistId: res.playlistId,
  114. mediaSource: res.mediaSource
  115. }
  116. });
  117. });
  118. });
  119. if (res.privacy === "public")
  120. WSModule.runJob("EMIT_TO_ROOM", {
  121. room: `profile.${res.createdBy}.playlists`,
  122. args: [
  123. "event:playlist.song.removed",
  124. {
  125. data: {
  126. playlistId: res.playlistId,
  127. mediaSource: res.mediaSource
  128. }
  129. }
  130. ]
  131. });
  132. }
  133. WSModule.runJob("EMIT_TO_ROOM", {
  134. room: "admin.playlists",
  135. args: [
  136. "event:admin.playlist.song.removed",
  137. { data: { playlistId: res.playlistId, mediaSource: res.mediaSource } }
  138. ]
  139. });
  140. }
  141. });
  142. CacheModule.runJob("SUB", {
  143. channel: "playlist.updateDisplayName",
  144. cb: res => {
  145. if (res.createdBy !== "Musare") {
  146. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.createdBy }, this).then(sockets => {
  147. sockets.forEach(socket => {
  148. socket.dispatch("event:playlist.displayName.updated", {
  149. data: {
  150. playlistId: res.playlistId,
  151. displayName: res.displayName
  152. }
  153. });
  154. });
  155. });
  156. if (res.privacy === "public")
  157. WSModule.runJob("EMIT_TO_ROOM", {
  158. room: `profile.${res.createdBy}.playlists`,
  159. args: [
  160. "event:playlist.displayName.updated",
  161. {
  162. data: {
  163. playlistId: res.playlistId,
  164. displayName: res.displayName
  165. }
  166. }
  167. ]
  168. });
  169. }
  170. WSModule.runJob("EMIT_TO_ROOM", {
  171. room: "admin.playlists",
  172. args: [
  173. "event:admin.playlist.displayName.updated",
  174. { data: { playlistId: res.playlistId, displayName: res.displayName } }
  175. ]
  176. });
  177. }
  178. });
  179. CacheModule.runJob("SUB", {
  180. channel: "playlist.updatePrivacy",
  181. cb: res => {
  182. WSModule.runJob("EMIT_TO_ROOM", {
  183. room: "admin.playlists",
  184. args: [
  185. "event:admin.playlist.privacy.updated",
  186. { data: { playlistId: res.playlist._id, privacy: res.playlist.privacy } }
  187. ]
  188. });
  189. if (res.createdBy !== "Musare") {
  190. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  191. sockets.forEach(socket => {
  192. socket.dispatch("event:playlist.privacy.updated", {
  193. data: {
  194. playlist: res.playlist
  195. }
  196. });
  197. });
  198. });
  199. if (res.playlist.privacy === "public")
  200. return WSModule.runJob("EMIT_TO_ROOM", {
  201. room: `profile.${res.userId}.playlists`,
  202. args: [
  203. "event:playlist.created",
  204. {
  205. data: {
  206. playlist: res.playlist
  207. }
  208. }
  209. ]
  210. });
  211. return WSModule.runJob("EMIT_TO_ROOM", {
  212. room: `profile.${res.userId}.playlists`,
  213. args: [
  214. "event:playlist.deleted",
  215. {
  216. data: {
  217. playlistId: res.playlist._id
  218. }
  219. }
  220. ]
  221. });
  222. }
  223. return null;
  224. }
  225. });
  226. CacheModule.runJob("SUB", {
  227. channel: "playlist.updated",
  228. cb: async data => {
  229. const playlistModel = await DBModule.runJob("GET_MODEL", {
  230. modelName: "playlist"
  231. });
  232. playlistModel.findOne(
  233. { _id: data.playlistId },
  234. ["_id", "displayName", "type", "privacy", "songs", "createdBy", "createdAt", "createdFor"],
  235. (err, playlist) => {
  236. const newPlaylist = {
  237. ...playlist._doc,
  238. songsCount: playlist.songs.length,
  239. songsLength: playlist.songs.reduce(
  240. (previous, current) => ({
  241. duration: previous.duration + current.duration
  242. }),
  243. { duration: 0 }
  244. ).duration
  245. };
  246. delete newPlaylist.songs;
  247. WSModule.runJob("EMIT_TO_ROOMS", {
  248. rooms: ["admin.playlists"],
  249. args: ["event:admin.playlist.updated", { data: { playlist: newPlaylist } }]
  250. });
  251. }
  252. );
  253. }
  254. });
  255. export default {
  256. /**
  257. * Gets playlists, used in the admin playlists page by the AdvancedTable component
  258. *
  259. * @param {object} session - the session object automatically added by the websocket
  260. * @param page - the page
  261. * @param pageSize - the size per page
  262. * @param properties - the properties to return for each playlist
  263. * @param sort - the sort object
  264. * @param queries - the queries array
  265. * @param operator - the operator for queries
  266. * @param cb
  267. */
  268. getData: useHasPermission(
  269. "admin.view.playlists",
  270. async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  271. async.waterfall(
  272. [
  273. next => {
  274. DBModule.runJob(
  275. "GET_DATA",
  276. {
  277. page,
  278. pageSize,
  279. properties,
  280. sort,
  281. queries,
  282. operator,
  283. modelName: "playlist",
  284. blacklistedProperties: [],
  285. specialProperties: {
  286. totalLength: [
  287. {
  288. $addFields: {
  289. totalLength: { $sum: "$songs.duration" }
  290. }
  291. }
  292. ],
  293. songsCount: [
  294. {
  295. $addFields: {
  296. songsCount: { $size: "$songs" }
  297. }
  298. }
  299. ],
  300. createdBy: [
  301. {
  302. $addFields: {
  303. createdByOID: {
  304. $convert: {
  305. input: "$createdBy",
  306. to: "objectId",
  307. onError: "unknown",
  308. onNull: "unknown"
  309. }
  310. }
  311. }
  312. },
  313. {
  314. $lookup: {
  315. from: "users",
  316. localField: "createdByOID",
  317. foreignField: "_id",
  318. as: "createdByUser"
  319. }
  320. },
  321. {
  322. $unwind: {
  323. path: "$createdByUser",
  324. preserveNullAndEmptyArrays: true
  325. }
  326. },
  327. {
  328. $addFields: {
  329. createdByUsername: {
  330. $cond: [
  331. { $eq: ["$createdBy", "Musare"] },
  332. "Musare",
  333. { $ifNull: ["$createdByUser.username", "unknown"] }
  334. ]
  335. }
  336. }
  337. },
  338. {
  339. $project: {
  340. createdByOID: 0,
  341. createdByUser: 0
  342. }
  343. }
  344. ]
  345. },
  346. specialQueries: {
  347. createdBy: newQuery => ({
  348. $or: [newQuery, { createdByUsername: newQuery.createdBy }]
  349. })
  350. }
  351. },
  352. this
  353. )
  354. .then(response => {
  355. next(null, response);
  356. })
  357. .catch(err => {
  358. next(err);
  359. });
  360. }
  361. ],
  362. async (err, response) => {
  363. if (err) {
  364. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  365. this.log("ERROR", "PLAYLISTS_GET_DATA", `Failed to get data from playlists. "${err}"`);
  366. return cb({ status: "error", message: err });
  367. }
  368. this.log("SUCCESS", "PLAYLISTS_GET_DATA", `Got data from playlists successfully.`);
  369. return cb({ status: "success", message: "Successfully got data from playlists.", data: response });
  370. }
  371. );
  372. }
  373. ),
  374. /**
  375. * Searches through all playlists that can be included in a community station
  376. *
  377. * @param {object} session - the session object automatically added by the websocket
  378. * @param {string} query - the query
  379. * @param {string} query - the page
  380. * @param {Function} cb - gets called with the result
  381. */
  382. searchCommunity: isLoginRequired(async function searchCommunity(session, query, page, cb) {
  383. async.waterfall(
  384. [
  385. next => {
  386. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  387. else next();
  388. },
  389. next => {
  390. PlaylistsModule.runJob("SEARCH", {
  391. query,
  392. includeUser: true,
  393. includeGenre: true,
  394. includeAdmin: true,
  395. includeOwn: true,
  396. includeSongs: true,
  397. userId: session.userId,
  398. page
  399. })
  400. .then(response => {
  401. next(null, response);
  402. })
  403. .catch(err => {
  404. next(err);
  405. });
  406. }
  407. ],
  408. async (err, data) => {
  409. if (err) {
  410. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  411. this.log("ERROR", "PLAYLISTS_SEARCH_COMMUNITY", `Searching playlists failed. "${err}"`);
  412. return cb({ status: "error", message: err });
  413. }
  414. this.log("SUCCESS", "PLAYLISTS_SEARCH_COMMUNITY", "Searching playlists successful.");
  415. return cb({ status: "success", data });
  416. }
  417. );
  418. }),
  419. /**
  420. * Searches through all playlists that can be included in an official station
  421. *
  422. * @param {object} session - the session object automatically added by the websocket
  423. * @param {string} query - the query
  424. * @param {string} query - the page
  425. * @param {Function} cb - gets called with the result
  426. */
  427. searchOfficial: useHasPermission("playlists.get", async function searchOfficial(session, query, page, cb) {
  428. async.waterfall(
  429. [
  430. next => {
  431. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  432. else next();
  433. },
  434. next => {
  435. PlaylistsModule.runJob("SEARCH", {
  436. query,
  437. includeGenre: true,
  438. includePrivate: true,
  439. includeSongs: true,
  440. includeAdmin: true,
  441. page
  442. })
  443. .then(response => {
  444. next(null, response);
  445. })
  446. .catch(err => {
  447. next(err);
  448. });
  449. }
  450. ],
  451. async (err, data) => {
  452. if (err) {
  453. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  454. this.log("ERROR", "PLAYLISTS_SEARCH_OFFICIAL", `Searching playlists failed. "${err}"`);
  455. return cb({ status: "error", message: err });
  456. }
  457. this.log("SUCCESS", "PLAYLISTS_SEARCH_OFFICIAL", "Searching playlists successful.");
  458. return cb({ status: "success", data });
  459. }
  460. );
  461. }),
  462. /**
  463. * Searches through all admin playlists
  464. *
  465. * @param {object} session - the session object automatically added by the websocket
  466. * @param {string} query - the query
  467. * @param {string} query - the page
  468. * @param {Function} cb - gets called with the result
  469. */
  470. searchAdmin: useHasPermission("playlists.get", async function searchAdmin(session, query, page, cb) {
  471. async.waterfall(
  472. [
  473. next => {
  474. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  475. else next();
  476. },
  477. next => {
  478. PlaylistsModule.runJob("SEARCH", {
  479. query,
  480. includePrivate: true,
  481. includeSongs: true,
  482. includeAdmin: true,
  483. page
  484. })
  485. .then(response => {
  486. next(null, response);
  487. })
  488. .catch(err => {
  489. next(err);
  490. });
  491. }
  492. ],
  493. async (err, data) => {
  494. if (err) {
  495. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  496. this.log("ERROR", "PLAYLISTS_SEARCH_ADMIN", `Searching playlists failed. "${err}"`);
  497. return cb({ status: "error", message: err });
  498. }
  499. this.log("SUCCESS", "PLAYLISTS_SEARCH_ADMIN", "Searching playlists successful.");
  500. return cb({ status: "success", data });
  501. }
  502. );
  503. }),
  504. /**
  505. * Gets the first song from a private playlist
  506. *
  507. * @param {object} session - the session object automatically added by the websocket
  508. * @param {string} playlistId - the id of the playlist we are getting the first song from
  509. * @param {Function} cb - gets called with the result
  510. */
  511. getFirstSong: isLoginRequired(function getFirstSong(session, playlistId, cb) {
  512. async.waterfall(
  513. [
  514. next => {
  515. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  516. .then(playlist => next(null, playlist))
  517. .catch(next);
  518. },
  519. (playlist, next) => {
  520. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  521. playlist.songs.sort((a, b) => a.position - b.position);
  522. return next(null, playlist.songs[0]);
  523. }
  524. ],
  525. async (err, song) => {
  526. if (err) {
  527. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  528. this.log(
  529. "ERROR",
  530. "PLAYLIST_GET_FIRST_SONG",
  531. `Getting the first song of playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  532. );
  533. return cb({ status: "error", message: err });
  534. }
  535. this.log(
  536. "SUCCESS",
  537. "PLAYLIST_GET_FIRST_SONG",
  538. `Successfully got the first song of playlist "${playlistId}" for user "${session.userId}".`
  539. );
  540. return cb({
  541. status: "success",
  542. data: { song }
  543. });
  544. }
  545. );
  546. }),
  547. /**
  548. * Gets a list of all the playlists for a specific user
  549. *
  550. * @param {object} session - the session object automatically added by the websocket
  551. * @param {string} userId - the user id in question
  552. * @param {Function} cb - gets called with the result
  553. */
  554. indexForUser: async function indexForUser(session, userId, cb) {
  555. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  556. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  557. async.waterfall(
  558. [
  559. next => {
  560. userModel.findById(userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  561. },
  562. (user, next) => {
  563. if (!user) next("User not found");
  564. else {
  565. const { preferences } = user;
  566. const { orderOfPlaylists } = preferences;
  567. const match = {
  568. createdBy: userId,
  569. type: { $in: ["user", "user-liked", "user-disliked"] }
  570. };
  571. // if a playlist order exists
  572. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  573. playlistModel
  574. .aggregate()
  575. .match(match)
  576. .addFields({
  577. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  578. })
  579. .sort({ weight: 1 })
  580. .exec(next);
  581. }
  582. },
  583. (playlists, next) => {
  584. if (session.userId === userId) return next(null, playlists); // user requesting playlists is the owner of the playlists
  585. const filteredPlaylists = [];
  586. return async.each(
  587. playlists,
  588. (playlist, nextPlaylist) => {
  589. if (playlist.privacy === "public") filteredPlaylists.push(playlist);
  590. return nextPlaylist();
  591. },
  592. () => next(null, filteredPlaylists)
  593. );
  594. }
  595. ],
  596. async (err, playlists) => {
  597. if (err) {
  598. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  599. this.log(
  600. "ERROR",
  601. "PLAYLIST_INDEX_FOR_USER",
  602. `Indexing playlists for user "${userId}" failed. "${err}"`
  603. );
  604. return cb({ status: "error", message: err });
  605. }
  606. this.log("SUCCESS", "PLAYLIST_INDEX_FOR_USER", `Successfully indexed playlists for user "${userId}".`);
  607. return cb({
  608. status: "success",
  609. data: { playlists }
  610. });
  611. }
  612. );
  613. },
  614. /**
  615. * Gets all playlists for the user requesting it
  616. *
  617. * @param {object} session - the session object automatically added by the websocket
  618. * @param {Function} cb - gets called with the result
  619. */
  620. indexMyPlaylists: isLoginRequired(async function indexMyPlaylists(session, cb) {
  621. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  622. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  623. async.waterfall(
  624. [
  625. next => {
  626. userModel.findById(session.userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  627. },
  628. (user, next) => {
  629. if (!user) next("User not found");
  630. else {
  631. const { preferences } = user;
  632. const { orderOfPlaylists } = preferences;
  633. const match = {
  634. createdBy: session.userId,
  635. type: { $in: ["user", "user-liked", "user-disliked"] }
  636. };
  637. // if a playlist order exists
  638. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  639. playlistModel
  640. .aggregate()
  641. .match(match)
  642. .addFields({
  643. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  644. })
  645. .sort({ weight: 1 })
  646. .exec(next);
  647. }
  648. }
  649. ],
  650. async (err, playlists) => {
  651. if (err) {
  652. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  653. this.log(
  654. "ERROR",
  655. "PLAYLIST_INDEX_FOR_ME",
  656. `Indexing playlists for user "${session.userId}" failed. "${err}"`
  657. );
  658. return cb({ status: "error", message: err });
  659. }
  660. this.log(
  661. "SUCCESS",
  662. "PLAYLIST_INDEX_FOR_ME",
  663. `Successfully indexed playlists for user "${session.userId}".`
  664. );
  665. return cb({
  666. status: "success",
  667. data: { playlists }
  668. });
  669. }
  670. );
  671. }),
  672. /**
  673. * Gets all playlists playlists
  674. *
  675. * @param {object} session - the session object automatically added by the websocket
  676. * @param {Function} cb - gets called with the result
  677. */
  678. indexFeaturedPlaylists: isLoginRequired(async function indexMyPlaylists(session, cb) {
  679. async.waterfall(
  680. [
  681. next => {
  682. const featuredPlaylistIds = config.get("featuredPlaylists");
  683. if (featuredPlaylistIds.length === 0) next(true, []);
  684. else next(null, featuredPlaylistIds);
  685. },
  686. (featuredPlaylistIds, next) => {
  687. const featuredPlaylists = [];
  688. async.eachLimit(
  689. featuredPlaylistIds,
  690. 1,
  691. (playlistId, next) => {
  692. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  693. .then(playlist => {
  694. if (playlist.privacy === "public") featuredPlaylists.push(playlist);
  695. next();
  696. })
  697. .catch(next);
  698. },
  699. err => {
  700. next(err, featuredPlaylists);
  701. }
  702. );
  703. }
  704. ],
  705. async (err, playlists) => {
  706. if (err && err !== true) {
  707. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  708. this.log("ERROR", "PLAYLIST_INDEX_FEATURED", `Indexing featured playlists failed. "${err}"`);
  709. return cb({ status: "error", message: err });
  710. }
  711. this.log("SUCCESS", "PLAYLIST_INDEX_FEATURED", `Successfully indexed featured playlists.`);
  712. return cb({
  713. status: "success",
  714. data: { playlists }
  715. });
  716. }
  717. );
  718. }),
  719. /**
  720. * Creates a new private playlist
  721. *
  722. * @param {object} session - the session object automatically added by the websocket
  723. * @param {object} data - the data for the new private playlist
  724. * @param {Function} cb - gets called with the result
  725. */
  726. create: isLoginRequired(async function create(session, data, cb) {
  727. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  728. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  729. const blacklist = ["liked songs", "likedsongs", "disliked songs", "dislikedsongs"];
  730. async.waterfall(
  731. [
  732. next => (data ? next() : cb({ status: "error", message: "Invalid data" })),
  733. next => {
  734. const { displayName, songs, privacy, admin } = data;
  735. if (blacklist.indexOf(displayName.toLowerCase()) !== -1)
  736. return next("That playlist name is blacklisted. Please use a different name.");
  737. return playlistModel.create(
  738. {
  739. displayName,
  740. songs,
  741. privacy,
  742. createdBy: admin ? "Musare" : session.userId,
  743. createdAt: Date.now(),
  744. createdFor: null,
  745. type: admin ? "admin" : "user"
  746. },
  747. next
  748. );
  749. },
  750. (playlist, next) => {
  751. if (data.admin) next(null, playlist);
  752. else
  753. userModel.updateOne(
  754. { _id: session.userId },
  755. { $push: { "preferences.orderOfPlaylists": playlist._id } },
  756. err => {
  757. if (err) return next(err);
  758. return next(null, playlist);
  759. }
  760. );
  761. }
  762. ],
  763. async (err, playlist) => {
  764. let type = "unknown";
  765. if (data && data.admin) type = "admin";
  766. else if (data && !data.admin) type = "user";
  767. if (err) {
  768. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  769. this.log(
  770. "ERROR",
  771. "PLAYLIST_CREATE",
  772. `Creating ${type} playlist failed for user "${session.userId}". "${err}"`
  773. );
  774. return cb({ status: "error", message: err });
  775. }
  776. CacheModule.runJob("PUB", {
  777. channel: "playlist.create",
  778. value: playlist
  779. });
  780. if (!data.admin)
  781. ActivitiesModule.runJob("ADD_ACTIVITY", {
  782. userId: playlist.createdBy,
  783. type: "playlist__create",
  784. payload: {
  785. message: `Created playlist <playlistId>${playlist.displayName}</playlistId>`,
  786. playlistId: playlist._id
  787. }
  788. });
  789. this.log(
  790. "SUCCESS",
  791. "PLAYLIST_CREATE",
  792. `Successfully created ${type} playlist for user "${session.userId}".`
  793. );
  794. return cb({
  795. status: "success",
  796. message: "Successfully created playlist",
  797. data: {
  798. playlistId: playlist._id
  799. }
  800. });
  801. }
  802. );
  803. }),
  804. /**
  805. * Gets a playlist from id
  806. *
  807. * @param {object} session - the session object automatically added by the websocket
  808. * @param {string} playlistId - the id of the playlist we are getting
  809. * @param {Function} cb - gets called with the result
  810. */
  811. getPlaylist: function getPlaylist(session, playlistId, cb) {
  812. async.waterfall(
  813. [
  814. next => {
  815. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  816. .then(playlist => next(null, playlist))
  817. .catch(next);
  818. },
  819. (playlist, next) => {
  820. if (!playlist) return next("Playlist not found");
  821. if (playlist.privacy !== "public" && playlist.createdBy !== session.userId)
  822. return hasPermission("playlists.get", session)
  823. .then(() => next(null, playlist))
  824. .catch(() => next("User unauthorised to view playlist."));
  825. return next(null, playlist);
  826. }
  827. ],
  828. async (err, playlist) => {
  829. if (err) {
  830. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  831. this.log(
  832. "ERROR",
  833. "PLAYLIST_GET",
  834. `Getting private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  835. );
  836. return cb({ status: "error", message: err });
  837. }
  838. this.log(
  839. "SUCCESS",
  840. "PLAYLIST_GET",
  841. `Successfully got private playlist "${playlistId}" for user "${session.userId}".`
  842. );
  843. return cb({
  844. status: "success",
  845. data: { playlist }
  846. });
  847. }
  848. );
  849. },
  850. /**
  851. * Gets a playlist from station id
  852. *
  853. * @param {object} session - the session object automatically added by the websocket
  854. * @param {string} stationId - the id of the station we are getting
  855. * @param {string} includeSongs - include songs
  856. * @param {Function} cb - gets called with the result
  857. */
  858. getPlaylistForStation: function getPlaylist(session, stationId, includeSongs, cb) {
  859. async.waterfall(
  860. [
  861. next => {
  862. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs }, this)
  863. .then(response => next(null, response.playlist))
  864. .catch(next);
  865. },
  866. (playlist, next) => {
  867. if (!playlist) return next("Playlist not found");
  868. if (playlist.privacy !== "public")
  869. return hasPermission("stations.view", session, stationId)
  870. .then(() => next(null, playlist))
  871. .catch(() => next("User unauthorised to view playlist."));
  872. return next(null, playlist);
  873. }
  874. ],
  875. async (err, playlist) => {
  876. if (err) {
  877. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  878. this.log(
  879. "ERROR",
  880. "PLAYLIST_GET",
  881. `Getting playlist for station "${stationId}" failed for user "${session.userId}". "${err}"`
  882. );
  883. return cb({ status: "error", message: err });
  884. }
  885. this.log(
  886. "SUCCESS",
  887. "PLAYLIST_GET",
  888. `Successfully got playlist for station "${stationId}" for user "${session.userId}".`
  889. );
  890. return cb({
  891. status: "success",
  892. data: { playlist }
  893. });
  894. }
  895. );
  896. },
  897. /**
  898. * Shuffles songs in a private playlist
  899. *
  900. * @param {object} session - the session object automatically added by the websocket
  901. * @param {string} playlistId - the id of the playlist we are updating
  902. * @param {Function} cb - gets called with the result
  903. */
  904. shuffle: isLoginRequired(async function shuffle(session, playlistId, cb) {
  905. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  906. async.waterfall(
  907. [
  908. next => {
  909. if (!playlistId) return next("No playlist id.");
  910. return next();
  911. },
  912. next => {
  913. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  914. .then(playlist => {
  915. if (!playlist || playlist.createdBy !== session.userId)
  916. return next("Something went wrong when trying to get the playlist");
  917. return next(null, playlist);
  918. })
  919. .catch(next);
  920. },
  921. (playlist, next) => {
  922. if (!playlist.isUserModifiable) return next("Playlist cannot be shuffled.");
  923. return UtilsModule.runJob("SHUFFLE_SONG_POSITIONS", { array: playlist.songs }, this)
  924. .then(result => next(null, result.array))
  925. .catch(next);
  926. },
  927. (songs, next) => {
  928. playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, { runValidators: true }, next);
  929. },
  930. (res, next) => {
  931. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  932. .then(playlist => next(null, playlist))
  933. .catch(next);
  934. }
  935. ],
  936. async (err, playlist) => {
  937. if (err) {
  938. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  939. this.log(
  940. "ERROR",
  941. "PLAYLIST_SHUFFLE",
  942. `Updating private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  943. );
  944. return cb({ status: "error", message: err });
  945. }
  946. this.log(
  947. "SUCCESS",
  948. "PLAYLIST_SHUFFLE",
  949. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  950. );
  951. return cb({
  952. status: "success",
  953. message: "Successfully shuffled playlist.",
  954. data: { playlist }
  955. });
  956. }
  957. );
  958. }),
  959. /**
  960. * Changes the order (position) of a song in a playlist
  961. *
  962. * @param {object} session - the session object automatically added by the websocket
  963. * @param {string} playlistId - the id of the playlist we are targeting
  964. * @param {object} song - the song to be repositioned
  965. * @param {string} song.mediaSource - the media source of the song being repositioned
  966. * @param {string} song.newIndex - the new position of the song in the playlist
  967. * @param {...any} song.args - any other elements that would be included with a song item in a playlist
  968. * @param {Function} cb - gets called with the result
  969. */
  970. repositionSong: isLoginRequired(async function repositionSong(session, playlistId, song, cb) {
  971. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  972. async.waterfall(
  973. [
  974. next => {
  975. if (!playlistId) return next("Please provide a playlist.");
  976. if (!song || !song.mediaSource) return next("You must provide a song to reposition.");
  977. return next();
  978. },
  979. next => {
  980. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  981. .then(playlist => {
  982. if (!playlist) return next("Playlist not found.");
  983. if (playlist.createdBy !== session.userId)
  984. return hasPermission("playlists.songs.reposition", session)
  985. .then(() => next())
  986. .catch(() => next("Invalid permissions."));
  987. return next();
  988. })
  989. .catch(next);
  990. },
  991. // remove song from playlist
  992. next => {
  993. playlistModel.updateOne(
  994. { _id: playlistId },
  995. { $pull: { songs: { mediaSource: song.mediaSource } } },
  996. next
  997. );
  998. },
  999. // add song back to playlist (in new position)
  1000. (res, next) => {
  1001. playlistModel.updateOne(
  1002. { _id: playlistId },
  1003. { $push: { songs: { $each: [song], $position: song.newIndex } } },
  1004. err => next(err)
  1005. );
  1006. },
  1007. // update the cache with the new songs positioning
  1008. next => {
  1009. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1010. .then(playlist => next(null, playlist))
  1011. .catch(next);
  1012. }
  1013. ],
  1014. async (err, playlist) => {
  1015. if (err) {
  1016. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1017. this.log(
  1018. "ERROR",
  1019. "PLAYLIST_REPOSITION_SONG",
  1020. `Repositioning song ${song.mediaSource} for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1021. );
  1022. return cb({ status: "error", message: err });
  1023. }
  1024. this.log(
  1025. "SUCCESS",
  1026. "PLAYLIST_REPOSITION_SONG",
  1027. `Successfully repositioned song ${song.mediaSource} for private playlist "${playlistId}" for user "${session.userId}".`
  1028. );
  1029. CacheModule.runJob("PUB", {
  1030. channel: "playlist.repositionSong",
  1031. value: {
  1032. createdBy: playlist.createdBy,
  1033. playlistId,
  1034. song
  1035. }
  1036. });
  1037. return cb({
  1038. status: "success",
  1039. message: "Successfully repositioned song"
  1040. });
  1041. }
  1042. );
  1043. }),
  1044. /**
  1045. * Adds a song to a private playlist
  1046. *
  1047. * @param {object} session - the session object automatically added by the websocket
  1048. * @param {boolean} isSet - is the song part of a set of songs to be added
  1049. * @param {string} mediaSource - the media source of the song we are trying to add
  1050. * @param {string} playlistId - the id of the playlist we are adding the song to
  1051. * @param {Function} cb - gets called with the result
  1052. */
  1053. addSongToPlaylist: isLoginRequired(async function addSongToPlaylist(session, isSet, mediaSource, playlistId, cb) {
  1054. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1055. async.waterfall(
  1056. [
  1057. next => {
  1058. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1059. .then(playlist => {
  1060. if (!playlist) return next("Playlist not found.");
  1061. if (playlist.createdBy !== session.userId)
  1062. return hasPermission("playlists.songs.add", session)
  1063. .then(() => next(null, playlist))
  1064. .catch(() => next("Invalid permissions."));
  1065. return next(null, playlist);
  1066. })
  1067. .catch(next);
  1068. },
  1069. (playlist, next) => {
  1070. MediaModule.runJob("GET_MEDIA", { mediaSource }, this)
  1071. .then(res =>
  1072. next(null, playlist, {
  1073. _id: res.song._id,
  1074. title: res.song.title,
  1075. thumbnail: res.song.thumbnail,
  1076. artists: res.song.artists,
  1077. mediaSource: res.song.mediaSource
  1078. })
  1079. )
  1080. .catch(next);
  1081. },
  1082. (playlist, song, next) => {
  1083. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1084. const oppositeType = playlist.type === "user-liked" ? "user-disliked" : "user-liked";
  1085. const oppositePlaylistName = oppositeType === "user-liked" ? "Liked Songs" : "Disliked Songs";
  1086. playlistModel.count(
  1087. { type: oppositeType, createdBy: session.userId, "songs.mediaSource": song.mediaSource },
  1088. (err, results) => {
  1089. if (err) next(err);
  1090. else if (results > 0)
  1091. next(
  1092. `That song is already in your ${oppositePlaylistName} playlist. A song cannot be in both the Liked Songs playlist and the Disliked Songs playlist at the same time.`
  1093. );
  1094. else next(null, song);
  1095. }
  1096. );
  1097. } else next(null, song);
  1098. },
  1099. (_song, next) => {
  1100. PlaylistsModule.runJob("ADD_SONG_TO_PLAYLIST", { playlistId, mediaSource: _song.mediaSource }, this)
  1101. .then(res => {
  1102. const { playlist, song, ratings } = res;
  1103. next(null, playlist, song, ratings);
  1104. })
  1105. .catch(next);
  1106. }
  1107. ],
  1108. async (err, playlist, newSong, ratings) => {
  1109. if (err) {
  1110. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1111. this.log(
  1112. "ERROR",
  1113. "PLAYLIST_ADD_SONG",
  1114. `Adding song "${mediaSource}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1115. );
  1116. return cb({ status: "error", message: err });
  1117. }
  1118. this.log(
  1119. "SUCCESS",
  1120. "PLAYLIST_ADD_SONG",
  1121. `Successfully added song "${mediaSource}" to private playlist "${playlistId}" for user "${session.userId}".`
  1122. );
  1123. if (!isSet && playlist.type === "user" && playlist.privacy === "public") {
  1124. const songName = newSong.artists
  1125. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  1126. : newSong.title;
  1127. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1128. userId: session.userId,
  1129. type: "playlist__add_song",
  1130. payload: {
  1131. message: `Added <mediaSource>${songName}</mediaSource> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1132. thumbnail: newSong.thumbnail,
  1133. playlistId,
  1134. mediaSource
  1135. }
  1136. });
  1137. }
  1138. CacheModule.runJob("PUB", {
  1139. channel: "playlist.addSong",
  1140. value: {
  1141. playlistId: playlist._id,
  1142. song: newSong,
  1143. createdBy: playlist.createdBy,
  1144. privacy: playlist.privacy
  1145. }
  1146. });
  1147. CacheModule.runJob("PUB", {
  1148. channel: "playlist.updated",
  1149. value: { playlistId }
  1150. });
  1151. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1152. const { _id, mediaSource, title, artists, thumbnail } = newSong;
  1153. const { likes, dislikes } = ratings;
  1154. if (_id) SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1155. if (playlist.type === "user-liked") {
  1156. CacheModule.runJob("PUB", {
  1157. channel: "ratings.like",
  1158. value: JSON.stringify({
  1159. mediaSource,
  1160. userId: session.userId,
  1161. likes,
  1162. dislikes
  1163. })
  1164. });
  1165. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1166. userId: session.userId,
  1167. type: "song__like",
  1168. payload: {
  1169. message: `Liked song <mediaSource>${title} by ${artists.join(", ")}</mediaSource>`,
  1170. mediaSource,
  1171. thumbnail
  1172. }
  1173. });
  1174. } else {
  1175. CacheModule.runJob("PUB", {
  1176. channel: "ratings.dislike",
  1177. value: JSON.stringify({
  1178. mediaSource,
  1179. userId: session.userId,
  1180. likes,
  1181. dislikes
  1182. })
  1183. });
  1184. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1185. userId: session.userId,
  1186. type: "song__dislike",
  1187. payload: {
  1188. message: `Disliked song <mediaSource>${title} by ${artists.join(
  1189. mediaSource
  1190. )}</mediaSource>`,
  1191. mediaSource,
  1192. thumbnail
  1193. }
  1194. });
  1195. }
  1196. }
  1197. return cb({
  1198. status: "success",
  1199. message: "Song has been successfully added to the playlist",
  1200. data: { songs: playlist.songs }
  1201. });
  1202. }
  1203. );
  1204. }),
  1205. /**
  1206. * Adds songs to a playlist
  1207. *
  1208. * @param {object} session - the session object automatically added by the websocket
  1209. * @param {string} playlistId - the id of the playlist we are adding the songs to
  1210. * @param {Array} mediaSources - the media sources of the songs we are trying to add
  1211. * @param {Function} cb - gets called with the result
  1212. */
  1213. addSongsToPlaylist: isLoginRequired(async function addSongsToPlaylist(session, playlistId, mediaSources, cb) {
  1214. const successful = [];
  1215. const existing = [];
  1216. const failed = {};
  1217. const errors = {};
  1218. const lastYoutubeId = "none";
  1219. const songsAdded = [];
  1220. const addError = message => {
  1221. if (!errors[message]) errors[message] = 1;
  1222. else errors[message] += 1;
  1223. };
  1224. async.waterfall(
  1225. [
  1226. next => {
  1227. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1228. .then(playlist => {
  1229. if (!playlist) return next("Playlist not found.");
  1230. if (playlist.createdBy !== session.userId)
  1231. return hasPermission("playlists.songs.add", session)
  1232. .then(() => next(null, playlist))
  1233. .catch(() => next("Invalid permissions."));
  1234. return next(null, playlist);
  1235. })
  1236. .catch(next);
  1237. },
  1238. async () => {
  1239. this.keepLongJob();
  1240. this.publishProgress({
  1241. status: "started",
  1242. title: "Bulk add songs to playlist",
  1243. message: "Adding songs to playlist.",
  1244. id: this.toString()
  1245. });
  1246. await CacheModule.runJob(
  1247. "RPUSH",
  1248. { key: `longJobs.${session.userId}`, value: this.toString() },
  1249. this
  1250. );
  1251. await CacheModule.runJob(
  1252. "PUB",
  1253. {
  1254. channel: "longJob.added",
  1255. value: { jobId: this.toString(), userId: session.userId }
  1256. },
  1257. this
  1258. );
  1259. },
  1260. (nothing, next) => {
  1261. async.eachLimit(
  1262. mediaSources,
  1263. 1,
  1264. (mediaSource, next) => {
  1265. this.publishProgress({ status: "update", message: `Adding song "${mediaSource}"` });
  1266. PlaylistsModule.runJob("ADD_SONG_TO_PLAYLIST", { playlistId, mediaSource }, this)
  1267. .then(({ song }) => {
  1268. successful.push(mediaSource);
  1269. songsAdded.push(song);
  1270. next();
  1271. })
  1272. .catch(async err => {
  1273. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1274. if (err === "That song is already in the playlist.") {
  1275. existing.push(mediaSource);
  1276. next();
  1277. } else {
  1278. addError(err);
  1279. failed[mediaSource] = err;
  1280. next();
  1281. }
  1282. });
  1283. },
  1284. err => {
  1285. if (err) next(err);
  1286. else next();
  1287. }
  1288. );
  1289. },
  1290. next => {
  1291. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1292. .then(playlist => {
  1293. if (!playlist) return next("Playlist not found.");
  1294. return next(null, playlist);
  1295. })
  1296. .catch(next);
  1297. }
  1298. ],
  1299. async (err, playlist) => {
  1300. if (err) {
  1301. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1302. this.log(
  1303. "ERROR",
  1304. "PLAYLIST_ADD_SONGS",
  1305. `Adding songs to playlist "${playlistId}" failed for user "${
  1306. session.userId
  1307. }". "${err}". Stats: successful:${successful.length}, existing:${existing.length}, failed:${
  1308. Object.keys(failed).length
  1309. }, last mediaSource:${lastYoutubeId}, mediaSources length:${
  1310. mediaSources ? mediaSources.length : null
  1311. }`
  1312. );
  1313. return cb({
  1314. status: "error",
  1315. message: err,
  1316. data: {
  1317. stats: {
  1318. successful,
  1319. existing,
  1320. failed,
  1321. errors
  1322. }
  1323. }
  1324. });
  1325. }
  1326. this.log(
  1327. "SUCCESS",
  1328. "PLAYLIST_ADD_SONGS",
  1329. `Successfully added songs to playlist "${playlistId}" for user "${
  1330. session.userId
  1331. }". Stats: successful:${successful.length}, existing:${existing.length}, failed:${
  1332. Object.keys(failed).length
  1333. }, mediaSources length:${mediaSources ? mediaSources.length : null}`
  1334. );
  1335. await async.eachLimit(songsAdded, 1, (song, next) => {
  1336. CacheModule.runJob("PUB", {
  1337. channel: "playlist.addSong",
  1338. value: {
  1339. playlistId: playlist._id,
  1340. song,
  1341. createdBy: playlist.createdBy,
  1342. privacy: playlist.privacy
  1343. }
  1344. });
  1345. next();
  1346. });
  1347. CacheModule.runJob("PUB", {
  1348. channel: "playlist.updated",
  1349. value: { playlistId }
  1350. });
  1351. const message = `Done adding songs. Succesful: ${successful.length}, failed: ${
  1352. Object.keys(failed).length
  1353. }, existing: ${existing.length}.`;
  1354. this.publishProgress({
  1355. status: "success",
  1356. message
  1357. });
  1358. return cb({
  1359. status: "success",
  1360. message,
  1361. data: {
  1362. songs: playlist.songs,
  1363. stats: {
  1364. successful,
  1365. existing,
  1366. failed,
  1367. errors
  1368. }
  1369. }
  1370. });
  1371. }
  1372. );
  1373. }),
  1374. /**
  1375. * Removes songs from a playlist
  1376. *
  1377. * @param {object} session - the session object automatically added by the websocket
  1378. * @param {string} playlistId - the id of the playlist we are removing the songs from
  1379. * @param {Array} mediaSources - the media sources of the songs we are trying to remove
  1380. * @param {Function} cb - gets called with the result
  1381. */
  1382. removeSongsFromPlaylist: useHasPermission(
  1383. "playlists.songs.remove",
  1384. async function removeSongsFromPlaylist(session, playlistId, mediaSources, cb) {
  1385. const successful = [];
  1386. const notInPlaylist = [];
  1387. const failed = {};
  1388. const errors = {};
  1389. const lastYoutubeId = "none";
  1390. const addError = message => {
  1391. if (!errors[message]) errors[message] = 1;
  1392. else errors[message] += 1;
  1393. };
  1394. this.keepLongJob();
  1395. this.publishProgress({
  1396. status: "started",
  1397. title: "Bulk remove songs from playlist",
  1398. message: "Removing songs from playlist.",
  1399. id: this.toString()
  1400. });
  1401. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1402. await CacheModule.runJob(
  1403. "PUB",
  1404. {
  1405. channel: "longJob.added",
  1406. value: { jobId: this.toString(), userId: session.userId }
  1407. },
  1408. this
  1409. );
  1410. async.waterfall(
  1411. [
  1412. next => {
  1413. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1414. .then(playlist => {
  1415. if (!playlist) return next("Playlist not found.");
  1416. return next(null, playlist);
  1417. })
  1418. .catch(next);
  1419. },
  1420. (playlist, next) => {
  1421. if (playlist.type !== "admin") return next("Playlist must be of type admin.");
  1422. return next();
  1423. },
  1424. next => {
  1425. async.eachLimit(
  1426. mediaSources,
  1427. 1,
  1428. (mediaSource, next) => {
  1429. this.publishProgress({ status: "update", message: `Removing song "${mediaSource}"` });
  1430. PlaylistsModule.runJob("REMOVE_FROM_PLAYLIST", { playlistId, mediaSource }, this)
  1431. .then(() => {
  1432. successful.push(mediaSource);
  1433. next();
  1434. })
  1435. .catch(async err => {
  1436. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1437. if (err === "That song is not currently in the playlist.") {
  1438. notInPlaylist.push(mediaSource);
  1439. next();
  1440. } else {
  1441. addError(err);
  1442. failed[mediaSource] = err;
  1443. next();
  1444. }
  1445. });
  1446. },
  1447. err => {
  1448. if (err) next(err);
  1449. else next();
  1450. }
  1451. );
  1452. },
  1453. next => {
  1454. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1455. .then(playlist => {
  1456. if (!playlist) return next("Playlist not found.");
  1457. return next(null, playlist);
  1458. })
  1459. .catch(next);
  1460. }
  1461. ],
  1462. async (err, playlist) => {
  1463. if (err) {
  1464. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1465. this.log(
  1466. "ERROR",
  1467. "PLAYLIST_REMOVE_SONGS",
  1468. `Removing songs from playlist "${playlistId}" failed for user "${
  1469. session.userId
  1470. }". "${err}". Stats: successful:${successful.length}, notInPlaylist:${
  1471. notInPlaylist.length
  1472. }, failed:${
  1473. Object.keys(failed).length
  1474. }, last mediaSource:${lastYoutubeId}, mediaSources length:${
  1475. mediaSources ? mediaSources.length : null
  1476. }`
  1477. );
  1478. return cb({
  1479. status: "error",
  1480. message: err,
  1481. data: {
  1482. stats: {
  1483. successful,
  1484. notInPlaylist,
  1485. failed,
  1486. errors
  1487. }
  1488. }
  1489. });
  1490. }
  1491. this.log(
  1492. "SUCCESS",
  1493. "PLAYLIST_REMOVE_SONGS",
  1494. `Successfully removed songs from playlist "${playlistId}" for user "${
  1495. session.userId
  1496. }". Stats: successful:${successful.length}, notInPlaylist:${notInPlaylist.length}, failed:${
  1497. Object.keys(failed).length
  1498. }, mediaSources length:${mediaSources ? mediaSources.length : null}`
  1499. );
  1500. CacheModule.runJob("PUB", {
  1501. channel: "playlist.updated",
  1502. value: { playlistId }
  1503. });
  1504. const message = `Done removing songs. Succesful: ${successful.length}, failed: ${
  1505. Object.keys(failed).length
  1506. }, not in playlist: ${notInPlaylist.length}.`;
  1507. this.publishProgress({
  1508. status: "success",
  1509. message
  1510. });
  1511. return cb({
  1512. status: "success",
  1513. message,
  1514. data: {
  1515. songs: playlist.songs,
  1516. stats: {
  1517. successful,
  1518. notInPlaylist,
  1519. failed,
  1520. errors
  1521. }
  1522. }
  1523. });
  1524. }
  1525. );
  1526. }
  1527. ),
  1528. /**
  1529. * Adds a set of songs to a private playlist
  1530. *
  1531. * @param {object} session - the session object automatically added by the websocket
  1532. * @param {string} url - the url of the the YouTube playlist
  1533. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1534. * @param {boolean} musicOnly - whether to only add music to the playlist
  1535. * @param {Function} cb - gets called with the result
  1536. */
  1537. addYoutubeSetToPlaylist: isLoginRequired(async function addYoutubeSetToPlaylist(
  1538. session,
  1539. url,
  1540. playlistId,
  1541. musicOnly,
  1542. cb
  1543. ) {
  1544. let videosInPlaylistTotal = 0;
  1545. let songsInPlaylistTotal = 0;
  1546. let addSongsStats = null;
  1547. const addedSongs = [];
  1548. this.keepLongJob();
  1549. this.publishProgress({
  1550. status: "started",
  1551. title: "Import YouTube playlist",
  1552. message: "Importing YouTube playlist.",
  1553. id: this.toString()
  1554. });
  1555. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1556. await CacheModule.runJob(
  1557. "PUB",
  1558. {
  1559. channel: "longJob.added",
  1560. value: { jobId: this.toString(), userId: session.userId }
  1561. },
  1562. this
  1563. );
  1564. async.waterfall(
  1565. [
  1566. next => {
  1567. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1568. userModel.findOne({ _id: session.userId }, (err, user) => {
  1569. if (user && user.role === "admin") return next(null, true);
  1570. return next(null, false);
  1571. });
  1572. });
  1573. },
  1574. (isAdmin, next) => {
  1575. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 1)` });
  1576. const playlistRegex = /[\\?&]list=([^&#]*)/;
  1577. const channelRegex =
  1578. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  1579. if (playlistRegex.exec(url) || channelRegex.exec(url))
  1580. YouTubeModule.runJob(
  1581. playlistRegex.exec(url) ? "GET_PLAYLIST" : "GET_CHANNEL",
  1582. {
  1583. url,
  1584. musicOnly,
  1585. disableSearch: !isAdmin
  1586. },
  1587. this
  1588. )
  1589. .then(res => {
  1590. if (res.filteredSongs) {
  1591. videosInPlaylistTotal = res.songs.length;
  1592. songsInPlaylistTotal = res.filteredSongs.length;
  1593. } else {
  1594. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  1595. }
  1596. next(null, res.songs);
  1597. })
  1598. .catch(next);
  1599. else next("Invalid YouTube URL.");
  1600. },
  1601. (mediaSources, next) => {
  1602. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 2)` });
  1603. let successful = 0;
  1604. let failed = 0;
  1605. let alreadyInPlaylist = 0;
  1606. let alreadyInLikedPlaylist = 0;
  1607. let alreadyInDislikedPlaylist = 0;
  1608. if (mediaSources.length === 0) next();
  1609. async.eachLimit(
  1610. mediaSources,
  1611. 1,
  1612. (mediaSource, next) => {
  1613. WSModule.runJob(
  1614. "RUN_ACTION2",
  1615. {
  1616. session,
  1617. namespace: "playlists",
  1618. action: "addSongToPlaylist",
  1619. args: [true, mediaSource, playlistId]
  1620. },
  1621. this
  1622. )
  1623. .then(res => {
  1624. if (res.status === "success") {
  1625. successful += 1;
  1626. addedSongs.push(mediaSource);
  1627. } else failed += 1;
  1628. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1629. else if (
  1630. res.message ===
  1631. "That song is already in your Liked Songs playlist. " +
  1632. "A song cannot be in both the Liked Songs playlist" +
  1633. " and the Disliked Songs playlist at the same time."
  1634. )
  1635. alreadyInLikedPlaylist += 1;
  1636. else if (
  1637. res.message ===
  1638. "That song is already in your Disliked Songs playlist. " +
  1639. "A song cannot be in both the Liked Songs playlist " +
  1640. "and the Disliked Songs playlist at the same time."
  1641. )
  1642. alreadyInDislikedPlaylist += 1;
  1643. })
  1644. .catch(() => {
  1645. failed += 1;
  1646. })
  1647. .finally(() => next());
  1648. },
  1649. () => {
  1650. addSongsStats = {
  1651. successful,
  1652. failed,
  1653. alreadyInPlaylist,
  1654. alreadyInLikedPlaylist,
  1655. alreadyInDislikedPlaylist
  1656. };
  1657. next(null);
  1658. }
  1659. );
  1660. },
  1661. next => {
  1662. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 3)` });
  1663. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1664. .then(playlist => next(null, playlist))
  1665. .catch(next);
  1666. },
  1667. (playlist, next) => {
  1668. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 4)` });
  1669. if (!playlist) return next("Playlist not found.");
  1670. if (playlist.createdBy !== session.userId)
  1671. return hasPermission("playlists.songs.add", session)
  1672. .then(() => next(null, playlist))
  1673. .catch(() => next("Invalid permissions."));
  1674. return next(null, playlist);
  1675. }
  1676. ],
  1677. async (err, playlist) => {
  1678. if (err) {
  1679. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1680. this.log(
  1681. "ERROR",
  1682. "PLAYLIST_IMPORT",
  1683. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1684. );
  1685. this.publishProgress({
  1686. status: "error",
  1687. message: err
  1688. });
  1689. return cb({ status: "error", message: err });
  1690. }
  1691. if (playlist.privacy === "public")
  1692. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1693. userId: session.userId,
  1694. type: "playlist__import_playlist",
  1695. payload: {
  1696. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1697. playlistId
  1698. }
  1699. });
  1700. this.log(
  1701. "SUCCESS",
  1702. "PLAYLIST_IMPORT",
  1703. `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}, already in liked ${addSongsStats.alreadyInLikedPlaylist}, already in disliked ${addSongsStats.alreadyInDislikedPlaylist}.`
  1704. );
  1705. this.publishProgress({
  1706. status: "success",
  1707. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`
  1708. });
  1709. return cb({
  1710. status: "success",
  1711. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1712. data: {
  1713. songs: playlist.songs,
  1714. stats: {
  1715. videosInPlaylistTotal,
  1716. songsInPlaylistTotal,
  1717. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1718. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1719. }
  1720. }
  1721. });
  1722. }
  1723. );
  1724. }),
  1725. /**
  1726. * Adds a set of Soundcloud songs to a private playlist
  1727. *
  1728. * @param {object} session - the session object automatically added by the websocket
  1729. * @param {string} url - the url of the the SoundCloud playlist
  1730. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1731. * @param {Function} cb - gets called with the result
  1732. */
  1733. addSoundcloudSetToPlaylist: isLoginRequired(async function addSoundcloudSetToPlaylist(
  1734. session,
  1735. url,
  1736. playlistId,
  1737. cb
  1738. ) {
  1739. let songsInPlaylistTotal = 0;
  1740. let addSongsStats = null;
  1741. const addedSongs = [];
  1742. this.keepLongJob();
  1743. this.publishProgress({
  1744. status: "started",
  1745. title: "Import SoundCloud playlist",
  1746. message: "Importing SoundCloud playlist.",
  1747. id: this.toString()
  1748. });
  1749. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1750. await CacheModule.runJob(
  1751. "PUB",
  1752. {
  1753. channel: "longJob.added",
  1754. value: { jobId: this.toString(), userId: session.userId }
  1755. },
  1756. this
  1757. );
  1758. async.waterfall(
  1759. [
  1760. next => {
  1761. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1762. userModel.findOne({ _id: session.userId }, (err, user) => {
  1763. if (user && user.role === "admin") return next(null, true);
  1764. return next(null, false);
  1765. });
  1766. });
  1767. },
  1768. (isAdmin, next) => {
  1769. this.publishProgress({ status: "update", message: `Importing SoundCloud playlist (stage 1)` });
  1770. SoundcloudModule.runJob(
  1771. "GET_PLAYLIST",
  1772. {
  1773. url
  1774. },
  1775. this
  1776. )
  1777. .then(res => {
  1778. songsInPlaylistTotal = res.songs.length;
  1779. const mediaSources = res.songs.map(song => `soundcloud:${song}`);
  1780. next(null, mediaSources);
  1781. })
  1782. .catch(next);
  1783. },
  1784. (mediaSources, next) => {
  1785. this.publishProgress({ status: "update", message: `Importing SoundCloud playlist (stage 2)` });
  1786. let successful = 0;
  1787. let failed = 0;
  1788. let alreadyInPlaylist = 0;
  1789. let alreadyInLikedPlaylist = 0;
  1790. let alreadyInDislikedPlaylist = 0;
  1791. if (mediaSources.length === 0) next();
  1792. async.eachLimit(
  1793. mediaSources,
  1794. 1,
  1795. (mediaSource, next) => {
  1796. WSModule.runJob(
  1797. "RUN_ACTION2",
  1798. {
  1799. session,
  1800. namespace: "playlists",
  1801. action: "addSongToPlaylist",
  1802. args: [true, mediaSource, playlistId]
  1803. },
  1804. this
  1805. )
  1806. .then(res => {
  1807. if (res.status === "success") {
  1808. successful += 1;
  1809. addedSongs.push(mediaSource);
  1810. } else failed += 1;
  1811. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1812. else if (
  1813. res.message ===
  1814. "That song is already in your Liked Songs playlist. " +
  1815. "A song cannot be in both the Liked Songs playlist" +
  1816. " and the Disliked Songs playlist at the same time."
  1817. )
  1818. alreadyInLikedPlaylist += 1;
  1819. else if (
  1820. res.message ===
  1821. "That song is already in your Disliked Songs playlist. " +
  1822. "A song cannot be in both the Liked Songs playlist " +
  1823. "and the Disliked Songs playlist at the same time."
  1824. )
  1825. alreadyInDislikedPlaylist += 1;
  1826. })
  1827. .catch(() => {
  1828. failed += 1;
  1829. })
  1830. .finally(() => next());
  1831. },
  1832. () => {
  1833. addSongsStats = {
  1834. successful,
  1835. failed,
  1836. alreadyInPlaylist,
  1837. alreadyInLikedPlaylist,
  1838. alreadyInDislikedPlaylist
  1839. };
  1840. next(null);
  1841. }
  1842. );
  1843. },
  1844. next => {
  1845. this.publishProgress({ status: "update", message: `Importing SoundCloud playlist (stage 3)` });
  1846. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1847. .then(playlist => next(null, playlist))
  1848. .catch(next);
  1849. },
  1850. (playlist, next) => {
  1851. this.publishProgress({ status: "update", message: `Importing SoundCloud playlist (stage 4)` });
  1852. if (!playlist) return next("Playlist not found.");
  1853. if (playlist.createdBy !== session.userId)
  1854. return hasPermission("playlists.songs.add", session)
  1855. .then(() => next(null, playlist))
  1856. .catch(() => next("Invalid permissions."));
  1857. return next(null, playlist);
  1858. }
  1859. ],
  1860. async (err, playlist) => {
  1861. if (err) {
  1862. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1863. this.log(
  1864. "ERROR",
  1865. "PLAYLIST_IMPORT",
  1866. `Importing a SoundCloud playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1867. );
  1868. this.publishProgress({
  1869. status: "error",
  1870. message: err
  1871. });
  1872. return cb({ status: "error", message: err });
  1873. }
  1874. if (playlist.privacy === "public")
  1875. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1876. userId: session.userId,
  1877. type: "playlist__import_playlist",
  1878. payload: {
  1879. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1880. playlistId
  1881. }
  1882. });
  1883. this.log(
  1884. "SUCCESS",
  1885. "PLAYLIST_IMPORT",
  1886. `Successfully imported a SoundCloud playlist to private playlist "${playlistId}" for user "${session.userId}". Songs in playlist: ${songsInPlaylistTotal}, songs successfully added: ${addSongsStats.successful}, songs failed: ${addSongsStats.failed}, already in playlist: ${addSongsStats.alreadyInPlaylist}, already in liked ${addSongsStats.alreadyInLikedPlaylist}, already in disliked ${addSongsStats.alreadyInDislikedPlaylist}.`
  1887. );
  1888. this.publishProgress({
  1889. status: "success",
  1890. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`
  1891. });
  1892. return cb({
  1893. status: "success",
  1894. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1895. data: {
  1896. songs: playlist.songs,
  1897. stats: {
  1898. songsInPlaylistTotal,
  1899. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1900. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1901. }
  1902. }
  1903. });
  1904. }
  1905. );
  1906. }),
  1907. /**
  1908. * Removes a song from a private playlist
  1909. *
  1910. * @param {object} session - the session object automatically added by the websocket
  1911. * @param {string} mediaSource - the media source of the song we are removing from the private playlist
  1912. * @param {string} playlistId - the id of the playlist we are removing the song from
  1913. * @param {Function} cb - gets called with the result
  1914. */
  1915. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(
  1916. session,
  1917. mediaSource,
  1918. playlistId,
  1919. cb
  1920. ) {
  1921. async.waterfall(
  1922. [
  1923. next => {
  1924. if (!mediaSource || typeof mediaSource !== "string") return next("Invalid song id.");
  1925. if (!playlistId || typeof mediaSource !== "string") return next("Invalid playlist id.");
  1926. return next();
  1927. },
  1928. next => {
  1929. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1930. .then(playlist => {
  1931. if (!playlist) return next("Playlist not found.");
  1932. if (playlist.createdBy !== session.userId)
  1933. return hasPermission("playlists.songs.remove", session)
  1934. .then(() => next(null, playlist))
  1935. .catch(() => next("Invalid permissions."));
  1936. return next(null, playlist);
  1937. })
  1938. .catch(next);
  1939. },
  1940. (playlist, next) => {
  1941. MediaModule.runJob("GET_MEDIA", { mediaSource }, this)
  1942. .then(res =>
  1943. next(null, playlist, {
  1944. _id: res.song._id,
  1945. title: res.song.title,
  1946. thumbnail: res.song.thumbnail,
  1947. artists: res.song.artists,
  1948. mediaSource: res.song.mediaSource
  1949. })
  1950. )
  1951. .catch(next);
  1952. },
  1953. (playlist, newSong, next) => {
  1954. PlaylistsModule.runJob("REMOVE_FROM_PLAYLIST", { playlistId, mediaSource }, this)
  1955. .then(res => {
  1956. const { ratings } = res;
  1957. next(null, playlist, newSong, ratings);
  1958. })
  1959. .catch(next);
  1960. },
  1961. (playlist, newSong, ratings, next) => {
  1962. const { _id, title, artists, thumbnail } = newSong;
  1963. const songName = artists ? `${title} by ${artists.join(", ")}` : title;
  1964. if (playlist.type === "user" && playlist.privacy === "public") {
  1965. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1966. userId: session.userId,
  1967. type: "playlist__remove_song",
  1968. payload: {
  1969. message: `Removed <mediaSource>${songName}</mediaSource> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1970. thumbnail,
  1971. playlistId,
  1972. mediaSource: newSong.mediaSource
  1973. }
  1974. });
  1975. }
  1976. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1977. const { likes, dislikes } = ratings;
  1978. if (_id) SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1979. if (playlist.type === "user-liked") {
  1980. CacheModule.runJob("PUB", {
  1981. channel: "ratings.unlike",
  1982. value: JSON.stringify({
  1983. mediaSource: newSong.mediaSource,
  1984. userId: session.userId,
  1985. likes,
  1986. dislikes
  1987. })
  1988. });
  1989. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1990. userId: session.userId,
  1991. type: "song__unlike",
  1992. payload: {
  1993. message: `Removed <mediaSource>${title} by ${artists.join(
  1994. ", "
  1995. )}</mediaSource> from your Liked Songs`,
  1996. mediaSource: newSong.mediaSource,
  1997. thumbnail
  1998. }
  1999. });
  2000. } else {
  2001. CacheModule.runJob("PUB", {
  2002. channel: "ratings.undislike",
  2003. value: JSON.stringify({
  2004. mediaSource: newSong.mediaSource,
  2005. userId: session.userId,
  2006. likes,
  2007. dislikes
  2008. })
  2009. });
  2010. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2011. userId: session.userId,
  2012. type: "song__undislike",
  2013. payload: {
  2014. message: `Removed <mediaSource>${title} by ${artists.join(
  2015. ", "
  2016. )}</mediaSource> from your Disliked Songs`,
  2017. mediaSource: newSong.mediaSource,
  2018. thumbnail
  2019. }
  2020. });
  2021. }
  2022. }
  2023. return next(null, playlist);
  2024. }
  2025. ],
  2026. async (err, playlist) => {
  2027. if (err) {
  2028. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2029. this.log(
  2030. "ERROR",
  2031. "PLAYLIST_REMOVE_SONG",
  2032. `Removing song "${mediaSource}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2033. );
  2034. return cb({ status: "error", message: err });
  2035. }
  2036. this.log(
  2037. "SUCCESS",
  2038. "PLAYLIST_REMOVE_SONG",
  2039. `Successfully removed song "${mediaSource}" from private playlist "${playlistId}" for user "${session.userId}".`
  2040. );
  2041. CacheModule.runJob("PUB", {
  2042. channel: "playlist.removeSong",
  2043. value: {
  2044. playlistId: playlist._id,
  2045. mediaSource,
  2046. createdBy: playlist.createdBy,
  2047. privacy: playlist.privacy
  2048. }
  2049. });
  2050. return cb({
  2051. status: "success",
  2052. message: "Song has been successfully removed from playlist",
  2053. data: { songs: playlist.songs }
  2054. });
  2055. }
  2056. );
  2057. }),
  2058. /**
  2059. * Updates the displayName of a private playlist
  2060. *
  2061. * @param {object} session - the session object automatically added by the websocket
  2062. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  2063. * @param {Function} cb - gets called with the result
  2064. */
  2065. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  2066. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2067. async.waterfall(
  2068. [
  2069. next => {
  2070. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2071. .then(playlist => next(null, playlist))
  2072. .catch(next);
  2073. },
  2074. (playlist, next) => {
  2075. if (playlist.type === "admin")
  2076. hasPermission("playlists.update.displayName", session)
  2077. .then(() => next())
  2078. .catch(() => next("Invalid permissions."));
  2079. else if (playlist.type !== "user" || playlist.createdBy !== session.userId)
  2080. next("Playlist cannot be modified.");
  2081. else next(null);
  2082. },
  2083. next => {
  2084. playlistModel.updateOne(
  2085. { _id: playlistId },
  2086. { $set: { displayName } },
  2087. { runValidators: true },
  2088. next
  2089. );
  2090. },
  2091. (res, next) => {
  2092. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  2093. .then(playlist => next(null, playlist))
  2094. .catch(next);
  2095. }
  2096. ],
  2097. async (err, playlist) => {
  2098. if (err) {
  2099. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2100. this.log(
  2101. "ERROR",
  2102. "PLAYLIST_UPDATE_DISPLAY_NAME",
  2103. `Updating display name to "${displayName}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2104. );
  2105. return cb({ status: "error", message: err });
  2106. }
  2107. this.log(
  2108. "SUCCESS",
  2109. "PLAYLIST_UPDATE_DISPLAY_NAME",
  2110. `Successfully updated display name to "${displayName}" for playlist "${playlistId}" for user "${session.userId}".`
  2111. );
  2112. CacheModule.runJob("PUB", {
  2113. channel: "playlist.updateDisplayName",
  2114. value: {
  2115. playlistId,
  2116. displayName,
  2117. createdBy: playlist.createdBy,
  2118. privacy: playlist.privacy
  2119. }
  2120. });
  2121. CacheModule.runJob("PUB", {
  2122. channel: "playlist.updated",
  2123. value: { playlistId }
  2124. });
  2125. if (playlist.type !== "admin")
  2126. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2127. userId: session.userId,
  2128. type: "playlist__edit_display_name",
  2129. payload: {
  2130. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  2131. playlistId
  2132. }
  2133. });
  2134. return cb({
  2135. status: "success",
  2136. message: "Playlist has been successfully updated"
  2137. });
  2138. }
  2139. );
  2140. }),
  2141. /**
  2142. * Removes a user's own modifiable user playlist
  2143. *
  2144. * @param {object} session - the session object automatically added by the websocket
  2145. * @param {string} playlistId - the id of the playlist we are removing
  2146. * @param {Function} cb - gets called with the result
  2147. */
  2148. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  2149. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2150. async.waterfall(
  2151. [
  2152. next => {
  2153. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2154. .then(playlist => next(null, playlist))
  2155. .catch(next);
  2156. },
  2157. (playlist, next) => {
  2158. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  2159. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  2160. return next(null, playlist);
  2161. },
  2162. (playlist, next) => {
  2163. userModel.updateOne(
  2164. { _id: playlist.createdBy },
  2165. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  2166. err => next(err, playlist)
  2167. );
  2168. },
  2169. (playlist, next) => {
  2170. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  2171. .then(() => next(null, playlist))
  2172. .catch(next);
  2173. }
  2174. ],
  2175. async (err, playlist) => {
  2176. if (err) {
  2177. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2178. this.log(
  2179. "ERROR",
  2180. "PLAYLIST_REMOVE",
  2181. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2182. );
  2183. return cb({ status: "error", message: err });
  2184. }
  2185. this.log(
  2186. "SUCCESS",
  2187. "PLAYLIST_REMOVE",
  2188. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  2189. );
  2190. CacheModule.runJob("PUB", {
  2191. channel: "playlist.delete",
  2192. value: {
  2193. createdBy: playlist.createdBy,
  2194. playlistId
  2195. }
  2196. });
  2197. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2198. userId: playlist.createdBy,
  2199. type: "playlist__remove",
  2200. payload: {
  2201. message: `Removed playlist ${playlist.displayName}`
  2202. }
  2203. });
  2204. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  2205. return cb({
  2206. status: "success",
  2207. message: "Playlist successfully removed"
  2208. });
  2209. }
  2210. );
  2211. }),
  2212. /**
  2213. * Removes a user's modifiable user playlist as an admin
  2214. *
  2215. * @param {object} session - the session object automatically added by the websocket
  2216. * @param {string} playlistId - the id of the playlist we are removing
  2217. * @param {Function} cb - gets called with the result
  2218. */
  2219. removeAdmin: useHasPermission("playlists.removeAdmin", async function removeAdmin(session, playlistId, cb) {
  2220. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2221. async.waterfall(
  2222. [
  2223. next => {
  2224. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2225. .then(playlist => next(null, playlist))
  2226. .catch(next);
  2227. },
  2228. (playlist, next) => {
  2229. if (playlist.type !== "user" && playlist.type !== "admin")
  2230. return next("Playlist cannot be removed.");
  2231. return next(null, playlist);
  2232. },
  2233. (playlist, next) => {
  2234. if (playlist.type === "admin") next(null, null);
  2235. else
  2236. userModel.updateOne(
  2237. { _id: playlist.createdBy },
  2238. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  2239. err => next(err, playlist.createdBy)
  2240. );
  2241. },
  2242. (playlistCreator, next) => {
  2243. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  2244. .then(() => next(null, playlistCreator))
  2245. .catch(next);
  2246. }
  2247. ],
  2248. async (err, playlistCreator) => {
  2249. if (err) {
  2250. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2251. this.log(
  2252. "ERROR",
  2253. "PLAYLIST_REMOVE_ADMIN",
  2254. `Removing playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2255. );
  2256. return cb({ status: "error", message: err });
  2257. }
  2258. this.log(
  2259. "SUCCESS",
  2260. "PLAYLIST_REMOVE_ADMIN",
  2261. `Successfully removed playlist "${playlistId}" for user "${session.userId}".`
  2262. );
  2263. CacheModule.runJob("PUB", {
  2264. channel: "playlist.delete",
  2265. value: {
  2266. createdBy: playlistCreator,
  2267. playlistId
  2268. }
  2269. });
  2270. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  2271. return cb({
  2272. status: "success",
  2273. message: "Playlist successfully removed"
  2274. });
  2275. }
  2276. );
  2277. }),
  2278. /**
  2279. * Updates the privacy of a private playlist
  2280. *
  2281. * @param {object} session - the session object automatically added by the websocket
  2282. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  2283. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  2284. * @param {Function} cb - gets called with the result
  2285. */
  2286. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  2287. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2288. async.waterfall(
  2289. [
  2290. next => {
  2291. playlistModel.updateOne(
  2292. { _id: playlistId, createdBy: session.userId },
  2293. { $set: { privacy } },
  2294. { runValidators: true },
  2295. next
  2296. );
  2297. },
  2298. (res, next) => {
  2299. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  2300. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  2301. else {
  2302. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  2303. .then(playlist => next(null, playlist))
  2304. .catch(next);
  2305. }
  2306. }
  2307. ],
  2308. async (err, playlist) => {
  2309. if (err) {
  2310. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2311. this.log(
  2312. "ERROR",
  2313. "PLAYLIST_UPDATE_PRIVACY",
  2314. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2315. );
  2316. return cb({ status: "error", message: err });
  2317. }
  2318. this.log(
  2319. "SUCCESS",
  2320. "PLAYLIST_UPDATE_PRIVACY",
  2321. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  2322. );
  2323. CacheModule.runJob("PUB", {
  2324. channel: "playlist.updatePrivacy",
  2325. value: {
  2326. createdBy: playlist.createdBy,
  2327. playlist
  2328. }
  2329. });
  2330. CacheModule.runJob("PUB", {
  2331. channel: "playlist.updated",
  2332. value: { playlistId }
  2333. });
  2334. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2335. userId: session.userId,
  2336. type: "playlist__edit_privacy",
  2337. payload: {
  2338. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  2339. playlistId
  2340. }
  2341. });
  2342. return cb({
  2343. status: "success",
  2344. message: "Playlist has been successfully updated"
  2345. });
  2346. }
  2347. );
  2348. }),
  2349. /**
  2350. * Updates the privacy of a playlist
  2351. *
  2352. * @param {object} session - the session object automatically added by the websocket
  2353. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  2354. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  2355. * @param {Function} cb - gets called with the result
  2356. */
  2357. updatePrivacyAdmin: useHasPermission(
  2358. "playlists.update.privacy",
  2359. async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  2360. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2361. async.waterfall(
  2362. [
  2363. next => {
  2364. playlistModel.updateOne(
  2365. { _id: playlistId },
  2366. { $set: { privacy } },
  2367. { runValidators: true },
  2368. next
  2369. );
  2370. },
  2371. (res, next) => {
  2372. if (res.n === 0) next("No playlist found with that id.");
  2373. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  2374. else {
  2375. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  2376. .then(playlist => next(null, playlist))
  2377. .catch(next);
  2378. }
  2379. }
  2380. ],
  2381. async (err, playlist) => {
  2382. if (err) {
  2383. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2384. this.log(
  2385. "ERROR",
  2386. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  2387. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2388. );
  2389. return cb({ status: "error", message: err });
  2390. }
  2391. this.log(
  2392. "SUCCESS",
  2393. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  2394. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  2395. );
  2396. if (playlist.type === "user") {
  2397. CacheModule.runJob("PUB", {
  2398. channel: "playlist.updatePrivacy",
  2399. value: {
  2400. userId: playlist.createdBy,
  2401. playlist
  2402. }
  2403. });
  2404. }
  2405. CacheModule.runJob("PUB", {
  2406. channel: "playlist.updated",
  2407. value: { playlistId }
  2408. });
  2409. return cb({
  2410. status: "success",
  2411. message: "Playlist has been successfully updated"
  2412. });
  2413. }
  2414. );
  2415. }
  2416. ),
  2417. /**
  2418. * Deletes all orphaned station playlists
  2419. *
  2420. * @param {object} session - the session object automatically added by socket.io
  2421. * @param {Function} cb - gets called with the result
  2422. */
  2423. deleteOrphanedStationPlaylists: useHasPermission("playlists.deleteOrphaned", async function index(session, cb) {
  2424. this.keepLongJob();
  2425. this.publishProgress({
  2426. status: "started",
  2427. title: "Delete orphaned station playlists",
  2428. message: "Deleting orphaned station playlists.",
  2429. id: this.toString()
  2430. });
  2431. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2432. await CacheModule.runJob(
  2433. "PUB",
  2434. {
  2435. channel: "longJob.added",
  2436. value: { jobId: this.toString(), userId: session.userId }
  2437. },
  2438. this
  2439. );
  2440. async.waterfall(
  2441. [
  2442. next => {
  2443. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  2444. .then(() => next())
  2445. .catch(next);
  2446. }
  2447. ],
  2448. async err => {
  2449. if (err) {
  2450. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2451. this.log(
  2452. "ERROR",
  2453. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  2454. `Deleting orphaned station playlists failed. "${err}"`
  2455. );
  2456. this.publishProgress({
  2457. status: "error",
  2458. message: err
  2459. });
  2460. return cb({ status: "error", message: err });
  2461. }
  2462. this.log(
  2463. "SUCCESS",
  2464. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  2465. "Deleting orphaned station playlists successful."
  2466. );
  2467. this.publishProgress({
  2468. status: "success",
  2469. message: "Successfully deleted orphaned station playlists."
  2470. });
  2471. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  2472. }
  2473. );
  2474. }),
  2475. /**
  2476. * Deletes all orphaned genre playlists
  2477. *
  2478. * @param {object} session - the session object automatically added by socket.io
  2479. * @param {Function} cb - gets called with the result
  2480. */
  2481. deleteOrphanedGenrePlaylists: useHasPermission("playlists.deleteOrphaned", async function index(session, cb) {
  2482. this.keepLongJob();
  2483. this.publishProgress({
  2484. status: "started",
  2485. title: "Delete orphaned genre playlists",
  2486. message: "Deleting orphaned genre playlists.",
  2487. id: this.toString()
  2488. });
  2489. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2490. await CacheModule.runJob(
  2491. "PUB",
  2492. {
  2493. channel: "longJob.added",
  2494. value: { jobId: this.toString(), userId: session.userId }
  2495. },
  2496. this
  2497. );
  2498. async.waterfall(
  2499. [
  2500. next => {
  2501. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  2502. .then(() => next())
  2503. .catch(next);
  2504. }
  2505. ],
  2506. async err => {
  2507. if (err) {
  2508. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2509. this.log(
  2510. "ERROR",
  2511. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  2512. `Deleting orphaned genre playlists failed. "${err}"`
  2513. );
  2514. this.publishProgress({
  2515. status: "error",
  2516. message: err
  2517. });
  2518. return cb({ status: "error", message: err });
  2519. }
  2520. this.log(
  2521. "SUCCESS",
  2522. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  2523. "Deleting orphaned genre playlists successful."
  2524. );
  2525. this.publishProgress({
  2526. status: "success",
  2527. message: "Successfully deleted orphaned genre playlists."
  2528. });
  2529. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  2530. }
  2531. );
  2532. }),
  2533. /**
  2534. * Requests orpahned playlist songs
  2535. *
  2536. * @param {object} session - the session object automatically added by socket.io
  2537. * @param {Function} cb - gets called with the result
  2538. */
  2539. requestOrphanedPlaylistSongs: useHasPermission(
  2540. "playlists.requestOrphanedPlaylistSongs",
  2541. async function index(session, cb) {
  2542. this.keepLongJob();
  2543. this.publishProgress({
  2544. status: "started",
  2545. title: "Request orphaned playlist songs",
  2546. message: "Requesting orphaned playlist songs.",
  2547. id: this.toString()
  2548. });
  2549. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2550. await CacheModule.runJob(
  2551. "PUB",
  2552. {
  2553. channel: "longJob.added",
  2554. value: { jobId: this.toString(), userId: session.userId }
  2555. },
  2556. this
  2557. );
  2558. async.waterfall(
  2559. [
  2560. next => {
  2561. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  2562. .then(() => next())
  2563. .catch(next);
  2564. }
  2565. ],
  2566. async err => {
  2567. if (err) {
  2568. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2569. this.log(
  2570. "ERROR",
  2571. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  2572. `Requesting orphaned playlist songs failed. "${err}"`
  2573. );
  2574. this.publishProgress({
  2575. status: "error",
  2576. message: err
  2577. });
  2578. return cb({ status: "error", message: err });
  2579. }
  2580. this.log(
  2581. "SUCCESS",
  2582. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  2583. "Requesting orphaned playlist songs was successful."
  2584. );
  2585. this.publishProgress({
  2586. status: "success",
  2587. message: "Successfully requested orphaned playlist songs."
  2588. });
  2589. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  2590. }
  2591. );
  2592. }
  2593. ),
  2594. /**
  2595. * Clears and refills a station playlist
  2596. *
  2597. * @param {object} session - the session object automatically added by socket.io
  2598. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2599. * @param {Function} cb - gets called with the result
  2600. */
  2601. clearAndRefillStationPlaylist: useHasPermission(
  2602. "playlists.clearAndRefill",
  2603. async function index(session, playlistId, cb) {
  2604. async.waterfall(
  2605. [
  2606. next => {
  2607. if (!playlistId) next("Please specify a playlist id");
  2608. else {
  2609. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  2610. .then(() => {
  2611. next();
  2612. })
  2613. .catch(err => {
  2614. next(err);
  2615. });
  2616. }
  2617. }
  2618. ],
  2619. async err => {
  2620. if (err) {
  2621. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2622. this.log(
  2623. "ERROR",
  2624. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2625. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2626. );
  2627. return cb({ status: "error", message: err });
  2628. }
  2629. this.log(
  2630. "SUCCESS",
  2631. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2632. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  2633. );
  2634. return cb({
  2635. status: "success",
  2636. message: "Playlist has been successfully cleared and refilled"
  2637. });
  2638. }
  2639. );
  2640. }
  2641. ),
  2642. /**
  2643. * Clears and refills a genre playlist
  2644. *
  2645. * @param {object} session - the session object automatically added by socket.io
  2646. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2647. * @param {Function} cb - gets called with the result
  2648. */
  2649. clearAndRefillGenrePlaylist: useHasPermission(
  2650. "playlists.clearAndRefill",
  2651. async function index(session, playlistId, cb) {
  2652. async.waterfall(
  2653. [
  2654. next => {
  2655. if (!playlistId) next("Please specify a playlist id");
  2656. else {
  2657. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  2658. .then(() => {
  2659. next();
  2660. })
  2661. .catch(err => {
  2662. next(err);
  2663. });
  2664. }
  2665. }
  2666. ],
  2667. async err => {
  2668. if (err) {
  2669. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2670. this.log(
  2671. "ERROR",
  2672. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2673. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2674. );
  2675. return cb({ status: "error", message: err });
  2676. }
  2677. this.log(
  2678. "SUCCESS",
  2679. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2680. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  2681. );
  2682. return cb({
  2683. status: "success",
  2684. message: "Playlist has been successfully cleared and refilled"
  2685. });
  2686. }
  2687. );
  2688. }
  2689. ),
  2690. /**
  2691. * Clears and refills all station playlists
  2692. *
  2693. * @param {object} session - the session object automatically added by socket.io
  2694. * @param {Function} cb - gets called with the result
  2695. */
  2696. clearAndRefillAllStationPlaylists: useHasPermission(
  2697. "playlists.clearAndRefillAll",
  2698. async function index(session, cb) {
  2699. this.keepLongJob();
  2700. this.publishProgress({
  2701. status: "started",
  2702. title: "Clear and refill all station playlists",
  2703. message: "Clearing and refilling all station playlists.",
  2704. id: this.toString()
  2705. });
  2706. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2707. await CacheModule.runJob(
  2708. "PUB",
  2709. {
  2710. channel: "longJob.added",
  2711. value: { jobId: this.toString(), userId: session.userId }
  2712. },
  2713. this
  2714. );
  2715. async.waterfall(
  2716. [
  2717. next => {
  2718. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  2719. .then(response => {
  2720. next(null, response.playlists);
  2721. })
  2722. .catch(err => {
  2723. next(err);
  2724. });
  2725. },
  2726. (playlists, next) => {
  2727. async.eachLimit(
  2728. playlists,
  2729. 1,
  2730. (playlist, next) => {
  2731. this.publishProgress({
  2732. status: "update",
  2733. message: `Clearing and refilling "${playlist._id}"`
  2734. });
  2735. PlaylistsModule.runJob(
  2736. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  2737. { playlistId: playlist._id },
  2738. this
  2739. )
  2740. .then(() => {
  2741. next();
  2742. })
  2743. .catch(err => {
  2744. next(err);
  2745. });
  2746. },
  2747. next
  2748. );
  2749. }
  2750. ],
  2751. async err => {
  2752. if (err) {
  2753. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2754. this.log(
  2755. "ERROR",
  2756. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2757. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  2758. );
  2759. this.publishProgress({
  2760. status: "error",
  2761. message: err
  2762. });
  2763. return cb({ status: "error", message: err });
  2764. }
  2765. this.log(
  2766. "SUCCESS",
  2767. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2768. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  2769. );
  2770. this.publishProgress({
  2771. status: "success",
  2772. message: "Playlists have been successfully cleared and refilled."
  2773. });
  2774. return cb({
  2775. status: "success",
  2776. message: "Playlists have been successfully cleared and refilled"
  2777. });
  2778. }
  2779. );
  2780. }
  2781. ),
  2782. /**
  2783. * Clears and refills all genre playlists
  2784. *
  2785. * @param {object} session - the session object automatically added by socket.io
  2786. * @param {Function} cb - gets called with the result
  2787. */
  2788. clearAndRefillAllGenrePlaylists: useHasPermission("playlists.clearAndRefillAll", async function index(session, cb) {
  2789. this.keepLongJob();
  2790. this.publishProgress({
  2791. status: "started",
  2792. title: "Clear and refill all genre playlists",
  2793. message: "Clearing and refilling all genre playlists.",
  2794. id: this.toString()
  2795. });
  2796. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2797. await CacheModule.runJob(
  2798. "PUB",
  2799. {
  2800. channel: "longJob.added",
  2801. value: { jobId: this.toString(), userId: session.userId }
  2802. },
  2803. this
  2804. );
  2805. async.waterfall(
  2806. [
  2807. next => {
  2808. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  2809. .then(response => {
  2810. next(null, response.playlists);
  2811. })
  2812. .catch(err => {
  2813. next(err);
  2814. });
  2815. },
  2816. (playlists, next) => {
  2817. async.eachLimit(
  2818. playlists,
  2819. 1,
  2820. (playlist, next) => {
  2821. this.publishProgress({
  2822. status: "update",
  2823. message: `Clearing and refilling "${playlist._id}"`
  2824. });
  2825. PlaylistsModule.runJob(
  2826. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2827. { playlistId: playlist._id },
  2828. this
  2829. )
  2830. .then(() => {
  2831. next();
  2832. })
  2833. .catch(err => {
  2834. next(err);
  2835. });
  2836. },
  2837. next
  2838. );
  2839. }
  2840. ],
  2841. async err => {
  2842. if (err) {
  2843. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2844. this.log(
  2845. "ERROR",
  2846. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2847. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  2848. );
  2849. this.publishProgress({
  2850. status: "error",
  2851. message: err
  2852. });
  2853. return cb({ status: "error", message: err });
  2854. }
  2855. this.log(
  2856. "SUCCESS",
  2857. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2858. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  2859. );
  2860. this.publishProgress({
  2861. status: "success",
  2862. message: "Playlists have been successfully cleared and refilled."
  2863. });
  2864. return cb({
  2865. status: "success",
  2866. message: "Playlists have been successfully cleared and refilled"
  2867. });
  2868. }
  2869. );
  2870. }),
  2871. /**
  2872. * Create missing genre playlists
  2873. *
  2874. * @param {object} session - the session object automatically added by socket.io
  2875. * @param {Function} cb - gets called with the result
  2876. */
  2877. createMissingGenrePlaylists: useHasPermission("playlists.createMissing", async function index(session, cb) {
  2878. this.keepLongJob();
  2879. this.publishProgress({
  2880. status: "started",
  2881. title: "Create missing genre playlists",
  2882. message: "Creating missing genre playlists.",
  2883. id: this.toString()
  2884. });
  2885. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2886. await CacheModule.runJob(
  2887. "PUB",
  2888. {
  2889. channel: "longJob.added",
  2890. value: { jobId: this.toString(), userId: session.userId }
  2891. },
  2892. this
  2893. );
  2894. async.waterfall(
  2895. [
  2896. next => {
  2897. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  2898. .then(() => {
  2899. next();
  2900. })
  2901. .catch(err => {
  2902. next(err);
  2903. });
  2904. }
  2905. ],
  2906. async err => {
  2907. if (err) {
  2908. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2909. this.log(
  2910. "ERROR",
  2911. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2912. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  2913. );
  2914. this.publishProgress({
  2915. status: "error",
  2916. message: err
  2917. });
  2918. return cb({ status: "error", message: err });
  2919. }
  2920. this.log(
  2921. "SUCCESS",
  2922. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2923. `Successfully created missing genre playlists for user "${session.userId}".`
  2924. );
  2925. this.publishProgress({
  2926. status: "success",
  2927. message: "Missing genre playlists have been successfully created."
  2928. });
  2929. return cb({
  2930. status: "success",
  2931. message: "Missing genre playlists have been successfully created"
  2932. });
  2933. }
  2934. );
  2935. })
  2936. };