playlists.js 103 KB

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