playlists.js 102 KB

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