summaryrefslogtreecommitdiff
path: root/src/api/traffic.ts
blob: 34e9c911c175b202a872c897a6fb80646ff2de45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import { ClashAPIConfig } from '~/types';

import { buildWebSocketURL, getURLAndInit } from '../misc/request-helper';

const endpoint = '/traffic';
const textDecoder = new TextDecoder('utf-8');

const Size = 150;

const traffic = {
  labels: Array(Size).fill(0),
  up: Array(Size),
  down: Array(Size),

  size: Size,
  subscribers: [],
  appendData(o: { up: number; down: number }) {
    this.up.shift();
    this.down.shift();
    this.labels.shift();

    const l = Date.now();
    this.up.push(o.up);
    this.down.push(o.down);
    this.labels.push(l);

    this.subscribers.forEach((f) => f(o));
  },

  subscribe(listener: (x: any) => void) {
    this.subscribers.push(listener);
    return () => {
      const idx = this.subscribers.indexOf(listener);
      this.subscribers.splice(idx, 1);
    };
  },
};

let fetched = false;
let decoded = '';

function parseAndAppend(x: string) {
  traffic.appendData(JSON.parse(x));
}

function pump(reader: ReadableStreamDefaultReader) {
  return reader.read().then(({ done, value }) => {
    const str = textDecoder.decode(value, { stream: !done });
    decoded += str;

    const splits = decoded.split('\n');

    const lastSplit = splits[splits.length - 1];

    for (let i = 0; i < splits.length - 1; i++) {
      parseAndAppend(splits[i]);
    }

    if (done) {
      parseAndAppend(lastSplit);
      decoded = '';

      // eslint-disable-next-line no-console
      console.log('GET /traffic streaming done');
      fetched = false;
      return;
    } else {
      decoded = lastSplit;
    }
    return pump(reader);
  });
}

// 1 OPEN
// other value CLOSED
// similar to ws readyState but not the same
// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState
let wsState: number;
function fetchData(apiConfig: ClashAPIConfig) {
  if (fetched || wsState === 1) return traffic;
  wsState = 1;
  const url = buildWebSocketURL(apiConfig, endpoint);
  const ws = new WebSocket(url);
  ws.addEventListener('error', function (_ev) {
    wsState = 3;
  });
  ws.addEventListener('close', function (_ev) {
    wsState = 3;
    fetchDataWithFetch(apiConfig);
  });
  ws.addEventListener('message', function (event) {
    parseAndAppend(event.data);
  });
  return traffic;
}

function fetchDataWithFetch(apiConfig: ClashAPIConfig) {
  if (fetched) return traffic;
  fetched = true;
  const { url, init } = getURLAndInit(apiConfig);
  fetch(url + endpoint, init).then(
    (response) => {
      if (response.ok) {
        const reader = response.body.getReader();
        pump(reader);
      } else {
        fetched = false;
      }
    },
    (err) => {
      // eslint-disable-next-line no-console
      console.log('fetch /traffic error', err);
      fetched = false;
    }
  );
  return traffic;
}

export { fetchData };