playlists.js 103 KB

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