playlists.js 103 KB

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