playlists.js 102 KB

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