1
0

playlists.js 89 KB

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