playlists.js 95 KB

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