utils.js 8.9 KB

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