playlists.js 102 KB

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