SocketHandler.class.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import ListenerHandler from "@/classes/ListenerHandler.class";
  2. import { useUserAuthStore } from "@/stores/userAuth";
  3. import utils from "@/utils";
  4. export default class SocketHandler {
  5. socket: WebSocket;
  6. url: string;
  7. dispatcher: ListenerHandler;
  8. onConnectCbs: {
  9. temp: any[];
  10. persist: any[];
  11. };
  12. ready: boolean;
  13. firstInit: boolean;
  14. pendingDispatches: any[];
  15. onDisconnectCbs: {
  16. temp: any[];
  17. persist: any[];
  18. };
  19. CB_REFS: object;
  20. PROGRESS_CB_REFS: object;
  21. data: {
  22. dispatch?: {
  23. [key: string]: (...args: any[]) => any;
  24. };
  25. progress?: {
  26. [key: string]: (...args: any[]) => any;
  27. };
  28. on?: {
  29. [key: string]: any;
  30. };
  31. }; // Mock only
  32. executeDispatch: boolean; // Mock only
  33. trigger: (type: string, target: string, data?: any) => void; // Mock only
  34. constructor(url: string) {
  35. this.dispatcher = new ListenerHandler();
  36. this.url = url;
  37. this.onConnectCbs = {
  38. temp: [],
  39. persist: []
  40. };
  41. this.ready = false;
  42. this.firstInit = true;
  43. this.pendingDispatches = [];
  44. this.onDisconnectCbs = {
  45. temp: [],
  46. persist: []
  47. };
  48. // references for when a dispatch event is ready to callback from server to client
  49. this.CB_REFS = {};
  50. this.PROGRESS_CB_REFS = {};
  51. this.init();
  52. }
  53. init() {
  54. this.socket = new WebSocket(this.url);
  55. const userAuthStore = useUserAuthStore();
  56. this.socket.onopen = () => {
  57. console.log("WS: SOCKET OPENED");
  58. };
  59. this.socket.onmessage = message => {
  60. const data = JSON.parse(message.data);
  61. const name = data.shift(0);
  62. if (name === "CB_REF") {
  63. const CB_REF = data.shift(0);
  64. this.CB_REFS[CB_REF](...data);
  65. return delete this.CB_REFS[CB_REF];
  66. }
  67. if (name === "PROGRESS_CB_REF") {
  68. const PROGRESS_CB_REF = data.shift(0);
  69. this.PROGRESS_CB_REFS[PROGRESS_CB_REF](...data);
  70. }
  71. if (name === "ERROR") console.log("WS: SOCKET ERROR:", data[0]);
  72. return this.dispatcher.dispatchEvent(
  73. new CustomEvent(name, {
  74. detail: data
  75. })
  76. );
  77. };
  78. this.socket.onclose = () => {
  79. console.log("WS: SOCKET CLOSED");
  80. this.ready = false;
  81. this.firstInit = false;
  82. this.onDisconnectCbs.temp.forEach(cb => cb());
  83. this.onDisconnectCbs.persist.forEach(cb => cb());
  84. // try to reconnect every 1000ms, if the user isn't banned
  85. if (!userAuthStore.banned) setTimeout(() => this.init(), 1000);
  86. };
  87. this.socket.onerror = err => {
  88. console.log("WS: SOCKET ERROR", err);
  89. };
  90. if (this.firstInit) {
  91. this.firstInit = false;
  92. this.on("ready", () => {
  93. console.log("WS: SOCKET READY");
  94. this.onConnectCbs.temp.forEach(cb => cb());
  95. this.onConnectCbs.persist.forEach(cb => cb());
  96. this.ready = true;
  97. setTimeout(() => {
  98. // dispatches that were attempted while the server was offline
  99. this.pendingDispatches.forEach(cb => cb());
  100. this.pendingDispatches = [];
  101. }, 150); // small delay between readyState being 1 and the server actually receiving dispatches
  102. userAuthStore.updatePermissions();
  103. });
  104. }
  105. }
  106. on(target, cb, options?) {
  107. this.dispatcher.addEventListener(
  108. target,
  109. event => cb(...event.detail),
  110. options
  111. );
  112. }
  113. dispatch(...args) {
  114. if (this.socket.readyState !== 1)
  115. return this.pendingDispatches.push(() => this.dispatch(...args));
  116. const lastArg = args[args.length - 1];
  117. const CB_REF = utils.guid();
  118. if (typeof lastArg === "function") {
  119. this.CB_REFS[CB_REF] = lastArg;
  120. return this.socket.send(
  121. JSON.stringify([...args.slice(0, -1), { CB_REF }])
  122. );
  123. }
  124. if (typeof lastArg === "object") {
  125. this.CB_REFS[CB_REF] = lastArg.cb;
  126. this.PROGRESS_CB_REFS[CB_REF] = lastArg.onProgress;
  127. return this.socket.send(
  128. JSON.stringify([
  129. ...args.slice(0, -1),
  130. { CB_REF, onProgress: true }
  131. ])
  132. );
  133. }
  134. return this.socket.send(JSON.stringify([...args]));
  135. }
  136. onConnect(...args) {
  137. const cb = args[1] || args[0];
  138. if (this.socket.readyState === 1 && this.ready) cb();
  139. if (args[0] === true) this.onConnectCbs.persist.push(cb);
  140. else this.onConnectCbs.temp.push(cb);
  141. }
  142. onDisconnect(...args) {
  143. const cb = args[1] || args[0];
  144. if (args[0] === true) this.onDisconnectCbs.persist.push(cb);
  145. else this.onDisconnectCbs.temp.push(cb);
  146. }
  147. clearCallbacks() {
  148. this.onConnectCbs.temp = [];
  149. this.onDisconnectCbs.temp = [];
  150. }
  151. destroyListeners() {
  152. Object.keys(this.CB_REFS).forEach(id => {
  153. if (
  154. id.indexOf("$event:") !== -1 &&
  155. id.indexOf("$event:keep.") === -1
  156. )
  157. delete this.CB_REFS[id];
  158. });
  159. Object.keys(this.PROGRESS_CB_REFS).forEach(id => {
  160. if (
  161. id.indexOf("$event:") !== -1 &&
  162. id.indexOf("$event:keep.") === -1
  163. )
  164. delete this.PROGRESS_CB_REFS[id];
  165. });
  166. // destroy all listeners that aren't site-wide
  167. Object.keys(this.dispatcher.listeners).forEach(type => {
  168. if (type.indexOf("keep.") === -1 && type !== "ready")
  169. delete this.dispatcher.listeners[type];
  170. });
  171. }
  172. destroyModalListeners(modalUuid) {
  173. // destroy all listeners for a specific modal
  174. Object.keys(this.dispatcher.listeners).forEach(type =>
  175. this.dispatcher.listeners[type].forEach((element, index) => {
  176. if (element.options && element.options.modalUuid === modalUuid)
  177. this.dispatcher.listeners[type].splice(index, 1);
  178. })
  179. );
  180. }
  181. }