playlists.js 101 KB

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