playlists.js 102 KB

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