aboutsummaryrefslogtreecommitdiffstats
path: root/src/electron/macOSPermissions.ts
blob: 0e183eeb722bf29dbeeb65f09f57d9b524468f6a (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
import { systemPreferences, BrowserWindow, dialog } from 'electron';
import { pathExistsSync, mkdirSync, writeFileSync } from 'fs-extra';
import macosVersion from 'macos-version';
import { dirname } from 'path';
// @ts-ignore
import { askForScreenCaptureAccess } from 'node-mac-permissions';
import { userDataPath } from '../environment-remote';

const debug = require('debug')('Ferdi:macOSPermissions');

const isExplicitScreenCapturePermissionReqd =
  macosVersion.isGreaterThanOrEqualTo('10.15');
debug(
  `Should check explicitly for screen-capture permissions: ${isExplicitScreenCapturePermissionReqd}`,
);

const filePath = userDataPath('.has-app-requested-screen-capture-permissions');

function hasPromptedForScreenCapturePermission(): string | boolean {
  if (!isExplicitScreenCapturePermissionReqd) {
    return false;
  }

  debug('Checking if status file exists');
  return filePath && pathExistsSync(filePath);
}

function hasScreenCapturePermissionAlreadyBeenGranted(): boolean {
  if (!isExplicitScreenCapturePermissionReqd) {
    return true;
  }

  const screenCaptureStatus = systemPreferences.getMediaAccessStatus('screen');
  debug(`screen-capture permissions status: ${screenCaptureStatus}`);
  return screenCaptureStatus === 'granted';
}

function createStatusFile() {
  try {
    writeFileSync(filePath, '');
  } catch (error) {
    if ((error as any).code === 'ENOENT') {
      mkdirSync(dirname(filePath));
      writeFileSync(filePath, '');
    }

    throw error;
  }
}

export const askFormacOSPermissions = async (mainWindow: BrowserWindow) => {
  debug('Checking camera & microphone permissions');
  systemPreferences.askForMediaAccess('camera');
  systemPreferences.askForMediaAccess('microphone');

  if (hasScreenCapturePermissionAlreadyBeenGranted()) {
    debug('Already obtained screen-capture permissions - writing status file');
    createStatusFile();
    return;
  }

  if (!hasPromptedForScreenCapturePermission()) {
    debug('Checking screen capture permissions');

    const { response } = await dialog.showMessageBox(mainWindow, {
      type: 'info',
      message: 'Enable Screen Sharing',
      detail:
        'To enable screen sharing for some services, Ferdi needs the permission to record your screen.',
      buttons: ['Allow screen sharing', 'No', 'Ask me later'],
      defaultId: 0,
      cancelId: 2,
    });

    if (response === 0) {
      debug('Asking for access');
      askForScreenCaptureAccess();
      createStatusFile();
    } else if (response === 1) {
      debug("Don't ask again");
      createStatusFile();
    }
  }
};