aboutsummaryrefslogtreecommitdiffstats
path: root/src/features/serviceProxy/index.ts
blob: bdc21e97e4bd86c7d870af0e8e9eee08840d1522 (plain) (blame)
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
import { autorun, observable } from 'mobx';
import { session } from '@electron/remote';

const debug = require('debug')('Ferdium:feature:serviceProxy');

export const config = observable({
  isEnabled: true,
});

export default function init(stores: {
  services: { enabled: any };
  settings: { proxy: any };
}) {
  debug('Initializing `serviceProxy` feature');

  autorun(() => {
    config.isEnabled = true;

    const services = stores.services.enabled;
    const proxySettings = stores.settings.proxy;

    debug('Service Proxy autorun');

    for (const service of services) {
      const s = session.fromPartition(`persist:service-${service.id}`);

      if (config.isEnabled) {
        const serviceProxyConfig = proxySettings[service.id];

        if (
          serviceProxyConfig &&
          serviceProxyConfig.isEnabled &&
          serviceProxyConfig.host
        ) {
          const proxyHost = `${serviceProxyConfig.host}${
            serviceProxyConfig.port ? `:${serviceProxyConfig.port}` : ''
          }`;
          debug(
            `Setting proxy config from service settings for "${service.name}" (${service.id}) to`,
            proxyHost,
          );

          s.setProxy({ proxyRules: proxyHost })
            .then(() => {
              debug(
                `Using proxy "${proxyHost}" for "${service.name}" (${service.id})`,
              );
            })
            .catch(error => console.error(error));
        }
      }
    }
  });
}