playlists.js 100 KB

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