File: debug.js

package info (click to toggle)
firefox 141.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,550,588 kB
  • sloc: cpp: 7,426,506; javascript: 6,367,238; ansic: 3,707,351; python: 1,369,002; xml: 623,983; asm: 426,918; java: 184,324; sh: 64,488; makefile: 19,203; objc: 13,059; perl: 12,955; yacc: 4,583; cs: 3,846; pascal: 3,352; lex: 1,720; ruby: 1,071; exp: 762; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10
file content (277 lines) | stat: -rw-r--r-- 8,967 bytes parent folder | download | duplicates (4)
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/* 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 https://mozilla.org/MPL/2.0/. */

/* import-globals-from /toolkit/content/preferencesBindings.js */

Preferences.addAll([
  { id: "browser.backup.enabled", type: "bool" },
  { id: "browser.backup.log", type: "bool" },
]);

const { BackupService } = ChromeUtils.importESModule(
  "resource:///modules/backup/BackupService.sys.mjs"
);

let DebugUI = {
  init() {
    let controls = document.querySelector("#controls");
    controls.addEventListener("click", this);

    let encryptionEnabled = document.querySelector("#encryption-enabled");
    encryptionEnabled.addEventListener("click", this);

    // We use `init` instead of `get` here, since this page might load before
    // the BackupService has had a chance to initialize itself.
    let service = BackupService.init();
    service.addEventListener("BackupService:StateUpdate", this);
    this.onStateUpdate();

    // Kick-off reading any pre-existing encryption state off of the disk.
    service.loadEncryptionState();
  },

  handleEvent(event) {
    switch (event.type) {
      case "BackupService:StateUpdate": {
        this.onStateUpdate();
        break;
      }
      case "click": {
        let target = event.target;
        if (HTMLButtonElement.isInstance(event.target)) {
          this.onButtonClick(target);
        } else if (
          HTMLInputElement.isInstance(event.target) &&
          event.target.type == "checkbox"
        ) {
          event.preventDefault();
          this.onCheckboxClick(target);
        }
        break;
      }
    }
  },

  secondsToHms(seconds) {
    let h = Math.floor(seconds / 3600);
    let m = Math.floor((seconds % 3600) / 60);
    let s = Math.floor((seconds % 3600) % 60);
    return `${h}h ${m}m ${s}s`;
  },

  async onButtonClick(button) {
    switch (button.id) {
      case "create-backup": {
        let service = BackupService.get();
        let lastBackupStatus = document.querySelector("#last-backup-status");
        lastBackupStatus.textContent = "Creating backup...";

        let then = Cu.now();
        button.disabled = true;
        await service.createBackup();
        let totalTimeSeconds = (Cu.now() - then) / 1000;
        button.disabled = false;
        new Notification(`Backup created`, {
          body: `Total time ${this.secondsToHms(totalTimeSeconds)}`,
        });
        lastBackupStatus.textContent = `Backup created - total time: ${this.secondsToHms(
          totalTimeSeconds
        )}`;
        break;
      }
      case "open-backup-folder": {
        let backupsDir = PathUtils.join(
          PathUtils.profileDir,
          BackupService.PROFILE_FOLDER_NAME
        );

        let nsLocalFile = Components.Constructor(
          "@mozilla.org/file/local;1",
          "nsIFile",
          "initWithPath"
        );

        if (await IOUtils.exists(backupsDir)) {
          new nsLocalFile(backupsDir).reveal();
        } else {
          alert("backups folder doesn't exist yet");
        }

        break;
      }
      case "recover-from-staging": {
        let backupsDir = PathUtils.join(
          PathUtils.profileDir,
          BackupService.PROFILE_FOLDER_NAME
        );
        let fp = Cc["@mozilla.org/filepicker;1"].createInstance(
          Ci.nsIFilePicker
        );
        fp.init(
          window.browsingContext,
          "Choose a staging folder",
          Ci.nsIFilePicker.modeGetFolder
        );
        fp.displayDirectory = await IOUtils.getDirectory(backupsDir);
        let result = await new Promise(resolve => fp.open(resolve));
        if (result == Ci.nsIFilePicker.returnCancel) {
          break;
        }

        let path = fp.file.path;
        let lastRecoveryStatus = document.querySelector(
          "#last-recovery-status"
        );
        lastRecoveryStatus.textContent = "Recovering from backup...";

        let service = BackupService.get();
        try {
          let newProfile = await service.recoverFromSnapshotFolder(
            path,
            true /* shouldLaunch */
          );
          lastRecoveryStatus.textContent = `Created profile ${newProfile.name} at ${newProfile.rootDir.path}`;
        } catch (e) {
          lastRecoveryStatus.textContent(
            `Failed to recover: ${e.message} Check the console for the full exception.`
          );
          throw e;
        }
        break;
      }
      case "extract-from-archive": {
        let backupsDir = PathUtils.join(
          PathUtils.profileDir,
          BackupService.PROFILE_FOLDER_NAME
        );
        let fp = Cc["@mozilla.org/filepicker;1"].createInstance(
          Ci.nsIFilePicker
        );
        fp.init(
          window.browsingContext,
          "Choose an archive file",
          Ci.nsIFilePicker.modeOpen
        );
        fp.displayDirectory = await IOUtils.getDirectory(backupsDir);
        let result = await new Promise(resolve => fp.open(resolve));
        if (result == Ci.nsIFilePicker.returnCancel) {
          break;
        }

        let extractionStatus = document.querySelector("#extraction-status");
        extractionStatus.textContent = "Extracting...";

        let path = fp.file.path;
        let dest = PathUtils.join(PathUtils.parent(path), "extraction.zip");
        let service = BackupService.get();
        try {
          let { isEncrypted } = await service.sampleArchive(path);
          let recoveryCode = undefined;
          if (isEncrypted) {
            recoveryCode = prompt("Please provide the decryption password");
          }
          await service.extractCompressedSnapshotFromArchive(
            path,
            dest,
            recoveryCode
          );
          extractionStatus.textContent = `Extracted ZIP file to ${dest}`;
        } catch (e) {
          extractionStatus.textContent = `Failed to extract: ${e.message} Check the console for the full exception.`;
          throw e;
        }
        break;
      }
      case "recover-from-archive": {
        let backupsDir = PathUtils.join(
          PathUtils.profileDir,
          BackupService.PROFILE_FOLDER_NAME
        );
        let fp = Cc["@mozilla.org/filepicker;1"].createInstance(
          Ci.nsIFilePicker
        );
        fp.init(
          window.browsingContext,
          "Choose an archive file",
          Ci.nsIFilePicker.modeOpen
        );
        fp.displayDirectory = await IOUtils.getDirectory(backupsDir);
        fp.appendFilters(Ci.nsIFilePicker.filterHTML);

        let result = await new Promise(resolve => fp.open(resolve));
        if (result == Ci.nsIFilePicker.returnCancel) {
          break;
        }

        let recoverFromArchiveStatus = document.querySelector(
          "#recover-from-archive-status"
        );
        recoverFromArchiveStatus.textContent =
          "Recovering from backup archive...";

        let path = fp.file.path;
        let service = BackupService.get();
        try {
          let { isEncrypted } = await service.sampleArchive(path);
          let recoveryCode = undefined;
          if (isEncrypted) {
            recoveryCode = prompt("Please provide the decryption password");
          }
          let newProfile = await service.recoverFromBackupArchive(
            path,
            recoveryCode,
            true /* shouldLaunch */
          );
          recoverFromArchiveStatus.textContent = `Created profile ${newProfile.name} at ${newProfile.rootDir.path}`;
        } catch (e) {
          recoverFromArchiveStatus.textContent = `Failed to recover: ${e.message} Check the console for the full exception.`;
          throw e;
        }
        break;
      }
    }
  },

  async onCheckboxClick(checkbox) {
    if (checkbox.id == "encryption-enabled") {
      let service = BackupService.get();
      if (checkbox.checked) {
        let password = prompt("What's the encryption password? (8 char min)");
        if (password != null) {
          try {
            await service.enableEncryption(password);
          } catch (e) {
            console.error(e);
          }
        }
      } else if (confirm("Disable encryption?")) {
        try {
          await service.disableEncryption();
        } catch (e) {
          console.error(e);
        }
      }
    }
  },

  onStateUpdate() {
    let service = BackupService.get();
    let state = service.state;

    let encryptionEnabled = document.querySelector("#encryption-enabled");
    encryptionEnabled.checked = state.encryptionEnabled;
  },
};

// Wait until the load event fires before setting up any listeners or updating
// any of the state of the page. We do this in order to avoid having any of
// our control states overwritten by SessionStore after a restoration, as
// restoration of form state occurs _prior_ to the load event firing.
addEventListener(
  "load",
  () => {
    DebugUI.init();
  },
  { once: true }
);