aboutsummaryrefslogtreecommitdiff
path: root/extension/src/features/settings.ts
blob: ad6c2f4ec48f055c6e6decb7957cef00ab7cd2d5 (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
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
// Copyright (C) 2024 Vaughn Nugent
//
// This program 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, either version 3 of the
// License, or (at your option) any later version.
//
// 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/>.

import { storage } from "webextension-polyfill"
import { defaultsDeep, defer, find, isArray, isEmpty } from 'lodash'
import { configureApi, debugLog } from '@vnuge/vnlib.browser'
import { computed, MaybeRefOrGetter, readonly, Ref, shallowRef, watch } from "vue";
import { JsonObject } from "type-fest";
import { Watchable } from "./types";
import { BgRuntime, FeatureApi, optionsOnly, IFeatureExport, exportForegroundApi, popupAndOptionsOnly } from './framework'
import { get, set } from "@vueuse/core";
import { waitForChangeFn, useStorage } from "./util";
import { ServerApi, useServerApi } from "./server-api";

export interface PluginConfig extends JsonObject {
    readonly discoveryUrl: string;
    readonly heartbeat: boolean;
    readonly maxHistory: number;
    readonly tagFilter: boolean;
    readonly authPopup: boolean;
    readonly darkMode: boolean;
}

//Default storage config
const defaultConfig : PluginConfig = Object.freeze({
    discoveryUrl: import.meta.env.VITE_DISCOVERY_URL,
    heartbeat: import.meta.env.VITE_HEARTBEAT_ENABLED === 'true',
    maxHistory: 50,
    tagFilter: true,
    authPopup: true,
    darkMode: false,
});

export interface EndpointConfig extends JsonObject {
   readonly apiBaseUrl: string;
   readonly accountBasePath: string;
   readonly nostrBasePath: string;
}

export interface ConfigStatus {
    readonly EpConfig: EndpointConfig;
    readonly isDarkMode: boolean;
    readonly isValid: boolean;
}

export interface AppSettings{
    saveConfig(config: PluginConfig): void;
    useStorageSlot<T>(slot: string, defaultValue: MaybeRefOrGetter<T>): Ref<T>;
    useServerApi(): ServerApi,
    setDarkMode(darkMode: boolean): void;
    readonly status: Readonly<Ref<ConfigStatus>>;
    readonly currentConfig: Readonly<Ref<PluginConfig>>;
}

export interface SettingsApi extends FeatureApi, Watchable {
    getSiteConfig: () => Promise<PluginConfig>;
    setSiteConfig: (config: PluginConfig) => Promise<PluginConfig>;
    setDarkMode: (darkMode: boolean) => Promise<void>;
    getStatus: () => Promise<ConfigStatus>;
    testServerAddress: (address: string) => Promise<boolean>;
}

interface ServerDiscoveryResult{
    readonly endpoints: {
        readonly name: string;
        readonly path: string;
    }[]
}

const discoverAndSetEndpoints = async (discoveryUrl: string, epConfig: Ref<EndpointConfig | undefined>) => {
    const res = await fetch(discoveryUrl)
    const { endpoints } = await res.json() as ServerDiscoveryResult;

    const urls: EndpointConfig = {
        apiBaseUrl: new URL(discoveryUrl).origin,
        accountBasePath: find(endpoints, p => p.name == "account")?.path || "/account",
        nostrBasePath: find(endpoints, p => p.name == "nostr")?.path || "/nostr",
    };

    //Set once the urls are discovered
    set(epConfig, urls);
}

export const useAppSettings = (): AppSettings => {

    const _storageBackend = storage.local;
    const _darkMode = shallowRef(false);
    const store = useStorage<PluginConfig>(_storageBackend, 'siteConfig', defaultConfig);
    const endpointConfig = shallowRef<EndpointConfig>({nostrBasePath: '', accountBasePath: '', apiBaseUrl: ''})

    const status = computed<ConfigStatus>(() => {
        return{
            EpConfig: get(endpointConfig),
            isDarkMode: get(_darkMode),
            isValid: !isEmpty(get(endpointConfig).nostrBasePath)
        }
    })

    //Merge the default config for nullables with the current config on startyup
    defaultsDeep(store.value, defaultConfig);

    //Watch for changes to the discovery url, then cause a discovery
    watch([store], ([{ discoveryUrl }]) => {
        defer(() => discoverAndSetEndpoints(discoveryUrl, endpointConfig))
    }, { immediate: true }) //alaways run on startup

    watch([endpointConfig], ([epconf]) => {
        //Configure the vnlib api
        configureApi({
            session: {
                cookiesEnabled: false,
                browserIdSize: 32,
            },
            user: {
                accountBasePath: epconf?.accountBasePath,
            },
            axios: {
                baseURL: epconf?.apiBaseUrl,
                tokenHeader: import.meta.env.VITE_WEB_TOKEN_HEADER,
            },
            storage: localStorage
        })

    }, { deep: true })

    //Save the config and update the current config
    const saveConfig = (config: PluginConfig) => set(store, config);
   
    //Local reactive server api
    const serverApi = useServerApi(endpointConfig)

    return {
        saveConfig,
        status, 
        currentConfig: readonly(store),
        useStorageSlot: <T>(slot: string, defaultValue: MaybeRefOrGetter<T>) => {
            return useStorage<T>(_storageBackend, slot, defaultValue)
        },
        useServerApi: () => serverApi,
        setDarkMode: (darkMode: boolean) => set(_darkMode, darkMode)
    }
}

export const useSettingsApi = () : IFeatureExport<AppSettings, SettingsApi> =>{

    return{
        background: ({ state }: BgRuntime<AppSettings>) => {

            return {
                waitForChange: waitForChangeFn([state.currentConfig, state.status]),
                getSiteConfig: () => Promise.resolve(state.currentConfig.value),
                setSiteConfig: optionsOnly(async (config: PluginConfig): Promise<PluginConfig> => {

                    //Save the config
                    state.saveConfig(config);

                    debugLog('Config settings saved!');

                    //Return the config
                    return get(state.currentConfig)
                }),
                setDarkMode: popupAndOptionsOnly((darkMode: boolean) => {
                    state.setDarkMode(darkMode);
                    return Promise.resolve();
                }),
                getStatus: () => {
                    //Since value is computed it needs to be manually unwrapped
                    const { isDarkMode, isValid, EpConfig } = get(state.status);
                    return Promise.resolve({ isDarkMode, isValid, EpConfig })
                },
                testServerAddress: optionsOnly(async (url: string) => {
                    const res = await fetch(url);
                    const data = await res.json() as ServerDiscoveryResult;
                    return isArray(data?.endpoints) && !isEmpty(data.endpoints);
                })
            }
        },
        foreground: exportForegroundApi([
            'getSiteConfig',
            'setSiteConfig',
            'setDarkMode',
            'waitForChange',
            'getStatus',
            'testServerAddress'
        ]) 
    }
}