playlists.js 102 KB

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