summaryrefslogtreecommitdiff
path: root/src/api/rule-provider.ts
blob: 14d99179af9952eb94ed53ad9c0b16dda738773f (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
import { getURLAndInit } from '~/misc/request-helper';
import { ClashAPIConfig } from '~/types';

export type RuleProvider = RuleProviderAPIItem & { idx: number };

export type RuleProviderAPIItem = {
  behavior: string;
  name: string;
  ruleCount: number;
  type: 'Rule';
  // example value "2020-06-30T16:23:01.44143802+08:00"
  updatedAt: string;
  vehicleType: 'HTTP' | 'File';
};

type RuleProviderAPIData = {
  providers: Record<string, RuleProviderAPIItem>;
};

function normalizeAPIResponse(data: RuleProviderAPIData) {
  const providers = data.providers;
  const names = Object.keys(providers);
  const byName: Record<string, RuleProvider> = {};

  // attach an idx to each item
  for (let i = 0; i < names.length; i++) {
    const name = names[i];
    byName[name] = { ...providers[name], idx: i };
  }

  return { byName, names };
}

export async function fetchRuleProviders(endpoint: string, apiConfig: ClashAPIConfig) {
  const { url, init } = getURLAndInit(apiConfig);

  let data = { providers: {} };
  try {
    const res = await fetch(url + endpoint, init);
    if (res.ok) {
      data = await res.json();
    }
  } catch (err) {
    // log and ignore
    // eslint-disable-next-line no-console
    console.log('failed to GET /providers/rules', err);
  }
  return normalizeAPIResponse(data);
}

export async function refreshRuleProviderByName({
  name,
  apiConfig,
}: {
  name: string;
  apiConfig: ClashAPIConfig;
}) {
  const { url, init } = getURLAndInit(apiConfig);
  try {
    const res = await fetch(url + `/providers/rules/${name}`, {
      method: 'PUT',
      ...init,
    });
    return res.ok;
  } catch (err) {
    // log and ignore
    // eslint-disable-next-line no-console
    console.log('failed to PUT /providers/rules/:name', err);
    return false;
  }
}

export async function updateRuleProviders({
  names,
  apiConfig,
}: {
  names: string[];
  apiConfig: ClashAPIConfig;
}) {
  for (let i = 0; i < names.length; i++) {
    // run in sequence
    await refreshRuleProviderByName({ name: names[i], apiConfig });
  }
}