aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/infrastructure/electron/impl/ElectronServiceView.ts
blob: 91247c84a0c370bfa6a72b8e628fa5d08fb7c0ce (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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/*
 * Copyright (C)  2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { BrowserView } from 'electron';

import type Service from '../../../stores/Service.js';
import getLogger from '../../../utils/getLogger.js';
import type Resources from '../../resources/Resources.js';
import type { ServiceView } from '../types.js';

import ElectronPartition from './ElectronPartition.js';
import type ElectronViewFactory from './ElectronViewFactory.js';

const log = getLogger('ElectronServiceView');

export default class ElectronServiceView implements ServiceView {
  readonly id: string;

  readonly partitionId: string;

  readonly browserView: BrowserView;

  constructor(
    private readonly service: Service,
    resources: Resources,
    partition: ElectronPartition,
    private readonly parent: ElectronViewFactory,
  ) {
    this.id = service.id;
    this.partitionId = partition.id;
    this.browserView = new BrowserView({
      webPreferences: {
        sandbox: true,
        nodeIntegrationInSubFrames: true,
        preload: resources.getPath('service-preload', 'index.cjs'),
        session: partition.session,
      },
    });

    this.browserView.setBackgroundColor('#fff');
    this.browserView.setAutoResize({
      width: true,
      height: true,
    });
    // Util we first attach `browserView` to a `BrowserWindow`,
    // `setBounds` calls will be ignored, so there's no point in callind `updateBounds` here.
    // It will be called by `ElectronMainWindow` when we first attach this service to it.

    const { webContents } = this.browserView;

    function setLocation(url: string) {
      service.setLocation({
        url,
        canGoBack: webContents.canGoBack(),
        canGoForward: webContents.canGoForward(),
      });
    }

    webContents.on('did-navigate', (_event, url) => {
      setLocation(url);
    });

    webContents.on('did-navigate-in-page', (_event, url, isMainFrame) => {
      if (isMainFrame) {
        setLocation(url);
      }
    });

    webContents.on(
      'did-fail-load',
      (_event, errorCode, errorDesc, url, isMainFrame) => {
        if (errorCode === -3) {
          // Do not signal error on ABORTED, since that corresponds to an action requested by the user.
          // Other events (`did-start-loading` or `did-stop-loading`) will cause service state changes
          // that are appropriate for the user action.
          log.debug('Loading', url, 'in service', this.id, 'aborted by user');
          return;
        }
        if (isMainFrame) {
          setLocation(url);
          service.setFailed(errorCode, errorDesc);
          log.warn(
            'Failed to load',
            url,
            'in service',
            this.id,
            errorCode,
            errorDesc,
          );
        }
      },
    );

    /**
     * We use the `'certificate-error'` event instead of `session.setCertificateVerifyProc`
     * because:
     *
     * 1. `'certificate-error'` is bound to the `webContents`, so we can display the certificate
     *    in the place of the correct service. Note that chromium still manages certificate trust
     *    per session, so we can't have different trusted certificates for each service of a
     *    profile.
     * 2. The results of `'certificate-error'` are _not_ cached, so we can initially reject
     *    the certificate but we can still accept it once the user trusts it temporarily.
     */
    webContents.on(
      'certificate-error',
      (event, url, error, certificate, callback, isMainFrame) => {
        if (service.isCertificateTemporarilyTrusted(certificate)) {
          event.preventDefault();
          callback(true);
          return;
        }
        if (isMainFrame) {
          setLocation(url);
          service.setCertificateError(error, certificate);
        }
        callback(false);
      },
    );

    webContents.on('page-title-updated', (_event, title) => {
      service.setTitle(title);
    });

    webContents.on('did-start-loading', () => {
      service.startLoading();
    });

    webContents.on('did-stop-loading', () => {
      service.finishLoading();
    });

    webContents.on('render-process-gone', (_event, details) => {
      const { reason, exitCode } = details;
      service.setCrashed(reason, exitCode);
    });

    webContents.setWindowOpenHandler(({ url }) => {
      // TODO Add filtering (allowlist) by URL.
      // TODO Handle `new-window` disposition where the service wants an object returned by
      // `window.open`.
      // TODO Handle downloads with `save-to-disk` disposition.
      // TODO Handle POST bodies where the window must be allowed to open or the data is lost.
      service.addBlockedPopup(url);
      return { action: 'deny' };
    });
  }

  get webContentsId(): number {
    return this.browserView.webContents.id;
  }

  loadURL(url: string): void {
    this.browserView.webContents.loadURL(url).catch((error) => {
      log.warn('Error while loading', url, 'in service', this.id, error);
    });
  }

  goBack(): void {
    this.browserView.webContents.goBack();
  }

  goForward(): void {
    this.browserView.webContents.goForward();
  }

  reload(ignoreCache: boolean): void {
    if (ignoreCache) {
      this.browserView.webContents.reloadIgnoringCache();
    } else {
      this.browserView.webContents.reload();
    }
  }

  stop(): void {
    this.browserView.webContents.stop();
  }

  toggleDeveloperTools(): void {
    this.browserView.webContents.toggleDevTools();
  }

  updateBounds(): void {
    const { x, y, width, height, hasBounds } = this.service;
    if (!hasBounds) {
      return;
    }
    this.browserView.setBounds({ x, y, width, height });
  }

  dispose(): void {
    setImmediate(() => {
      this.parent.unregisterServiceView(this.webContentsId);
      // Undocumented electron API, see e.g., https://github.com/electron/electron/issues/29626
      (
        this.browserView.webContents as unknown as { destroy(): void }
      ).destroy();
    });
  }
}