playlists.js 103 KB

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