Socketio.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. <template>
  2. <AppPaneLayout>
  3. <template #primary>
  4. <div
  5. class="sticky top-0 z-10 flex flex-shrink-0 p-4 overflow-x-auto space-x-2 bg-primary hide-scrollbar"
  6. >
  7. <div class="inline-flex flex-1 space-x-2">
  8. <div class="flex flex-1">
  9. <label for="client-version">
  10. <tippy
  11. ref="versionOptions"
  12. interactive
  13. trigger="click"
  14. theme="popover"
  15. arrow
  16. >
  17. <template #trigger>
  18. <span class="select-wrapper">
  19. <input
  20. id="client-version"
  21. v-tippy="{ theme: 'tooltip' }"
  22. title="socket.io-client version"
  23. class="flex px-4 py-2 font-semibold border rounded-l cursor-pointer bg-primaryLight border-divider text-secondaryDark w-26"
  24. :value="`Client ${clientVersion}`"
  25. readonly
  26. :disabled="connectionState"
  27. />
  28. </span>
  29. </template>
  30. <div class="flex flex-col" role="menu">
  31. <SmartItem
  32. v-for="(_, version) in socketIoClients"
  33. :key="`client-${version}`"
  34. :label="`Client ${version}`"
  35. @click.native="onSelectVersion(version)"
  36. />
  37. </div>
  38. </tippy>
  39. </label>
  40. <input
  41. id="socketio-url"
  42. v-model="url"
  43. type="url"
  44. autocomplete="off"
  45. spellcheck="false"
  46. :class="{ error: !urlValid }"
  47. class="flex flex-1 w-full px-4 py-2 border bg-primaryLight border-divider text-secondaryDark"
  48. :placeholder="$t('socketio.url')"
  49. :disabled="connectionState"
  50. @keyup.enter="urlValid ? toggleConnection() : null"
  51. />
  52. <input
  53. id="socketio-path"
  54. v-model="path"
  55. class="flex flex-1 w-full px-4 py-2 border rounded-r bg-primaryLight border-divider text-secondaryDark"
  56. spellcheck="false"
  57. :disabled="connectionState"
  58. @keyup.enter="urlValid ? toggleConnection() : null"
  59. />
  60. </div>
  61. <ButtonPrimary
  62. id="connect"
  63. :disabled="!urlValid"
  64. name="connect"
  65. class="w-32"
  66. :label="
  67. !connectionState ? $t('action.connect') : $t('action.disconnect')
  68. "
  69. :loading="connectingState"
  70. @click.native="toggleConnection"
  71. />
  72. </div>
  73. </div>
  74. <div
  75. class="sticky z-10 flex items-center justify-between pl-4 border-b bg-primary border-dividerLight top-upperPrimaryStickyFold"
  76. >
  77. <span class="flex items-center">
  78. <label class="font-semibold text-secondaryLight">
  79. {{ $t("authorization.type") }}
  80. </label>
  81. <tippy
  82. ref="authTypeOptions"
  83. interactive
  84. trigger="click"
  85. theme="popover"
  86. arrow
  87. >
  88. <template #trigger>
  89. <span class="select-wrapper">
  90. <ButtonSecondary
  91. class="pr-8 ml-2 rounded-none"
  92. :label="authType"
  93. />
  94. </span>
  95. </template>
  96. <div class="flex flex-col" role="menu">
  97. <SmartItem
  98. label="None"
  99. :icon="
  100. authType === 'None'
  101. ? 'radio_button_checked'
  102. : 'radio_button_unchecked'
  103. "
  104. :active="authType === 'None'"
  105. @click.native="
  106. () => {
  107. authType = 'None'
  108. authTypeOptions.tippy().hide()
  109. }
  110. "
  111. />
  112. <SmartItem
  113. label="Bearer Token"
  114. :icon="
  115. authType === 'Bearer'
  116. ? 'radio_button_checked'
  117. : 'radio_button_unchecked'
  118. "
  119. :active="authType === 'Bearer'"
  120. @click.native="
  121. () => {
  122. authType = 'Bearer'
  123. authTypeOptions.tippy().hide()
  124. }
  125. "
  126. />
  127. </div>
  128. </tippy>
  129. </span>
  130. <div class="flex">
  131. <SmartCheckbox
  132. :on="authActive"
  133. class="px-2"
  134. @change="authActive = !authActive"
  135. >
  136. {{ $t("state.enabled") }}
  137. </SmartCheckbox>
  138. <ButtonSecondary
  139. v-tippy="{ theme: 'tooltip' }"
  140. to="https://docs.hoppscotch.io/features/authorization"
  141. blank
  142. :title="$t('app.wiki')"
  143. svg="help-circle"
  144. />
  145. <ButtonSecondary
  146. v-tippy="{ theme: 'tooltip' }"
  147. :title="$t('action.clear')"
  148. svg="trash-2"
  149. @click.native="clearContent"
  150. />
  151. </div>
  152. </div>
  153. <div
  154. v-if="authType === 'None'"
  155. class="flex flex-col items-center justify-center p-4 text-secondaryLight"
  156. >
  157. <img
  158. :src="`/images/states/${$colorMode.value}/login.svg`"
  159. loading="lazy"
  160. class="inline-flex flex-col object-contain object-center w-16 h-16 my-4"
  161. :alt="$t('empty.authorization')"
  162. />
  163. <span class="pb-4 text-center">
  164. This SocketIO connection does not use any authentication.
  165. </span>
  166. <ButtonSecondary
  167. outline
  168. :label="$t('app.documentation')"
  169. to="https://docs.hoppscotch.io/features/authorization"
  170. blank
  171. svg="external-link"
  172. reverse
  173. class="mb-4"
  174. />
  175. </div>
  176. <div
  177. v-if="authType === 'Bearer'"
  178. class="flex flex-1 border-b border-dividerLight"
  179. >
  180. <div class="w-2/3 border-r border-dividerLight">
  181. <div class="flex flex-1 border-b border-dividerLight">
  182. <SmartEnvInput v-model="bearerToken" placeholder="Token" />
  183. </div>
  184. </div>
  185. <div
  186. class="sticky h-full p-4 overflow-auto bg-primary top-upperTertiaryStickyFold min-w-46 max-w-1/3 z-9"
  187. >
  188. <div class="p-2">
  189. <div class="pb-2 text-secondaryLight">
  190. {{ $t("helpers.authorization") }}
  191. </div>
  192. <SmartAnchor
  193. class="link"
  194. :label="`${$t('authorization.learn')} \xA0 →`"
  195. to="https://docs.hoppscotch.io/features/authorization"
  196. blank
  197. />
  198. </div>
  199. </div>
  200. </div>
  201. </template>
  202. <template #secondary>
  203. <RealtimeLog :title="$t('socketio.log')" :log="log" />
  204. </template>
  205. <template #sidebar>
  206. <div class="flex items-center justify-between p-4">
  207. <label for="events" class="font-semibold text-secondaryLight">
  208. {{ $t("socketio.events") }}
  209. </label>
  210. </div>
  211. <div class="flex px-4">
  212. <input
  213. id="event_name"
  214. v-model="communication.eventName"
  215. class="input"
  216. name="event_name"
  217. :placeholder="$t('socketio.event_name')"
  218. type="text"
  219. autocomplete="off"
  220. :disabled="!connectionState"
  221. />
  222. </div>
  223. <div class="flex items-center justify-between p-4">
  224. <label class="font-semibold text-secondaryLight">
  225. {{ $t("socketio.communication") }}
  226. </label>
  227. <div class="flex">
  228. <ButtonSecondary
  229. v-tippy="{ theme: 'tooltip' }"
  230. :title="$t('add.new')"
  231. svg="plus"
  232. @click.native="addCommunicationInput"
  233. />
  234. </div>
  235. </div>
  236. <div class="flex flex-col px-4 pb-4 space-y-2">
  237. <div
  238. v-for="(input, index) of communication.inputs"
  239. :key="`input-${index}`"
  240. >
  241. <div class="flex space-x-2">
  242. <input
  243. v-model="communication.inputs[index]"
  244. class="input"
  245. name="message"
  246. :placeholder="$t('count.message', { count: index + 1 })"
  247. type="text"
  248. autocomplete="off"
  249. :disabled="!connectionState"
  250. @keyup.enter="connectionState ? sendMessage() : null"
  251. />
  252. <ButtonSecondary
  253. v-if="index + 1 !== communication.inputs.length"
  254. v-tippy="{ theme: 'tooltip' }"
  255. :title="$t('action.remove')"
  256. svg="trash"
  257. color="red"
  258. outline
  259. @click.native="removeCommunicationInput({ index })"
  260. />
  261. <ButtonPrimary
  262. v-if="index + 1 === communication.inputs.length"
  263. id="send"
  264. name="send"
  265. :disabled="!connectionState"
  266. :label="$t('action.send')"
  267. @click.native="sendMessage"
  268. />
  269. </div>
  270. </div>
  271. </div>
  272. </template>
  273. </AppPaneLayout>
  274. </template>
  275. <script>
  276. import { defineComponent, ref } from "@nuxtjs/composition-api"
  277. // All Socket.IO client version imports
  278. import ClientV2 from "socket.io-client-v2"
  279. import { io as ClientV3 } from "socket.io-client-v3"
  280. import { io as ClientV4 } from "socket.io-client-v4"
  281. import wildcard from "socketio-wildcard"
  282. import debounce from "lodash/debounce"
  283. import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
  284. import {
  285. SIOEndpoint$,
  286. setSIOEndpoint,
  287. SIOVersion$,
  288. setSIOVersion,
  289. SIOPath$,
  290. setSIOPath,
  291. SIOConnectionState$,
  292. SIOConnectingState$,
  293. setSIOConnectionState,
  294. setSIOConnectingState,
  295. SIOSocket$,
  296. setSIOSocket,
  297. SIOLog$,
  298. setSIOLog,
  299. addSIOLogLine,
  300. } from "~/newstore/SocketIOSession"
  301. import { useStream } from "~/helpers/utils/composables"
  302. const socketIoClients = {
  303. v4: ClientV4,
  304. v3: ClientV3,
  305. v2: ClientV2,
  306. }
  307. export default defineComponent({
  308. setup() {
  309. return {
  310. socketIoClients,
  311. url: useStream(SIOEndpoint$, "", setSIOEndpoint),
  312. clientVersion: useStream(SIOVersion$, "", setSIOVersion),
  313. path: useStream(SIOPath$, "", setSIOPath),
  314. connectingState: useStream(
  315. SIOConnectingState$,
  316. false,
  317. setSIOConnectingState
  318. ),
  319. connectionState: useStream(
  320. SIOConnectionState$,
  321. false,
  322. setSIOConnectionState
  323. ),
  324. io: useStream(SIOSocket$, null, setSIOSocket),
  325. log: useStream(SIOLog$, [], setSIOLog),
  326. authTypeOptions: ref(null),
  327. }
  328. },
  329. data() {
  330. return {
  331. isUrlValid: true,
  332. communication: {
  333. eventName: "",
  334. inputs: [""],
  335. },
  336. authType: "None",
  337. bearerToken: "",
  338. authActive: true,
  339. }
  340. },
  341. computed: {
  342. urlValid() {
  343. return this.isUrlValid
  344. },
  345. },
  346. watch: {
  347. url() {
  348. this.debouncer()
  349. },
  350. connectionState(connected) {
  351. if (connected) this.$refs.versionOptions.tippy().disable()
  352. else this.$refs.versionOptions.tippy().enable()
  353. },
  354. },
  355. created() {
  356. if (process.browser) {
  357. this.worker = this.$worker.createRejexWorker()
  358. this.worker.addEventListener("message", this.workerResponseHandler)
  359. }
  360. },
  361. destroyed() {
  362. this.worker.terminate()
  363. },
  364. methods: {
  365. debouncer: debounce(function () {
  366. this.worker.postMessage({ type: "socketio", url: this.url })
  367. }, 1000),
  368. workerResponseHandler({ data }) {
  369. if (data.url === this.url) this.isUrlValid = data.result
  370. },
  371. removeCommunicationInput({ index }) {
  372. this.$delete(this.communication.inputs, index)
  373. },
  374. addCommunicationInput() {
  375. this.communication.inputs.push("")
  376. },
  377. toggleConnection() {
  378. // If it is connecting:
  379. if (!this.connectionState) return this.connect()
  380. // Otherwise, it's disconnecting.
  381. else return this.disconnect()
  382. },
  383. connect() {
  384. this.connectingState = true
  385. this.log = [
  386. {
  387. payload: this.$t("state.connecting_to", { name: this.url }),
  388. source: "info",
  389. color: "var(--accent-color)",
  390. },
  391. ]
  392. try {
  393. if (!this.path) {
  394. this.path = "/socket.io"
  395. }
  396. const Client = socketIoClients[this.clientVersion]
  397. if (this.authActive && this.authType === "Bearer") {
  398. this.io = new Client(this.url, {
  399. path: this.path,
  400. auth: {
  401. token: this.bearerToken,
  402. },
  403. })
  404. } else {
  405. this.io = new Client(this.url, { path: this.path })
  406. }
  407. // Add ability to listen to all events
  408. wildcard(Client.Manager)(this.io)
  409. this.io.on("connect", () => {
  410. this.connectingState = false
  411. this.connectionState = true
  412. this.log = [
  413. {
  414. payload: this.$t("state.connected_to", { name: this.url }),
  415. source: "info",
  416. color: "var(--accent-color)",
  417. ts: new Date().toLocaleTimeString(),
  418. },
  419. ]
  420. this.$toast.success(this.$t("state.connected"))
  421. })
  422. this.io.on("*", ({ data }) => {
  423. const [eventName, message] = data
  424. addSIOLogLine({
  425. payload: `[${eventName}] ${message ? JSON.stringify(message) : ""}`,
  426. source: "server",
  427. ts: new Date().toLocaleTimeString(),
  428. })
  429. })
  430. this.io.on("connect_error", (error) => {
  431. this.handleError(error)
  432. })
  433. this.io.on("reconnect_error", (error) => {
  434. this.handleError(error)
  435. })
  436. this.io.on("error", () => {
  437. this.handleError()
  438. })
  439. this.io.on("disconnect", () => {
  440. this.connectingState = false
  441. this.connectionState = false
  442. addSIOLogLine({
  443. payload: this.$t("state.disconnected_from", { name: this.url }),
  444. source: "info",
  445. color: "#ff5555",
  446. ts: new Date().toLocaleTimeString(),
  447. })
  448. this.$toast.error(this.$t("state.disconnected"))
  449. })
  450. } catch (e) {
  451. this.handleError(e)
  452. this.$toast.error(this.$t("error.something_went_wrong"))
  453. }
  454. logHoppRequestRunToAnalytics({
  455. platform: "socketio",
  456. })
  457. },
  458. disconnect() {
  459. this.io.close()
  460. },
  461. handleError(error) {
  462. this.disconnect()
  463. this.connectingState = false
  464. this.connectionState = false
  465. addSIOLogLine({
  466. payload: this.$t("error.something_went_wrong"),
  467. source: "info",
  468. color: "#ff5555",
  469. ts: new Date().toLocaleTimeString(),
  470. })
  471. if (error !== null)
  472. addSIOLogLine({
  473. payload: error,
  474. source: "info",
  475. color: "#ff5555",
  476. ts: new Date().toLocaleTimeString(),
  477. })
  478. },
  479. sendMessage() {
  480. const eventName = this.communication.eventName
  481. const messages = (this.communication.inputs || [])
  482. .map((input) => {
  483. try {
  484. return JSON.parse(input)
  485. } catch (e) {
  486. return input
  487. }
  488. })
  489. .filter((message) => !!message)
  490. if (this.io) {
  491. this.io.emit(eventName, ...messages, (data) => {
  492. // receive response from server
  493. addSIOLogLine({
  494. payload: `[${eventName}] ${JSON.stringify(data)}`,
  495. source: "server",
  496. ts: new Date().toLocaleTimeString(),
  497. })
  498. })
  499. addSIOLogLine({
  500. payload: `[${eventName}] ${JSON.stringify(messages)}`,
  501. source: "client",
  502. ts: new Date().toLocaleTimeString(),
  503. })
  504. this.communication.inputs = [""]
  505. }
  506. },
  507. onSelectVersion(version) {
  508. this.clientVersion = version
  509. this.$refs.versionOptions.tippy().hide()
  510. },
  511. },
  512. })
  513. </script>