playlists.js 102 KB

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