playlists.js 100 KB

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