playlists.js 101 KB

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