presence.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const presence = new Presence({
  2. clientId: "731472884337475596",
  3. });
  4. let currentURL = new URL(document.location.href),
  5. currentPath = currentURL.pathname.replace(/^\/|\/$/g, "").split("/");
  6. const browsingTimestamp = Math.floor(Date.now() / 1000);
  7. let presenceData: PresenceData = {
  8. details: "Viewing an unsupported page",
  9. largeImageKey:
  10. "https://cdn.rcd.gg/PreMiD/websites/W/Wikiwand/assets/logo.png",
  11. startTimestamp: browsingTimestamp,
  12. };
  13. const updateCallback = {
  14. _function: null as () => void,
  15. get function(): () => void {
  16. return this._function;
  17. },
  18. set function(parameter) {
  19. this._function = parameter;
  20. },
  21. get present(): boolean {
  22. return this._function !== null;
  23. },
  24. },
  25. /**
  26. * Initialize/reset presenceData.
  27. */
  28. resetData = (
  29. defaultData: PresenceData = {
  30. details: "Viewing an unsupported page",
  31. largeImageKey:
  32. "https://cdn.rcd.gg/PreMiD/websites/W/Wikiwand/assets/logo.png",
  33. startTimestamp: browsingTimestamp,
  34. }
  35. ): void => {
  36. currentURL = new URL(document.location.href);
  37. currentPath = currentURL.pathname.replace(/^\/|\/$/g, "").split("/");
  38. presenceData = { ...defaultData };
  39. };
  40. ((): void => {
  41. let title: string;
  42. try {
  43. title = document.querySelector("h1.firstHeading span").textContent;
  44. } catch (e) {
  45. title = decodeURI(currentPath.slice(1).join("/").replaceAll("_", " "));
  46. }
  47. if (currentPath[0] === "") presenceData.details = "On the main page";
  48. else if (document.querySelector(".error_content"))
  49. presenceData.details = "On a non-existent page";
  50. else if (title) {
  51. presenceData.details = "Reading a wiki page";
  52. presenceData.state = title;
  53. if (currentPath[0] !== "en") presenceData.state += ` (${currentPath[0]})`;
  54. } else {
  55. presenceData.details = "Viewing a page";
  56. presenceData.state = document.title.replace(" - Wikiwand", "");
  57. }
  58. })();
  59. if (updateCallback.present) {
  60. const defaultData = { ...presenceData };
  61. presence.on("UpdateData", async () => {
  62. resetData(defaultData);
  63. updateCallback.function();
  64. presence.setActivity(presenceData);
  65. });
  66. } else {
  67. presence.on("UpdateData", async () => {
  68. presence.setActivity(presenceData);
  69. });
  70. }