soundcloud.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. import mongoose from "mongoose";
  2. import async from "async";
  3. import config from "config";
  4. import sckey from "soundcloud-key-fetch";
  5. import * as rax from "retry-axios";
  6. import axios from "axios";
  7. import CoreClass from "../core";
  8. let SoundCloudModule;
  9. let DBModule;
  10. let CacheModule;
  11. let MediaModule;
  12. const soundcloudTrackObjectToMusareTrackObject = soundcloudTrackObject => {
  13. const {
  14. id,
  15. title,
  16. artwork_url: artworkUrl,
  17. created_at: createdAt,
  18. duration,
  19. genre,
  20. kind,
  21. license,
  22. likes_count: likesCount,
  23. playback_count: playbackCount,
  24. public: _public,
  25. tag_list: tagList,
  26. user_id: userId,
  27. user,
  28. track_format: trackFormat,
  29. permalink
  30. } = soundcloudTrackObject;
  31. return {
  32. trackId: id,
  33. title,
  34. artworkUrl,
  35. soundcloudCreatedAt: new Date(createdAt),
  36. duration: duration / 1000,
  37. genre,
  38. kind,
  39. license,
  40. likesCount,
  41. playbackCount,
  42. public: _public,
  43. tagList,
  44. userId,
  45. username: user.username,
  46. userPermalink: user.permalink,
  47. trackFormat,
  48. permalink
  49. };
  50. };
  51. class RateLimitter {
  52. /**
  53. * Constructor
  54. *
  55. * @param {number} timeBetween - The time between each allowed YouTube request
  56. */
  57. constructor(timeBetween) {
  58. this.dateStarted = Date.now();
  59. this.timeBetween = timeBetween;
  60. }
  61. /**
  62. * Returns a promise that resolves whenever the ratelimit of a YouTube request is done
  63. *
  64. * @returns {Promise} - promise that gets resolved when the rate limit allows it
  65. */
  66. continue() {
  67. return new Promise(resolve => {
  68. if (Date.now() - this.dateStarted >= this.timeBetween) resolve();
  69. else setTimeout(resolve, this.dateStarted + this.timeBetween - Date.now());
  70. });
  71. }
  72. /**
  73. * Restart the rate limit timer
  74. */
  75. restart() {
  76. this.dateStarted = Date.now();
  77. }
  78. }
  79. class _SoundCloudModule extends CoreClass {
  80. // eslint-disable-next-line require-jsdoc
  81. constructor() {
  82. super("soundcloud");
  83. SoundCloudModule = this;
  84. }
  85. /**
  86. * Initialises the soundcloud module
  87. *
  88. * @returns {Promise} - returns promise (reject, resolve)
  89. */
  90. async initialize() {
  91. DBModule = this.moduleManager.modules.db;
  92. CacheModule = this.moduleManager.modules.cache;
  93. MediaModule = this.moduleManager.modules.media;
  94. // this.youtubeApiRequestModel = this.YoutubeApiRequestModel = await DBModule.runJob("GET_MODEL", {
  95. // modelName: "youtubeApiRequest"
  96. // });
  97. this.soundcloudTrackModel = this.SoundCloudTrackModel = await DBModule.runJob("GET_MODEL", {
  98. modelName: "soundcloudTrack"
  99. });
  100. return new Promise((resolve, reject) => {
  101. this.rateLimiter = new RateLimitter(config.get("apis.soundcloud.rateLimit"));
  102. this.requestTimeout = config.get("apis.soundcloud.requestTimeout");
  103. this.axios = axios.create();
  104. this.axios.defaults.raxConfig = {
  105. instance: this.axios,
  106. retry: config.get("apis.soundcloud.retryAmount"),
  107. noResponseRetries: config.get("apis.soundcloud.retryAmount")
  108. };
  109. rax.attach(this.axios);
  110. this.apiKey = null;
  111. SoundCloudModule.runJob("TEST_SOUNDCLOUD_API_KEY", {}, null, -1)
  112. .then(result => {
  113. if (result) {
  114. resolve();
  115. return;
  116. }
  117. SoundCloudModule.runJob("GENERATE_SOUNDCLOUD_API_KEY", {}, null, -1)
  118. .then(() => {
  119. resolve();
  120. })
  121. .catch(reject);
  122. })
  123. .catch(reject);
  124. });
  125. }
  126. /**
  127. *
  128. * @returns
  129. */
  130. GENERATE_SOUNDCLOUD_API_KEY() {
  131. return new Promise((resolve, reject) => {
  132. this.log("INFO", "Fetching new SoundCloud API key.");
  133. sckey
  134. .fetchKey()
  135. .then(soundcloudApiKey => {
  136. if (!soundcloudApiKey) {
  137. this.log("ERROR", "Couldn't fetch new SoundCloud API key.");
  138. reject(new Error("Couldn't fetch SoundCloud key."));
  139. return;
  140. }
  141. SoundCloudModule.soundcloudApiKey = soundcloudApiKey;
  142. CacheModule.runJob("SET", { key: "soundcloudApiKey", value: soundcloudApiKey }, this)
  143. .then(() => {
  144. SoundCloudModule.runJob("TEST_SOUNDCLOUD_API_KEY", {}, this).then(result => {
  145. if (!result) {
  146. this.log("ERROR", "Fetched SoundCloud API key is invalid.");
  147. reject(new Error("SoundCloud key isn't valid."));
  148. } else {
  149. this.log("INFO", "Fetched new valid SoundCloud API key.");
  150. resolve();
  151. }
  152. });
  153. })
  154. .catch(err => {
  155. this.log("ERROR", `Couldn't set new SoundCloud API key in cache. Error: ${err.message}`);
  156. reject(err);
  157. });
  158. })
  159. .catch(err => {
  160. this.log("ERROR", `Couldn't fetch new SoundCloud API key. Error: ${err.message}`);
  161. reject(new Error("Couldn't fetch SoundCloud key."));
  162. });
  163. });
  164. }
  165. /**
  166. *
  167. * @returns
  168. */
  169. TEST_SOUNDCLOUD_API_KEY() {
  170. return new Promise((resolve, reject) => {
  171. this.log("INFO", "Testing SoundCloud API key.");
  172. CacheModule.runJob("GET", { key: "soundcloudApiKey" }, this).then(soundcloudApiKey => {
  173. if (!soundcloudApiKey) {
  174. this.log("ERROR", "No SoundCloud API key found in cache.");
  175. return resolve(false);
  176. }
  177. sckey
  178. .testKey(soundcloudApiKey)
  179. .then(res => {
  180. this.log("INFO", `Tested SoundCloud API key. Result: ${res}`);
  181. resolve(res);
  182. })
  183. .catch(err => {
  184. this.log("ERROR", `Testing SoundCloud API key error: ${err.message}`);
  185. reject(err);
  186. });
  187. });
  188. });
  189. }
  190. /**
  191. * Perform SoundCloud API get track request
  192. *
  193. * @param {object} payload - object that contains the payload
  194. * @param {object} payload.params - request parameters
  195. * @returns {Promise} - returns promise (reject, resolve)
  196. */
  197. API_GET_TRACK(payload) {
  198. return new Promise((resolve, reject) => {
  199. const { trackId } = payload;
  200. SoundCloudModule.runJob(
  201. "API_CALL",
  202. {
  203. url: `https://api-v2.soundcloud.com/tracks/${trackId}`
  204. },
  205. this
  206. )
  207. .then(response => {
  208. resolve(response);
  209. })
  210. .catch(err => {
  211. reject(err);
  212. });
  213. });
  214. }
  215. /**
  216. * Perform SoundCloud API call
  217. *
  218. * @param {object} payload - object that contains the payload
  219. * @param {object} payload.url - request url
  220. * @param {object} payload.params - request parameters
  221. * @param {object} payload.quotaCost - request quotaCost
  222. * @returns {Promise} - returns promise (reject, resolve)
  223. */
  224. API_CALL(payload) {
  225. return new Promise((resolve, reject) => {
  226. // const { url, params, quotaCost } = payload;
  227. const { url } = payload;
  228. const { soundcloudApiKey } = SoundCloudModule;
  229. const params = {
  230. client_id: soundcloudApiKey
  231. };
  232. SoundCloudModule.axios
  233. .get(url, {
  234. params,
  235. timeout: SoundCloudModule.requestTimeout
  236. })
  237. .then(response => {
  238. if (response.data.error) {
  239. reject(new Error(response.data.error));
  240. } else {
  241. resolve({ response });
  242. }
  243. })
  244. .catch(err => {
  245. reject(err);
  246. });
  247. // }
  248. });
  249. }
  250. /**
  251. * Create SoundCloud track
  252. *
  253. * @param {object} payload - an object containing the payload
  254. * @param {string} payload.soundcloudTrack - the soundcloudTrack object
  255. * @returns {Promise} - returns a promise (resolve, reject)
  256. */
  257. CREATE_TRACK(payload) {
  258. return new Promise((resolve, reject) => {
  259. async.waterfall(
  260. [
  261. next => {
  262. const { soundcloudTrack } = payload;
  263. if (typeof soundcloudTrack !== "object") next("Invalid soundcloudTrack type");
  264. else {
  265. SoundCloudModule.soundcloudTrackModel.insertMany(soundcloudTrack, next);
  266. }
  267. },
  268. (soundcloudTracks, next) => {
  269. const mediaSources = soundcloudTracks.map(
  270. soundcloudTrack => `soundcloud:${soundcloudTrack.trackId}`
  271. );
  272. async.eachLimit(
  273. mediaSources,
  274. 2,
  275. (mediaSource, next) => {
  276. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource }, this)
  277. .then(() => next())
  278. .catch(next);
  279. },
  280. err => {
  281. if (err) next(err);
  282. else next(null, soundcloudTracks);
  283. }
  284. );
  285. }
  286. ],
  287. (err, soundcloudTracks) => {
  288. if (err) reject(new Error(err));
  289. else resolve({ soundcloudTracks });
  290. }
  291. );
  292. });
  293. }
  294. /**
  295. * Get SoundCloud track
  296. *
  297. * @param {object} payload - an object containing the payload
  298. * @param {string} payload.identifier - the soundcloud track ObjectId or track id
  299. * @param {string} payload.createMissing - attempt to fetch and create track if not in db
  300. * @returns {Promise} - returns a promise (resolve, reject)
  301. */
  302. GET_TRACK(payload) {
  303. return new Promise((resolve, reject) => {
  304. async.waterfall(
  305. [
  306. next => {
  307. const query = mongoose.isObjectIdOrHexString(payload.identifier)
  308. ? { _id: payload.identifier }
  309. : { trackId: payload.identifier };
  310. return SoundCloudModule.soundcloudTrackModel.findOne(query, next);
  311. },
  312. (track, next) => {
  313. if (track) return next(null, track, false);
  314. if (mongoose.isObjectIdOrHexString(payload.identifier) || !payload.createMissing)
  315. return next("SoundCloud track not found.");
  316. return SoundCloudModule.runJob("API_GET_TRACK", { trackId: payload.identifier }, this)
  317. .then(({ response }) => {
  318. const { data } = response;
  319. if (!data || !data.id)
  320. return next("The specified track does not exist or cannot be publicly accessed.");
  321. const soundcloudTrack = soundcloudTrackObjectToMusareTrackObject(data);
  322. return next(null, false, soundcloudTrack);
  323. })
  324. .catch(next);
  325. },
  326. (track, soundcloudTrack, next) => {
  327. if (track) return next(null, track, true);
  328. return SoundCloudModule.runJob("CREATE_TRACK", { soundcloudTrack }, this)
  329. .then(res => {
  330. if (res.soundcloudTracks.length === 1) next(null, res.soundcloudTracks[0], false);
  331. else next("SoundCloud track not found.");
  332. })
  333. .catch(next);
  334. }
  335. ],
  336. (err, track, existing) => {
  337. if (err) reject(new Error(err));
  338. else resolve({ track, existing });
  339. }
  340. );
  341. });
  342. }
  343. /**
  344. * Gets a track from a SoundCloud URL
  345. *
  346. * @param {*} payload
  347. * @returns {Promise}
  348. */
  349. GET_TRACK_FROM_URL(payload) {
  350. return new Promise((resolve, reject) => {
  351. const scRegex =
  352. /soundcloud\.com\/(?<userPermalink>[A-Za-z0-9]+([-_][A-Za-z0-9]+)*)\/(?<permalink>[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*)/;
  353. async.waterfall(
  354. [
  355. next => {
  356. const match = scRegex.exec(payload.identifier);
  357. if (!match || !match.groups) return next("Invalid SoundCloud URL.");
  358. const { userPermalink, permalink } = match.groups;
  359. SoundCloudModule.soundcloudTrackModel.findOne({ userPermalink, permalink }, next);
  360. },
  361. (_dbTrack, next) => {
  362. if (_dbTrack) return next(null, _dbTrack, true);
  363. SoundCloudModule.runJob("API_RESOLVE", { url: payload.identifier }, this)
  364. .then(({ response }) => {
  365. const { data } = response;
  366. if (!data || !data.id)
  367. return next("The provided URL does not exist or cannot be accessed.");
  368. if (data.kind !== "track") return next(`Invalid URL provided. Kind got: ${data.kind}.`);
  369. // TODO get more data here
  370. const { id: trackId } = data;
  371. SoundCloudModule.soundcloudTrackModel.findOne({ trackId }, (err, dbTrack) => {
  372. if (err) next(err);
  373. else if (dbTrack) {
  374. next(null, dbTrack, true);
  375. } else {
  376. const soundcloudTrack = soundcloudTrackObjectToMusareTrackObject(data);
  377. SoundCloudModule.runJob("CREATE_TRACK", { soundcloudTrack }, this)
  378. .then(res => {
  379. if (res.soundcloudTracks.length === 1)
  380. next(null, res.soundcloudTracks[0], false);
  381. else next("SoundCloud track not found.");
  382. })
  383. .catch(next);
  384. }
  385. });
  386. })
  387. .catch(next);
  388. }
  389. ],
  390. (err, track, existing) => {
  391. if (err) reject(new Error(err));
  392. else resolve({ track, existing });
  393. }
  394. );
  395. });
  396. }
  397. /**
  398. * Returns an array of songs taken from a SoundCloud playlist
  399. *
  400. * @param {object} payload - object that contains the payload
  401. * @param {string} payload.url - the url of the SoundCloud playlist
  402. * @returns {Promise} - returns promise (reject, resolve)
  403. */
  404. GET_PLAYLIST(payload) {
  405. return new Promise((resolve, reject) => {
  406. async.waterfall(
  407. [
  408. next => {
  409. SoundCloudModule.runJob("API_RESOLVE", { url: payload.url }, this)
  410. .then(({ response }) => {
  411. const { data } = response;
  412. if (!data || !data.id)
  413. return next("The provided URL does not exist or cannot be accessed.");
  414. if (data.kind !== "playlist")
  415. return next(`Invalid URL provided. Kind got: ${data.kind}.`);
  416. const { tracks } = data;
  417. // TODO get more data here
  418. const soundcloudTrackIds = tracks.map(track => track.id);
  419. return next(null, soundcloudTrackIds);
  420. })
  421. .catch(next);
  422. }
  423. ],
  424. (err, soundcloudTrackIds) => {
  425. if (err && err !== true) {
  426. SoundCloudModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  427. reject(new Error(err.message));
  428. } else {
  429. resolve({ songs: soundcloudTrackIds });
  430. }
  431. }
  432. );
  433. // kind;
  434. });
  435. }
  436. /**
  437. * @param {object} payload - object that contains the payload
  438. * @param {string} payload.url - the url of the SoundCloud resource
  439. */
  440. API_RESOLVE(payload) {
  441. return new Promise((resolve, reject) => {
  442. const { url } = payload;
  443. SoundCloudModule.runJob(
  444. "API_CALL",
  445. {
  446. url: `https://api-v2.soundcloud.com/resolve?url=${encodeURIComponent(url)}`
  447. },
  448. this
  449. )
  450. .then(response => {
  451. resolve(response);
  452. })
  453. .catch(err => {
  454. reject(err);
  455. });
  456. });
  457. }
  458. }
  459. export default new _SoundCloudModule();