| // Copyright 2022 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| import { randomUUID } from 'crypto'; |
| import * as vscode from 'vscode'; |
| |
| import * as metric_properties from './metric_properties'; |
| |
| const ENABLED_PROPERTY = 'analytics-status'; |
| const UUID_PROPERTY = 'uuid'; |
| |
| export class PersistentStatus { |
| private readonly launchedProperty; |
| |
| constructor(toolName: string) { |
| this.launchedProperty = `${toolName}-launched`; |
| } |
| |
| async enable(): Promise<void> { |
| await metric_properties.setBoolean(ENABLED_PROPERTY, true); |
| await metric_properties.set(UUID_PROPERTY, randomUUID()); |
| } |
| |
| async disable(): Promise<void> { |
| await metric_properties.setBoolean(ENABLED_PROPERTY, false); |
| await metric_properties.deleteProperty(UUID_PROPERTY); |
| } |
| |
| async isEnabled(): Promise<boolean> { |
| // Treat undefined as false |
| return (await metric_properties.getBoolean(ENABLED_PROPERTY)) === true; |
| } |
| |
| async getUuid(): Promise<string | undefined> { |
| return await metric_properties.get(UUID_PROPERTY); |
| } |
| |
| async isFirstLaunchOfFirstTool(): Promise<boolean> { |
| return !(await metric_properties.exists(ENABLED_PROPERTY)); |
| } |
| |
| async markAsDirectlyLaunched() { |
| await metric_properties.set(this.launchedProperty, ''); |
| } |
| async isFirstDirectLaunch(): Promise<boolean> { |
| return !(await metric_properties.exists(this.launchedProperty)); |
| } |
| |
| onDidChangeEnabled(watcher: EnabledPropertyWatcher, listener: (enabled: boolean) => any) { |
| return watcher.onDidChange(async (e) => { |
| listener(await this.isEnabled()); |
| }); |
| } |
| } |
| |
| export class EnabledPropertyWatcher { |
| private readonly watcher: vscode.FileSystemWatcher; |
| |
| constructor() { |
| const pattern = |
| new vscode.RelativePattern(metric_properties.getMetricDirectory(), ENABLED_PROPERTY); |
| this.watcher = vscode.workspace.createFileSystemWatcher(pattern); |
| } |
| |
| onDidChange(listener: (e: vscode.Uri) => any) { |
| return this.watcher.onDidChange(listener); |
| } |
| |
| dispose() { |
| this.watcher.dispose(); |
| } |
| } |