utils.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import crypto from "crypto";
  2. import CoreClass from "../core";
  3. let UtilsModule;
  4. let WSModule;
  5. class _UtilsModule extends CoreClass {
  6. // eslint-disable-next-line require-jsdoc
  7. constructor() {
  8. super("utils");
  9. UtilsModule = this;
  10. }
  11. /**
  12. * Initialises the utils module
  13. *
  14. * @returns {Promise} - returns promise (reject, resolve)
  15. */
  16. initialize() {
  17. return new Promise(resolve => {
  18. WSModule = this.moduleManager.modules.ws;
  19. resolve();
  20. });
  21. }
  22. /**
  23. * Parses the cookie into a readable object
  24. *
  25. * @param {object} payload - object that contains the payload
  26. * @param {string} payload.cookieString - the cookie string
  27. * @returns {Promise} - returns promise (reject, resolve)
  28. */
  29. PARSE_COOKIES(payload) {
  30. return new Promise((resolve, reject) => {
  31. const cookies = {};
  32. if (typeof payload.cookieString !== "string") return reject(new Error("Cookie string is not a string"));
  33. // eslint-disable-next-line array-callback-return
  34. payload.cookieString.split("; ").map(cookie => {
  35. cookies[cookie.substring(0, cookie.indexOf("="))] = cookie.substring(
  36. cookie.indexOf("=") + 1,
  37. cookie.length
  38. );
  39. });
  40. return resolve(cookies);
  41. });
  42. }
  43. // COOKIES_TO_STRING() {//cookies
  44. // return new Promise((resolve, reject) => {
  45. // let newCookie = [];
  46. // for (let prop in cookie) {
  47. // newCookie.push(prop + "=" + cookie[prop]);
  48. // }
  49. // return newCookie.join("; ");
  50. // });
  51. // }
  52. /**
  53. * Removes a cookie by name
  54. *
  55. * @param {object} payload - object that contains the payload
  56. * @param {object} payload.cookieString - the cookie string
  57. * @param {string} payload.cookieName - the unique name of the cookie
  58. * @returns {Promise} - returns promise (reject, resolve)
  59. */
  60. REMOVE_COOKIE(payload) {
  61. return new Promise((resolve, reject) => {
  62. let cookies;
  63. try {
  64. cookies = UtilsModule.runJob(
  65. "PARSE_COOKIES",
  66. {
  67. cookieString: payload.cookieString
  68. },
  69. this
  70. );
  71. } catch (err) {
  72. return reject(err);
  73. }
  74. delete cookies[payload.cookieName];
  75. return resolve();
  76. });
  77. }
  78. /**
  79. * Replaces any html reserved characters in a string with html entities
  80. *
  81. * @param {object} payload - object that contains the payload
  82. * @param {string} payload.str - the string to replace characters with html entities
  83. * @returns {Promise} - returns promise (reject, resolve)
  84. */
  85. HTML_ENTITIES(payload) {
  86. return new Promise(resolve => {
  87. resolve(
  88. String(payload.str)
  89. .replace(/&/g, "&")
  90. .replace(/</g, "&lt;")
  91. .replace(/>/g, "&gt;")
  92. .replace(/"/g, "&quot;")
  93. );
  94. });
  95. }
  96. /**
  97. * Generates a random string of a specified length
  98. *
  99. * @param {object} payload - object that contains the payload
  100. * @param {number} payload.length - the length the random string should be
  101. * @returns {Promise} - returns promise (reject, resolve)
  102. */
  103. async GENERATE_RANDOM_STRING(payload) {
  104. const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");
  105. const promises = [];
  106. for (let i = 0; i < payload.length; i += 1) {
  107. promises.push(
  108. UtilsModule.runJob(
  109. "GET_RANDOM_NUMBER",
  110. {
  111. min: 0,
  112. max: chars.length - 1
  113. },
  114. this
  115. )
  116. );
  117. }
  118. const randomNums = await Promise.all(promises);
  119. const randomChars = [];
  120. for (let i = 0; i < payload.length; i += 1) {
  121. randomChars.push(chars[randomNums[i]]);
  122. }
  123. return new Promise(resolve => resolve(randomChars.join("")));
  124. }
  125. /**
  126. * Creates a random number within a range
  127. *
  128. * @param {object} payload - object that contains the payload
  129. * @param {number} payload.min - the minimum number the result should be
  130. * @param {number} payload.max - the maximum number the result should be
  131. * @returns {Promise} - returns promise (reject, resolve)
  132. */
  133. GET_RANDOM_NUMBER(payload) {
  134. // min, max
  135. return new Promise(resolve =>
  136. resolve(Math.floor(Math.random() * (payload.max - payload.min + 1)) + payload.min)
  137. );
  138. }
  139. /**
  140. * Converts ISO8601 time format (YouTube API) to HH:MM:SS
  141. *
  142. * @param {object} payload - object contaiing the payload
  143. * @param {string} payload.duration - string in the format of ISO8601
  144. * @returns {Promise} - returns a promise (resolve, reject)
  145. */
  146. CONVERT_TIME(payload) {
  147. // duration
  148. return new Promise(resolve => {
  149. let { duration } = payload;
  150. let a = duration.match(/\d+/g);
  151. if (duration.indexOf("M") >= 0 && duration.indexOf("H") === -1 && duration.indexOf("S") === -1) {
  152. a = [0, a[0], 0];
  153. }
  154. if (duration.indexOf("H") >= 0 && duration.indexOf("M") === -1) {
  155. a = [a[0], 0, a[1]];
  156. }
  157. if (duration.indexOf("H") >= 0 && duration.indexOf("M") === -1 && duration.indexOf("S") === -1) {
  158. a = [a[0], 0, 0];
  159. }
  160. duration = 0;
  161. if (a.length === 3) {
  162. duration += parseInt(a[0]) * 3600;
  163. duration += parseInt(a[1]) * 60;
  164. duration += parseInt(a[2]);
  165. }
  166. if (a.length === 2) {
  167. duration += parseInt(a[0]) * 60;
  168. duration += parseInt(a[1]);
  169. }
  170. if (a.length === 1) {
  171. duration += parseInt(a[0]);
  172. }
  173. const hours = Math.floor(duration / 3600);
  174. const minutes = Math.floor((duration % 3600) / 60);
  175. const seconds = Math.floor((duration % 3600) % 60);
  176. resolve(
  177. (hours < 10 ? `0${hours}:` : `${hours}:`) +
  178. (minutes < 10 ? `0${minutes}:` : `${minutes}:`) +
  179. (seconds < 10 ? `0${seconds}` : seconds)
  180. );
  181. });
  182. }
  183. /**
  184. * Creates a random identifier for e.g. sessionId
  185. *
  186. * @returns {Promise} - returns promise (reject, resolve)
  187. */
  188. GUID() {
  189. return new Promise(resolve => {
  190. resolve(
  191. [1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1]
  192. .map(b =>
  193. b
  194. ? Math.floor((1 + Math.random()) * 0x10000)
  195. .toString(16)
  196. .substring(1)
  197. : "-"
  198. )
  199. .join("")
  200. );
  201. });
  202. }
  203. /**
  204. * Shuffles an array of songs by their position property
  205. *
  206. * @param {object} payload - object that contains the payload
  207. * @param {object} payload.array - an array of songs that should be shuffled
  208. * @returns {Promise} - returns promise (reject, resolve)
  209. */
  210. SHUFFLE(payload) {
  211. // array
  212. return new Promise(resolve => {
  213. const { array } = payload;
  214. // get array of positions
  215. const positions = [];
  216. array.forEach(song => positions.push(song.position));
  217. // sort the positions array
  218. let currentIndex = positions.length;
  219. let temporaryValue;
  220. let randomIndex;
  221. // While there remain elements to shuffle...
  222. while (currentIndex !== 0) {
  223. // Pick a remaining element...
  224. randomIndex = Math.floor(Math.random() * currentIndex);
  225. currentIndex -= 1;
  226. // And swap it with the current element.
  227. temporaryValue = positions[currentIndex];
  228. positions[currentIndex] = positions[randomIndex];
  229. positions[randomIndex] = temporaryValue;
  230. }
  231. // assign new positions
  232. array.forEach((song, index) => {
  233. song.position = positions[index];
  234. });
  235. resolve({ array });
  236. });
  237. }
  238. /**
  239. * Creates an error
  240. *
  241. * @param {object} payload - object that contains the payload
  242. * @param {object} payload.error - object that contains the error
  243. * @param {string} payload.message - possible error message
  244. * @param {object} payload.errors - possible object that contains multiple errors
  245. * @returns {Promise} - returns promise (reject, resolve)
  246. */
  247. GET_ERROR(payload) {
  248. return new Promise(resolve => {
  249. let error = "An error occurred.";
  250. if (typeof payload.error === "string") error = payload.error;
  251. else if (payload.error.message) {
  252. if (payload.error.message !== "Validation failed") error = payload.error.message;
  253. else error = payload.error.errors[Object.keys(payload.error.errors)].message;
  254. }
  255. resolve(error);
  256. });
  257. }
  258. /**
  259. * Creates the gravatar url for a specified email address
  260. *
  261. * @param {object} payload - object that contains the payload
  262. * @param {string} payload.email - the email address
  263. * @returns {Promise} - returns promise (reject, resolve)
  264. */
  265. CREATE_GRAVATAR(payload) {
  266. return new Promise(resolve => {
  267. const hash = crypto.createHash("md5").update(payload.email).digest("hex");
  268. resolve(`https://www.gravatar.com/avatar/${hash}`);
  269. });
  270. }
  271. /**
  272. * @returns {Promise} - returns promise (reject, resolve)
  273. */
  274. DEBUG() {
  275. return new Promise(resolve => resolve());
  276. }
  277. }
  278. export default new _UtilsModule();