playlists.js 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634
  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. console.log(55, isSet, mediaSource, playlistId);
  1100. async.waterfall(
  1101. [
  1102. next => {
  1103. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1104. .then(playlist => {
  1105. if (!playlist) return next("Playlist not found.");
  1106. if (playlist.createdBy !== session.userId)
  1107. return hasPermission("playlists.songs.add", session)
  1108. .then(() => next(null, playlist))
  1109. .catch(() => next("Invalid permissions."));
  1110. return next(null, playlist);
  1111. })
  1112. .catch(next);
  1113. },
  1114. (playlist, next) => {
  1115. MediaModule.runJob("GET_MEDIA", { mediaSource }, this)
  1116. .then(res =>
  1117. next(null, playlist, {
  1118. _id: res.song._id,
  1119. title: res.song.title,
  1120. thumbnail: res.song.thumbnail,
  1121. artists: res.song.artists,
  1122. mediaSource: res.song.mediaSource
  1123. })
  1124. )
  1125. .catch(next);
  1126. },
  1127. (playlist, song, next) => {
  1128. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1129. const oppositeType = playlist.type === "user-liked" ? "user-disliked" : "user-liked";
  1130. const oppositePlaylistName = oppositeType === "user-liked" ? "Liked Songs" : "Disliked Songs";
  1131. playlistModel.count(
  1132. { type: oppositeType, createdBy: session.userId, "songs.mediaSource": song.mediaSource },
  1133. (err, results) => {
  1134. if (err) next(err);
  1135. else if (results > 0)
  1136. next(
  1137. `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.`
  1138. );
  1139. else next(null, song);
  1140. }
  1141. );
  1142. } else next(null, song);
  1143. },
  1144. (_song, next) => {
  1145. PlaylistsModule.runJob("ADD_SONG_TO_PLAYLIST", { playlistId, mediaSource: _song.mediaSource }, this)
  1146. .then(res => {
  1147. const { playlist, song, ratings } = res;
  1148. next(null, playlist, song, ratings);
  1149. })
  1150. .catch(next);
  1151. }
  1152. ],
  1153. async (err, playlist, newSong, ratings) => {
  1154. if (err) {
  1155. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1156. this.log(
  1157. "ERROR",
  1158. "PLAYLIST_ADD_SONG",
  1159. `Adding song "${mediaSource}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1160. );
  1161. return cb({ status: "error", message: err });
  1162. }
  1163. this.log(
  1164. "SUCCESS",
  1165. "PLAYLIST_ADD_SONG",
  1166. `Successfully added song "${mediaSource}" to private playlist "${playlistId}" for user "${session.userId}".`
  1167. );
  1168. if (!isSet && playlist.type === "user" && playlist.privacy === "public") {
  1169. const songName = newSong.artists
  1170. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  1171. : newSong.title;
  1172. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1173. userId: session.userId,
  1174. type: "playlist__add_song",
  1175. payload: {
  1176. message: `Added <mediaSource>${songName}</mediaSource> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1177. thumbnail: newSong.thumbnail,
  1178. playlistId,
  1179. mediaSource
  1180. }
  1181. });
  1182. }
  1183. CacheModule.runJob("PUB", {
  1184. channel: "playlist.addSong",
  1185. value: {
  1186. playlistId: playlist._id,
  1187. song: newSong,
  1188. createdBy: playlist.createdBy,
  1189. privacy: playlist.privacy
  1190. }
  1191. });
  1192. CacheModule.runJob("PUB", {
  1193. channel: "playlist.updated",
  1194. value: { playlistId }
  1195. });
  1196. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1197. const { _id, mediaSource, title, artists, thumbnail } = newSong;
  1198. const { likes, dislikes } = ratings;
  1199. if (_id) SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1200. if (playlist.type === "user-liked") {
  1201. CacheModule.runJob("PUB", {
  1202. channel: "ratings.like",
  1203. value: JSON.stringify({
  1204. mediaSource,
  1205. userId: session.userId,
  1206. likes,
  1207. dislikes
  1208. })
  1209. });
  1210. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1211. userId: session.userId,
  1212. type: "song__like",
  1213. payload: {
  1214. message: `Liked song <mediaSource>${title} by ${artists.join(", ")}</mediaSource>`,
  1215. mediaSource,
  1216. thumbnail
  1217. }
  1218. });
  1219. } else {
  1220. CacheModule.runJob("PUB", {
  1221. channel: "ratings.dislike",
  1222. value: JSON.stringify({
  1223. mediaSource,
  1224. userId: session.userId,
  1225. likes,
  1226. dislikes
  1227. })
  1228. });
  1229. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1230. userId: session.userId,
  1231. type: "song__dislike",
  1232. payload: {
  1233. message: `Disliked song <mediaSource>${title} by ${artists.join(
  1234. mediaSource
  1235. )}</mediaSource>`,
  1236. mediaSource,
  1237. thumbnail
  1238. }
  1239. });
  1240. }
  1241. }
  1242. return cb({
  1243. status: "success",
  1244. message: "Song has been successfully added to the playlist",
  1245. data: { songs: playlist.songs }
  1246. });
  1247. }
  1248. );
  1249. }),
  1250. /**
  1251. * Adds a song to a private playlist
  1252. *
  1253. * @param {object} session - the session object automatically added by the websocket
  1254. * @param {string} oldMediaSource -
  1255. * @param {string} newMediaSource -
  1256. * @param {string} playlistId -
  1257. * @param {Function} cb - gets called with the result
  1258. */
  1259. replaceSongInPlaylist: isLoginRequired(async function replaceSongInPlaylist(
  1260. session,
  1261. oldMediaSource,
  1262. newMediaSource,
  1263. playlistId,
  1264. cb
  1265. ) {
  1266. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1267. async.waterfall(
  1268. [
  1269. next => {
  1270. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1271. .then(playlist => {
  1272. if (!playlist) return next("Playlist not found.");
  1273. if (playlist.createdBy !== session.userId)
  1274. return hasPermission("playlists.songs.add", session)
  1275. .then(() => next(null, playlist))
  1276. .catch(() => next("Invalid permissions."));
  1277. return next(null, playlist);
  1278. })
  1279. .catch(next);
  1280. },
  1281. (playlist, next) => {
  1282. MediaModule.runJob("GET_MEDIA", { mediaSource: newMediaSource }, this)
  1283. .then(res =>
  1284. next(null, playlist, {
  1285. _id: res.song._id,
  1286. title: res.song.title,
  1287. thumbnail: res.song.thumbnail,
  1288. artists: res.song.artists,
  1289. mediaSource: res.song.mediaSource
  1290. })
  1291. )
  1292. .catch(next);
  1293. },
  1294. (playlist, song, next) => {
  1295. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1296. const oppositeType = playlist.type === "user-liked" ? "user-disliked" : "user-liked";
  1297. const oppositePlaylistName = oppositeType === "user-liked" ? "Liked Songs" : "Disliked Songs";
  1298. playlistModel.count(
  1299. { type: oppositeType, createdBy: session.userId, "songs.mediaSource": song.mediaSource },
  1300. (err, results) => {
  1301. if (err) next(err);
  1302. else if (results > 0)
  1303. next(
  1304. `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.`
  1305. );
  1306. else next(null, song);
  1307. }
  1308. );
  1309. } else next(null, song);
  1310. },
  1311. (_song, next) => {
  1312. PlaylistsModule.runJob(
  1313. "REPLACE_SONG_IN_PLAYLIST",
  1314. { playlistId, oldMediaSource, newMediaSource },
  1315. this
  1316. )
  1317. .then(res => {
  1318. const { playlist, song } = res;
  1319. next(null, playlist, song);
  1320. })
  1321. .catch(next);
  1322. }
  1323. ],
  1324. async (err, playlist, newSong) => {
  1325. if (err) {
  1326. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1327. this.log(
  1328. "ERROR",
  1329. "PLAYLIST_ADD_SONG",
  1330. `Replacing song "${oldMediaSource}" with "${newMediaSource}" in private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1331. );
  1332. return cb({ status: "error", message: err });
  1333. }
  1334. this.log(
  1335. "SUCCESS",
  1336. "PLAYLIST_ADD_SONG",
  1337. `Successfully replaced song "${oldMediaSource}" with "${newMediaSource}" in private playlist "${playlistId}" for user "${session.userId}".`
  1338. );
  1339. // if (!isSet && playlist.type === "user" && playlist.privacy === "public") {
  1340. // const songName = newSong.artists
  1341. // ? `${newSong.title} by ${newSong.artists.join(", ")}`
  1342. // : newSong.title;
  1343. // ActivitiesModule.runJob("ADD_ACTIVITY", {
  1344. // userId: session.userId,
  1345. // type: "playlist__add_song",
  1346. // payload: {
  1347. // message: `Added <mediaSource>${songName}</mediaSource> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1348. // thumbnail: newSong.thumbnail,
  1349. // playlistId,
  1350. // mediaSource
  1351. // }
  1352. // });
  1353. // }
  1354. CacheModule.runJob("PUB", {
  1355. channel: "playlist.replaceSong",
  1356. value: {
  1357. playlistId: playlist._id,
  1358. song: newSong,
  1359. oldMediaSource,
  1360. createdBy: playlist.createdBy,
  1361. privacy: playlist.privacy
  1362. }
  1363. });
  1364. CacheModule.runJob("PUB", {
  1365. channel: "playlist.updated",
  1366. value: { playlistId }
  1367. });
  1368. // if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1369. // const { _id, mediaSource, title, artists, thumbnail } = newSong;
  1370. // const { likes, dislikes } = ratings;
  1371. // if (_id) SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1372. // if (playlist.type === "user-liked") {
  1373. // CacheModule.runJob("PUB", {
  1374. // channel: "ratings.like",
  1375. // value: JSON.stringify({
  1376. // mediaSource,
  1377. // userId: session.userId,
  1378. // likes,
  1379. // dislikes
  1380. // })
  1381. // });
  1382. // ActivitiesModule.runJob("ADD_ACTIVITY", {
  1383. // userId: session.userId,
  1384. // type: "song__like",
  1385. // payload: {
  1386. // message: `Liked song <mediaSource>${title} by ${artists.join(", ")}</mediaSource>`,
  1387. // mediaSource,
  1388. // thumbnail
  1389. // }
  1390. // });
  1391. // } else {
  1392. // CacheModule.runJob("PUB", {
  1393. // channel: "ratings.dislike",
  1394. // value: JSON.stringify({
  1395. // mediaSource,
  1396. // userId: session.userId,
  1397. // likes,
  1398. // dislikes
  1399. // })
  1400. // });
  1401. // ActivitiesModule.runJob("ADD_ACTIVITY", {
  1402. // userId: session.userId,
  1403. // type: "song__dislike",
  1404. // payload: {
  1405. // message: `Disliked song <mediaSource>${title} by ${artists.join(
  1406. // mediaSource
  1407. // )}</mediaSource>`,
  1408. // mediaSource,
  1409. // thumbnail
  1410. // }
  1411. // });
  1412. // }
  1413. // }
  1414. return cb({
  1415. status: "success",
  1416. message: "Song has been successfully replaced in the playlist",
  1417. data: { songs: playlist.songs }
  1418. });
  1419. }
  1420. );
  1421. }),
  1422. /**
  1423. * Adds songs to a playlist
  1424. *
  1425. * @param {object} session - the session object automatically added by the websocket
  1426. * @param {string} playlistId - the id of the playlist we are adding the songs to
  1427. * @param {Array} mediaSources - the media sources of the songs we are trying to add
  1428. * @param {Function} cb - gets called with the result
  1429. */
  1430. addSongsToPlaylist: isLoginRequired(async function addSongsToPlaylist(session, playlistId, mediaSources, cb) {
  1431. const successful = [];
  1432. const existing = [];
  1433. const failed = {};
  1434. const errors = {};
  1435. const lastYoutubeId = "none";
  1436. const songsAdded = [];
  1437. const addError = message => {
  1438. if (!errors[message]) errors[message] = 1;
  1439. else errors[message] += 1;
  1440. };
  1441. async.waterfall(
  1442. [
  1443. next => {
  1444. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1445. .then(playlist => {
  1446. if (!playlist) return next("Playlist not found.");
  1447. if (playlist.createdBy !== session.userId)
  1448. return hasPermission("playlists.songs.add", session)
  1449. .then(() => next(null, playlist))
  1450. .catch(() => next("Invalid permissions."));
  1451. return next(null, playlist);
  1452. })
  1453. .catch(next);
  1454. },
  1455. next => {
  1456. this.keepLongJob();
  1457. this.publishProgress({
  1458. status: "started",
  1459. title: "Bulk add songs to playlist",
  1460. message: "Adding songs to playlist.",
  1461. id: this.toString()
  1462. });
  1463. CacheModule.runJob(
  1464. "RPUSH",
  1465. {
  1466. key: `longJobs.${session.userId}`,
  1467. value: this.toString()
  1468. },
  1469. this
  1470. )
  1471. .then(() => {
  1472. CacheModule.runJob(
  1473. "PUB",
  1474. {
  1475. channel: "longJob.added",
  1476. value: {
  1477. jobId: this.toString(),
  1478. userId: session.userId
  1479. }
  1480. },
  1481. this
  1482. )
  1483. .then(() => next())
  1484. .catch(next);
  1485. })
  1486. .catch(next);
  1487. },
  1488. (nothing, next) => {
  1489. async.eachLimit(
  1490. mediaSources,
  1491. 1,
  1492. (mediaSource, next) => {
  1493. this.publishProgress({ status: "update", message: `Adding song "${mediaSource}"` });
  1494. PlaylistsModule.runJob("ADD_SONG_TO_PLAYLIST", { playlistId, mediaSource }, this)
  1495. .then(({ song }) => {
  1496. successful.push(mediaSource);
  1497. songsAdded.push(song);
  1498. next();
  1499. })
  1500. .catch(async err => {
  1501. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1502. if (err === "That song is already in the playlist.") {
  1503. existing.push(mediaSource);
  1504. next();
  1505. } else {
  1506. addError(err);
  1507. failed[mediaSource] = err;
  1508. next();
  1509. }
  1510. });
  1511. },
  1512. err => {
  1513. if (err) next(err);
  1514. else next();
  1515. }
  1516. );
  1517. },
  1518. next => {
  1519. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1520. .then(playlist => {
  1521. if (!playlist) return next("Playlist not found.");
  1522. return next(null, playlist);
  1523. })
  1524. .catch(next);
  1525. }
  1526. ],
  1527. async (err, playlist) => {
  1528. if (err) {
  1529. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1530. this.log(
  1531. "ERROR",
  1532. "PLAYLIST_ADD_SONGS",
  1533. `Adding songs to playlist "${playlistId}" failed for user "${
  1534. session.userId
  1535. }". "${err}". Stats: successful:${successful.length}, existing:${existing.length}, failed:${
  1536. Object.keys(failed).length
  1537. }, last mediaSource:${lastYoutubeId}, mediaSources length:${
  1538. mediaSources ? mediaSources.length : null
  1539. }`
  1540. );
  1541. return cb({
  1542. status: "error",
  1543. message: err,
  1544. data: {
  1545. stats: {
  1546. successful,
  1547. existing,
  1548. failed,
  1549. errors
  1550. }
  1551. }
  1552. });
  1553. }
  1554. this.log(
  1555. "SUCCESS",
  1556. "PLAYLIST_ADD_SONGS",
  1557. `Successfully added songs to playlist "${playlistId}" for user "${
  1558. session.userId
  1559. }". Stats: successful:${successful.length}, existing:${existing.length}, failed:${
  1560. Object.keys(failed).length
  1561. }, mediaSources length:${mediaSources ? mediaSources.length : null}`
  1562. );
  1563. await async.eachLimit(songsAdded, 1, (song, next) => {
  1564. CacheModule.runJob("PUB", {
  1565. channel: "playlist.addSong",
  1566. value: {
  1567. playlistId: playlist._id,
  1568. song,
  1569. createdBy: playlist.createdBy,
  1570. privacy: playlist.privacy
  1571. }
  1572. });
  1573. next();
  1574. });
  1575. CacheModule.runJob("PUB", {
  1576. channel: "playlist.updated",
  1577. value: { playlistId }
  1578. });
  1579. const message = `Done adding songs. Succesful: ${successful.length}, failed: ${
  1580. Object.keys(failed).length
  1581. }, existing: ${existing.length}.`;
  1582. this.publishProgress({
  1583. status: "success",
  1584. message
  1585. });
  1586. return cb({
  1587. status: "success",
  1588. message,
  1589. data: {
  1590. songs: playlist.songs,
  1591. stats: {
  1592. successful,
  1593. existing,
  1594. failed,
  1595. errors
  1596. }
  1597. }
  1598. });
  1599. }
  1600. );
  1601. }),
  1602. /**
  1603. * Removes songs from a playlist
  1604. *
  1605. * @param {object} session - the session object automatically added by the websocket
  1606. * @param {string} playlistId - the id of the playlist we are removing the songs from
  1607. * @param {Array} mediaSources - the media sources of the songs we are trying to remove
  1608. * @param {Function} cb - gets called with the result
  1609. */
  1610. removeSongsFromPlaylist: useHasPermission(
  1611. "playlists.songs.remove",
  1612. async function removeSongsFromPlaylist(session, playlistId, mediaSources, cb) {
  1613. const successful = [];
  1614. const notInPlaylist = [];
  1615. const failed = {};
  1616. const errors = {};
  1617. const lastYoutubeId = "none";
  1618. const addError = message => {
  1619. if (!errors[message]) errors[message] = 1;
  1620. else errors[message] += 1;
  1621. };
  1622. this.keepLongJob();
  1623. this.publishProgress({
  1624. status: "started",
  1625. title: "Bulk remove songs from playlist",
  1626. message: "Removing songs from playlist.",
  1627. id: this.toString()
  1628. });
  1629. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1630. await CacheModule.runJob(
  1631. "PUB",
  1632. {
  1633. channel: "longJob.added",
  1634. value: { jobId: this.toString(), userId: session.userId }
  1635. },
  1636. this
  1637. );
  1638. async.waterfall(
  1639. [
  1640. next => {
  1641. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1642. .then(playlist => {
  1643. if (!playlist) return next("Playlist not found.");
  1644. return next(null, playlist);
  1645. })
  1646. .catch(next);
  1647. },
  1648. (playlist, next) => {
  1649. if (playlist.type !== "admin") return next("Playlist must be of type admin.");
  1650. return next();
  1651. },
  1652. next => {
  1653. async.eachLimit(
  1654. mediaSources,
  1655. 1,
  1656. (mediaSource, next) => {
  1657. this.publishProgress({ status: "update", message: `Removing song "${mediaSource}"` });
  1658. PlaylistsModule.runJob("REMOVE_FROM_PLAYLIST", { playlistId, mediaSource }, this)
  1659. .then(() => {
  1660. successful.push(mediaSource);
  1661. next();
  1662. })
  1663. .catch(async err => {
  1664. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1665. if (err === "That song is not currently in the playlist.") {
  1666. notInPlaylist.push(mediaSource);
  1667. next();
  1668. } else {
  1669. addError(err);
  1670. failed[mediaSource] = err;
  1671. next();
  1672. }
  1673. });
  1674. },
  1675. err => {
  1676. if (err) next(err);
  1677. else next();
  1678. }
  1679. );
  1680. },
  1681. next => {
  1682. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1683. .then(playlist => {
  1684. if (!playlist) return next("Playlist not found.");
  1685. return next(null, playlist);
  1686. })
  1687. .catch(next);
  1688. }
  1689. ],
  1690. async (err, playlist) => {
  1691. if (err) {
  1692. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1693. this.log(
  1694. "ERROR",
  1695. "PLAYLIST_REMOVE_SONGS",
  1696. `Removing songs from playlist "${playlistId}" failed for user "${
  1697. session.userId
  1698. }". "${err}". Stats: successful:${successful.length}, notInPlaylist:${
  1699. notInPlaylist.length
  1700. }, failed:${
  1701. Object.keys(failed).length
  1702. }, last mediaSource:${lastYoutubeId}, mediaSources length:${
  1703. mediaSources ? mediaSources.length : null
  1704. }`
  1705. );
  1706. return cb({
  1707. status: "error",
  1708. message: err,
  1709. data: {
  1710. stats: {
  1711. successful,
  1712. notInPlaylist,
  1713. failed,
  1714. errors
  1715. }
  1716. }
  1717. });
  1718. }
  1719. this.log(
  1720. "SUCCESS",
  1721. "PLAYLIST_REMOVE_SONGS",
  1722. `Successfully removed songs from playlist "${playlistId}" for user "${
  1723. session.userId
  1724. }". Stats: successful:${successful.length}, notInPlaylist:${notInPlaylist.length}, failed:${
  1725. Object.keys(failed).length
  1726. }, mediaSources length:${mediaSources ? mediaSources.length : null}`
  1727. );
  1728. CacheModule.runJob("PUB", {
  1729. channel: "playlist.updated",
  1730. value: { playlistId }
  1731. });
  1732. const message = `Done removing songs. Succesful: ${successful.length}, failed: ${
  1733. Object.keys(failed).length
  1734. }, not in playlist: ${notInPlaylist.length}.`;
  1735. this.publishProgress({
  1736. status: "success",
  1737. message
  1738. });
  1739. return cb({
  1740. status: "success",
  1741. message,
  1742. data: {
  1743. songs: playlist.songs,
  1744. stats: {
  1745. successful,
  1746. notInPlaylist,
  1747. failed,
  1748. errors
  1749. }
  1750. }
  1751. });
  1752. }
  1753. );
  1754. }
  1755. ),
  1756. /**
  1757. * Adds a set of songs to a private playlist
  1758. *
  1759. * @param {object} session - the session object automatically added by the websocket
  1760. * @param {string} url - the url of the the YouTube playlist
  1761. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1762. * @param {boolean} musicOnly - whether to only add music to the playlist
  1763. * @param {Function} cb - gets called with the result
  1764. */
  1765. addYoutubeSetToPlaylist: isLoginRequired(async function addYoutubeSetToPlaylist(
  1766. session,
  1767. url,
  1768. playlistId,
  1769. musicOnly,
  1770. cb
  1771. ) {
  1772. let videosInPlaylistTotal = 0;
  1773. let songsInPlaylistTotal = 0;
  1774. let addSongsStats = null;
  1775. const addedSongs = [];
  1776. this.keepLongJob();
  1777. this.publishProgress({
  1778. status: "started",
  1779. title: "Import YouTube playlist",
  1780. message: "Importing YouTube playlist.",
  1781. id: this.toString()
  1782. });
  1783. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1784. await CacheModule.runJob(
  1785. "PUB",
  1786. {
  1787. channel: "longJob.added",
  1788. value: { jobId: this.toString(), userId: session.userId }
  1789. },
  1790. this
  1791. );
  1792. async.waterfall(
  1793. [
  1794. next => {
  1795. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1796. userModel.findOne({ _id: session.userId }, (err, user) => {
  1797. if (user && user.role === "admin") return next(null, true);
  1798. return next(null, false);
  1799. });
  1800. });
  1801. },
  1802. (isAdmin, next) => {
  1803. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 1)` });
  1804. const playlistRegex = /[\\?&]list=([^&#]*)/;
  1805. const channelRegex =
  1806. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  1807. if (playlistRegex.exec(url) || channelRegex.exec(url))
  1808. YouTubeModule.runJob(
  1809. playlistRegex.exec(url) ? "GET_PLAYLIST" : "GET_CHANNEL_VIDEOS",
  1810. {
  1811. url,
  1812. musicOnly,
  1813. disableSearch: !isAdmin
  1814. },
  1815. this
  1816. )
  1817. .then(res => {
  1818. if (res.filteredSongs) {
  1819. videosInPlaylistTotal = res.songs.length;
  1820. songsInPlaylistTotal = res.filteredSongs.length;
  1821. } else {
  1822. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  1823. }
  1824. next(null, res.songs);
  1825. })
  1826. .catch(next);
  1827. else next("Invalid YouTube URL.");
  1828. },
  1829. (youtubeIds, next) => {
  1830. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 2)` });
  1831. let successful = 0;
  1832. let failed = 0;
  1833. let alreadyInPlaylist = 0;
  1834. let alreadyInLikedPlaylist = 0;
  1835. let alreadyInDislikedPlaylist = 0;
  1836. if (youtubeIds.length === 0) next();
  1837. const mediaSources = youtubeIds.map(youtubeId => `youtube:${youtubeId}`);
  1838. async.eachLimit(
  1839. mediaSources,
  1840. 1,
  1841. (mediaSource, next) => {
  1842. WSModule.runJob(
  1843. "RUN_ACTION2",
  1844. {
  1845. session,
  1846. namespace: "playlists",
  1847. action: "addSongToPlaylist",
  1848. args: [true, mediaSource, playlistId]
  1849. },
  1850. this
  1851. )
  1852. .then(res => {
  1853. if (res.status === "success") {
  1854. successful += 1;
  1855. addedSongs.push(mediaSource);
  1856. } else failed += 1;
  1857. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1858. else if (
  1859. res.message ===
  1860. "That song is already in your Liked Songs playlist. " +
  1861. "A song cannot be in both the Liked Songs playlist" +
  1862. " and the Disliked Songs playlist at the same time."
  1863. )
  1864. alreadyInLikedPlaylist += 1;
  1865. else if (
  1866. res.message ===
  1867. "That song is already in your Disliked Songs playlist. " +
  1868. "A song cannot be in both the Liked Songs playlist " +
  1869. "and the Disliked Songs playlist at the same time."
  1870. )
  1871. alreadyInDislikedPlaylist += 1;
  1872. })
  1873. .catch(() => {
  1874. failed += 1;
  1875. })
  1876. .finally(() => next());
  1877. },
  1878. () => {
  1879. addSongsStats = {
  1880. successful,
  1881. failed,
  1882. alreadyInPlaylist,
  1883. alreadyInLikedPlaylist,
  1884. alreadyInDislikedPlaylist
  1885. };
  1886. next(null);
  1887. }
  1888. );
  1889. },
  1890. next => {
  1891. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 3)` });
  1892. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1893. .then(playlist => next(null, playlist))
  1894. .catch(next);
  1895. },
  1896. (playlist, next) => {
  1897. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 4)` });
  1898. if (!playlist) return next("Playlist not found.");
  1899. if (playlist.createdBy !== session.userId)
  1900. return hasPermission("playlists.songs.add", session)
  1901. .then(() => next(null, playlist))
  1902. .catch(() => next("Invalid permissions."));
  1903. return next(null, playlist);
  1904. }
  1905. ],
  1906. async (err, playlist) => {
  1907. if (err) {
  1908. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1909. this.log(
  1910. "ERROR",
  1911. "PLAYLIST_IMPORT",
  1912. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1913. );
  1914. this.publishProgress({
  1915. status: "error",
  1916. message: err
  1917. });
  1918. return cb({ status: "error", message: err });
  1919. }
  1920. if (playlist.privacy === "public")
  1921. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1922. userId: session.userId,
  1923. type: "playlist__import_playlist",
  1924. payload: {
  1925. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1926. playlistId
  1927. }
  1928. });
  1929. this.log(
  1930. "SUCCESS",
  1931. "PLAYLIST_IMPORT",
  1932. `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}.`
  1933. );
  1934. this.publishProgress({
  1935. status: "success",
  1936. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`
  1937. });
  1938. return cb({
  1939. status: "success",
  1940. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1941. data: {
  1942. songs: playlist.songs,
  1943. stats: {
  1944. videosInPlaylistTotal,
  1945. songsInPlaylistTotal,
  1946. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1947. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1948. }
  1949. }
  1950. });
  1951. }
  1952. );
  1953. }),
  1954. /**
  1955. * Adds a set of Soundcloud songs to a private playlist
  1956. *
  1957. * @param {object} session - the session object automatically added by the websocket
  1958. * @param {string} url - the url of the the SoundCloud playlist
  1959. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1960. * @param {Function} cb - gets called with the result
  1961. */
  1962. addSoundcloudSetToPlaylist: isLoginRequired(async function addSoundcloudSetToPlaylist(
  1963. session,
  1964. url,
  1965. playlistId,
  1966. cb
  1967. ) {
  1968. if (!config.get("experimental.soundcloud"))
  1969. return cb({ status: "error", message: "SoundCloud is not enabled" });
  1970. let songsInPlaylistTotal = 0;
  1971. let addSongsStats = null;
  1972. const addedSongs = [];
  1973. this.keepLongJob();
  1974. this.publishProgress({
  1975. status: "started",
  1976. title: "Import SoundCloud playlist",
  1977. message: "Importing SoundCloud playlist.",
  1978. id: this.toString()
  1979. });
  1980. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1981. await CacheModule.runJob(
  1982. "PUB",
  1983. {
  1984. channel: "longJob.added",
  1985. value: { jobId: this.toString(), userId: session.userId }
  1986. },
  1987. this
  1988. );
  1989. return async.waterfall(
  1990. [
  1991. next => {
  1992. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1993. userModel.findOne({ _id: session.userId }, (err, user) => {
  1994. if (user && user.role === "admin") return next(null, true);
  1995. return next(null, false);
  1996. });
  1997. });
  1998. },
  1999. (isAdmin, next) => {
  2000. this.publishProgress({ status: "update", message: `Importing SoundCloud playlist (stage 1)` });
  2001. SoundcloudModule.runJob(
  2002. "GET_PLAYLIST",
  2003. {
  2004. url
  2005. },
  2006. this
  2007. )
  2008. .then(res => {
  2009. songsInPlaylistTotal = res.songs.length;
  2010. const mediaSources = res.songs.map(song => `soundcloud:${song}`);
  2011. next(null, mediaSources);
  2012. })
  2013. .catch(next);
  2014. },
  2015. (mediaSources, next) => {
  2016. this.publishProgress({ status: "update", message: `Importing SoundCloud playlist (stage 2)` });
  2017. let successful = 0;
  2018. let failed = 0;
  2019. let alreadyInPlaylist = 0;
  2020. let alreadyInLikedPlaylist = 0;
  2021. let alreadyInDislikedPlaylist = 0;
  2022. if (mediaSources.length === 0) next();
  2023. async.eachLimit(
  2024. mediaSources,
  2025. 1,
  2026. (mediaSource, next) => {
  2027. WSModule.runJob(
  2028. "RUN_ACTION2",
  2029. {
  2030. session,
  2031. namespace: "playlists",
  2032. action: "addSongToPlaylist",
  2033. args: [true, mediaSource, playlistId]
  2034. },
  2035. this
  2036. )
  2037. .then(res => {
  2038. if (res.status === "success") {
  2039. successful += 1;
  2040. addedSongs.push(mediaSource);
  2041. } else failed += 1;
  2042. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  2043. else if (
  2044. res.message ===
  2045. "That song is already in your Liked Songs playlist. " +
  2046. "A song cannot be in both the Liked Songs playlist" +
  2047. " and the Disliked Songs playlist at the same time."
  2048. )
  2049. alreadyInLikedPlaylist += 1;
  2050. else if (
  2051. res.message ===
  2052. "That song is already in your Disliked Songs playlist. " +
  2053. "A song cannot be in both the Liked Songs playlist " +
  2054. "and the Disliked Songs playlist at the same time."
  2055. )
  2056. alreadyInDislikedPlaylist += 1;
  2057. })
  2058. .catch(() => {
  2059. failed += 1;
  2060. })
  2061. .finally(() => next());
  2062. },
  2063. () => {
  2064. addSongsStats = {
  2065. successful,
  2066. failed,
  2067. alreadyInPlaylist,
  2068. alreadyInLikedPlaylist,
  2069. alreadyInDislikedPlaylist
  2070. };
  2071. next(null);
  2072. }
  2073. );
  2074. },
  2075. next => {
  2076. this.publishProgress({ status: "update", message: `Importing SoundCloud playlist (stage 3)` });
  2077. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2078. .then(playlist => next(null, playlist))
  2079. .catch(next);
  2080. },
  2081. (playlist, next) => {
  2082. this.publishProgress({ status: "update", message: `Importing SoundCloud playlist (stage 4)` });
  2083. if (!playlist) return next("Playlist not found.");
  2084. if (playlist.createdBy !== session.userId)
  2085. return hasPermission("playlists.songs.add", session)
  2086. .then(() => next(null, playlist))
  2087. .catch(() => next("Invalid permissions."));
  2088. return next(null, playlist);
  2089. }
  2090. ],
  2091. async (err, playlist) => {
  2092. if (err) {
  2093. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2094. this.log(
  2095. "ERROR",
  2096. "PLAYLIST_IMPORT",
  2097. `Importing a SoundCloud playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2098. );
  2099. this.publishProgress({
  2100. status: "error",
  2101. message: err
  2102. });
  2103. return cb({ status: "error", message: err });
  2104. }
  2105. if (playlist.privacy === "public")
  2106. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2107. userId: session.userId,
  2108. type: "playlist__import_playlist",
  2109. payload: {
  2110. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  2111. playlistId
  2112. }
  2113. });
  2114. this.log(
  2115. "SUCCESS",
  2116. "PLAYLIST_IMPORT",
  2117. `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}.`
  2118. );
  2119. this.publishProgress({
  2120. status: "success",
  2121. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`
  2122. });
  2123. return cb({
  2124. status: "success",
  2125. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  2126. data: {
  2127. songs: playlist.songs,
  2128. stats: {
  2129. songsInPlaylistTotal,
  2130. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  2131. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  2132. }
  2133. }
  2134. });
  2135. }
  2136. );
  2137. }),
  2138. /**
  2139. * Adds a set of Spotify songs to a private playlist
  2140. *
  2141. * @param {object} session - the session object automatically added by the websocket
  2142. * @param {string} url - the url of the the Spotify playlist
  2143. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  2144. * @param {Function} cb - gets called with the result
  2145. */
  2146. addSpotifySetToPlaylist: isLoginRequired(async function addSpotifySetToPlaylist(session, url, playlistId, cb) {
  2147. if (!config.get("experimental.spotify")) return cb({ status: "error", message: "Spotify is not enabled" });
  2148. let songsInPlaylistTotal = 0;
  2149. let addSongsStats = null;
  2150. const addedSongs = [];
  2151. this.keepLongJob();
  2152. this.publishProgress({
  2153. status: "started",
  2154. title: "Import Spotify playlist",
  2155. message: "Importing Spotify playlist.",
  2156. id: this.toString()
  2157. });
  2158. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2159. await CacheModule.runJob(
  2160. "PUB",
  2161. {
  2162. channel: "longJob.added",
  2163. value: { jobId: this.toString(), userId: session.userId }
  2164. },
  2165. this
  2166. );
  2167. return async.waterfall(
  2168. [
  2169. next => {
  2170. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  2171. userModel.findOne({ _id: session.userId }, (err, user) => {
  2172. if (user && user.role === "admin") return next(null, true);
  2173. return next(null, false);
  2174. });
  2175. });
  2176. },
  2177. (isAdmin, next) => {
  2178. this.publishProgress({ status: "update", message: `Importing Spotify playlist (stage 1)` });
  2179. SpotifyModule.runJob(
  2180. "GET_PLAYLIST",
  2181. {
  2182. url
  2183. },
  2184. this
  2185. )
  2186. .then(res => {
  2187. songsInPlaylistTotal = res.songs.length;
  2188. const mediaSources = res.songs.map(song => `spotify:${song}`);
  2189. next(null, mediaSources);
  2190. })
  2191. .catch(next);
  2192. },
  2193. (mediaSources, next) => {
  2194. this.publishProgress({ status: "update", message: `Importing Spotify playlist (stage 2)` });
  2195. let successful = 0;
  2196. let failed = 0;
  2197. let alreadyInPlaylist = 0;
  2198. let alreadyInLikedPlaylist = 0;
  2199. let alreadyInDislikedPlaylist = 0;
  2200. if (mediaSources.length === 0) next();
  2201. async.eachLimit(
  2202. mediaSources,
  2203. 1,
  2204. (mediaSource, next) => {
  2205. WSModule.runJob(
  2206. "RUN_ACTION2",
  2207. {
  2208. session,
  2209. namespace: "playlists",
  2210. action: "addSongToPlaylist",
  2211. args: [true, mediaSource, playlistId]
  2212. },
  2213. this
  2214. )
  2215. .then(res => {
  2216. if (res.status === "success") {
  2217. successful += 1;
  2218. addedSongs.push(mediaSource);
  2219. } else failed += 1;
  2220. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  2221. else if (
  2222. res.message ===
  2223. "That song is already in your Liked Songs playlist. " +
  2224. "A song cannot be in both the Liked Songs playlist" +
  2225. " and the Disliked Songs playlist at the same time."
  2226. )
  2227. alreadyInLikedPlaylist += 1;
  2228. else if (
  2229. res.message ===
  2230. "That song is already in your Disliked Songs playlist. " +
  2231. "A song cannot be in both the Liked Songs playlist " +
  2232. "and the Disliked Songs playlist at the same time."
  2233. )
  2234. alreadyInDislikedPlaylist += 1;
  2235. })
  2236. .catch(() => {
  2237. failed += 1;
  2238. })
  2239. .finally(() => next());
  2240. },
  2241. () => {
  2242. addSongsStats = {
  2243. successful,
  2244. failed,
  2245. alreadyInPlaylist,
  2246. alreadyInLikedPlaylist,
  2247. alreadyInDislikedPlaylist
  2248. };
  2249. next(null);
  2250. }
  2251. );
  2252. },
  2253. next => {
  2254. this.publishProgress({ status: "update", message: `Importing Spotify playlist (stage 3)` });
  2255. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2256. .then(playlist => next(null, playlist))
  2257. .catch(next);
  2258. },
  2259. (playlist, next) => {
  2260. this.publishProgress({ status: "update", message: `Importing Spotify playlist (stage 4)` });
  2261. if (!playlist) return next("Playlist not found.");
  2262. if (playlist.createdBy !== session.userId)
  2263. return hasPermission("playlists.songs.add", session)
  2264. .then(() => next(null, playlist))
  2265. .catch(() => next("Invalid permissions."));
  2266. return next(null, playlist);
  2267. }
  2268. ],
  2269. async (err, playlist) => {
  2270. if (err) {
  2271. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2272. this.log(
  2273. "ERROR",
  2274. "PLAYLIST_IMPORT",
  2275. `Importing a Spotify playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2276. );
  2277. this.publishProgress({
  2278. status: "error",
  2279. message: err
  2280. });
  2281. return cb({ status: "error", message: err });
  2282. }
  2283. if (playlist.privacy === "public")
  2284. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2285. userId: session.userId,
  2286. type: "playlist__import_playlist",
  2287. payload: {
  2288. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  2289. playlistId
  2290. }
  2291. });
  2292. this.log(
  2293. "SUCCESS",
  2294. "PLAYLIST_IMPORT",
  2295. `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}.`
  2296. );
  2297. this.publishProgress({
  2298. status: "success",
  2299. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`
  2300. });
  2301. return cb({
  2302. status: "success",
  2303. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  2304. data: {
  2305. songs: playlist.songs,
  2306. stats: {
  2307. songsInPlaylistTotal,
  2308. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  2309. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  2310. }
  2311. }
  2312. });
  2313. }
  2314. );
  2315. }),
  2316. /**
  2317. * Removes a song from a private playlist
  2318. *
  2319. * @param {object} session - the session object automatically added by the websocket
  2320. * @param {string} mediaSource - the media source of the song we are removing from the private playlist
  2321. * @param {string} playlistId - the id of the playlist we are removing the song from
  2322. * @param {Function} cb - gets called with the result
  2323. */
  2324. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(
  2325. session,
  2326. mediaSource,
  2327. playlistId,
  2328. cb
  2329. ) {
  2330. async.waterfall(
  2331. [
  2332. next => {
  2333. if (!mediaSource || typeof mediaSource !== "string") return next("Invalid song id.");
  2334. if (!playlistId || typeof mediaSource !== "string") return next("Invalid playlist id.");
  2335. return next();
  2336. },
  2337. next => {
  2338. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2339. .then(playlist => {
  2340. if (!playlist) return next("Playlist not found.");
  2341. if (playlist.createdBy !== session.userId)
  2342. return hasPermission("playlists.songs.remove", session)
  2343. .then(() => next(null, playlist))
  2344. .catch(() => next("Invalid permissions."));
  2345. return next(null, playlist);
  2346. })
  2347. .catch(next);
  2348. },
  2349. (playlist, next) => {
  2350. let normalizedSong = null;
  2351. const song = playlist.songs.find(song => song.mediaSource === mediaSource);
  2352. if (song) {
  2353. normalizedSong = {
  2354. _id: song._id,
  2355. title: song.title,
  2356. thumbnail: song.thumbnail,
  2357. artists: song.artists,
  2358. mediaSource: song.mediaSource
  2359. };
  2360. }
  2361. next(null, playlist, normalizedSong);
  2362. },
  2363. (playlist, newSong, next) => {
  2364. PlaylistsModule.runJob("REMOVE_FROM_PLAYLIST", { playlistId, mediaSource }, this)
  2365. .then(res => {
  2366. const { ratings } = res;
  2367. next(null, playlist, newSong, ratings);
  2368. })
  2369. .catch(next);
  2370. },
  2371. (playlist, newSong, ratings, next) => {
  2372. const { _id, title, artists, thumbnail } = newSong;
  2373. const songName = artists ? `${title} by ${artists.join(", ")}` : title;
  2374. if (playlist.type === "user" && playlist.privacy === "public") {
  2375. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2376. userId: session.userId,
  2377. type: "playlist__remove_song",
  2378. payload: {
  2379. message: `Removed <mediaSource>${songName}</mediaSource> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  2380. thumbnail,
  2381. playlistId,
  2382. mediaSource: newSong.mediaSource
  2383. }
  2384. });
  2385. }
  2386. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  2387. const { likes, dislikes } = ratings;
  2388. if (_id) SongsModule.runJob("UPDATE_SONG", { songId: _id });
  2389. if (playlist.type === "user-liked") {
  2390. CacheModule.runJob("PUB", {
  2391. channel: "ratings.unlike",
  2392. value: JSON.stringify({
  2393. mediaSource: newSong.mediaSource,
  2394. userId: session.userId,
  2395. likes,
  2396. dislikes
  2397. })
  2398. });
  2399. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2400. userId: session.userId,
  2401. type: "song__unlike",
  2402. payload: {
  2403. message: `Removed <mediaSource>${title} by ${artists.join(
  2404. ", "
  2405. )}</mediaSource> from your Liked Songs`,
  2406. mediaSource: newSong.mediaSource,
  2407. thumbnail
  2408. }
  2409. });
  2410. } else {
  2411. CacheModule.runJob("PUB", {
  2412. channel: "ratings.undislike",
  2413. value: JSON.stringify({
  2414. mediaSource: newSong.mediaSource,
  2415. userId: session.userId,
  2416. likes,
  2417. dislikes
  2418. })
  2419. });
  2420. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2421. userId: session.userId,
  2422. type: "song__undislike",
  2423. payload: {
  2424. message: `Removed <mediaSource>${title} by ${artists.join(
  2425. ", "
  2426. )}</mediaSource> from your Disliked Songs`,
  2427. mediaSource: newSong.mediaSource,
  2428. thumbnail
  2429. }
  2430. });
  2431. }
  2432. }
  2433. return next(null, playlist);
  2434. }
  2435. ],
  2436. async (err, playlist) => {
  2437. if (err) {
  2438. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2439. this.log(
  2440. "ERROR",
  2441. "PLAYLIST_REMOVE_SONG",
  2442. `Removing song "${mediaSource}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2443. );
  2444. return cb({ status: "error", message: err });
  2445. }
  2446. this.log(
  2447. "SUCCESS",
  2448. "PLAYLIST_REMOVE_SONG",
  2449. `Successfully removed song "${mediaSource}" from private playlist "${playlistId}" for user "${session.userId}".`
  2450. );
  2451. CacheModule.runJob("PUB", {
  2452. channel: "playlist.removeSong",
  2453. value: {
  2454. playlistId: playlist._id,
  2455. mediaSource,
  2456. createdBy: playlist.createdBy,
  2457. privacy: playlist.privacy
  2458. }
  2459. });
  2460. return cb({
  2461. status: "success",
  2462. message: "Song has been successfully removed from playlist",
  2463. data: { songs: playlist.songs }
  2464. });
  2465. }
  2466. );
  2467. }),
  2468. /**
  2469. * Updates the displayName of a private playlist
  2470. *
  2471. * @param {object} session - the session object automatically added by the websocket
  2472. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  2473. * @param {Function} cb - gets called with the result
  2474. */
  2475. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  2476. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2477. async.waterfall(
  2478. [
  2479. next => {
  2480. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2481. .then(playlist => next(null, playlist))
  2482. .catch(next);
  2483. },
  2484. (playlist, next) => {
  2485. if (playlist.type === "admin")
  2486. hasPermission("playlists.update.displayName", session)
  2487. .then(() => next())
  2488. .catch(() => next("Invalid permissions."));
  2489. else if (playlist.type !== "user" || playlist.createdBy !== session.userId)
  2490. next("Playlist cannot be modified.");
  2491. else next(null);
  2492. },
  2493. next => {
  2494. playlistModel.updateOne(
  2495. { _id: playlistId },
  2496. { $set: { displayName } },
  2497. { runValidators: true },
  2498. next
  2499. );
  2500. },
  2501. (res, next) => {
  2502. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  2503. .then(playlist => next(null, playlist))
  2504. .catch(next);
  2505. }
  2506. ],
  2507. async (err, playlist) => {
  2508. if (err) {
  2509. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2510. this.log(
  2511. "ERROR",
  2512. "PLAYLIST_UPDATE_DISPLAY_NAME",
  2513. `Updating display name to "${displayName}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2514. );
  2515. return cb({ status: "error", message: err });
  2516. }
  2517. this.log(
  2518. "SUCCESS",
  2519. "PLAYLIST_UPDATE_DISPLAY_NAME",
  2520. `Successfully updated display name to "${displayName}" for playlist "${playlistId}" for user "${session.userId}".`
  2521. );
  2522. CacheModule.runJob("PUB", {
  2523. channel: "playlist.updateDisplayName",
  2524. value: {
  2525. playlistId,
  2526. displayName,
  2527. createdBy: playlist.createdBy,
  2528. privacy: playlist.privacy
  2529. }
  2530. });
  2531. CacheModule.runJob("PUB", {
  2532. channel: "playlist.updated",
  2533. value: { playlistId }
  2534. });
  2535. if (playlist.type !== "admin")
  2536. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2537. userId: session.userId,
  2538. type: "playlist__edit_display_name",
  2539. payload: {
  2540. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  2541. playlistId
  2542. }
  2543. });
  2544. return cb({
  2545. status: "success",
  2546. message: "Playlist has been successfully updated"
  2547. });
  2548. }
  2549. );
  2550. }),
  2551. /**
  2552. * Removes a user's own modifiable user playlist
  2553. *
  2554. * @param {object} session - the session object automatically added by the websocket
  2555. * @param {string} playlistId - the id of the playlist we are removing
  2556. * @param {Function} cb - gets called with the result
  2557. */
  2558. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  2559. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2560. async.waterfall(
  2561. [
  2562. next => {
  2563. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2564. .then(playlist => next(null, playlist))
  2565. .catch(next);
  2566. },
  2567. (playlist, next) => {
  2568. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  2569. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  2570. return next(null, playlist);
  2571. },
  2572. (playlist, next) => {
  2573. userModel.updateOne(
  2574. { _id: playlist.createdBy },
  2575. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  2576. err => next(err, playlist)
  2577. );
  2578. },
  2579. (playlist, next) => {
  2580. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  2581. .then(() => next(null, playlist))
  2582. .catch(next);
  2583. }
  2584. ],
  2585. async (err, playlist) => {
  2586. if (err) {
  2587. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2588. this.log(
  2589. "ERROR",
  2590. "PLAYLIST_REMOVE",
  2591. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2592. );
  2593. return cb({ status: "error", message: err });
  2594. }
  2595. this.log(
  2596. "SUCCESS",
  2597. "PLAYLIST_REMOVE",
  2598. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  2599. );
  2600. CacheModule.runJob("PUB", {
  2601. channel: "playlist.delete",
  2602. value: {
  2603. createdBy: playlist.createdBy,
  2604. playlistId
  2605. }
  2606. });
  2607. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2608. userId: playlist.createdBy,
  2609. type: "playlist__remove",
  2610. payload: {
  2611. message: `Removed playlist ${playlist.displayName}`
  2612. }
  2613. });
  2614. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  2615. return cb({
  2616. status: "success",
  2617. message: "Playlist successfully removed"
  2618. });
  2619. }
  2620. );
  2621. }),
  2622. /**
  2623. * Removes a user's modifiable user playlist as an admin
  2624. *
  2625. * @param {object} session - the session object automatically added by the websocket
  2626. * @param {string} playlistId - the id of the playlist we are removing
  2627. * @param {Function} cb - gets called with the result
  2628. */
  2629. removeAdmin: useHasPermission("playlists.removeAdmin", async function removeAdmin(session, playlistId, cb) {
  2630. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2631. async.waterfall(
  2632. [
  2633. next => {
  2634. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2635. .then(playlist => next(null, playlist))
  2636. .catch(next);
  2637. },
  2638. (playlist, next) => {
  2639. if (playlist.type !== "user" && playlist.type !== "admin")
  2640. return next("Playlist cannot be removed.");
  2641. return next(null, playlist);
  2642. },
  2643. (playlist, next) => {
  2644. if (playlist.type === "admin") next(null, null);
  2645. else
  2646. userModel.updateOne(
  2647. { _id: playlist.createdBy },
  2648. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  2649. err => next(err, playlist.createdBy)
  2650. );
  2651. },
  2652. (playlistCreator, next) => {
  2653. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  2654. .then(() => next(null, playlistCreator))
  2655. .catch(next);
  2656. }
  2657. ],
  2658. async (err, playlistCreator) => {
  2659. if (err) {
  2660. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2661. this.log(
  2662. "ERROR",
  2663. "PLAYLIST_REMOVE_ADMIN",
  2664. `Removing playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2665. );
  2666. return cb({ status: "error", message: err });
  2667. }
  2668. this.log(
  2669. "SUCCESS",
  2670. "PLAYLIST_REMOVE_ADMIN",
  2671. `Successfully removed playlist "${playlistId}" for user "${session.userId}".`
  2672. );
  2673. CacheModule.runJob("PUB", {
  2674. channel: "playlist.delete",
  2675. value: {
  2676. createdBy: playlistCreator,
  2677. playlistId
  2678. }
  2679. });
  2680. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  2681. return cb({
  2682. status: "success",
  2683. message: "Playlist successfully removed"
  2684. });
  2685. }
  2686. );
  2687. }),
  2688. /**
  2689. * Updates the privacy of a private playlist
  2690. *
  2691. * @param {object} session - the session object automatically added by the websocket
  2692. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  2693. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  2694. * @param {Function} cb - gets called with the result
  2695. */
  2696. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  2697. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2698. async.waterfall(
  2699. [
  2700. next => {
  2701. playlistModel.updateOne(
  2702. { _id: playlistId, createdBy: session.userId },
  2703. { $set: { privacy } },
  2704. { runValidators: true },
  2705. next
  2706. );
  2707. },
  2708. (res, next) => {
  2709. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  2710. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  2711. else {
  2712. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  2713. .then(playlist => next(null, playlist))
  2714. .catch(next);
  2715. }
  2716. }
  2717. ],
  2718. async (err, playlist) => {
  2719. if (err) {
  2720. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2721. this.log(
  2722. "ERROR",
  2723. "PLAYLIST_UPDATE_PRIVACY",
  2724. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2725. );
  2726. return cb({ status: "error", message: err });
  2727. }
  2728. this.log(
  2729. "SUCCESS",
  2730. "PLAYLIST_UPDATE_PRIVACY",
  2731. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  2732. );
  2733. CacheModule.runJob("PUB", {
  2734. channel: "playlist.updatePrivacy",
  2735. value: {
  2736. createdBy: playlist.createdBy,
  2737. playlist
  2738. }
  2739. });
  2740. CacheModule.runJob("PUB", {
  2741. channel: "playlist.updated",
  2742. value: { playlistId }
  2743. });
  2744. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2745. userId: session.userId,
  2746. type: "playlist__edit_privacy",
  2747. payload: {
  2748. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  2749. playlistId
  2750. }
  2751. });
  2752. return cb({
  2753. status: "success",
  2754. message: "Playlist has been successfully updated"
  2755. });
  2756. }
  2757. );
  2758. }),
  2759. /**
  2760. * Updates the privacy of a playlist
  2761. *
  2762. * @param {object} session - the session object automatically added by the websocket
  2763. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  2764. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  2765. * @param {Function} cb - gets called with the result
  2766. */
  2767. updatePrivacyAdmin: useHasPermission(
  2768. "playlists.update.privacy",
  2769. async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  2770. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2771. async.waterfall(
  2772. [
  2773. next => {
  2774. playlistModel.updateOne(
  2775. { _id: playlistId },
  2776. { $set: { privacy } },
  2777. { runValidators: true },
  2778. next
  2779. );
  2780. },
  2781. (res, next) => {
  2782. if (res.n === 0) next("No playlist found with that id.");
  2783. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  2784. else {
  2785. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  2786. .then(playlist => next(null, playlist))
  2787. .catch(next);
  2788. }
  2789. }
  2790. ],
  2791. async (err, playlist) => {
  2792. if (err) {
  2793. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2794. this.log(
  2795. "ERROR",
  2796. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  2797. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2798. );
  2799. return cb({ status: "error", message: err });
  2800. }
  2801. this.log(
  2802. "SUCCESS",
  2803. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  2804. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  2805. );
  2806. if (playlist.type === "user") {
  2807. CacheModule.runJob("PUB", {
  2808. channel: "playlist.updatePrivacy",
  2809. value: {
  2810. userId: playlist.createdBy,
  2811. playlist
  2812. }
  2813. });
  2814. }
  2815. CacheModule.runJob("PUB", {
  2816. channel: "playlist.updated",
  2817. value: { playlistId }
  2818. });
  2819. return cb({
  2820. status: "success",
  2821. message: "Playlist has been successfully updated"
  2822. });
  2823. }
  2824. );
  2825. }
  2826. ),
  2827. /**
  2828. * Deletes all orphaned station playlists
  2829. *
  2830. * @param {object} session - the session object automatically added by socket.io
  2831. * @param {Function} cb - gets called with the result
  2832. */
  2833. deleteOrphanedStationPlaylists: useHasPermission("playlists.deleteOrphaned", async function index(session, cb) {
  2834. this.keepLongJob();
  2835. this.publishProgress({
  2836. status: "started",
  2837. title: "Delete orphaned station playlists",
  2838. message: "Deleting orphaned station playlists.",
  2839. id: this.toString()
  2840. });
  2841. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2842. await CacheModule.runJob(
  2843. "PUB",
  2844. {
  2845. channel: "longJob.added",
  2846. value: { jobId: this.toString(), userId: session.userId }
  2847. },
  2848. this
  2849. );
  2850. async.waterfall(
  2851. [
  2852. next => {
  2853. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  2854. .then(() => next())
  2855. .catch(next);
  2856. }
  2857. ],
  2858. async err => {
  2859. if (err) {
  2860. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2861. this.log(
  2862. "ERROR",
  2863. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  2864. `Deleting orphaned station playlists failed. "${err}"`
  2865. );
  2866. this.publishProgress({
  2867. status: "error",
  2868. message: err
  2869. });
  2870. return cb({ status: "error", message: err });
  2871. }
  2872. this.log(
  2873. "SUCCESS",
  2874. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  2875. "Deleting orphaned station playlists successful."
  2876. );
  2877. this.publishProgress({
  2878. status: "success",
  2879. message: "Successfully deleted orphaned station playlists."
  2880. });
  2881. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  2882. }
  2883. );
  2884. }),
  2885. /**
  2886. * Deletes all orphaned genre playlists
  2887. *
  2888. * @param {object} session - the session object automatically added by socket.io
  2889. * @param {Function} cb - gets called with the result
  2890. */
  2891. deleteOrphanedGenrePlaylists: useHasPermission("playlists.deleteOrphaned", async function index(session, cb) {
  2892. this.keepLongJob();
  2893. this.publishProgress({
  2894. status: "started",
  2895. title: "Delete orphaned genre playlists",
  2896. message: "Deleting orphaned genre playlists.",
  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. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, 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. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  2922. `Deleting orphaned genre playlists 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. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  2933. "Deleting orphaned genre playlists successful."
  2934. );
  2935. this.publishProgress({
  2936. status: "success",
  2937. message: "Successfully deleted orphaned genre playlists."
  2938. });
  2939. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  2940. }
  2941. );
  2942. }),
  2943. /**
  2944. * Requests orpahned playlist songs
  2945. *
  2946. * @param {object} session - the session object automatically added by socket.io
  2947. * @param {Function} cb - gets called with the result
  2948. */
  2949. requestOrphanedPlaylistSongs: useHasPermission(
  2950. "playlists.requestOrphanedPlaylistSongs",
  2951. async function index(session, cb) {
  2952. this.keepLongJob();
  2953. this.publishProgress({
  2954. status: "started",
  2955. title: "Request orphaned playlist songs",
  2956. message: "Requesting orphaned playlist songs.",
  2957. id: this.toString()
  2958. });
  2959. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2960. await CacheModule.runJob(
  2961. "PUB",
  2962. {
  2963. channel: "longJob.added",
  2964. value: { jobId: this.toString(), userId: session.userId }
  2965. },
  2966. this
  2967. );
  2968. async.waterfall(
  2969. [
  2970. next => {
  2971. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  2972. .then(() => next())
  2973. .catch(next);
  2974. }
  2975. ],
  2976. async err => {
  2977. if (err) {
  2978. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2979. this.log(
  2980. "ERROR",
  2981. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  2982. `Requesting orphaned playlist songs failed. "${err}"`
  2983. );
  2984. this.publishProgress({
  2985. status: "error",
  2986. message: err
  2987. });
  2988. return cb({ status: "error", message: err });
  2989. }
  2990. this.log(
  2991. "SUCCESS",
  2992. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  2993. "Requesting orphaned playlist songs was successful."
  2994. );
  2995. this.publishProgress({
  2996. status: "success",
  2997. message: "Successfully requested orphaned playlist songs."
  2998. });
  2999. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  3000. }
  3001. );
  3002. }
  3003. ),
  3004. /**
  3005. * Clears and refills a station playlist
  3006. *
  3007. * @param {object} session - the session object automatically added by socket.io
  3008. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  3009. * @param {Function} cb - gets called with the result
  3010. */
  3011. clearAndRefillStationPlaylist: useHasPermission(
  3012. "playlists.clearAndRefill",
  3013. async function index(session, playlistId, cb) {
  3014. async.waterfall(
  3015. [
  3016. next => {
  3017. if (!playlistId) next("Please specify a playlist id");
  3018. else {
  3019. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  3020. .then(() => {
  3021. next();
  3022. })
  3023. .catch(err => {
  3024. next(err);
  3025. });
  3026. }
  3027. }
  3028. ],
  3029. async err => {
  3030. if (err) {
  3031. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3032. this.log(
  3033. "ERROR",
  3034. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  3035. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  3036. );
  3037. return cb({ status: "error", message: err });
  3038. }
  3039. this.log(
  3040. "SUCCESS",
  3041. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  3042. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  3043. );
  3044. return cb({
  3045. status: "success",
  3046. message: "Playlist has been successfully cleared and refilled"
  3047. });
  3048. }
  3049. );
  3050. }
  3051. ),
  3052. /**
  3053. * Clears and refills a genre playlist
  3054. *
  3055. * @param {object} session - the session object automatically added by socket.io
  3056. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  3057. * @param {Function} cb - gets called with the result
  3058. */
  3059. clearAndRefillGenrePlaylist: useHasPermission(
  3060. "playlists.clearAndRefill",
  3061. async function index(session, playlistId, cb) {
  3062. async.waterfall(
  3063. [
  3064. next => {
  3065. if (!playlistId) next("Please specify a playlist id");
  3066. else {
  3067. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  3068. .then(() => {
  3069. next();
  3070. })
  3071. .catch(err => {
  3072. next(err);
  3073. });
  3074. }
  3075. }
  3076. ],
  3077. async err => {
  3078. if (err) {
  3079. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3080. this.log(
  3081. "ERROR",
  3082. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  3083. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  3084. );
  3085. return cb({ status: "error", message: err });
  3086. }
  3087. this.log(
  3088. "SUCCESS",
  3089. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  3090. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  3091. );
  3092. return cb({
  3093. status: "success",
  3094. message: "Playlist has been successfully cleared and refilled"
  3095. });
  3096. }
  3097. );
  3098. }
  3099. ),
  3100. /**
  3101. * Clears and refills all station playlists
  3102. *
  3103. * @param {object} session - the session object automatically added by socket.io
  3104. * @param {Function} cb - gets called with the result
  3105. */
  3106. clearAndRefillAllStationPlaylists: useHasPermission(
  3107. "playlists.clearAndRefillAll",
  3108. async function index(session, cb) {
  3109. this.keepLongJob();
  3110. this.publishProgress({
  3111. status: "started",
  3112. title: "Clear and refill all station playlists",
  3113. message: "Clearing and refilling all station playlists.",
  3114. id: this.toString()
  3115. });
  3116. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  3117. await CacheModule.runJob(
  3118. "PUB",
  3119. {
  3120. channel: "longJob.added",
  3121. value: { jobId: this.toString(), userId: session.userId }
  3122. },
  3123. this
  3124. );
  3125. async.waterfall(
  3126. [
  3127. next => {
  3128. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  3129. .then(response => {
  3130. next(null, response.playlists);
  3131. })
  3132. .catch(err => {
  3133. next(err);
  3134. });
  3135. },
  3136. (playlists, next) => {
  3137. async.eachLimit(
  3138. playlists,
  3139. 1,
  3140. (playlist, next) => {
  3141. this.publishProgress({
  3142. status: "update",
  3143. message: `Clearing and refilling "${playlist._id}"`
  3144. });
  3145. PlaylistsModule.runJob(
  3146. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  3147. { playlistId: playlist._id },
  3148. this
  3149. )
  3150. .then(() => {
  3151. next();
  3152. })
  3153. .catch(err => {
  3154. next(err);
  3155. });
  3156. },
  3157. next
  3158. );
  3159. }
  3160. ],
  3161. async err => {
  3162. if (err) {
  3163. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3164. this.log(
  3165. "ERROR",
  3166. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  3167. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  3168. );
  3169. this.publishProgress({
  3170. status: "error",
  3171. message: err
  3172. });
  3173. return cb({ status: "error", message: err });
  3174. }
  3175. this.log(
  3176. "SUCCESS",
  3177. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  3178. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  3179. );
  3180. this.publishProgress({
  3181. status: "success",
  3182. message: "Playlists have been successfully cleared and refilled."
  3183. });
  3184. return cb({
  3185. status: "success",
  3186. message: "Playlists have been successfully cleared and refilled"
  3187. });
  3188. }
  3189. );
  3190. }
  3191. ),
  3192. /**
  3193. * Clears and refills all genre playlists
  3194. *
  3195. * @param {object} session - the session object automatically added by socket.io
  3196. * @param {Function} cb - gets called with the result
  3197. */
  3198. clearAndRefillAllGenrePlaylists: useHasPermission("playlists.clearAndRefillAll", async function index(session, cb) {
  3199. this.keepLongJob();
  3200. this.publishProgress({
  3201. status: "started",
  3202. title: "Clear and refill all genre playlists",
  3203. message: "Clearing and refilling all genre playlists.",
  3204. id: this.toString()
  3205. });
  3206. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  3207. await CacheModule.runJob(
  3208. "PUB",
  3209. {
  3210. channel: "longJob.added",
  3211. value: { jobId: this.toString(), userId: session.userId }
  3212. },
  3213. this
  3214. );
  3215. async.waterfall(
  3216. [
  3217. next => {
  3218. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  3219. .then(response => {
  3220. next(null, response.playlists);
  3221. })
  3222. .catch(err => {
  3223. next(err);
  3224. });
  3225. },
  3226. (playlists, next) => {
  3227. async.eachLimit(
  3228. playlists,
  3229. 1,
  3230. (playlist, next) => {
  3231. this.publishProgress({
  3232. status: "update",
  3233. message: `Clearing and refilling "${playlist._id}"`
  3234. });
  3235. PlaylistsModule.runJob(
  3236. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  3237. { playlistId: playlist._id },
  3238. this
  3239. )
  3240. .then(() => {
  3241. next();
  3242. })
  3243. .catch(err => {
  3244. next(err);
  3245. });
  3246. },
  3247. next
  3248. );
  3249. }
  3250. ],
  3251. async err => {
  3252. if (err) {
  3253. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3254. this.log(
  3255. "ERROR",
  3256. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  3257. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  3258. );
  3259. this.publishProgress({
  3260. status: "error",
  3261. message: err
  3262. });
  3263. return cb({ status: "error", message: err });
  3264. }
  3265. this.log(
  3266. "SUCCESS",
  3267. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  3268. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  3269. );
  3270. this.publishProgress({
  3271. status: "success",
  3272. message: "Playlists have been successfully cleared and refilled."
  3273. });
  3274. return cb({
  3275. status: "success",
  3276. message: "Playlists have been successfully cleared and refilled"
  3277. });
  3278. }
  3279. );
  3280. }),
  3281. /**
  3282. * Create missing genre playlists
  3283. *
  3284. * @param {object} session - the session object automatically added by socket.io
  3285. * @param {Function} cb - gets called with the result
  3286. */
  3287. createMissingGenrePlaylists: useHasPermission("playlists.createMissing", async function index(session, cb) {
  3288. this.keepLongJob();
  3289. this.publishProgress({
  3290. status: "started",
  3291. title: "Create missing genre playlists",
  3292. message: "Creating missing genre playlists.",
  3293. id: this.toString()
  3294. });
  3295. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  3296. await CacheModule.runJob(
  3297. "PUB",
  3298. {
  3299. channel: "longJob.added",
  3300. value: { jobId: this.toString(), userId: session.userId }
  3301. },
  3302. this
  3303. );
  3304. async.waterfall(
  3305. [
  3306. next => {
  3307. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  3308. .then(() => {
  3309. next();
  3310. })
  3311. .catch(err => {
  3312. next(err);
  3313. });
  3314. }
  3315. ],
  3316. async err => {
  3317. if (err) {
  3318. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3319. this.log(
  3320. "ERROR",
  3321. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  3322. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  3323. );
  3324. this.publishProgress({
  3325. status: "error",
  3326. message: err
  3327. });
  3328. return cb({ status: "error", message: err });
  3329. }
  3330. this.log(
  3331. "SUCCESS",
  3332. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  3333. `Successfully created missing genre playlists for user "${session.userId}".`
  3334. );
  3335. this.publishProgress({
  3336. status: "success",
  3337. message: "Missing genre playlists have been successfully created."
  3338. });
  3339. return cb({
  3340. status: "success",
  3341. message: "Missing genre playlists have been successfully created"
  3342. });
  3343. }
  3344. );
  3345. })
  3346. };