summaryrefslogtreecommitdiffstats
path: root/browser/extensions/webcompat/lib/picture_in_picture_overrides.js
blob: febee193aa98ce10c893375df53950202a2d9eb0 (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

/* globals browser, module */

class PictureInPictureOverrides {
  constructor(availableOverrides) {
    this.pref = "enable_picture_in_picture_overrides";
    this._prefEnabledOverrides = new Set();
    this._availableOverrides = availableOverrides;
    this.policies = browser.pictureInPictureChild.getPolicies();
  }

  async _checkGlobalPref() {
    await browser.aboutConfigPrefs.getPref(this.pref).then(value => {
      if (value === false) {
        this._enabled = false;
      } else {
        if (value === undefined) {
          browser.aboutConfigPrefs.setPref(this.pref, true);
        }
        this._enabled = true;
      }
    });
  }

  async _checkSpecificOverridePref(id, pref) {
    const isDisabled = await browser.aboutConfigPrefs.getPref(pref);
    if (isDisabled === true) {
      this._prefEnabledOverrides.delete(id);
    } else {
      this._prefEnabledOverrides.add(id);
    }
  }

  bootup() {
    const checkGlobal = async () => {
      await this._checkGlobalPref();
      this._onAvailableOverridesChanged();
    };
    browser.aboutConfigPrefs.onPrefChange.addListener(checkGlobal, this.pref);

    const bootupPrefCheckPromises = [this._checkGlobalPref()];

    for (const id of Object.keys(this._availableOverrides)) {
      const pref = `disabled_picture_in_picture_overrides.${id}`;
      const checkSingle = async () => {
        await this._checkSpecificOverridePref(id, pref);
        this._onAvailableOverridesChanged();
      };
      browser.aboutConfigPrefs.onPrefChange.addListener(checkSingle, pref);
      bootupPrefCheckPromises.push(this._checkSpecificOverridePref(id, pref));
    }

    Promise.all(bootupPrefCheckPromises).then(() => {
      this._onAvailableOverridesChanged();
    });
  }

  async _onAvailableOverridesChanged() {
    const policies = await this.policies;
    let enabledOverrides = {};
    for (const [id, override] of Object.entries(this._availableOverrides)) {
      const enabled = this._enabled && this._prefEnabledOverrides.has(id);
      for (const [url, policy] of Object.entries(override)) {
        enabledOverrides[url] = enabled ? policy : policies.DEFAULT;
      }
    }
    browser.pictureInPictureParent.setOverrides(enabledOverrides);
  }
}