aboutsummaryrefslogtreecommitdiff
path: root/src/FaunerieLoader.ts
blob: 926ece6be22aee03c933ef5744ccd0383bc23668 (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
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
import {FaunerieApp} from "./FaunerieApp";
import {ipcRenderer} from "electron";
import * as si from "systeminformation";
import fs from "fs";
import {Faunerie, FaunerieListType} from "libfaunerie";

export class FaunerieLoader {
    instance: FaunerieApp;
    dataPath: string;

    constructor(instance: FaunerieApp) {
        this.instance = instance;
    }

    async requestDatabaseOpen() {
        if (localStorage.getItem("path") === null) {
            let path = await ipcRenderer.invoke("openFolder");
            if (typeof path !== "object" && typeof path !== "string") {
                alert("Please select a folder and try again.");
                this.instance.dataStore.unloaded = true;
                window.close();
                return;
            }

            if (path instanceof Array) {
                localStorage.setItem("path", path[0]);
            } else {
                localStorage.setItem("path", path);
            }

            if (!require('fs').existsSync(localStorage.getItem("path") + "/instance.pbmk")) require('fs').writeFileSync(localStorage.getItem("path") + "/instance.pbmk", "");
        }
    }

    async getPossibleSources() {
        let mounts = (await si.fsSize()).map(i => i.mount);
        let list = [localStorage.getItem("path").replaceAll("\\", "/")];
        let parts = localStorage.getItem("path").replaceAll("\\", "/").split("/").filter(i => i.trim() !== "");

        for (let i = 1; i <= parts.length; i++) {
            for (let mount of mounts) {
                list.push(mount + "/" + parts.slice(0, i).join("/"));
            }
        }

        for (let i = 1; i <= parts.length; i++) {
            for (let mount of mounts) {
                let j = i + 1;

                while (j <= parts.length) {
                    list.push(mount + "/" + parts.slice(i, j).join("/"));
                    j++;
                }
            }
        }

        for (let i = 1; i <= parts.length; i++) {
            for (let mount of mounts) {
                list.push(mount + "/" + parts.slice(i, i + 1).join("/"));
            }
        }

        return [...new Set(list.map(i => i.replaceAll("//", "/").replaceAll("\\", "/")))];
    }

    async filterValidSources(list: string[]) {
        let validSources = [];
        let statFolders = ["images", "thumbnails"];
        let statFiles = ["current.pbdb", "instance.pbmk"];

        for (let item of list) {
            let validFolders = 0;
            let validFiles = 0;

            for (let folder of statFolders) {
                let valid = false;

                try {
                    valid = (await fs.promises.lstat(item + "/" + folder)).isDirectory();
                } catch (e) {
                }

                if (valid) validFolders++;
            }

            for (let file of statFiles) {
                let valid = false;

                try {
                    valid = (await fs.promises.lstat(item + "/" + file)).isFile();
                } catch (e) {
                }

                if (valid) validFiles++;
            }

            if (validFolders > 0 || validFiles > 0) {
                validSources.push(item);
            }
        }

        return validSources;
    }

    openFirstSource(validSources: string[]) {
        let selectedSource: string;

        if (validSources.filter(i => i === localStorage.getItem("path").replaceAll("\\", "/")).length > 0) {
            selectedSource = validSources.filter(i => i === localStorage.getItem("path").replaceAll("\\", "/"))[0];
        } else {
            selectedSource = validSources[0];
            this.instance.loadingError("Database was read from " + selectedSource + " as the normal path is not available");
        }

        return selectedSource;
    }

    async triggerInvalidSource(list: string[]) {
        alert("Unable to load images as no valid image source could be found.\n\nTried: " + list.join(", "));

        let path = await ipcRenderer.invoke("openFolder");
        if (typeof path !== "object" && typeof path !== "string") {
            alert("Please select a folder and try again.");
            this.instance.dataStore.unloaded = true;
            window.close();
            return;
        }

        if (path instanceof Array) {
            localStorage.setItem("path", path[0]);
        } else {
            localStorage.setItem("path", path);
        }

        if (!require('fs').existsSync(localStorage.getItem("path") + "/instance.pbmk")) require('fs').writeFileSync(localStorage.getItem("path") + "/instance.pbmk", "");

        location.reload();
    }

    async loadFromCache() {
        let _dataStore = this.instance.dataStore;
        let valid = false;

        try {
            valid = (await fs.promises.lstat(_dataStore.appData + "/FaunerieCache/current.pbdb")).isFile();
        } catch (e) {
            valid = false;
        }

        if (valid) {
            this.instance.loadingError("No valid image source found, images will be downloaded from their source");
            _dataStore.loadedFromCache = true;
            return _dataStore.appData + "/FaunerieCache";
        } else {
            alert("Unable to load images from cache as the cache is empty or corrupted.");
            this.instance.dataStore.unloaded = true;
            window.close();
        }
    }

    async loadAppropriateSource() {
        let _dataStore = this.instance.dataStore;

        _dataStore.loadedFromCache = false;

        let list = await this.getPossibleSources();
        let validSources = await this.filterValidSources(list);

        if (validSources.length > 0) {
            return this.openFirstSource(validSources);
        } else {
            if (fs.existsSync(_dataStore.appData + "/FaunerieCache")) {
                return await this.loadFromCache();
            } else {
                await this.triggerInvalidSource(list);
            }
        }
    }

    async findDatabase(): Promise<string> {
        document.getElementById("load").innerText = "Finding database...";

        await this.requestDatabaseOpen();

        document.getElementById("progress").classList.remove("progress-bar-striped");
        document.getElementById("progress").style.width = "0%";

        document.getElementById("progress").classList.remove("progress-bar-striped");
        document.getElementById("progress").style.width = "0%";

        this.instance.dataStore.source = this.dataPath = await this.loadAppropriateSource();
        return this.dataPath;
    }

    checkBusyUpdating() {
        if (require('fs').existsSync(this.dataPath + "/updater.pbmk")) {
            let pid = parseInt(require('fs').readFileSync(this.dataPath + "/updater.pbmk").toString().trim());
            let isUpdating = false;

            try {
                process.kill(pid, 0);
                isUpdating = true;
            } catch (e) {
                isUpdating = false;
            }

            if (isUpdating) {
                alert("This database is locked because an external Faunerie Updater is updating its content. Please try again later.");
                this.instance.dataStore.unloaded = true;
                window.close();
            }
        }
    }

    async initializeDatabase() {
        let _dataStore = this.instance.dataStore;

        _dataStore.database = new Faunerie({
            database: this.dataPath,
            cachePath: _dataStore.appData,
            sqlitePath: process.platform === "darwin" ? "../../../sql/mac" : "../../../sql/win",
            readOnly: false,
            sensitiveImageProtocol: true
        });

        await _dataStore.database.initialize(true);
        this.instance.createPropertyStore();
    }

    async updateCache() {
        let _dataStore = this.instance.dataStore;

        if (!_dataStore.loadedFromCache) {
            document.getElementById("load").innerText = "Updating cache...";
            document.getElementById("progress").classList.remove("progress-bar-striped");
            document.getElementById("progress").style.width = "0%";

            if (!fs.existsSync(_dataStore.appData + "/FaunerieCache")) await fs.promises.mkdir(_dataStore.appData + "/FaunerieCache");
            await fs.promises.copyFile(this.dataPath + "/current.pbdb", _dataStore.appData + "/FaunerieCache/current.pbdb");

            document.getElementById("progress").style.width = "100%";
        }
    }

    async completeLoading() {
        let _dataStore = this.instance.dataStore;

        _dataStore.db = await _dataStore.database.frontend.getAllImages(FaunerieListType.Object);
        _dataStore.tags = _dataStore.database.frontend.tags;
        _dataStore.tagsHashed = _dataStore.database.frontend.tagsHashed;

        if (_dataStore.hadErrorsLoading) {
            document.getElementById("load").innerText = "Finished loading with warnings.";
            document.getElementById("progress").classList.remove("progress-bar-striped");
            document.getElementById("progress").style.width = "100%";
            document.getElementById("loading-btn").classList.remove("disabled");
        } else {
            this.instance.finishLoading();
        }
    }
}