Compare commits
11 Commits
migrate-de
...
capacitor-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a1b6add178 | ||
|
|
d3a26a54d4 | ||
|
|
122b5b1a06 | ||
|
|
9e8f08aa49 | ||
|
|
1529cc9689 | ||
|
|
f7ed05d13f | ||
|
|
7c8a6d0666 | ||
|
|
1aa285be55 | ||
|
|
2635c22c33 | ||
|
|
2d516b90b0 | ||
|
|
7a1329e1a4 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -21,6 +21,7 @@ npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
android/app/src/main/res/
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
@@ -55,4 +56,3 @@ build_logs/
|
||||
icons
|
||||
|
||||
|
||||
android/app/src/main/res/
|
||||
47
BUILDING.md
47
BUILDING.md
@@ -64,14 +64,14 @@ Install dependencies:
|
||||
|
||||
* Commit everything (since the commit hash is used the app).
|
||||
|
||||
* Put the commit hash in the changelog (which will help you remember to bump the version in the step later).
|
||||
* Put the commit hash in the changelog (which will help you remember to bump the version later).
|
||||
|
||||
* Tag with the new version, [online](https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa/releases) or `git tag 1.0.0 && git push origin 1.0.0`.
|
||||
* Tag with the new version, [online](https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa/releases) or `git tag 0.3.55 && git push origin 0.3.55`.
|
||||
|
||||
* For test, build the app (because test server is not yet set up to build):
|
||||
|
||||
```bash
|
||||
TIME_SAFARI_APP_TITLE="TimeSafari_Test" VITE_APP_SERVER=https://test.timesafari.app VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app VITE_DEFAULT_PARTNER_API_SERVER=https://test-partner-api.endorser.ch VITE_DEFAULT_PUSH_SERVER=https://test.timesafari.app VITE_PASSKEYS_ENABLED=true npm run build:web
|
||||
TIME_SAFARI_APP_TITLE="TimeSafari_Test" VITE_APP_SERVER=https://test.timesafari.app VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app VITE_DEFAULT_PARTNER_API_SERVER=https://test-partner-api.endorser.ch VITE_DEFAULT_PUSH_SERVER=https://test.timesafari.app VITE_PASSKEYS_ENABLED=true npm run build
|
||||
```
|
||||
|
||||
... and transfer to the test server:
|
||||
@@ -90,13 +90,13 @@ TIME_SAFARI_APP_TITLE="TimeSafari_Test" VITE_APP_SERVER=https://test.timesafari.
|
||||
|
||||
* `pkgx +npm sh`
|
||||
|
||||
* `cd crowd-funder-for-time-pwa && git checkout master && git pull && git checkout 1.0.0 && npm install && npm run build:web && cd -`
|
||||
* `cd crowd-funder-for-time-pwa && git checkout master && git pull && git checkout 0.3.55 && npm install && npm run build && cd -`
|
||||
|
||||
(The plain `npm run build:web` uses the .env.production file.)
|
||||
(The plain `npm run build` uses the .env.production file.)
|
||||
|
||||
* Back up the time-safari/dist folder & deploy: `mv time-safari/dist time-safari-dist-prev-1 && mv crowd-funder-for-time-pwa/dist time-safari/`
|
||||
* Back up the time-safari/dist folder & deploy: `mv time-safari/dist time-safari-dist-prev.0 && mv crowd-funder-for-time-pwa/dist time-safari/`
|
||||
|
||||
* Record the new hash in the changelog. Edit package.json to increment version & add "-beta", `npm install`, commit, and push. Also record what version is on production.
|
||||
* Record the new hash in the changelog. Edit package.json to increment version & add "-beta", `npm install`, and commit. Also record what version is on production.
|
||||
|
||||
## Docker Deployment
|
||||
|
||||
@@ -321,11 +321,11 @@ Prerequisites: macOS with Xcode installed
|
||||
|
||||
#### Each Release
|
||||
|
||||
0. First time (or if dependencies change):
|
||||
0. First time (or if XCode dependencies change):
|
||||
|
||||
- `pkgx +rubygems.org sh`
|
||||
|
||||
- ... and you may have to fix these, especially with pkgx:
|
||||
- ... and you may have to fix these, especially with pkgx
|
||||
|
||||
```bash
|
||||
gem_path=$(which gem)
|
||||
@@ -334,12 +334,23 @@ Prerequisites: macOS with Xcode installed
|
||||
export GEM_PATH=$shortened_path
|
||||
```
|
||||
|
||||
1. Build the web assets & update ios:
|
||||
```bash
|
||||
cd ios/App
|
||||
pod install
|
||||
```
|
||||
|
||||
1. Build the web assets:
|
||||
|
||||
```bash
|
||||
rm -rf dist
|
||||
npm run build:web
|
||||
npm run build:capacitor
|
||||
```
|
||||
|
||||
|
||||
2. Update iOS project with latest build:
|
||||
|
||||
```bash
|
||||
npx cap sync ios
|
||||
```
|
||||
|
||||
@@ -356,14 +367,15 @@ Prerequisites: macOS with Xcode installed
|
||||
npx capacitor-assets generate --ios
|
||||
```
|
||||
|
||||
4. Bump the version to match Android & package.json:
|
||||
4. Bump the version to match Android:
|
||||
|
||||
```
|
||||
cd ios/App
|
||||
xcrun agvtool new-version 33
|
||||
xcrun agvtool new-version 25
|
||||
# Unfortunately this edits Info.plist directly.
|
||||
#xcrun agvtool new-marketing-version 0.4.5
|
||||
cat App.xcodeproj/project.pbxproj | sed "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 0.5.7;/g" > temp && mv temp App.xcodeproj/project.pbxproj
|
||||
cat App.xcodeproj/project.pbxproj | sed "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 0.5.1;/g" > temp
|
||||
mv temp App.xcodeproj/project.pbxproj
|
||||
cd -
|
||||
```
|
||||
|
||||
@@ -415,7 +427,7 @@ Prerequisites: Android Studio with Java SDK installed
|
||||
npx capacitor-assets generate --android
|
||||
```
|
||||
|
||||
4. Bump version to match iOS & package.json: android/app/build.gradle
|
||||
4. Bump version to match iOS: android/app/build.gradle
|
||||
|
||||
5. Open the project in Android Studio:
|
||||
|
||||
@@ -432,6 +444,7 @@ Prerequisites: Android Studio with Java SDK installed
|
||||
./gradlew clean
|
||||
./gradlew build -Dlint.baselines.continue=true
|
||||
cd -
|
||||
npx cap run android
|
||||
```
|
||||
|
||||
... or, to create the `aab` file, `bundle` instead of `build`:
|
||||
@@ -465,7 +478,7 @@ At play.google.com/console:
|
||||
- Note that if you add testers, you have to go to "Publishing Overview" and send those changes or your (closed) testers won't see it.
|
||||
|
||||
|
||||
## Android Configuration for deep links
|
||||
## First-time Android Configuration for deep links
|
||||
|
||||
You must add the following intent filter to the `android/app/src/main/AndroidManifest.xml` file:
|
||||
|
||||
@@ -476,6 +489,4 @@ You must add the following intent filter to the `android/app/src/main/AndroidMan
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="timesafari" />
|
||||
</intent-filter>
|
||||
```
|
||||
|
||||
... though when we tried that most recently it failed to 'build' the APK with: http(s) scheme and host attribute are missing, but are required for Android App Links [AppLinkUrlError]
|
||||
```
|
||||
@@ -7,11 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
|
||||
|
||||
## [1.0.0] - 2025.06.20 - 5aa693de6337e5dbb278bfddc6bd39094bc14f73
|
||||
### Added
|
||||
- Web-oriented migration from IndexedDB to SQLite
|
||||
|
||||
|
||||
## [0.4.7]
|
||||
### Fixed
|
||||
- Cameras everywhere
|
||||
|
||||
533
CONTACT_BACKUP_SYSTEM.md
Normal file
533
CONTACT_BACKUP_SYSTEM.md
Normal file
@@ -0,0 +1,533 @@
|
||||
# TimeSafari Contact Backup System
|
||||
|
||||
## Overview
|
||||
|
||||
The TimeSafari application implements a comprehensive contact backup and listing system that works across multiple platforms (Web, iOS, Android, Desktop). This document breaks down how contacts are saved, exported, and listed as backups.
|
||||
|
||||
## Architecture Components
|
||||
|
||||
### 1. Database Layer
|
||||
|
||||
#### Contact Data Structure
|
||||
```typescript
|
||||
interface Contact {
|
||||
did: string; // Decentralized Identifier (primary key)
|
||||
contactMethods?: ContactMethod[]; // Array of contact methods (EMAIL, SMS, etc.)
|
||||
name?: string; // Display name
|
||||
nextPubKeyHashB64?: string; // Base64 hash of next public key
|
||||
notes?: string; // User notes
|
||||
profileImageUrl?: string; // Profile image URL
|
||||
publicKeyBase64?: string; // Base64 encoded public key
|
||||
seesMe?: boolean; // Visibility setting
|
||||
registered?: boolean; // Registration status
|
||||
}
|
||||
|
||||
interface ContactMethod {
|
||||
label: string; // Display label
|
||||
type: string; // Type (EMAIL, SMS, WHATSAPP, etc.)
|
||||
value: string; // Contact value
|
||||
}
|
||||
```
|
||||
|
||||
#### Database Schema
|
||||
```sql
|
||||
CREATE TABLE contacts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
did TEXT NOT NULL, -- Decentralized Identifier
|
||||
name TEXT, -- Display name
|
||||
contactMethods TEXT, -- JSON string of contact methods
|
||||
nextPubKeyHashB64 TEXT, -- Next public key hash
|
||||
notes TEXT, -- User notes
|
||||
profileImageUrl TEXT, -- Profile image URL
|
||||
publicKeyBase64 TEXT, -- Public key
|
||||
seesMe BOOLEAN, -- Visibility flag
|
||||
registered BOOLEAN -- Registration status
|
||||
);
|
||||
|
||||
CREATE INDEX idx_contacts_did ON contacts(did);
|
||||
CREATE INDEX idx_contacts_name ON contacts(name);
|
||||
```
|
||||
|
||||
### 2. Contact Saving Operations
|
||||
|
||||
#### A. Adding New Contacts
|
||||
|
||||
**1. QR Code Scanning (`ContactQRScanFullView.vue`)**
|
||||
```typescript
|
||||
async addNewContact(contact: Contact) {
|
||||
// Check for existing contact
|
||||
const existingContacts = await platformService.dbQuery(
|
||||
"SELECT * FROM contacts WHERE did = ?", [contact.did]
|
||||
);
|
||||
|
||||
if (existingContact) {
|
||||
// Handle duplicate
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert contactMethods to JSON string for storage
|
||||
contact.contactMethods = JSON.stringify(
|
||||
parseJsonField(contact.contactMethods, [])
|
||||
);
|
||||
|
||||
// Insert into database
|
||||
const { sql, params } = databaseUtil.generateInsertStatement(
|
||||
contact as unknown as Record<string, unknown>, "contacts"
|
||||
);
|
||||
await platformService.dbExec(sql, params);
|
||||
}
|
||||
```
|
||||
|
||||
**2. Manual Contact Addition (`ContactsView.vue`)**
|
||||
```typescript
|
||||
private async addContact(newContact: Contact) {
|
||||
// Validate DID format
|
||||
if (!isDid(newContact.did)) {
|
||||
throw new Error("Invalid DID format");
|
||||
}
|
||||
|
||||
// Generate and execute INSERT statement
|
||||
const { sql, params } = databaseUtil.generateInsertStatement(
|
||||
newContact as unknown as Record<string, unknown>, "contacts"
|
||||
);
|
||||
await platformService.dbExec(sql, params);
|
||||
}
|
||||
```
|
||||
|
||||
**3. Contact Import (`ContactImportView.vue`)**
|
||||
```typescript
|
||||
async importContacts() {
|
||||
for (const contact of selectedContacts) {
|
||||
const contactToStore = contactToDbRecord(contact);
|
||||
|
||||
if (existingContact) {
|
||||
// Update existing contact
|
||||
const { sql, params } = databaseUtil.generateUpdateStatement(
|
||||
contactToStore, "contacts", "did = ?", [contact.did]
|
||||
);
|
||||
await platformService.dbExec(sql, params);
|
||||
} else {
|
||||
// Add new contact
|
||||
const { sql, params } = databaseUtil.generateInsertStatement(
|
||||
contactToStore, "contacts"
|
||||
);
|
||||
await platformService.dbExec(sql, params);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### B. Updating Existing Contacts
|
||||
|
||||
**Contact Editing (`ContactEditView.vue`)**
|
||||
```typescript
|
||||
async saveEdit() {
|
||||
// Normalize contact methods
|
||||
const contactMethods = this.contactMethods.map(method => ({
|
||||
...method,
|
||||
type: method.type.toUpperCase()
|
||||
}));
|
||||
|
||||
// Update database
|
||||
const contactMethodsString = JSON.stringify(contactMethods);
|
||||
await platformService.dbExec(
|
||||
"UPDATE contacts SET name = ?, notes = ?, contactMethods = ? WHERE did = ?",
|
||||
[this.contactName, this.contactNotes, contactMethodsString, this.contact?.did]
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Contact Export/Backup System
|
||||
|
||||
#### A. Export Process (`DataExportSection.vue`)
|
||||
|
||||
#### 1. Data Retrieval
|
||||
|
||||
```typescript
|
||||
async exportDatabase() {
|
||||
// Query all contacts from database
|
||||
const result = await platformService.dbQuery("SELECT * FROM contacts");
|
||||
const allContacts = databaseUtil.mapQueryResultToValues(result) as Contact[];
|
||||
|
||||
// Convert to export format
|
||||
const exportData = contactsToExportJson(allContacts);
|
||||
const jsonStr = JSON.stringify(exportData, null, 2);
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. Export Format Conversion (`libs/util.ts`)
|
||||
|
||||
```typescript
|
||||
export const contactsToExportJson = (contacts: Contact[]): DatabaseExport => {
|
||||
const rows = contacts.map((contact) => ({
|
||||
did: contact.did,
|
||||
name: contact.name || null,
|
||||
contactMethods: contact.contactMethods
|
||||
? JSON.stringify(parseJsonField(contact.contactMethods, []))
|
||||
: null,
|
||||
nextPubKeyHashB64: contact.nextPubKeyHashB64 || null,
|
||||
notes: contact.notes || null,
|
||||
profileImageUrl: contact.profileImageUrl || null,
|
||||
publicKeyBase64: contact.publicKeyBase64 || null,
|
||||
seesMe: contact.seesMe || false,
|
||||
registered: contact.registered || false,
|
||||
}));
|
||||
|
||||
return {
|
||||
data: {
|
||||
data: [{ tableName: "contacts", rows }]
|
||||
}
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
#### 3. File Generation
|
||||
|
||||
```typescript
|
||||
// Create timestamped filename
|
||||
const timestamp = getTimestampForFilename();
|
||||
const fileName = `${AppString.APP_NAME_NO_SPACES}-backup-contacts-${timestamp}.json`;
|
||||
|
||||
// Create blob and save
|
||||
const blob = new Blob([jsonStr], { type: "application/json" });
|
||||
```
|
||||
|
||||
#### B. Platform-Specific File Saving
|
||||
|
||||
##### 1. Web Platform (`WebPlatformService.ts`)**
|
||||
|
||||
```typescript
|
||||
// Uses browser download API
|
||||
const downloadUrl = URL.createObjectURL(blob);
|
||||
const downloadAnchor = this.$refs.downloadLink as HTMLAnchorElement;
|
||||
downloadAnchor.href = downloadUrl;
|
||||
downloadAnchor.download = fileName;
|
||||
downloadAnchor.click();
|
||||
```
|
||||
|
||||
##### 2. Mobile Platforms (`CapacitorPlatformService.ts`)
|
||||
|
||||
```typescript
|
||||
async writeAndShareFile(fileName: string, content: string, options = {}) {
|
||||
let fileUri: string;
|
||||
|
||||
if (options.allowLocationSelection) {
|
||||
// User chooses location
|
||||
fileUri = await this.saveWithUserChoice(fileName, content, options.mimeType);
|
||||
} else if (options.saveToPrivateStorage) {
|
||||
// Save to app-private storage
|
||||
const result = await Filesystem.writeFile({
|
||||
path: fileName,
|
||||
data: content,
|
||||
directory: Directory.Data,
|
||||
encoding: Encoding.UTF8,
|
||||
recursive: true,
|
||||
});
|
||||
fileUri = result.uri;
|
||||
} else {
|
||||
// Save to user-accessible location (Downloads/Documents)
|
||||
fileUri = await this.saveToDownloads(fileName, content);
|
||||
}
|
||||
|
||||
// Share the file
|
||||
return await this.shareFile(fileUri, fileName);
|
||||
}
|
||||
```
|
||||
|
||||
##### 3. Desktop Platforms (`ElectronPlatformService.ts`, `PyWebViewPlatformService.ts`)
|
||||
|
||||
```typescript
|
||||
// Not implemented - returns empty results
|
||||
async listBackupFiles(): Promise<Array<{name: string, uri: string, size?: number, type: 'contacts' | 'seed' | 'other', path?: string}>> {
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Backup File Listing System
|
||||
|
||||
#### A. File Discovery (`CapacitorPlatformService.ts`)
|
||||
|
||||
##### 1. Enhanced File Discovery
|
||||
|
||||
```typescript
|
||||
async listUserAccessibleFilesEnhanced(): Promise<Array<{name: string, uri: string, size?: number, path?: string}>> {
|
||||
const allFiles: Array<{name: string, uri: string, size?: number, path?: string}> = [];
|
||||
|
||||
if (this.getCapabilities().isIOS) {
|
||||
// iOS: Documents directory
|
||||
const result = await Filesystem.readdir({
|
||||
path: ".",
|
||||
directory: Directory.Documents,
|
||||
});
|
||||
const files = result.files.map((file) => ({
|
||||
name: typeof file === "string" ? file : file.name,
|
||||
uri: `file://${file.uri || file}`,
|
||||
size: typeof file === "string" ? undefined : file.size,
|
||||
path: "Documents"
|
||||
}));
|
||||
allFiles.push(...files);
|
||||
} else {
|
||||
// Android: Multiple locations
|
||||
const commonPaths = ["Download", "Documents", "Backups", "TimeSafari", "Data"];
|
||||
|
||||
for (const path of commonPaths) {
|
||||
try {
|
||||
const result = await Filesystem.readdir({
|
||||
path: path,
|
||||
directory: Directory.ExternalStorage,
|
||||
});
|
||||
|
||||
// Filter for TimeSafari-related files
|
||||
const relevantFiles = result.files
|
||||
.filter(file => {
|
||||
const fileName = typeof file === "string" ? file : file.name;
|
||||
const name = fileName.toLowerCase();
|
||||
return name.includes('timesafari') ||
|
||||
name.includes('backup') ||
|
||||
name.includes('contacts') ||
|
||||
name.endsWith('.json');
|
||||
})
|
||||
.map((file) => ({
|
||||
name: typeof file === "string" ? file : file.name,
|
||||
uri: `file://${file.uri || file}`,
|
||||
size: typeof file === "string" ? undefined : file.size,
|
||||
path: path
|
||||
}));
|
||||
|
||||
allFiles.push(...relevantFiles);
|
||||
} catch (error) {
|
||||
// Silently skip inaccessible directories
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return allFiles;
|
||||
}
|
||||
```
|
||||
|
||||
**2. Backup File Filtering**
|
||||
```typescript
|
||||
async listBackupFiles(): Promise<Array<{name: string, uri: string, size?: number, type: 'contacts' | 'seed' | 'other', path?: string}>> {
|
||||
const allFiles = await this.listUserAccessibleFilesEnhanced();
|
||||
|
||||
const backupFiles = allFiles
|
||||
.filter(file => {
|
||||
const name = file.name.toLowerCase();
|
||||
|
||||
// Exclude directory-access notification files
|
||||
if (name.startsWith('timesafari-directory-access-') && name.endsWith('.txt')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check backup criteria
|
||||
const isJson = name.endsWith('.json');
|
||||
const hasTimeSafari = name.includes('timesafari');
|
||||
const hasBackup = name.includes('backup');
|
||||
const hasContacts = name.includes('contacts');
|
||||
const hasSeed = name.includes('seed');
|
||||
const hasExport = name.includes('export');
|
||||
const hasData = name.includes('data');
|
||||
|
||||
return isJson || hasTimeSafari || hasBackup || hasContacts || hasSeed || hasExport || hasData;
|
||||
})
|
||||
.map(file => {
|
||||
const name = file.name.toLowerCase();
|
||||
let type: 'contacts' | 'seed' | 'other' = 'other';
|
||||
|
||||
// Categorize files
|
||||
if (name.includes('contacts') || (name.includes('timesafari') && name.includes('backup'))) {
|
||||
type = 'contacts';
|
||||
} else if (name.includes('seed') || name.includes('mnemonic') || name.includes('private')) {
|
||||
type = 'seed';
|
||||
} else if (name.endsWith('.json')) {
|
||||
type = 'other';
|
||||
}
|
||||
|
||||
return { ...file, type };
|
||||
});
|
||||
|
||||
return backupFiles;
|
||||
}
|
||||
```
|
||||
|
||||
#### B. UI Components (`BackupFilesList.vue`)
|
||||
|
||||
**1. File Display**
|
||||
```typescript
|
||||
@Component
|
||||
export default class BackupFilesList extends Vue {
|
||||
backupFiles: Array<{name: string, uri: string, size?: number, type: 'contacts' | 'seed' | 'other', path?: string}> = [];
|
||||
selectedType: 'all' | 'contacts' | 'seed' | 'other' = 'all';
|
||||
isLoading = false;
|
||||
|
||||
async refreshFiles() {
|
||||
this.isLoading = true;
|
||||
try {
|
||||
this.backupFiles = await this.platformService.listBackupFiles();
|
||||
|
||||
// Log file type distribution
|
||||
const typeCounts = {
|
||||
contacts: this.backupFiles.filter(f => f.type === 'contacts').length,
|
||||
seed: this.backupFiles.filter(f => f.type === 'seed').length,
|
||||
other: this.backupFiles.filter(f => f.type === 'other').length,
|
||||
total: this.backupFiles.length
|
||||
};
|
||||
} catch (error) {
|
||||
// Handle error
|
||||
} finally {
|
||||
this.isLoading = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**2. File Operations**
|
||||
```typescript
|
||||
async openFile(fileUri: string, fileName: string) {
|
||||
const result = await this.platformService.openFile(fileUri, fileName);
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || "Failed to open file");
|
||||
}
|
||||
}
|
||||
|
||||
async openBackupDirectory() {
|
||||
const result = await this.platformService.openBackupDirectory();
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || "Failed to open backup directory");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Platform-Specific Storage Locations
|
||||
|
||||
#### A. iOS Platform
|
||||
- **Primary Location**: Documents folder (accessible via Files app)
|
||||
- **Persistence**: Survives app installations
|
||||
- **Access**: Through iOS Files app
|
||||
- **File Format**: JSON with timestamped filenames
|
||||
|
||||
#### B. Android Platform
|
||||
- **Primary Locations**:
|
||||
- `Download/TimeSafari/` (external storage)
|
||||
- `TimeSafari/` (external storage)
|
||||
- User-chosen locations via file picker
|
||||
- **Persistence**: Survives app installations
|
||||
- **Access**: Through file managers
|
||||
- **File Format**: JSON with timestamped filenames
|
||||
|
||||
#### C. Web Platform
|
||||
- **Primary Location**: Browser downloads folder
|
||||
- **Persistence**: Depends on browser settings
|
||||
- **Access**: Through browser download manager
|
||||
- **File Format**: JSON with timestamped filenames
|
||||
|
||||
#### D. Desktop Platforms (Electron/PyWebView)
|
||||
- **Status**: Not implemented
|
||||
- **Fallback**: Returns empty arrays for file operations
|
||||
|
||||
### 6. File Naming Convention
|
||||
|
||||
#### A. Contact Backup Files
|
||||
```
|
||||
TimeSafari-backup-contacts-YYYY-MM-DD-HH-MM-SS.json
|
||||
```
|
||||
|
||||
#### B. File Content Structure
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"data": [
|
||||
{
|
||||
"tableName": "contacts",
|
||||
"rows": [
|
||||
{
|
||||
"did": "did:ethr:0x...",
|
||||
"name": "Contact Name",
|
||||
"contactMethods": "[{\"type\":\"EMAIL\",\"value\":\"email@example.com\"}]",
|
||||
"notes": "User notes",
|
||||
"profileImageUrl": "https://...",
|
||||
"publicKeyBase64": "base64...",
|
||||
"seesMe": true,
|
||||
"registered": false
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 7. Error Handling and Logging
|
||||
|
||||
#### A. Comprehensive Logging
|
||||
```typescript
|
||||
logger.log("[CapacitorPlatformService] File write successful:", {
|
||||
uri: fileUri,
|
||||
saved,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
|
||||
logger.log("[BackupFilesList] Refreshed backup files:", {
|
||||
count: this.backupFiles.length,
|
||||
files: this.backupFiles.map(f => ({
|
||||
name: f.name,
|
||||
type: f.type,
|
||||
path: f.path,
|
||||
size: f.size
|
||||
})),
|
||||
platform: this.platformCapabilities.isIOS ? "iOS" : "Android",
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
```
|
||||
|
||||
#### B. Error Recovery
|
||||
```typescript
|
||||
try {
|
||||
// File operations
|
||||
} catch (error) {
|
||||
logger.error("[CapacitorPlatformService] Failed to list backup files:", error);
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
### 8. Security Considerations
|
||||
|
||||
#### A. Data Privacy
|
||||
- Contact data is stored locally on device
|
||||
- No cloud synchronization of contact data
|
||||
- User controls visibility settings per contact
|
||||
- Backup files contain only user-authorized data
|
||||
|
||||
#### B. File Access
|
||||
- Platform-specific permission handling
|
||||
- User choice for file locations
|
||||
- Secure storage options for sensitive data
|
||||
- Proper error handling for access failures
|
||||
|
||||
### 9. Performance Optimizations
|
||||
|
||||
#### A. Database Operations
|
||||
- Indexed queries on `did` and `name` fields
|
||||
- Batch operations for multiple contacts
|
||||
- Efficient JSON serialization/deserialization
|
||||
- Connection pooling and reuse
|
||||
|
||||
#### B. File Operations
|
||||
- Asynchronous file I/O
|
||||
- Efficient file discovery algorithms
|
||||
- Caching of file lists
|
||||
- Background refresh operations
|
||||
|
||||
## Summary
|
||||
|
||||
The TimeSafari contact backup system provides:
|
||||
|
||||
1. **Robust Data Storage**: SQLite-based contact storage with proper indexing
|
||||
2. **Cross-Platform Compatibility**: Works on web, iOS, Android, and desktop
|
||||
3. **Flexible Export Options**: Multiple file formats and storage locations
|
||||
4. **Intelligent File Discovery**: Finds backup files regardless of user-chosen locations
|
||||
5. **User-Friendly Interface**: Clear categorization and easy file management
|
||||
6. **Comprehensive Logging**: Detailed tracking for debugging and monitoring
|
||||
7. **Security-First Design**: Privacy-preserving with user-controlled data access
|
||||
|
||||
The system ensures that users can reliably backup and restore their contact data across different platforms while maintaining data integrity and user privacy.
|
||||
47
README.md
47
README.md
@@ -3,32 +3,6 @@
|
||||
[Time Safari](https://timesafari.org/) allows people to ease into collaboration: start with expressions of gratitude
|
||||
and expand to crowd-fund with time & money, then record and see the impact of contributions.
|
||||
|
||||
## Database Migration Status
|
||||
|
||||
**Current Status**: The application is undergoing a migration from Dexie (IndexedDB) to SQLite using absurd-sql. This migration is in **Phase 2** with a well-defined migration fence in place.
|
||||
|
||||
### Migration Progress
|
||||
- ✅ **SQLite Database Service**: Fully implemented with absurd-sql
|
||||
- ✅ **Platform Service Layer**: Unified database interface across platforms
|
||||
- ✅ **Settings Migration**: Core user settings transferred
|
||||
- ✅ **Account Migration**: Identity and key management
|
||||
- 🔄 **Contact Migration**: User contact data (via import interface)
|
||||
- 📋 **Code Cleanup**: Remove unused Dexie imports
|
||||
|
||||
### Migration Fence
|
||||
The migration is controlled by a **migration fence** that separates legacy Dexie code from the new SQLite implementation. See [Migration Fence Definition](doc/migration-fence-definition.md) for complete details.
|
||||
|
||||
**Key Points**:
|
||||
- Legacy Dexie database is disabled by default (`USE_DEXIE_DB = false`)
|
||||
- All database operations go through `PlatformService`
|
||||
- Migration tools provide controlled access to both databases
|
||||
- Clear separation between legacy and new code
|
||||
|
||||
### Migration Documentation
|
||||
- [Migration Guide](doc/migration-to-wa-sqlite.md) - Complete migration process
|
||||
- [Migration Fence Definition](doc/migration-fence-definition.md) - Fence boundaries and rules
|
||||
- [Database Migration Guide](doc/database-migration-guide.md) - User-facing migration tools
|
||||
|
||||
## Roadmap
|
||||
|
||||
See [project.task.yaml](project.task.yaml) for current priorities.
|
||||
@@ -47,10 +21,16 @@ npm run dev
|
||||
|
||||
See [BUILDING.md](BUILDING.md) for more details.
|
||||
|
||||
|
||||
|
||||
|
||||
## Tests
|
||||
|
||||
See [TESTING.md](test-playwright/TESTING.md) for detailed test instructions.
|
||||
|
||||
|
||||
|
||||
|
||||
## Icons
|
||||
|
||||
Application icons are in the `assets` directory, processed by the `capacitor-assets` command.
|
||||
@@ -86,21 +66,6 @@ Key principles:
|
||||
- Common interfaces are shared through `common.ts`
|
||||
- Type definitions are generated from Zod schemas where possible
|
||||
|
||||
### Database Architecture
|
||||
|
||||
The application uses a platform-agnostic database layer:
|
||||
|
||||
* `src/services/PlatformService.ts` - Database interface definition
|
||||
* `src/services/PlatformServiceFactory.ts` - Platform-specific service factory
|
||||
* `src/services/AbsurdSqlDatabaseService.ts` - SQLite implementation
|
||||
* `src/db/` - Legacy Dexie database (migration in progress)
|
||||
|
||||
**Development Guidelines**:
|
||||
- Always use `PlatformService` for database operations
|
||||
- Never import Dexie directly in application code
|
||||
- Test with `USE_DEXIE_DB = false` for new features
|
||||
- Use migration tools for data transfer between systems
|
||||
|
||||
### Kudos
|
||||
|
||||
Gifts make the world go 'round!
|
||||
|
||||
@@ -31,8 +31,8 @@ android {
|
||||
applicationId "app.timesafari.app"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 33
|
||||
versionName "0.5.7"
|
||||
versionCode 26
|
||||
versionName "0.5.1"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
|
||||
@@ -1,295 +0,0 @@
|
||||
# Database Migration Guide
|
||||
|
||||
## Overview
|
||||
|
||||
The Database Migration feature allows you to compare and migrate data between Dexie (IndexedDB) and SQLite databases in the TimeSafari application. This is particularly useful during the transition from the old Dexie-based storage system to the new SQLite-based system.
|
||||
|
||||
## Features
|
||||
|
||||
### 1. Database Comparison
|
||||
|
||||
- Compare data between Dexie and SQLite databases
|
||||
- View detailed differences in contacts and settings
|
||||
- Identify added, modified, and missing records
|
||||
- Export comparison results for analysis
|
||||
|
||||
### 2. Data Migration
|
||||
|
||||
- Migrate contacts from Dexie to SQLite
|
||||
- Migrate settings from Dexie to SQLite
|
||||
- Option to overwrite existing records or skip them
|
||||
- Comprehensive error handling and reporting
|
||||
|
||||
### 3. User Interface
|
||||
|
||||
- Modern, responsive UI built with Tailwind CSS
|
||||
- Real-time loading states and progress indicators
|
||||
- Clear success and error messaging
|
||||
- Export functionality for comparison data
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### Enable Dexie Database
|
||||
|
||||
Before using the migration features, you must enable the Dexie database by setting:
|
||||
|
||||
```typescript
|
||||
// In constants/app.ts
|
||||
export const USE_DEXIE_DB = true;
|
||||
```
|
||||
|
||||
**Note**: This should only be enabled temporarily during migration. Remember to set it back to `false` after migration is complete.
|
||||
|
||||
## Accessing the Migration Interface
|
||||
|
||||
1. Navigate to the **Account** page in the TimeSafari app
|
||||
2. Scroll down to find the **Database Migration** link
|
||||
3. Click the link to open the migration interface
|
||||
|
||||
## Using the Migration Interface
|
||||
|
||||
### Step 1: Compare Databases
|
||||
|
||||
1. Click the **"Compare Databases"** button
|
||||
2. The system will retrieve data from both Dexie and SQLite databases
|
||||
3. Review the comparison results showing:
|
||||
- Summary counts for each database
|
||||
- Detailed differences (added, modified, missing records)
|
||||
- Specific records that need attention
|
||||
|
||||
### Step 2: Review Differences
|
||||
|
||||
The comparison results are displayed in several sections:
|
||||
|
||||
#### Summary Cards
|
||||
|
||||
- **Dexie Contacts**: Number of contacts in Dexie database
|
||||
- **SQLite Contacts**: Number of contacts in SQLite database
|
||||
- **Dexie Settings**: Number of settings in Dexie database
|
||||
- **SQLite Settings**: Number of settings in SQLite database
|
||||
|
||||
#### Contact Differences
|
||||
|
||||
- **Added**: Contacts in Dexie but not in SQLite
|
||||
- **Modified**: Contacts that differ between databases
|
||||
- **Missing**: Contacts in SQLite but not in Dexie
|
||||
|
||||
#### Settings Differences
|
||||
|
||||
- **Added**: Settings in Dexie but not in SQLite
|
||||
- **Modified**: Settings that differ between databases
|
||||
- **Missing**: Settings in SQLite but not in Dexie
|
||||
|
||||
### Step 3: Configure Migration Options
|
||||
|
||||
Before migrating data, configure the migration options:
|
||||
|
||||
- **Overwrite existing records**: When enabled, existing records in SQLite will be updated with data from Dexie. When disabled, existing records will be skipped.
|
||||
|
||||
### Step 4: Migrate Data
|
||||
|
||||
#### Migrate Contacts
|
||||
|
||||
1. Click the **"Migrate Contacts"** button
|
||||
2. The system will transfer contacts from Dexie to SQLite
|
||||
3. Review the migration results showing:
|
||||
- Number of contacts successfully migrated
|
||||
- Any warnings or errors encountered
|
||||
|
||||
#### Migrate Settings
|
||||
|
||||
1. Click the **"Migrate Settings"** button
|
||||
2. The system will transfer settings from Dexie to SQLite
|
||||
3. Review the migration results showing:
|
||||
- Number of settings successfully migrated
|
||||
- Any warnings or errors encountered
|
||||
|
||||
### Step 5: Export Comparison (Optional)
|
||||
|
||||
1. Click the **"Export Comparison"** button
|
||||
2. A JSON file will be downloaded containing the complete comparison data
|
||||
3. This file can be used for analysis or backup purposes
|
||||
|
||||
## Migration Process Details
|
||||
|
||||
### Contact Migration
|
||||
|
||||
The contact migration process:
|
||||
|
||||
1. **Retrieves** all contacts from Dexie database
|
||||
2. **Checks** for existing contacts in SQLite by DID
|
||||
3. **Inserts** new contacts or **updates** existing ones (if overwrite is enabled)
|
||||
4. **Handles** complex fields like `contactMethods` (JSON arrays)
|
||||
5. **Reports** success/failure for each contact
|
||||
|
||||
### Settings Migration
|
||||
|
||||
The settings migration process:
|
||||
|
||||
1. **Retrieves** all settings from Dexie database
|
||||
2. **Focuses** on key user-facing settings:
|
||||
- `firstName`
|
||||
- `isRegistered`
|
||||
- `profileImageUrl`
|
||||
- `showShortcutBvc`
|
||||
- `searchBoxes`
|
||||
3. **Preserves** other settings in SQLite
|
||||
4. **Reports** success/failure for each setting
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### Dexie Database Not Enabled
|
||||
|
||||
**Error**: "Dexie database is not enabled"
|
||||
**Solution**: Set `USE_DEXIE_DB = true` in `constants/app.ts`
|
||||
|
||||
#### Database Connection Issues
|
||||
|
||||
**Error**: "Failed to retrieve Dexie contacts"
|
||||
**Solution**: Check that the Dexie database is properly initialized and accessible
|
||||
|
||||
#### SQLite Query Errors
|
||||
|
||||
**Error**: "Failed to retrieve SQLite contacts"
|
||||
**Solution**: Verify that the SQLite database is properly set up and the platform service is working
|
||||
|
||||
#### Migration Failures
|
||||
|
||||
**Error**: "Migration failed: [specific error]"
|
||||
**Solution**: Review the error details and check data integrity in both databases
|
||||
|
||||
### Error Recovery
|
||||
|
||||
1. **Review** the error messages carefully
|
||||
2. **Check** the browser console for additional details
|
||||
3. **Verify** database connectivity and permissions
|
||||
4. **Retry** the operation if appropriate
|
||||
5. **Export** comparison data for manual review if needed
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Before Migration
|
||||
|
||||
1. **Backup** your data if possible
|
||||
2. **Test** the migration on a small dataset first
|
||||
3. **Verify** that both databases are accessible
|
||||
4. **Review** the comparison results before migrating
|
||||
|
||||
### During Migration
|
||||
|
||||
1. **Don't** interrupt the migration process
|
||||
2. **Monitor** the progress and error messages
|
||||
3. **Note** any warnings or skipped records
|
||||
4. **Export** comparison data for reference
|
||||
|
||||
### After Migration
|
||||
|
||||
1. **Verify** that data was migrated correctly
|
||||
2. **Test** the application functionality
|
||||
3. **Disable** Dexie database (`USE_DEXIE_DB = false`)
|
||||
4. **Clean up** any temporary files or exports
|
||||
|
||||
## Technical Details
|
||||
|
||||
### Database Schema
|
||||
|
||||
The migration handles the following data structures:
|
||||
|
||||
#### Contacts Table
|
||||
|
||||
```typescript
|
||||
interface Contact {
|
||||
did: string; // Decentralized Identifier
|
||||
name: string; // Contact name
|
||||
contactMethods: ContactMethod[]; // Array of contact methods
|
||||
nextPubKeyHashB64: string; // Next public key hash
|
||||
notes: string; // Contact notes
|
||||
profileImageUrl: string; // Profile image URL
|
||||
publicKeyBase64: string; // Public key in base64
|
||||
seesMe: boolean; // Visibility flag
|
||||
registered: boolean; // Registration status
|
||||
}
|
||||
```
|
||||
|
||||
#### Settings Table
|
||||
|
||||
```typescript
|
||||
interface Settings {
|
||||
id: number; // Settings ID
|
||||
accountDid: string; // Account DID
|
||||
activeDid: string; // Active DID
|
||||
firstName: string; // User's first name
|
||||
isRegistered: boolean; // Registration status
|
||||
profileImageUrl: string; // Profile image URL
|
||||
showShortcutBvc: boolean; // UI preference
|
||||
searchBoxes: any[]; // Search configuration
|
||||
// ... other fields
|
||||
}
|
||||
```
|
||||
|
||||
### Migration Logic
|
||||
|
||||
The migration service uses sophisticated comparison logic:
|
||||
|
||||
1. **Primary Key Matching**: Uses DID for contacts, ID for settings
|
||||
2. **Deep Comparison**: Compares all fields including complex objects
|
||||
3. **JSON Handling**: Properly handles JSON fields like `contactMethods` and `searchBoxes`
|
||||
4. **Conflict Resolution**: Provides options for handling existing records
|
||||
|
||||
### Performance Considerations
|
||||
|
||||
- **Batch Processing**: Processes records one by one for reliability
|
||||
- **Error Isolation**: Individual record failures don't stop the entire migration
|
||||
- **Memory Management**: Handles large datasets efficiently
|
||||
- **Progress Reporting**: Provides real-time feedback during migration
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Migration Stuck
|
||||
|
||||
If the migration appears to be stuck:
|
||||
|
||||
1. **Check** the browser console for errors
|
||||
2. **Refresh** the page and try again
|
||||
3. **Verify** database connectivity
|
||||
4. **Check** for large datasets that might take time
|
||||
|
||||
### Incomplete Migration
|
||||
|
||||
If migration doesn't complete:
|
||||
|
||||
1. **Review** error messages
|
||||
2. **Check** data integrity in both databases
|
||||
3. **Export** comparison data for manual review
|
||||
4. **Consider** migrating in smaller batches
|
||||
|
||||
### Data Inconsistencies
|
||||
|
||||
If you notice data inconsistencies:
|
||||
|
||||
1. **Export** comparison data
|
||||
2. **Review** the differences carefully
|
||||
3. **Manually** verify critical records
|
||||
4. **Consider** selective migration of specific records
|
||||
|
||||
## Support
|
||||
|
||||
For issues with the Database Migration feature:
|
||||
|
||||
1. **Check** this documentation first
|
||||
2. **Review** the browser console for error details
|
||||
3. **Export** comparison data for analysis
|
||||
4. **Contact** the development team with specific error details
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- **Data Privacy**: Migration data is processed locally and not sent to external servers
|
||||
- **Access Control**: Only users with access to the account can perform migration
|
||||
- **Data Integrity**: Migration preserves data integrity and handles conflicts gracefully
|
||||
- **Audit Trail**: Export functionality provides an audit trail of migration operations
|
||||
|
||||
---
|
||||
|
||||
**Note**: This migration tool is designed for the transition period between database systems. Once migration is complete and verified, the Dexie database should be disabled to avoid confusion and potential data conflicts.
|
||||
@@ -3,7 +3,6 @@
|
||||
## Schema Mapping
|
||||
|
||||
### Current Dexie Schema
|
||||
|
||||
```typescript
|
||||
// Current Dexie schema
|
||||
const db = new Dexie('TimeSafariDB');
|
||||
@@ -16,7 +15,6 @@ db.version(1).stores({
|
||||
```
|
||||
|
||||
### New SQLite Schema
|
||||
|
||||
```sql
|
||||
-- New SQLite schema
|
||||
CREATE TABLE accounts (
|
||||
@@ -52,7 +50,6 @@ CREATE INDEX idx_settings_updated_at ON settings(updated_at);
|
||||
### 1. Account Operations
|
||||
|
||||
#### Get Account by DID
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
const account = await db.accounts.get(did);
|
||||
@@ -65,7 +62,6 @@ const account = result[0]?.values[0];
|
||||
```
|
||||
|
||||
#### Get All Accounts
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
const accounts = await db.accounts.toArray();
|
||||
@@ -78,7 +74,6 @@ const accounts = result[0]?.values || [];
|
||||
```
|
||||
|
||||
#### Add Account
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.accounts.add({
|
||||
@@ -96,7 +91,6 @@ await db.run(`
|
||||
```
|
||||
|
||||
#### Update Account
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.accounts.update(did, {
|
||||
@@ -106,7 +100,7 @@ await db.accounts.update(did, {
|
||||
|
||||
// absurd-sql
|
||||
await db.run(`
|
||||
UPDATE accounts
|
||||
UPDATE accounts
|
||||
SET public_key_hex = ?, updated_at = ?
|
||||
WHERE did = ?
|
||||
`, [publicKeyHex, Date.now(), did]);
|
||||
@@ -115,7 +109,6 @@ await db.run(`
|
||||
### 2. Settings Operations
|
||||
|
||||
#### Get Setting
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
const setting = await db.settings.get(key);
|
||||
@@ -128,7 +121,6 @@ const setting = result[0]?.values[0];
|
||||
```
|
||||
|
||||
#### Set Setting
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.settings.put({
|
||||
@@ -150,7 +142,6 @@ await db.run(`
|
||||
### 3. Contact Operations
|
||||
|
||||
#### Get Contacts by Account
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
const contacts = await db.contacts
|
||||
@@ -160,7 +151,7 @@ const contacts = await db.contacts
|
||||
|
||||
// absurd-sql
|
||||
const result = await db.exec(`
|
||||
SELECT * FROM contacts
|
||||
SELECT * FROM contacts
|
||||
WHERE did = ?
|
||||
ORDER BY created_at DESC
|
||||
`, [accountDid]);
|
||||
@@ -168,7 +159,6 @@ const contacts = result[0]?.values || [];
|
||||
```
|
||||
|
||||
#### Add Contact
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.contacts.add({
|
||||
@@ -189,7 +179,6 @@ await db.run(`
|
||||
## Transaction Mapping
|
||||
|
||||
### Batch Operations
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.transaction('rw', [db.accounts, db.contacts], async () => {
|
||||
@@ -221,11 +210,10 @@ try {
|
||||
## Migration Helper Functions
|
||||
|
||||
### 1. Data Export (Dexie to JSON)
|
||||
|
||||
```typescript
|
||||
async function exportDexieData(): Promise<MigrationData> {
|
||||
const db = new Dexie('TimeSafariDB');
|
||||
|
||||
|
||||
return {
|
||||
accounts: await db.accounts.toArray(),
|
||||
settings: await db.settings.toArray(),
|
||||
@@ -240,7 +228,6 @@ async function exportDexieData(): Promise<MigrationData> {
|
||||
```
|
||||
|
||||
### 2. Data Import (JSON to absurd-sql)
|
||||
|
||||
```typescript
|
||||
async function importToAbsurdSql(data: MigrationData): Promise<void> {
|
||||
await db.exec('BEGIN TRANSACTION;');
|
||||
@@ -252,7 +239,7 @@ async function importToAbsurdSql(data: MigrationData): Promise<void> {
|
||||
VALUES (?, ?, ?, ?)
|
||||
`, [account.did, account.publicKeyHex, account.createdAt, account.updatedAt]);
|
||||
}
|
||||
|
||||
|
||||
// Import settings
|
||||
for (const setting of data.settings) {
|
||||
await db.run(`
|
||||
@@ -260,7 +247,7 @@ async function importToAbsurdSql(data: MigrationData): Promise<void> {
|
||||
VALUES (?, ?, ?)
|
||||
`, [setting.key, setting.value, setting.updatedAt]);
|
||||
}
|
||||
|
||||
|
||||
// Import contacts
|
||||
for (const contact of data.contacts) {
|
||||
await db.run(`
|
||||
@@ -277,7 +264,6 @@ async function importToAbsurdSql(data: MigrationData): Promise<void> {
|
||||
```
|
||||
|
||||
### 3. Verification
|
||||
|
||||
```typescript
|
||||
async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
|
||||
// Verify account count
|
||||
@@ -286,21 +272,21 @@ async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
|
||||
if (accountCount !== dexieData.accounts.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Verify settings count
|
||||
const settingsResult = await db.exec('SELECT COUNT(*) as count FROM settings');
|
||||
const settingsCount = settingsResult[0].values[0][0];
|
||||
if (settingsCount !== dexieData.settings.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Verify contacts count
|
||||
const contactsResult = await db.exec('SELECT COUNT(*) as count FROM contacts');
|
||||
const contactsCount = contactsResult[0].values[0][0];
|
||||
if (contactsCount !== dexieData.contacts.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Verify data integrity
|
||||
for (const account of dexieData.accounts) {
|
||||
const result = await db.exec(
|
||||
@@ -308,12 +294,12 @@ async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
|
||||
[account.did]
|
||||
);
|
||||
const migratedAccount = result[0]?.values[0];
|
||||
if (!migratedAccount ||
|
||||
if (!migratedAccount ||
|
||||
migratedAccount[1] !== account.publicKeyHex) { // public_key_hex is second column
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
@@ -321,21 +307,18 @@ async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
|
||||
## Performance Considerations
|
||||
|
||||
### 1. Indexing
|
||||
|
||||
- Dexie automatically creates indexes based on the schema
|
||||
- absurd-sql requires explicit index creation
|
||||
- Added indexes for frequently queried fields
|
||||
- Use `PRAGMA journal_mode=MEMORY;` for better performance
|
||||
|
||||
### 2. Batch Operations
|
||||
|
||||
- Dexie has built-in bulk operations
|
||||
- absurd-sql uses transactions for batch operations
|
||||
- Consider chunking large datasets
|
||||
- Use prepared statements for repeated queries
|
||||
|
||||
### 3. Query Optimization
|
||||
|
||||
- Dexie uses IndexedDB's native indexing
|
||||
- absurd-sql requires explicit query optimization
|
||||
- Use prepared statements for repeated queries
|
||||
@@ -344,7 +327,6 @@ async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
|
||||
## Error Handling
|
||||
|
||||
### 1. Common Errors
|
||||
|
||||
```typescript
|
||||
// Dexie errors
|
||||
try {
|
||||
@@ -369,7 +351,6 @@ try {
|
||||
```
|
||||
|
||||
### 2. Transaction Recovery
|
||||
|
||||
```typescript
|
||||
// Dexie transaction
|
||||
try {
|
||||
@@ -415,4 +396,4 @@ try {
|
||||
- Remove Dexie database
|
||||
- Clear IndexedDB storage
|
||||
- Update application code
|
||||
- Remove old dependencies
|
||||
- Remove old dependencies
|
||||
@@ -1,272 +0,0 @@
|
||||
# Migration Fence Definition: Dexie to SQLite
|
||||
|
||||
## Overview
|
||||
|
||||
This document defines the **migration fence** - the boundary between the legacy Dexie (IndexedDB) storage system and the new SQLite-based storage system in TimeSafari. The fence ensures controlled migration while maintaining data integrity and application stability.
|
||||
|
||||
## Current Migration Status
|
||||
|
||||
### ✅ Completed Components
|
||||
- **SQLite Database Service**: Fully implemented with absurd-sql
|
||||
- **Platform Service Layer**: Unified database interface across platforms
|
||||
- **Migration Tools**: Data comparison and transfer utilities
|
||||
- **Schema Migration**: Complete table structure migration
|
||||
- **Data Export/Import**: Backup and restore functionality
|
||||
|
||||
### 🔄 Active Migration Components
|
||||
- **Settings Migration**: Core user settings transferred
|
||||
- **Account Migration**: Identity and key management
|
||||
- **Contact Migration**: User contact data (via import interface)
|
||||
|
||||
### ❌ Legacy Components (Fence Boundary)
|
||||
- **Dexie Database**: Legacy IndexedDB storage (disabled by default)
|
||||
- **Dexie-Specific Code**: Direct database access patterns
|
||||
- **Legacy Migration Paths**: Old data transfer methods
|
||||
|
||||
## Migration Fence Definition
|
||||
|
||||
### 1. Configuration Boundary
|
||||
|
||||
```typescript
|
||||
// src/constants/app.ts
|
||||
export const USE_DEXIE_DB = false; // FENCE: Controls legacy database access
|
||||
```
|
||||
|
||||
**Fence Rule**: When `USE_DEXIE_DB = false`:
|
||||
- All new data operations use SQLite
|
||||
- Legacy Dexie database is not initialized
|
||||
- Migration tools are the only path to legacy data
|
||||
|
||||
**Fence Rule**: When `USE_DEXIE_DB = true`:
|
||||
- Legacy database is available for migration
|
||||
- Dual-write operations may be enabled
|
||||
- Migration tools can access both databases
|
||||
|
||||
### 2. Service Layer Boundary
|
||||
|
||||
```typescript
|
||||
// src/services/PlatformServiceFactory.ts
|
||||
export class PlatformServiceFactory {
|
||||
public static getInstance(): PlatformService {
|
||||
// FENCE: All database operations go through platform service
|
||||
// No direct Dexie access outside migration tools
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Fence Rule**: All database operations must use:
|
||||
- `PlatformService.dbQuery()` for read operations
|
||||
- `PlatformService.dbExec()` for write operations
|
||||
- No direct `db.` or `accountsDBPromise` access in application code
|
||||
|
||||
### 3. Data Access Patterns
|
||||
|
||||
#### ✅ Allowed (Inside Fence)
|
||||
```typescript
|
||||
// Use platform service for all database operations
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const contacts = await platformService.dbQuery(
|
||||
"SELECT * FROM contacts WHERE did = ?",
|
||||
[accountDid]
|
||||
);
|
||||
```
|
||||
|
||||
#### ❌ Forbidden (Outside Fence)
|
||||
```typescript
|
||||
// Direct Dexie access (legacy pattern)
|
||||
const contacts = await db.contacts.where('did').equals(accountDid).toArray();
|
||||
|
||||
// Direct database reference
|
||||
const result = await accountsDBPromise;
|
||||
```
|
||||
|
||||
### 4. Migration Tool Boundary
|
||||
|
||||
```typescript
|
||||
// src/services/indexedDBMigrationService.ts
|
||||
// FENCE: Only migration tools can access both databases
|
||||
export async function compareDatabases(): Promise<DataComparison> {
|
||||
// This is the ONLY place where both databases are accessed
|
||||
}
|
||||
```
|
||||
|
||||
**Fence Rule**: Migration tools are the exclusive interface between:
|
||||
- Legacy Dexie database
|
||||
- New SQLite database
|
||||
- Data comparison and transfer operations
|
||||
|
||||
## Migration Fence Guidelines
|
||||
|
||||
### 1. Code Development Rules
|
||||
|
||||
#### New Feature Development
|
||||
- **Always** use `PlatformService` for database operations
|
||||
- **Never** import or reference Dexie directly
|
||||
- **Always** test with `USE_DEXIE_DB = false`
|
||||
|
||||
#### Legacy Code Maintenance
|
||||
- **Only** modify Dexie code for migration purposes
|
||||
- **Always** add migration tests for schema changes
|
||||
- **Never** add new Dexie-specific features
|
||||
|
||||
### 2. Data Integrity Rules
|
||||
|
||||
#### Migration Safety
|
||||
- **Always** create backups before migration
|
||||
- **Always** verify data integrity after migration
|
||||
- **Never** delete legacy data until verified
|
||||
|
||||
#### Rollback Strategy
|
||||
- **Always** maintain ability to rollback to Dexie
|
||||
- **Always** preserve migration logs
|
||||
- **Never** assume migration is irreversible
|
||||
|
||||
### 3. Testing Requirements
|
||||
|
||||
#### Migration Testing
|
||||
```typescript
|
||||
// Required test pattern for migration
|
||||
describe('Database Migration', () => {
|
||||
it('should migrate data without loss', async () => {
|
||||
// 1. Enable Dexie
|
||||
// 2. Create test data
|
||||
// 3. Run migration
|
||||
// 4. Verify data integrity
|
||||
// 5. Disable Dexie
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
#### Application Testing
|
||||
```typescript
|
||||
// Required test pattern for application features
|
||||
describe('Feature with Database', () => {
|
||||
it('should work with SQLite only', async () => {
|
||||
// Test with USE_DEXIE_DB = false
|
||||
// Verify all operations use PlatformService
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Migration Fence Enforcement
|
||||
|
||||
### 1. Static Analysis
|
||||
|
||||
#### ESLint Rules
|
||||
```json
|
||||
{
|
||||
"rules": {
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
"patterns": [
|
||||
{
|
||||
"group": ["../db/index"],
|
||||
"message": "Use PlatformService instead of direct Dexie access"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### TypeScript Rules
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"noImplicitAny": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Runtime Checks
|
||||
|
||||
#### Development Mode Validation
|
||||
```typescript
|
||||
// Development-only fence validation
|
||||
if (import.meta.env.DEV && USE_DEXIE_DB) {
|
||||
console.warn('⚠️ Dexie is enabled - migration mode active');
|
||||
}
|
||||
```
|
||||
|
||||
#### Production Safety
|
||||
```typescript
|
||||
// Production fence enforcement
|
||||
if (import.meta.env.PROD && USE_DEXIE_DB) {
|
||||
throw new Error('Dexie cannot be enabled in production');
|
||||
}
|
||||
```
|
||||
|
||||
## Migration Fence Timeline
|
||||
|
||||
### Phase 1: Fence Establishment ✅
|
||||
- [x] Define migration fence boundaries
|
||||
- [x] Implement PlatformService layer
|
||||
- [x] Create migration tools
|
||||
- [x] Set `USE_DEXIE_DB = false` by default
|
||||
|
||||
### Phase 2: Data Migration 🔄
|
||||
- [x] Migrate core settings
|
||||
- [x] Migrate account data
|
||||
- [ ] Complete contact migration
|
||||
- [ ] Verify all data integrity
|
||||
|
||||
### Phase 3: Code Cleanup 📋
|
||||
- [ ] Remove unused Dexie imports
|
||||
- [ ] Clean up legacy database code
|
||||
- [ ] Update all documentation
|
||||
- [ ] Remove migration tools
|
||||
|
||||
### Phase 4: Fence Removal 🎯
|
||||
- [ ] Remove `USE_DEXIE_DB` constant
|
||||
- [ ] Remove Dexie dependencies
|
||||
- [ ] Remove migration service
|
||||
- [ ] Finalize SQLite-only architecture
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### 1. Data Protection
|
||||
- **Encryption**: Maintain encryption standards across migration
|
||||
- **Access Control**: Preserve user privacy during migration
|
||||
- **Audit Trail**: Log all migration operations
|
||||
|
||||
### 2. Error Handling
|
||||
- **Graceful Degradation**: Handle migration failures gracefully
|
||||
- **User Communication**: Clear messaging about migration status
|
||||
- **Recovery Options**: Provide rollback mechanisms
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### 1. Migration Performance
|
||||
- **Batch Operations**: Use transactions for bulk data transfer
|
||||
- **Progress Indicators**: Show migration progress to users
|
||||
- **Background Processing**: Non-blocking migration operations
|
||||
|
||||
### 2. Application Performance
|
||||
- **Query Optimization**: Optimize SQLite queries for performance
|
||||
- **Indexing Strategy**: Maintain proper database indexes
|
||||
- **Memory Management**: Efficient memory usage during migration
|
||||
|
||||
## Documentation Requirements
|
||||
|
||||
### 1. Code Documentation
|
||||
- **Migration Fence Comments**: Document fence boundaries in code
|
||||
- **API Documentation**: Update all database API documentation
|
||||
- **Migration Guides**: Comprehensive migration documentation
|
||||
|
||||
### 2. User Documentation
|
||||
- **Migration Instructions**: Clear user migration steps
|
||||
- **Troubleshooting**: Common migration issues and solutions
|
||||
- **Rollback Instructions**: How to revert if needed
|
||||
|
||||
## Conclusion
|
||||
|
||||
The migration fence provides a controlled boundary between legacy and new database systems, ensuring:
|
||||
- **Data Integrity**: No data loss during migration
|
||||
- **Application Stability**: Consistent behavior across platforms
|
||||
- **Development Clarity**: Clear guidelines for code development
|
||||
- **Migration Safety**: Controlled and reversible migration process
|
||||
|
||||
This fence will remain in place until all data is successfully migrated and verified, at which point the legacy system can be safely removed.
|
||||
@@ -1,355 +0,0 @@
|
||||
# Database Migration Security Audit Checklist
|
||||
|
||||
## Overview
|
||||
|
||||
This document provides a comprehensive security audit checklist for the Dexie to SQLite migration in TimeSafari. The checklist ensures that data protection, privacy, and security are maintained throughout the migration process.
|
||||
|
||||
## Pre-Migration Security Assessment
|
||||
|
||||
### 1. Data Classification and Sensitivity
|
||||
|
||||
- [ ] **Data Inventory**
|
||||
- [ ] Identify all sensitive data types (DIDs, private keys, personal information)
|
||||
- [ ] Document data retention requirements
|
||||
- [ ] Map data relationships and dependencies
|
||||
- [ ] Assess data sensitivity levels (public, internal, confidential, restricted)
|
||||
|
||||
- [ ] **Encryption Assessment**
|
||||
- [ ] Verify current encryption methods for sensitive data
|
||||
- [ ] Document encryption keys and their management
|
||||
- [ ] Assess encryption strength and compliance
|
||||
- [ ] Plan encryption migration strategy
|
||||
|
||||
### 2. Access Control Review
|
||||
|
||||
- [ ] **User Access Rights**
|
||||
- [ ] Audit current user permissions and roles
|
||||
- [ ] Document access control mechanisms
|
||||
- [ ] Verify principle of least privilege
|
||||
- [ ] Plan access control migration
|
||||
|
||||
- [ ] **System Access**
|
||||
- [ ] Review database access patterns
|
||||
- [ ] Document authentication mechanisms
|
||||
- [ ] Assess session management
|
||||
- [ ] Plan authentication migration
|
||||
|
||||
### 3. Compliance Requirements
|
||||
|
||||
- [ ] **Regulatory Compliance**
|
||||
- [ ] Identify applicable regulations (GDPR, CCPA, etc.)
|
||||
- [ ] Document data processing requirements
|
||||
- [ ] Assess privacy impact
|
||||
- [ ] Plan compliance verification
|
||||
|
||||
- [ ] **Industry Standards**
|
||||
- [ ] Review security standards compliance
|
||||
- [ ] Document security controls
|
||||
- [ ] Assess audit requirements
|
||||
- [ ] Plan standards compliance
|
||||
|
||||
## Migration Security Controls
|
||||
|
||||
### 1. Data Protection During Migration
|
||||
|
||||
- [ ] **Encryption in Transit**
|
||||
- [ ] Verify all data transfers are encrypted
|
||||
- [ ] Use secure communication protocols (TLS 1.3+)
|
||||
- [ ] Implement secure API endpoints
|
||||
- [ ] Monitor encryption status
|
||||
|
||||
- [ ] **Encryption at Rest**
|
||||
- [ ] Maintain encryption for stored data
|
||||
- [ ] Verify encryption key management
|
||||
- [ ] Test encryption/decryption processes
|
||||
- [ ] Document encryption procedures
|
||||
|
||||
### 2. Access Control During Migration
|
||||
|
||||
- [ ] **Authentication**
|
||||
- [ ] Maintain user authentication during migration
|
||||
- [ ] Verify session management
|
||||
- [ ] Implement secure token handling
|
||||
- [ ] Monitor authentication events
|
||||
|
||||
- [ ] **Authorization**
|
||||
- [ ] Preserve user permissions during migration
|
||||
- [ ] Verify role-based access control
|
||||
- [ ] Implement audit logging
|
||||
- [ ] Monitor access patterns
|
||||
|
||||
### 3. Data Integrity
|
||||
|
||||
- [ ] **Data Validation**
|
||||
- [ ] Implement input validation for all data
|
||||
- [ ] Verify data format consistency
|
||||
- [ ] Test data transformation processes
|
||||
- [ ] Document validation rules
|
||||
|
||||
- [ ] **Data Verification**
|
||||
- [ ] Implement checksums for data integrity
|
||||
- [ ] Verify data completeness after migration
|
||||
- [ ] Test data consistency checks
|
||||
- [ ] Document verification procedures
|
||||
|
||||
## Migration Process Security
|
||||
|
||||
### 1. Backup Security
|
||||
|
||||
- [ ] **Backup Creation**
|
||||
- [ ] Create encrypted backups before migration
|
||||
- [ ] Verify backup integrity
|
||||
- [ ] Store backups securely
|
||||
- [ ] Test backup restoration
|
||||
|
||||
- [ ] **Backup Access**
|
||||
- [ ] Limit backup access to authorized personnel
|
||||
- [ ] Implement backup access logging
|
||||
- [ ] Verify backup encryption
|
||||
- [ ] Document backup procedures
|
||||
|
||||
### 2. Migration Tool Security
|
||||
|
||||
- [ ] **Tool Authentication**
|
||||
- [ ] Implement secure authentication for migration tools
|
||||
- [ ] Verify tool access controls
|
||||
- [ ] Monitor tool usage
|
||||
- [ ] Document tool security
|
||||
|
||||
- [ ] **Tool Validation**
|
||||
- [ ] Verify migration tool integrity
|
||||
- [ ] Test tool security features
|
||||
- [ ] Validate tool outputs
|
||||
- [ ] Document tool validation
|
||||
|
||||
### 3. Error Handling
|
||||
|
||||
- [ ] **Error Security**
|
||||
- [ ] Implement secure error handling
|
||||
- [ ] Avoid information disclosure in errors
|
||||
- [ ] Log security-relevant errors
|
||||
- [ ] Document error procedures
|
||||
|
||||
- [ ] **Recovery Security**
|
||||
- [ ] Implement secure recovery procedures
|
||||
- [ ] Verify recovery data protection
|
||||
- [ ] Test recovery processes
|
||||
- [ ] Document recovery security
|
||||
|
||||
## Post-Migration Security
|
||||
|
||||
### 1. Data Verification
|
||||
|
||||
- [ ] **Data Completeness**
|
||||
- [ ] Verify all data was migrated successfully
|
||||
- [ ] Check for data corruption
|
||||
- [ ] Validate data relationships
|
||||
- [ ] Document verification results
|
||||
|
||||
- [ ] **Data Accuracy**
|
||||
- [ ] Verify data accuracy after migration
|
||||
- [ ] Test data consistency
|
||||
- [ ] Validate data integrity
|
||||
- [ ] Document accuracy checks
|
||||
|
||||
### 2. Access Control Verification
|
||||
|
||||
- [ ] **User Access**
|
||||
- [ ] Verify user access rights after migration
|
||||
- [ ] Test authentication mechanisms
|
||||
- [ ] Validate authorization rules
|
||||
- [ ] Document access verification
|
||||
|
||||
- [ ] **System Access**
|
||||
- [ ] Verify system access controls
|
||||
- [ ] Test API security
|
||||
- [ ] Validate session management
|
||||
- [ ] Document system security
|
||||
|
||||
### 3. Security Testing
|
||||
|
||||
- [ ] **Penetration Testing**
|
||||
- [ ] Conduct security penetration testing
|
||||
- [ ] Test for common vulnerabilities
|
||||
- [ ] Verify security controls
|
||||
- [ ] Document test results
|
||||
|
||||
- [ ] **Vulnerability Assessment**
|
||||
- [ ] Scan for security vulnerabilities
|
||||
- [ ] Assess security posture
|
||||
- [ ] Identify security gaps
|
||||
- [ ] Document assessment results
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
### 1. Security Monitoring
|
||||
|
||||
- [ ] **Access Monitoring**
|
||||
- [ ] Monitor database access patterns
|
||||
- [ ] Track user authentication events
|
||||
- [ ] Monitor system access
|
||||
- [ ] Document monitoring procedures
|
||||
|
||||
- [ ] **Data Monitoring**
|
||||
- [ ] Monitor data access patterns
|
||||
- [ ] Track data modification events
|
||||
- [ ] Monitor data integrity
|
||||
- [ ] Document data monitoring
|
||||
|
||||
### 2. Security Logging
|
||||
|
||||
- [ ] **Audit Logging**
|
||||
- [ ] Implement comprehensive audit logging
|
||||
- [ ] Log all security-relevant events
|
||||
- [ ] Secure log storage and access
|
||||
- [ ] Document logging procedures
|
||||
|
||||
- [ ] **Log Analysis**
|
||||
- [ ] Implement log analysis tools
|
||||
- [ ] Monitor for security incidents
|
||||
- [ ] Analyze security trends
|
||||
- [ ] Document analysis procedures
|
||||
|
||||
## Incident Response
|
||||
|
||||
### 1. Security Incident Planning
|
||||
|
||||
- [ ] **Incident Response Plan**
|
||||
- [ ] Develop security incident response plan
|
||||
- [ ] Define incident response procedures
|
||||
- [ ] Train incident response team
|
||||
- [ ] Document response procedures
|
||||
|
||||
- [ ] **Incident Detection**
|
||||
- [ ] Implement incident detection mechanisms
|
||||
- [ ] Monitor for security incidents
|
||||
- [ ] Establish incident reporting procedures
|
||||
- [ ] Document detection procedures
|
||||
|
||||
### 2. Recovery Procedures
|
||||
|
||||
- [ ] **Data Recovery**
|
||||
- [ ] Develop data recovery procedures
|
||||
- [ ] Test recovery processes
|
||||
- [ ] Verify recovery data integrity
|
||||
- [ ] Document recovery procedures
|
||||
|
||||
- [ ] **System Recovery**
|
||||
- [ ] Develop system recovery procedures
|
||||
- [ ] Test system recovery
|
||||
- [ ] Verify system security after recovery
|
||||
- [ ] Document recovery procedures
|
||||
|
||||
## Compliance Verification
|
||||
|
||||
### 1. Regulatory Compliance
|
||||
|
||||
- [ ] **Privacy Compliance**
|
||||
- [ ] Verify GDPR compliance
|
||||
- [ ] Check CCPA compliance
|
||||
- [ ] Assess other privacy regulations
|
||||
- [ ] Document compliance status
|
||||
|
||||
- [ ] **Security Compliance**
|
||||
- [ ] Verify security standard compliance
|
||||
- [ ] Check industry requirements
|
||||
- [ ] Assess security certifications
|
||||
- [ ] Document compliance status
|
||||
|
||||
### 2. Audit Requirements
|
||||
|
||||
- [ ] **Audit Trail**
|
||||
- [ ] Maintain comprehensive audit trail
|
||||
- [ ] Verify audit log integrity
|
||||
- [ ] Test audit log accessibility
|
||||
- [ ] Document audit procedures
|
||||
|
||||
- [ ] **Audit Reporting**
|
||||
- [ ] Generate audit reports
|
||||
- [ ] Verify report accuracy
|
||||
- [ ] Distribute reports securely
|
||||
- [ ] Document reporting procedures
|
||||
|
||||
## Documentation and Training
|
||||
|
||||
### 1. Security Documentation
|
||||
|
||||
- [ ] **Security Procedures**
|
||||
- [ ] Document security procedures
|
||||
- [ ] Update security policies
|
||||
- [ ] Create security guidelines
|
||||
- [ ] Maintain documentation
|
||||
|
||||
- [ ] **Security Training**
|
||||
- [ ] Develop security training materials
|
||||
- [ ] Train staff on security procedures
|
||||
- [ ] Verify training effectiveness
|
||||
- [ ] Document training procedures
|
||||
|
||||
### 2. Ongoing Security
|
||||
|
||||
- [ ] **Security Maintenance**
|
||||
- [ ] Establish security maintenance procedures
|
||||
- [ ] Schedule security updates
|
||||
- [ ] Monitor security trends
|
||||
- [ ] Document maintenance procedures
|
||||
|
||||
- [ ] **Security Review**
|
||||
- [ ] Conduct regular security reviews
|
||||
- [ ] Update security controls
|
||||
- [ ] Assess security effectiveness
|
||||
- [ ] Document review procedures
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
### 1. Risk Identification
|
||||
|
||||
- [ ] **Security Risks**
|
||||
- [ ] Identify potential security risks
|
||||
- [ ] Assess risk likelihood and impact
|
||||
- [ ] Prioritize security risks
|
||||
- [ ] Document risk assessment
|
||||
|
||||
- [ ] **Mitigation Strategies**
|
||||
- [ ] Develop risk mitigation strategies
|
||||
- [ ] Implement risk controls
|
||||
- [ ] Monitor risk status
|
||||
- [ ] Document mitigation procedures
|
||||
|
||||
### 2. Risk Monitoring
|
||||
|
||||
- [ ] **Risk Tracking**
|
||||
- [ ] Track identified risks
|
||||
- [ ] Monitor risk status
|
||||
- [ ] Update risk assessments
|
||||
- [ ] Document risk tracking
|
||||
|
||||
- [ ] **Risk Reporting**
|
||||
- [ ] Generate risk reports
|
||||
- [ ] Distribute risk information
|
||||
- [ ] Update risk documentation
|
||||
- [ ] Document reporting procedures
|
||||
|
||||
## Conclusion
|
||||
|
||||
This security audit checklist ensures that the database migration maintains the highest standards of data protection, privacy, and security. Regular review and updates of this checklist are essential to maintain security throughout the migration process and beyond.
|
||||
|
||||
### Security Checklist Summary
|
||||
|
||||
- [ ] **Pre-Migration Assessment**: Complete
|
||||
- [ ] **Migration Controls**: Complete
|
||||
- [ ] **Process Security**: Complete
|
||||
- [ ] **Post-Migration Verification**: Complete
|
||||
- [ ] **Monitoring and Logging**: Complete
|
||||
- [ ] **Incident Response**: Complete
|
||||
- [ ] **Compliance Verification**: Complete
|
||||
- [ ] **Documentation and Training**: Complete
|
||||
- [ ] **Risk Assessment**: Complete
|
||||
|
||||
**Overall Security Status**: [ ] Secure [ ] Needs Attention [ ] Critical Issues
|
||||
|
||||
**Next Review Date**: _______________
|
||||
|
||||
**Reviewed By**: _______________
|
||||
|
||||
**Approved By**: _______________
|
||||
@@ -4,223 +4,610 @@
|
||||
|
||||
This document outlines the migration process from Dexie.js to absurd-sql for the TimeSafari app's storage implementation. The migration aims to provide a consistent SQLite-based storage solution across all platforms while maintaining data integrity and ensuring a smooth transition for users.
|
||||
|
||||
**Current Status**: The migration is in **Phase 2** with a well-defined migration fence in place. Core settings and account data have been migrated, with contact migration in progress. **ActiveDid migration has been implemented** to ensure user identity continuity.
|
||||
|
||||
## Migration Goals
|
||||
|
||||
1. **Data Integrity**
|
||||
- Preserve all existing data
|
||||
- Maintain data relationships
|
||||
- Ensure data consistency
|
||||
- **Preserve user's active identity**
|
||||
|
||||
2. **Performance**
|
||||
- Improve query performance
|
||||
- Reduce storage overhead
|
||||
- Optimize for platform-specific capabilities
|
||||
- Optimize for platform-specific features
|
||||
|
||||
3. **User Experience**
|
||||
- Seamless transition with no data loss
|
||||
- Maintain user's active identity and preferences
|
||||
- Preserve application state
|
||||
3. **Security**
|
||||
- Maintain or improve encryption
|
||||
- Preserve access controls
|
||||
- Enhance data protection
|
||||
|
||||
## Migration Architecture
|
||||
4. **User Experience**
|
||||
- Zero data loss
|
||||
- Minimal downtime
|
||||
- Automatic migration where possible
|
||||
|
||||
### Migration Fence
|
||||
The migration fence is defined by the `USE_DEXIE_DB` constant in `src/constants/app.ts`:
|
||||
- `USE_DEXIE_DB = false` (default): Uses SQLite database
|
||||
- `USE_DEXIE_DB = true`: Uses Dexie database (for migration purposes)
|
||||
## Prerequisites
|
||||
|
||||
### Migration Order
|
||||
The migration follows a specific order to maintain data integrity:
|
||||
1. **Backup Requirements**
|
||||
```typescript
|
||||
interface MigrationBackup {
|
||||
timestamp: number;
|
||||
accounts: Account[];
|
||||
settings: Setting[];
|
||||
contacts: Contact[];
|
||||
metadata: {
|
||||
version: string;
|
||||
platform: string;
|
||||
dexieVersion: string;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
1. **Accounts** (foundational - contains DIDs)
|
||||
2. **Settings** (references accountDid, activeDid)
|
||||
3. **ActiveDid** (depends on accounts and settings) ⭐ **NEW**
|
||||
4. **Contacts** (independent, but migrated after accounts for consistency)
|
||||
2. **Dependencies**
|
||||
```json
|
||||
{
|
||||
"@jlongster/sql.js": "^1.8.0",
|
||||
"absurd-sql": "^1.8.0"
|
||||
}
|
||||
```
|
||||
|
||||
## ActiveDid Migration ⭐ **NEW FEATURE**
|
||||
3. **Storage Requirements**
|
||||
- Sufficient IndexedDB quota
|
||||
- Available disk space for SQLite
|
||||
- Backup storage space
|
||||
|
||||
### Problem Solved
|
||||
Previously, the `activeDid` setting was not migrated from Dexie to SQLite, causing users to lose their active identity after migration.
|
||||
|
||||
### Solution Implemented
|
||||
The migration now includes a dedicated step for migrating the `activeDid`:
|
||||
|
||||
1. **Detection**: Identifies the `activeDid` from Dexie master settings
|
||||
2. **Validation**: Verifies the `activeDid` exists in SQLite accounts
|
||||
3. **Migration**: Updates SQLite master settings with the `activeDid`
|
||||
4. **Error Handling**: Graceful handling of missing accounts
|
||||
|
||||
### Implementation Details
|
||||
|
||||
#### New Function: `migrateActiveDid()`
|
||||
```typescript
|
||||
export async function migrateActiveDid(): Promise<MigrationResult> {
|
||||
// 1. Get Dexie settings to find the activeDid
|
||||
const dexieSettings = await getDexieSettings();
|
||||
const masterSettings = dexieSettings.find(setting => !setting.accountDid);
|
||||
|
||||
// 2. Verify the activeDid exists in SQLite accounts
|
||||
const accountExists = await platformService.dbQuery(
|
||||
"SELECT did FROM accounts WHERE did = ?",
|
||||
[dexieActiveDid],
|
||||
);
|
||||
|
||||
// 3. Update SQLite master settings
|
||||
await updateDefaultSettings({ activeDid: dexieActiveDid });
|
||||
}
|
||||
```
|
||||
|
||||
#### Enhanced `migrateSettings()` Function
|
||||
The settings migration now includes activeDid handling:
|
||||
- Extracts `activeDid` from Dexie master settings
|
||||
- Validates account existence in SQLite
|
||||
- Updates SQLite master settings with the `activeDid`
|
||||
|
||||
#### Updated `migrateAll()` Function
|
||||
The complete migration now includes a dedicated step for activeDid:
|
||||
```typescript
|
||||
// Step 3: Migrate ActiveDid (depends on accounts and settings)
|
||||
logger.info("[MigrationService] Step 3: Migrating activeDid...");
|
||||
const activeDidResult = await migrateActiveDid();
|
||||
```
|
||||
|
||||
### Benefits
|
||||
- ✅ **User Identity Preservation**: Users maintain their active identity
|
||||
- ✅ **Seamless Experience**: No need to manually select identity after migration
|
||||
- ✅ **Data Consistency**: Ensures all identity-related settings are preserved
|
||||
- ✅ **Error Resilience**: Graceful handling of edge cases
|
||||
4. **Platform Support**
|
||||
- Web: Modern browser with IndexedDB support
|
||||
- iOS: iOS 13+ with SQLite support
|
||||
- Android: Android 5+ with SQLite support
|
||||
- Electron: Latest version with SQLite support
|
||||
|
||||
## Migration Process
|
||||
|
||||
### Phase 1: Preparation ✅
|
||||
- [x] Enable Dexie database access
|
||||
- [x] Implement data comparison tools
|
||||
- [x] Create migration service structure
|
||||
### 1. Preparation
|
||||
|
||||
### Phase 2: Core Migration ✅
|
||||
- [x] Account migration with `importFromMnemonic`
|
||||
- [x] Settings migration (excluding activeDid)
|
||||
- [x] **ActiveDid migration** ⭐ **COMPLETED**
|
||||
- [x] Contact migration framework
|
||||
|
||||
### Phase 3: Validation and Cleanup 🔄
|
||||
- [ ] Comprehensive data validation
|
||||
- [ ] Performance testing
|
||||
- [ ] User acceptance testing
|
||||
- [ ] Dexie removal
|
||||
|
||||
## Usage
|
||||
|
||||
### Manual Migration
|
||||
```typescript
|
||||
import { migrateAll, migrateActiveDid } from '../services/indexedDBMigrationService';
|
||||
// src/services/storage/migration/MigrationService.ts
|
||||
import initSqlJs from '@jlongster/sql.js';
|
||||
import { SQLiteFS } from 'absurd-sql';
|
||||
import IndexedDBBackend from 'absurd-sql/dist/indexeddb-backend';
|
||||
|
||||
// Complete migration
|
||||
const result = await migrateAll();
|
||||
export class MigrationService {
|
||||
private static instance: MigrationService;
|
||||
private backup: MigrationBackup | null = null;
|
||||
private sql: any = null;
|
||||
private db: any = null;
|
||||
|
||||
// Or migrate just the activeDid
|
||||
const activeDidResult = await migrateActiveDid();
|
||||
async prepare(): Promise<void> {
|
||||
try {
|
||||
// 1. Check prerequisites
|
||||
await this.checkPrerequisites();
|
||||
|
||||
// 2. Create backup
|
||||
this.backup = await this.createBackup();
|
||||
|
||||
// 3. Verify backup integrity
|
||||
await this.verifyBackup();
|
||||
|
||||
// 4. Initialize absurd-sql
|
||||
await this.initializeAbsurdSql();
|
||||
} catch (error) {
|
||||
throw new StorageError(
|
||||
'Migration preparation failed',
|
||||
StorageErrorCodes.MIGRATION_FAILED,
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async initializeAbsurdSql(): Promise<void> {
|
||||
// Initialize SQL.js
|
||||
this.sql = await initSqlJs({
|
||||
locateFile: (file: string) => {
|
||||
return new URL(`/node_modules/@jlongster/sql.js/dist/${file}`, import.meta.url).href;
|
||||
}
|
||||
});
|
||||
|
||||
// Setup SQLiteFS with IndexedDB backend
|
||||
const sqlFS = new SQLiteFS(this.sql.FS, new IndexedDBBackend());
|
||||
this.sql.register_for_idb(sqlFS);
|
||||
|
||||
// Create and mount filesystem
|
||||
this.sql.FS.mkdir('/sql');
|
||||
this.sql.FS.mount(sqlFS, {}, '/sql');
|
||||
|
||||
// Open database
|
||||
const path = '/sql/db.sqlite';
|
||||
if (typeof SharedArrayBuffer === 'undefined') {
|
||||
let stream = this.sql.FS.open(path, 'a+');
|
||||
await stream.node.contents.readIfFallback();
|
||||
this.sql.FS.close(stream);
|
||||
}
|
||||
|
||||
this.db = new this.sql.Database(path, { filename: true });
|
||||
if (!this.db) {
|
||||
throw new StorageError(
|
||||
'Database initialization failed',
|
||||
StorageErrorCodes.INITIALIZATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
// Configure database
|
||||
await this.db.exec(`PRAGMA journal_mode=MEMORY;`);
|
||||
}
|
||||
|
||||
private async checkPrerequisites(): Promise<void> {
|
||||
// Check IndexedDB availability
|
||||
if (!window.indexedDB) {
|
||||
throw new StorageError(
|
||||
'IndexedDB not available',
|
||||
StorageErrorCodes.INITIALIZATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
// Check storage quota
|
||||
const quota = await navigator.storage.estimate();
|
||||
if (quota.quota && quota.usage && quota.usage > quota.quota * 0.9) {
|
||||
throw new StorageError(
|
||||
'Insufficient storage space',
|
||||
StorageErrorCodes.STORAGE_FULL
|
||||
);
|
||||
}
|
||||
|
||||
// Check platform support
|
||||
const capabilities = await PlatformDetection.getCapabilities();
|
||||
if (!capabilities.hasFileSystem) {
|
||||
throw new StorageError(
|
||||
'Platform does not support required features',
|
||||
StorageErrorCodes.INITIALIZATION_FAILED
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async createBackup(): Promise<MigrationBackup> {
|
||||
const dexieDB = new Dexie('TimeSafariDB');
|
||||
|
||||
return {
|
||||
timestamp: Date.now(),
|
||||
accounts: await dexieDB.accounts.toArray(),
|
||||
settings: await dexieDB.settings.toArray(),
|
||||
contacts: await dexieDB.contacts.toArray(),
|
||||
metadata: {
|
||||
version: '1.0.0',
|
||||
platform: await PlatformDetection.getPlatform(),
|
||||
dexieVersion: Dexie.version
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Migration Verification
|
||||
### 2. Data Migration
|
||||
|
||||
```typescript
|
||||
import { compareDatabases } from '../services/indexedDBMigrationService';
|
||||
// src/services/storage/migration/DataMigration.ts
|
||||
export class DataMigration {
|
||||
async migrate(backup: MigrationBackup): Promise<void> {
|
||||
try {
|
||||
// 1. Create new database schema
|
||||
await this.createSchema();
|
||||
|
||||
// 2. Migrate accounts
|
||||
await this.migrateAccounts(backup.accounts);
|
||||
|
||||
// 3. Migrate settings
|
||||
await this.migrateSettings(backup.settings);
|
||||
|
||||
// 4. Migrate contacts
|
||||
await this.migrateContacts(backup.contacts);
|
||||
|
||||
// 5. Verify migration
|
||||
await this.verifyMigration(backup);
|
||||
} catch (error) {
|
||||
// 6. Handle failure
|
||||
await this.handleMigrationFailure(error, backup);
|
||||
}
|
||||
}
|
||||
|
||||
const comparison = await compareDatabases();
|
||||
console.log('Migration differences:', comparison.differences);
|
||||
private async migrateAccounts(accounts: Account[]): Promise<void> {
|
||||
// Use transaction for atomicity
|
||||
await this.db.exec('BEGIN TRANSACTION;');
|
||||
try {
|
||||
for (const account of accounts) {
|
||||
await this.db.run(`
|
||||
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`, [
|
||||
account.did,
|
||||
account.publicKeyHex,
|
||||
account.createdAt,
|
||||
account.updatedAt
|
||||
]);
|
||||
}
|
||||
await this.db.exec('COMMIT;');
|
||||
} catch (error) {
|
||||
await this.db.exec('ROLLBACK;');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async verifyMigration(backup: MigrationBackup): Promise<void> {
|
||||
// Verify account count
|
||||
const result = await this.db.exec('SELECT COUNT(*) as count FROM accounts');
|
||||
const accountCount = result[0].values[0][0];
|
||||
|
||||
if (accountCount !== backup.accounts.length) {
|
||||
throw new StorageError(
|
||||
'Account count mismatch',
|
||||
StorageErrorCodes.VERIFICATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
// Verify data integrity
|
||||
await this.verifyDataIntegrity(backup);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
### 3. Rollback Strategy
|
||||
|
||||
### ActiveDid Migration Errors
|
||||
- **Missing Account**: If the `activeDid` from Dexie doesn't exist in SQLite accounts
|
||||
- **Database Errors**: Connection or query failures
|
||||
- **Settings Update Failures**: Issues updating SQLite master settings
|
||||
|
||||
### Recovery Strategies
|
||||
1. **Automatic Recovery**: Migration continues even if activeDid migration fails
|
||||
2. **Manual Recovery**: Users can manually select their identity after migration
|
||||
3. **Fallback**: System creates new identity if none exists
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Data Protection
|
||||
- All sensitive data (mnemonics, private keys) are encrypted
|
||||
- Migration preserves encryption standards
|
||||
- No plaintext data exposure during migration
|
||||
|
||||
### Identity Verification
|
||||
- ActiveDid migration validates account existence
|
||||
- Prevents setting non-existent identities as active
|
||||
- Maintains cryptographic integrity
|
||||
|
||||
## Testing
|
||||
|
||||
### Migration Testing
|
||||
```bash
|
||||
# Enable Dexie for testing
|
||||
# Set USE_DEXIE_DB = true in constants/app.ts
|
||||
|
||||
# Run migration
|
||||
npm run migrate
|
||||
|
||||
# Verify results
|
||||
npm run test:migration
|
||||
```
|
||||
|
||||
### ActiveDid Testing
|
||||
```typescript
|
||||
// Test activeDid migration specifically
|
||||
const result = await migrateActiveDid();
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.warnings).toContain('Successfully migrated activeDid');
|
||||
// src/services/storage/migration/RollbackService.ts
|
||||
export class RollbackService {
|
||||
async rollback(backup: MigrationBackup): Promise<void> {
|
||||
try {
|
||||
// 1. Stop all database operations
|
||||
await this.stopDatabaseOperations();
|
||||
|
||||
// 2. Restore from backup
|
||||
await this.restoreFromBackup(backup);
|
||||
|
||||
// 3. Verify restoration
|
||||
await this.verifyRestoration(backup);
|
||||
|
||||
// 4. Clean up absurd-sql
|
||||
await this.cleanupAbsurdSql();
|
||||
} catch (error) {
|
||||
throw new StorageError(
|
||||
'Rollback failed',
|
||||
StorageErrorCodes.ROLLBACK_FAILED,
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async restoreFromBackup(backup: MigrationBackup): Promise<void> {
|
||||
const dexieDB = new Dexie('TimeSafariDB');
|
||||
|
||||
// Restore accounts
|
||||
await dexieDB.accounts.bulkPut(backup.accounts);
|
||||
|
||||
// Restore settings
|
||||
await dexieDB.settings.bulkPut(backup.settings);
|
||||
|
||||
// Restore contacts
|
||||
await dexieDB.contacts.bulkPut(backup.contacts);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
## Migration UI
|
||||
|
||||
### Common Issues
|
||||
```vue
|
||||
<!-- src/components/MigrationProgress.vue -->
|
||||
<template>
|
||||
<div class="migration-progress">
|
||||
<h2>Database Migration</h2>
|
||||
|
||||
<div class="progress-container">
|
||||
<div class="progress-bar" :style="{ width: `${progress}%` }" />
|
||||
<div class="progress-text">{{ progress }}%</div>
|
||||
</div>
|
||||
|
||||
<div class="status-message">{{ statusMessage }}</div>
|
||||
|
||||
<div v-if="error" class="error-message">
|
||||
{{ error }}
|
||||
<button @click="retryMigration">Retry</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
1. **ActiveDid Not Found**
|
||||
- Ensure accounts were migrated before activeDid migration
|
||||
- Check that the Dexie activeDid exists in SQLite accounts
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { MigrationService } from '@/services/storage/migration/MigrationService';
|
||||
|
||||
2. **Migration Failures**
|
||||
- Verify Dexie database is accessible
|
||||
- Check SQLite database permissions
|
||||
- Review migration logs for specific errors
|
||||
const progress = ref(0);
|
||||
const statusMessage = ref('Preparing migration...');
|
||||
const error = ref<string | null>(null);
|
||||
|
||||
3. **Data Inconsistencies**
|
||||
- Use `compareDatabases()` to identify differences
|
||||
- Re-run migration if necessary
|
||||
- Check for duplicate or conflicting records
|
||||
const migrationService = MigrationService.getInstance();
|
||||
|
||||
### Debugging
|
||||
```typescript
|
||||
// Enable detailed logging
|
||||
logger.setLevel('debug');
|
||||
async function startMigration() {
|
||||
try {
|
||||
// 1. Preparation
|
||||
statusMessage.value = 'Creating backup...';
|
||||
await migrationService.prepare();
|
||||
progress.value = 20;
|
||||
|
||||
// 2. Data migration
|
||||
statusMessage.value = 'Migrating data...';
|
||||
await migrationService.migrate();
|
||||
progress.value = 80;
|
||||
|
||||
// 3. Verification
|
||||
statusMessage.value = 'Verifying migration...';
|
||||
await migrationService.verify();
|
||||
progress.value = 100;
|
||||
|
||||
statusMessage.value = 'Migration completed successfully!';
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : 'Migration failed';
|
||||
statusMessage.value = 'Migration failed';
|
||||
}
|
||||
}
|
||||
|
||||
// Check migration status
|
||||
const comparison = await compareDatabases();
|
||||
console.log('Settings differences:', comparison.differences.settings);
|
||||
async function retryMigration() {
|
||||
error.value = null;
|
||||
progress.value = 0;
|
||||
await startMigration();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
startMigration();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.migration-progress {
|
||||
padding: 2rem;
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.progress-container {
|
||||
position: relative;
|
||||
height: 20px;
|
||||
background: #eee;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
position: absolute;
|
||||
height: 100%;
|
||||
background: #4CAF50;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
line-height: 20px;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.status-message {
|
||||
text-align: center;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
color: #f44336;
|
||||
text-align: center;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
button {
|
||||
margin-top: 1rem;
|
||||
padding: 0.5rem 1rem;
|
||||
background: #2196F3;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: #1976D2;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Future Enhancements
|
||||
## Testing Strategy
|
||||
|
||||
### Planned Improvements
|
||||
1. **Batch Processing**: Optimize for large datasets
|
||||
2. **Incremental Migration**: Support partial migrations
|
||||
3. **Rollback Capability**: Ability to revert migration
|
||||
4. **Progress Tracking**: Real-time migration progress
|
||||
1. **Unit Tests**
|
||||
```typescript
|
||||
// src/services/storage/migration/__tests__/MigrationService.spec.ts
|
||||
describe('MigrationService', () => {
|
||||
it('should initialize absurd-sql correctly', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
await service.initializeAbsurdSql();
|
||||
|
||||
expect(service.isInitialized()).toBe(true);
|
||||
expect(service.getDatabase()).toBeDefined();
|
||||
});
|
||||
|
||||
### Performance Optimizations
|
||||
1. **Parallel Processing**: Migrate independent data concurrently
|
||||
2. **Memory Management**: Optimize for large datasets
|
||||
3. **Transaction Batching**: Reduce database round trips
|
||||
it('should create valid backup', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
const backup = await service.createBackup();
|
||||
|
||||
expect(backup).toBeDefined();
|
||||
expect(backup.accounts).toBeInstanceOf(Array);
|
||||
expect(backup.settings).toBeInstanceOf(Array);
|
||||
expect(backup.contacts).toBeInstanceOf(Array);
|
||||
});
|
||||
|
||||
## Conclusion
|
||||
it('should migrate data correctly', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
const backup = await service.createBackup();
|
||||
|
||||
await service.migrate(backup);
|
||||
|
||||
// Verify migration
|
||||
const accounts = await service.getMigratedAccounts();
|
||||
expect(accounts).toHaveLength(backup.accounts.length);
|
||||
});
|
||||
|
||||
The Dexie to SQLite migration provides a robust, secure, and user-friendly transition path. The addition of activeDid migration ensures that users maintain their identity continuity throughout the migration process, significantly improving the user experience.
|
||||
it('should handle rollback correctly', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
const backup = await service.createBackup();
|
||||
|
||||
// Simulate failed migration
|
||||
await service.migrate(backup);
|
||||
await service.simulateFailure();
|
||||
|
||||
// Perform rollback
|
||||
await service.rollback(backup);
|
||||
|
||||
// Verify rollback
|
||||
const accounts = await service.getOriginalAccounts();
|
||||
expect(accounts).toHaveLength(backup.accounts.length);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
The migration fence architecture allows for controlled, reversible migration while maintaining application stability and data integrity.
|
||||
2. **Integration Tests**
|
||||
```typescript
|
||||
// src/services/storage/migration/__tests__/integration/Migration.spec.ts
|
||||
describe('Migration Integration', () => {
|
||||
it('should handle concurrent access during migration', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
|
||||
// Start migration
|
||||
const migrationPromise = service.migrate();
|
||||
|
||||
// Simulate concurrent access
|
||||
const accessPromises = Array(5).fill(null).map(() =>
|
||||
service.getAccount('did:test:123')
|
||||
);
|
||||
|
||||
// Wait for all operations
|
||||
const [migrationResult, ...accessResults] = await Promise.allSettled([
|
||||
migrationPromise,
|
||||
...accessPromises
|
||||
]);
|
||||
|
||||
// Verify results
|
||||
expect(migrationResult.status).toBe('fulfilled');
|
||||
expect(accessResults.some(r => r.status === 'rejected')).toBe(true);
|
||||
});
|
||||
|
||||
it('should maintain data integrity during platform transition', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
|
||||
// Simulate platform change
|
||||
await service.simulatePlatformChange();
|
||||
|
||||
// Verify data
|
||||
const accounts = await service.getAllAccounts();
|
||||
const settings = await service.getAllSettings();
|
||||
const contacts = await service.getAllContacts();
|
||||
|
||||
expect(accounts).toBeDefined();
|
||||
expect(settings).toBeDefined();
|
||||
expect(contacts).toBeDefined();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Success Criteria
|
||||
|
||||
1. **Data Integrity**
|
||||
- [ ] All accounts migrated successfully
|
||||
- [ ] All settings preserved
|
||||
- [ ] All contacts transferred
|
||||
- [ ] No data corruption
|
||||
|
||||
2. **Performance**
|
||||
- [ ] Migration completes within acceptable time
|
||||
- [ ] No significant performance degradation
|
||||
- [ ] Efficient storage usage
|
||||
- [ ] Smooth user experience
|
||||
|
||||
3. **Security**
|
||||
- [ ] Encrypted data remains secure
|
||||
- [ ] Access controls maintained
|
||||
- [ ] No sensitive data exposure
|
||||
- [ ] Secure backup process
|
||||
|
||||
4. **User Experience**
|
||||
- [ ] Clear migration progress
|
||||
- [ ] Informative error messages
|
||||
- [ ] Automatic recovery from failures
|
||||
- [ ] No data loss
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
1. **Automatic Rollback**
|
||||
- Triggered by migration failure
|
||||
- Restores from verified backup
|
||||
- Maintains data consistency
|
||||
- Logs rollback reason
|
||||
|
||||
2. **Manual Rollback**
|
||||
- Available through settings
|
||||
- Requires user confirmation
|
||||
- Preserves backup data
|
||||
- Provides rollback status
|
||||
|
||||
3. **Emergency Recovery**
|
||||
- Manual backup restoration
|
||||
- Database repair tools
|
||||
- Data recovery procedures
|
||||
- Support contact information
|
||||
|
||||
## Post-Migration
|
||||
|
||||
1. **Verification**
|
||||
- Data integrity checks
|
||||
- Performance monitoring
|
||||
- Error rate tracking
|
||||
- User feedback collection
|
||||
|
||||
2. **Cleanup**
|
||||
- Remove old database
|
||||
- Clear migration artifacts
|
||||
- Update application state
|
||||
- Archive backup data
|
||||
|
||||
3. **Monitoring**
|
||||
- Track migration success rate
|
||||
- Monitor performance metrics
|
||||
- Collect error reports
|
||||
- Gather user feedback
|
||||
|
||||
## Support
|
||||
|
||||
For assistance with migration:
|
||||
1. Check the troubleshooting guide
|
||||
2. Review error logs
|
||||
3. Contact support team
|
||||
4. Submit issue report
|
||||
|
||||
## Timeline
|
||||
|
||||
1. **Preparation Phase** (1 week)
|
||||
- Backup system implementation
|
||||
- Migration service development
|
||||
- Testing framework setup
|
||||
|
||||
2. **Testing Phase** (2 weeks)
|
||||
- Unit testing
|
||||
- Integration testing
|
||||
- Performance testing
|
||||
- Security testing
|
||||
|
||||
3. **Deployment Phase** (1 week)
|
||||
- Staged rollout
|
||||
- Monitoring
|
||||
- Support preparation
|
||||
- Documentation updates
|
||||
|
||||
4. **Post-Deployment** (2 weeks)
|
||||
- Monitoring
|
||||
- Bug fixes
|
||||
- Performance optimization
|
||||
- User feedback collection
|
||||
@@ -403,7 +403,7 @@
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 33;
|
||||
CURRENT_PROJECT_VERSION = 26;
|
||||
DEVELOPMENT_TEAM = GM3FS5JQPH;
|
||||
ENABLE_APP_SANDBOX = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
@@ -413,7 +413,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 0.5.7;
|
||||
MARKETING_VERSION = 0.5.1;
|
||||
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
@@ -430,7 +430,7 @@
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 33;
|
||||
CURRENT_PROJECT_VERSION = 26;
|
||||
DEVELOPMENT_TEAM = GM3FS5JQPH;
|
||||
ENABLE_APP_SANDBOX = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
@@ -440,7 +440,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 0.5.7;
|
||||
MARKETING_VERSION = 0.5.1;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
|
||||
|
||||
@@ -49,16 +49,5 @@
|
||||
</array>
|
||||
<key>UIViewControllerBasedStatusBarAppearance</key>
|
||||
<true/>
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>app.timesafari</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>timesafari</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
597
package-lock.json
generated
597
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "timesafari",
|
||||
"version": "1.0.1-beta",
|
||||
"version": "0.5.1",
|
||||
"description": "Time Safari Application",
|
||||
"author": {
|
||||
"name": "Time Safari Team"
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
{
|
||||
"warning": {
|
||||
"fillRule": "evenodd",
|
||||
"d": "M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z",
|
||||
"clipRule": "evenodd"
|
||||
},
|
||||
"spinner": {
|
||||
"d": "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||
},
|
||||
"chart": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
|
||||
},
|
||||
"plus": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M12 4v16m8-8H4"
|
||||
},
|
||||
"settings": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
|
||||
},
|
||||
"settingsDot": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M15 12a3 3 0 11-6 0 3 3 0 016 0z"
|
||||
},
|
||||
"lock": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
|
||||
},
|
||||
"download": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
|
||||
},
|
||||
"check": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
},
|
||||
"edit": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
|
||||
},
|
||||
"trash": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
|
||||
},
|
||||
"plusCircle": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M12 6v6m0 0v6m0-6h6m-6 0H6"
|
||||
},
|
||||
"info": {
|
||||
"fillRule": "evenodd",
|
||||
"d": "M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z",
|
||||
"clipRule": "evenodd"
|
||||
}
|
||||
}
|
||||
894
src/components/BackupFilesList.vue
Normal file
894
src/components/BackupFilesList.vue
Normal file
@@ -0,0 +1,894 @@
|
||||
/** * Backup Files List Component * * Displays a list of backup files saved by
|
||||
the app and provides options to: * - View backup files by type (contacts, seed,
|
||||
other) * - Open individual files in the device's file viewer * - Access the
|
||||
backup directory in the device's file explorer * * @component * @displayName
|
||||
BackupFilesList * @example * ```vue *
|
||||
<BackupFilesList />
|
||||
* ``` */
|
||||
|
||||
<template>
|
||||
<div class="backup-files-list">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="text-lg font-semibold">Backup Files</h3>
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
v-if="platformCapabilities.hasFileSystem"
|
||||
class="text-sm bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded"
|
||||
:disabled="isLoading"
|
||||
@click="refreshFiles()"
|
||||
>
|
||||
<font-awesome
|
||||
icon="refresh"
|
||||
class="fa-fw"
|
||||
:class="{ 'animate-spin': isLoading }"
|
||||
/>
|
||||
Refresh
|
||||
</button>
|
||||
<button
|
||||
v-if="platformCapabilities.hasFileSystem"
|
||||
class="text-sm bg-green-500 hover:bg-green-600 text-white px-3 py-1 rounded"
|
||||
:disabled="isLoading"
|
||||
@click="openBackupDirectory()"
|
||||
>
|
||||
<font-awesome icon="folder-open" class="fa-fw" />
|
||||
Open Directory
|
||||
</button>
|
||||
<button
|
||||
v-if="platformCapabilities.hasFileSystem && isDevelopment"
|
||||
class="text-sm bg-yellow-500 hover:bg-yellow-600 text-white px-3 py-1 rounded"
|
||||
:disabled="isLoading"
|
||||
title="Debug file discovery (development only)"
|
||||
@click="debugFileDiscovery()"
|
||||
>
|
||||
<font-awesome icon="bug" class="fa-fw" />
|
||||
Debug
|
||||
</button>
|
||||
<button
|
||||
:disabled="isLoading"
|
||||
class="px-3 py-1 bg-green-500 text-white rounded text-sm hover:bg-green-600 disabled:opacity-50"
|
||||
@click="createTestBackup"
|
||||
>
|
||||
Create Test Backup
|
||||
</button>
|
||||
<button
|
||||
:disabled="isLoading"
|
||||
class="px-3 py-1 bg-purple-500 text-white rounded text-sm hover:bg-purple-600 disabled:opacity-50"
|
||||
@click="testDirectoryContexts"
|
||||
>
|
||||
Test Contexts
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="isLoading" class="text-center py-4">
|
||||
<font-awesome icon="spinner" class="animate-spin fa-2x" />
|
||||
<p class="mt-2">Loading backup files...</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="backupFiles.length === 0"
|
||||
class="text-center py-4 text-gray-500"
|
||||
>
|
||||
<font-awesome icon="folder-open" class="fa-2x mb-2" />
|
||||
<p>No backup files found</p>
|
||||
<p class="text-sm mt-1">
|
||||
Create backups using the export functions above
|
||||
</p>
|
||||
<div
|
||||
class="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg text-left"
|
||||
>
|
||||
<p class="text-sm font-medium text-blue-800 mb-2">
|
||||
💡 How to create backup files:
|
||||
</p>
|
||||
<ul class="text-xs text-blue-700 space-y-1">
|
||||
<li>
|
||||
• Use the "Export Contacts" button above to create contact backups
|
||||
</li>
|
||||
<li>• Use the "Export Seed" button to backup your recovery phrase</li>
|
||||
<li>
|
||||
• Backup files are saved to persistent storage that survives app
|
||||
installations
|
||||
</li>
|
||||
<li
|
||||
v-if="platformCapabilities.isMobile && !platformCapabilities.isIOS"
|
||||
class="text-orange-700"
|
||||
>
|
||||
• On Android: Files are saved to Downloads/TimeSafari or app data
|
||||
directory
|
||||
</li>
|
||||
<li v-if="platformCapabilities.isIOS" class="text-orange-700">
|
||||
• On iOS: Files are saved to Documents folder (accessible via Files
|
||||
app)
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-2">
|
||||
<!-- File Type Filter -->
|
||||
<div class="flex gap-2 mb-3">
|
||||
<button
|
||||
v-for="type in ['all', 'contacts', 'seed', 'other'] as const"
|
||||
:key="type"
|
||||
:class="[
|
||||
'text-sm px-3 py-1 rounded border',
|
||||
selectedType === type
|
||||
? 'bg-blue-500 text-white border-blue-500'
|
||||
: 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50',
|
||||
]"
|
||||
@click="selectedType = type"
|
||||
>
|
||||
{{
|
||||
type === "all"
|
||||
? "All"
|
||||
: type.charAt(0).toUpperCase() + type.slice(1)
|
||||
}}
|
||||
<span class="ml-1 text-xs"> ({{ getFileCountByType(type) }}) </span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Files List -->
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<span v-for="(crumb, idx) in breadcrumbs" :key="idx">
|
||||
<span
|
||||
v-if="idx < breadcrumbs.length - 1"
|
||||
class="text-blue-600 cursor-pointer underline"
|
||||
@click="goToBreadcrumb(idx)"
|
||||
>
|
||||
{{ crumb }}
|
||||
</span>
|
||||
<span v-else class="font-bold">{{ crumb }}</span>
|
||||
<span v-if="idx < breadcrumbs.length - 1"> / </span>
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="currentPath.length > 1" class="mb-2">
|
||||
<button class="text-xs text-blue-500 underline" @click="goUp">
|
||||
⬅ Up
|
||||
</button>
|
||||
</div>
|
||||
<div class="mb-2">
|
||||
<label class="inline-flex items-center">
|
||||
<input
|
||||
v-model="debugShowAll"
|
||||
type="checkbox"
|
||||
class="mr-2"
|
||||
@change="loadDirectory"
|
||||
/>
|
||||
<span class="text-xs">Debug: Show all entries as files</span>
|
||||
</label>
|
||||
<span v-if="debugShowAll" class="text-xs text-red-600 ml-2"
|
||||
>[Debug mode: forcibly treating all entries as files]</span
|
||||
>
|
||||
</div>
|
||||
<div class="space-y-2 max-h-64 overflow-y-auto">
|
||||
<div
|
||||
v-for="entry in folders"
|
||||
:key="'folder-' + entry.path"
|
||||
class="flex items-center justify-between p-3 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer"
|
||||
@click="openFolder(entry)"
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<font-awesome icon="folder" class="fa-fw text-yellow-500" />
|
||||
<span class="font-medium">{{ entry.name }}</span>
|
||||
<span
|
||||
class="text-xs bg-gray-200 text-gray-700 px-2 py-0.5 rounded-full ml-2"
|
||||
>Folder</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-for="entry in files"
|
||||
:key="'file-' + entry.path"
|
||||
class="flex items-center justify-between p-3 bg-white border border-gray-200 rounded-lg hover:bg-gray-50"
|
||||
>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<font-awesome icon="file-alt" class="fa-fw text-gray-500" />
|
||||
<span class="font-medium truncate">{{ entry.name }}</span>
|
||||
</div>
|
||||
<div class="text-sm text-gray-500 mt-1">
|
||||
<span v-if="entry.size">{{ formatFileSize(entry.size) }}</span>
|
||||
<span v-else>Size unknown</span>
|
||||
<span
|
||||
v-if="entry.path && !platformCapabilities.isIOS"
|
||||
class="ml-2 text-xs text-blue-600"
|
||||
>📁 {{ entry.path }}</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-2 ml-3">
|
||||
<button
|
||||
class="text-blue-500 hover:text-blue-700 p-1"
|
||||
title="Open file"
|
||||
@click="openFile(entry.uri, entry.name)"
|
||||
>
|
||||
<font-awesome icon="external-link-alt" class="fa-fw" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Summary -->
|
||||
<div class="text-sm text-gray-500 mt-3 pt-3 border-t">
|
||||
Showing {{ filteredFiles.length }} of {{ backupFiles.length }} backup
|
||||
files
|
||||
</div>
|
||||
|
||||
<div class="text-sm text-gray-600 mb-2">
|
||||
<p>
|
||||
📁 Backup files are saved to persistent storage that survives app
|
||||
installations:
|
||||
</p>
|
||||
<ul class="list-disc list-inside ml-2 mt-1 text-xs">
|
||||
<li v-if="platformCapabilities.isIOS">
|
||||
iOS: Documents folder (accessible via Files app)
|
||||
</li>
|
||||
<li
|
||||
v-if="platformCapabilities.isMobile && !platformCapabilities.isIOS"
|
||||
>
|
||||
Android: Downloads/TimeSafari or external storage (accessible via
|
||||
file managers)
|
||||
</li>
|
||||
<li v-if="!platformCapabilities.isMobile">
|
||||
Desktop: User's download directory
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Vue, Watch } from "vue-facing-decorator";
|
||||
import { NotificationIface } from "../constants/app";
|
||||
import { logger } from "../utils/logger";
|
||||
import { PlatformServiceFactory } from "../services/PlatformServiceFactory";
|
||||
import {
|
||||
PlatformService,
|
||||
PlatformCapabilities,
|
||||
} from "../services/PlatformService";
|
||||
|
||||
/**
|
||||
* @vue-component
|
||||
* Backup Files List Component
|
||||
* Displays and manages backup files with platform-specific functionality
|
||||
*/
|
||||
@Component
|
||||
export default class BackupFilesList extends Vue {
|
||||
/**
|
||||
* Notification function injected by Vue
|
||||
* Used to show success/error messages to the user
|
||||
*/
|
||||
$notify!: (notification: NotificationIface, timeout?: number) => void;
|
||||
|
||||
/**
|
||||
* Platform service instance for platform-specific operations
|
||||
*/
|
||||
private platformService: PlatformService =
|
||||
PlatformServiceFactory.getInstance();
|
||||
|
||||
/**
|
||||
* Platform capabilities for the current platform
|
||||
*/
|
||||
private get platformCapabilities(): PlatformCapabilities {
|
||||
return this.platformService.getCapabilities();
|
||||
}
|
||||
|
||||
/**
|
||||
* List of backup files found on the device
|
||||
*/
|
||||
backupFiles: Array<{
|
||||
name: string;
|
||||
uri: string;
|
||||
size?: number;
|
||||
type: "contacts" | "seed" | "other";
|
||||
path?: string;
|
||||
}> = [];
|
||||
|
||||
/**
|
||||
* Currently selected file type filter
|
||||
*/
|
||||
selectedType: "all" | "contacts" | "seed" | "other" = "all";
|
||||
|
||||
/**
|
||||
* Loading state for file operations
|
||||
*/
|
||||
isLoading = false;
|
||||
|
||||
/**
|
||||
* Interval for periodic refresh (5 minutes)
|
||||
*/
|
||||
private refreshInterval: number | null = null;
|
||||
|
||||
/**
|
||||
* Current path for folder navigation (array for breadcrumbs)
|
||||
*/
|
||||
currentPath: string[] = [];
|
||||
|
||||
/**
|
||||
* List of files/folders in the current directory
|
||||
*/
|
||||
directoryEntries: Array<{
|
||||
name: string;
|
||||
uri: string;
|
||||
size?: number;
|
||||
path: string;
|
||||
type: "file" | "folder";
|
||||
}> = [];
|
||||
|
||||
/**
|
||||
* Temporary debug mode to show all entries as files
|
||||
*/
|
||||
debugShowAll = false;
|
||||
|
||||
/**
|
||||
* Checks and requests storage permissions if needed.
|
||||
* Returns true if permission is granted, false otherwise.
|
||||
*/
|
||||
private async ensureStoragePermission(): Promise<boolean> {
|
||||
logger.log(
|
||||
"[BackupFilesList] ensureStoragePermission called. platformCapabilities:",
|
||||
this.platformCapabilities,
|
||||
);
|
||||
if (!this.platformCapabilities.hasFileSystem) return true;
|
||||
// Only relevant for native platforms (Android/iOS)
|
||||
const platformService = this.platformService as any;
|
||||
if (typeof platformService.checkStoragePermissions === "function") {
|
||||
try {
|
||||
await platformService.checkStoragePermissions();
|
||||
logger.log("[BackupFilesList] Storage permission granted.");
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error("[BackupFilesList] Storage permission denied:", error);
|
||||
|
||||
// Get specific guidance for the platform
|
||||
let guidance =
|
||||
"This app needs permission to access your files to list and restore backups.";
|
||||
if (
|
||||
typeof platformService.getStoragePermissionGuidance === "function"
|
||||
) {
|
||||
try {
|
||||
guidance = await platformService.getStoragePermissionGuidance();
|
||||
} catch (guidanceError) {
|
||||
logger.warn(
|
||||
"[BackupFilesList] Could not get permission guidance:",
|
||||
guidanceError,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "warning",
|
||||
title: "Storage Permission Required",
|
||||
text: guidance,
|
||||
},
|
||||
10000, // Show for 10 seconds to give user time to read
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lifecycle hook to load backup files when component is mounted
|
||||
*/
|
||||
async mounted() {
|
||||
logger.log(
|
||||
"[BackupFilesList] mounted hook called. platformCapabilities:",
|
||||
this.platformCapabilities,
|
||||
);
|
||||
if (this.platformCapabilities.hasFileSystem) {
|
||||
// Check/request permission before loading
|
||||
const hasPermission = await this.ensureStoragePermission();
|
||||
if (hasPermission) {
|
||||
// Set default root path
|
||||
if (this.platformCapabilities.isIOS) {
|
||||
this.currentPath = ["."];
|
||||
} else {
|
||||
this.currentPath = ["Download", "TimeSafari"];
|
||||
}
|
||||
await this.loadDirectory();
|
||||
this.refreshInterval = window.setInterval(
|
||||
() => {
|
||||
this.loadDirectory();
|
||||
},
|
||||
5 * 60 * 1000,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lifecycle hook to clean up resources when component is unmounted
|
||||
*/
|
||||
beforeUnmount() {
|
||||
if (this.refreshInterval) {
|
||||
clearInterval(this.refreshInterval);
|
||||
this.refreshInterval = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed property for filtered files based on selected type
|
||||
* Note: The 'All' tab count is sometimes too small. Logging for debugging.
|
||||
*/
|
||||
get filteredFiles() {
|
||||
if (this.selectedType === "all") {
|
||||
logger.log("[BackupFilesList] filteredFiles (All):", this.backupFiles);
|
||||
return this.backupFiles;
|
||||
}
|
||||
const filtered = this.backupFiles.filter(
|
||||
(file) => file.type === this.selectedType,
|
||||
);
|
||||
logger.log(
|
||||
`[BackupFilesList] filteredFiles (${this.selectedType}):`,
|
||||
filtered,
|
||||
);
|
||||
return filtered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed property to check if we're in development mode
|
||||
*/
|
||||
get isDevelopment(): boolean {
|
||||
return import.meta.env.DEV;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the current directory entries
|
||||
*/
|
||||
async loadDirectory() {
|
||||
if (!this.platformCapabilities.hasFileSystem) return;
|
||||
this.isLoading = true;
|
||||
try {
|
||||
const path =
|
||||
this.currentPath.join("/") ||
|
||||
(this.platformCapabilities.isIOS ? "." : "Download/TimeSafari");
|
||||
this.directoryEntries = await (
|
||||
this.platformService as PlatformService
|
||||
).listFilesInDirectory(path, this.debugShowAll);
|
||||
logger.log("[BackupFilesList] Loaded directory:", {
|
||||
path,
|
||||
entries: this.directoryEntries,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error("[BackupFilesList] Failed to load directory:", error);
|
||||
this.directoryEntries = [];
|
||||
} finally {
|
||||
this.isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate into a folder
|
||||
*/
|
||||
async openFolder(entry: { name: string; path: string }) {
|
||||
this.currentPath.push(entry.name);
|
||||
await this.loadDirectory();
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to a breadcrumb
|
||||
*/
|
||||
async goToBreadcrumb(index: number) {
|
||||
this.currentPath = this.currentPath.slice(0, index + 1);
|
||||
await this.loadDirectory();
|
||||
}
|
||||
|
||||
/**
|
||||
* Go up one directory
|
||||
*/
|
||||
async goUp() {
|
||||
if (this.currentPath.length > 1) {
|
||||
this.currentPath.pop();
|
||||
await this.loadDirectory();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed property for breadcrumbs
|
||||
*/
|
||||
get breadcrumbs() {
|
||||
return this.currentPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed property for showing files and folders
|
||||
*/
|
||||
get folders() {
|
||||
return this.directoryEntries.filter((e) => e.type === "folder");
|
||||
}
|
||||
get files() {
|
||||
return this.directoryEntries.filter((e) => e.type === "file");
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes the list of backup files from the device
|
||||
*/
|
||||
async refreshFiles() {
|
||||
logger.log("[BackupFilesList] refreshFiles called.");
|
||||
if (!this.platformCapabilities.hasFileSystem) {
|
||||
return;
|
||||
}
|
||||
// Check/request permission before refreshing
|
||||
const hasPermission = await this.ensureStoragePermission();
|
||||
if (!hasPermission) {
|
||||
this.backupFiles = [];
|
||||
this.isLoading = false;
|
||||
return;
|
||||
}
|
||||
this.isLoading = true;
|
||||
try {
|
||||
this.backupFiles = await this.platformService.listBackupFiles();
|
||||
logger.log("[BackupFilesList] Refreshed backup files:", {
|
||||
count: this.backupFiles.length,
|
||||
files: this.backupFiles.map((f) => ({
|
||||
name: f.name,
|
||||
type: f.type,
|
||||
path: f.path,
|
||||
size: f.size,
|
||||
})),
|
||||
platform: this.platformCapabilities.isIOS ? "iOS" : "Android",
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
// Debug: Log file type distribution
|
||||
const typeCounts = {
|
||||
contacts: this.backupFiles.filter((f) => f.type === "contacts").length,
|
||||
seed: this.backupFiles.filter((f) => f.type === "seed").length,
|
||||
other: this.backupFiles.filter((f) => f.type === "other").length,
|
||||
total: this.backupFiles.length,
|
||||
};
|
||||
logger.log("[BackupFilesList] File type distribution:", typeCounts);
|
||||
// Log the full backupFiles array for debugging the 'All' tab count
|
||||
logger.log(
|
||||
"[BackupFilesList] backupFiles array for All tab:",
|
||||
this.backupFiles,
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error("[BackupFilesList] Failed to refresh backup files:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Error Loading Files",
|
||||
text: "Failed to load backup files from your device.",
|
||||
},
|
||||
5000,
|
||||
);
|
||||
} finally {
|
||||
this.isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a test backup file for debugging purposes
|
||||
*/
|
||||
async createTestBackup() {
|
||||
try {
|
||||
this.isLoading = true;
|
||||
logger.log("[BackupFilesList] Creating test backup file");
|
||||
|
||||
const result = await this.platformService.createTestBackupFile();
|
||||
|
||||
if (result.success) {
|
||||
logger.log("[BackupFilesList] Test backup file created successfully:", {
|
||||
fileName: result.fileName,
|
||||
uri: result.uri,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "success",
|
||||
title: "Test Backup Created",
|
||||
text: `Test backup file "${result.fileName}" created successfully. Refresh the list to see it.`,
|
||||
},
|
||||
5000,
|
||||
);
|
||||
|
||||
// Refresh the file list to show the new test file
|
||||
await this.refreshFiles();
|
||||
} else {
|
||||
throw new Error(result.error || "Failed to create test backup file");
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
"[BackupFilesList] Failed to create test backup file:",
|
||||
error,
|
||||
);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Test Backup Failed",
|
||||
text: "Failed to create test backup file. Check the console for details.",
|
||||
},
|
||||
5000,
|
||||
);
|
||||
} finally {
|
||||
this.isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests different directory contexts to debug file visibility issues
|
||||
*/
|
||||
async testDirectoryContexts() {
|
||||
try {
|
||||
this.isLoading = true;
|
||||
logger.log("[BackupFilesList] Testing directory contexts");
|
||||
|
||||
const debugOutput = await this.platformService.testDirectoryContexts();
|
||||
|
||||
logger.log(
|
||||
"[BackupFilesList] Directory context test results:",
|
||||
debugOutput,
|
||||
);
|
||||
|
||||
// Show the debug output in a notification or alert
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "info",
|
||||
title: "Directory Context Test",
|
||||
text: "Directory context test completed. Check the console for detailed results.",
|
||||
},
|
||||
5000,
|
||||
);
|
||||
|
||||
// Also log the full output to console for easy access
|
||||
logger.log("=== Directory Context Test Results ===");
|
||||
logger.log(debugOutput);
|
||||
logger.log("=== End Test Results ===");
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
"[BackupFilesList] Failed to test directory contexts:",
|
||||
error,
|
||||
);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Context Test Failed",
|
||||
text: "Failed to test directory contexts. Check the console for details.",
|
||||
},
|
||||
5000,
|
||||
);
|
||||
} finally {
|
||||
this.isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes the file list after a backup is created
|
||||
* This method can be called from parent components
|
||||
*/
|
||||
async refreshAfterSave() {
|
||||
logger.log("[BackupFilesList] refreshAfterSave called");
|
||||
await this.refreshFiles();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a specific file in the device's file viewer
|
||||
* @param fileUri - URI of the file to open
|
||||
* @param fileName - Name of the file for display
|
||||
*/
|
||||
async openFile(fileUri: string, fileName: string) {
|
||||
try {
|
||||
const result = await this.platformService.openFile(fileUri, fileName);
|
||||
|
||||
if (result.success) {
|
||||
logger.log("[BackupFilesList] File opened successfully:", {
|
||||
fileName,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} else {
|
||||
throw new Error(result.error || "Failed to open file");
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("[BackupFilesList] Failed to open file:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Error Opening File",
|
||||
text: `Failed to open ${fileName}. ${error instanceof Error ? error.message : String(error)}`,
|
||||
},
|
||||
5000,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the backup directory in the device's file explorer
|
||||
*/
|
||||
async openBackupDirectory() {
|
||||
try {
|
||||
const result = await this.platformService.openBackupDirectory();
|
||||
|
||||
if (result.success) {
|
||||
logger.log("[BackupFilesList] Backup directory opened successfully:", {
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} else {
|
||||
throw new Error(result.error || "Failed to open backup directory");
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("[BackupFilesList] Failed to open backup directory:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Error Opening Directory",
|
||||
text: `Failed to open backup directory. ${error instanceof Error ? error.message : String(error)}`,
|
||||
},
|
||||
5000,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the count of files for a specific type
|
||||
* Note: The 'All' tab count is sometimes too small. Logging for debugging.
|
||||
*/
|
||||
getFileCountByType(type: "all" | "contacts" | "seed" | "other"): number {
|
||||
let count;
|
||||
if (type === "all") {
|
||||
count = this.backupFiles.length;
|
||||
logger.log(
|
||||
"[BackupFilesList] getFileCountByType (All):",
|
||||
count,
|
||||
this.backupFiles,
|
||||
);
|
||||
return count;
|
||||
}
|
||||
count = this.backupFiles.filter((file) => file.type === type).length;
|
||||
logger.log(`[BackupFilesList] getFileCountByType (${type}):`, count);
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the appropriate icon for a file type
|
||||
* @param type - File type
|
||||
* @returns FontAwesome icon name
|
||||
*/
|
||||
getFileIcon(type: "contacts" | "seed" | "other"): string {
|
||||
switch (type) {
|
||||
case "contacts":
|
||||
return "address-book";
|
||||
case "seed":
|
||||
return "key";
|
||||
default:
|
||||
return "file-alt";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the appropriate icon color for a file type
|
||||
* @param type - File type
|
||||
* @returns CSS color class
|
||||
*/
|
||||
getFileIconColor(type: "contacts" | "seed" | "other"): string {
|
||||
switch (type) {
|
||||
case "contacts":
|
||||
return "text-blue-500";
|
||||
case "seed":
|
||||
return "text-orange-500";
|
||||
default:
|
||||
return "text-gray-500";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the appropriate badge color for a file type
|
||||
* @param type - File type
|
||||
* @returns CSS color class
|
||||
*/
|
||||
getTypeBadgeColor(type: "contacts" | "seed" | "other"): string {
|
||||
switch (type) {
|
||||
case "contacts":
|
||||
return "bg-blue-100 text-blue-800";
|
||||
case "seed":
|
||||
return "bg-orange-100 text-orange-800";
|
||||
default:
|
||||
return "bg-gray-100 text-gray-800";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats file size in human-readable format
|
||||
* @param bytes - File size in bytes
|
||||
* @returns Formatted file size string
|
||||
*/
|
||||
formatFileSize(bytes: number): string {
|
||||
if (bytes === 0) return "0 Bytes";
|
||||
|
||||
const k = 1024;
|
||||
const sizes = ["Bytes", "KB", "MB", "GB"];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug method to test file discovery
|
||||
* Can be called from browser console for troubleshooting
|
||||
*/
|
||||
public async debugFileDiscovery() {
|
||||
try {
|
||||
logger.log("[BackupFilesList] Starting debug file discovery...");
|
||||
|
||||
// Test the platform service's test methods
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
|
||||
// Test listing all user files
|
||||
const allFilesResult = await platformService.testListUserFiles();
|
||||
logger.log(
|
||||
"[BackupFilesList] All user files test result:",
|
||||
allFilesResult,
|
||||
);
|
||||
|
||||
// Test listing backup files specifically
|
||||
const backupFilesResult = await platformService.testBackupFiles();
|
||||
logger.log(
|
||||
"[BackupFilesList] Backup files test result:",
|
||||
backupFilesResult,
|
||||
);
|
||||
|
||||
// Note: testListAllBackupFiles method is not part of the PlatformService interface
|
||||
// It exists only in CapacitorPlatformService implementation
|
||||
// If needed, this could be added to the interface or called via type assertion
|
||||
|
||||
// Test debug listing all files without filtering (if available)
|
||||
if ("debugListAllFiles" in platformService) {
|
||||
const debugAllFiles = await (
|
||||
platformService as any
|
||||
).debugListAllFiles();
|
||||
logger.log("[BackupFilesList] Debug all files (no filtering):", {
|
||||
count: debugAllFiles.length,
|
||||
files: debugAllFiles.map((f: any) => ({
|
||||
name: f.name,
|
||||
path: f.path,
|
||||
size: f.size,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
// Test comprehensive step-by-step debug (if available)
|
||||
if ("debugFileDiscoveryStepByStep" in platformService) {
|
||||
const stepByStepDebug = await (
|
||||
platformService as any
|
||||
).debugFileDiscoveryStepByStep();
|
||||
logger.log(
|
||||
"[BackupFilesList] Step-by-step debug output:",
|
||||
stepByStepDebug,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
allFiles: allFilesResult,
|
||||
backupFiles: backupFilesResult,
|
||||
currentBackupFiles: this.backupFiles,
|
||||
debugAllFiles:
|
||||
"debugListAllFiles" in platformService
|
||||
? await (platformService as any).debugListAllFiles()
|
||||
: null,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error("[BackupFilesList] Debug file discovery failed:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@Watch("platformCapabilities.hasFileSystem", { immediate: true })
|
||||
async onFileSystemCapabilityChanged(newVal: boolean) {
|
||||
if (newVal) {
|
||||
await this.refreshFiles();
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -1,7 +1,8 @@
|
||||
/** * Data Export Section Component * * Provides UI and functionality for
|
||||
exporting user data and backing up identifier seeds. * Includes buttons for seed
|
||||
backup and database export, with platform-specific download instructions. * *
|
||||
@component * @displayName DataExportSection * @example * ```vue *
|
||||
backup and database export, with platform-specific download instructions. * Also
|
||||
displays a list of backup files with options to open them in the device's file
|
||||
explorer. * * @component * @displayName DataExportSection * @example * ```vue *
|
||||
<DataExportSection :active-did="currentDid" />
|
||||
* ``` */
|
||||
|
||||
@@ -43,18 +44,27 @@ backup and database export, with platform-specific download instructions. * *
|
||||
v-if="platformCapabilities.isIOS"
|
||||
class="list-disc list-outside ml-4"
|
||||
>
|
||||
On iOS: You will be prompted to choose a location to save your backup
|
||||
file.
|
||||
On iOS: Files are saved to Documents folder (accessible via Files app)
|
||||
and persist between app installations.
|
||||
</li>
|
||||
<li
|
||||
v-if="platformCapabilities.isMobile && !platformCapabilities.isIOS"
|
||||
class="list-disc list-outside ml-4"
|
||||
>
|
||||
On Android: You will be prompted to choose a location to save your
|
||||
backup file.
|
||||
On Android: Files are saved to Downloads/TimeSafari or external
|
||||
storage (accessible via file managers) and persist between app
|
||||
installations.
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!-- Backup Files List -->
|
||||
<div
|
||||
v-if="platformCapabilities.hasFileSystem"
|
||||
class="mt-6 pt-6 border-t border-gray-300"
|
||||
>
|
||||
<BackupFilesList ref="backupFilesList" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -65,20 +75,21 @@ import { AppString, NotificationIface } from "../constants/app";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
|
||||
import { logger } from "../utils/logger";
|
||||
import { logger, getTimestampForFilename } from "../utils/logger";
|
||||
import { PlatformServiceFactory } from "../services/PlatformServiceFactory";
|
||||
import {
|
||||
PlatformService,
|
||||
PlatformCapabilities,
|
||||
} from "../services/PlatformService";
|
||||
import { contactsToExportJson } from "../libs/util";
|
||||
import BackupFilesList from "./BackupFilesList.vue";
|
||||
|
||||
/**
|
||||
* @vue-component
|
||||
* Data Export Section Component
|
||||
* Handles database export and seed backup functionality with platform-specific behavior
|
||||
*/
|
||||
@Component
|
||||
@Component({ components: { BackupFilesList } })
|
||||
export default class DataExportSection extends Vue {
|
||||
/**
|
||||
* Notification function injected by Vue
|
||||
@@ -151,7 +162,9 @@ export default class DataExportSection extends Vue {
|
||||
const jsonStr = JSON.stringify(exportData, null, 2);
|
||||
const blob = new Blob([jsonStr], { type: "application/json" });
|
||||
|
||||
const fileName = `${AppString.APP_NAME_NO_SPACES}-backup-contacts.json`;
|
||||
// Create timestamped filename
|
||||
const timestamp = getTimestampForFilename();
|
||||
const fileName = `${AppString.APP_NAME_NO_SPACES}-backup-contacts-${timestamp}.json`;
|
||||
|
||||
if (this.platformCapabilities.hasFileDownload) {
|
||||
// Web platform: Use download link
|
||||
@@ -162,8 +175,21 @@ export default class DataExportSection extends Vue {
|
||||
downloadAnchor.click();
|
||||
setTimeout(() => URL.revokeObjectURL(this.downloadUrl), 1000);
|
||||
} else if (this.platformCapabilities.hasFileSystem) {
|
||||
// Native platform: Write to app directory
|
||||
await this.platformService.writeAndShareFile(fileName, jsonStr);
|
||||
// Native platform: Write to user-accessible location and share
|
||||
const result = await this.platformService.writeAndShareFile(
|
||||
fileName,
|
||||
jsonStr,
|
||||
{
|
||||
allowLocationSelection: true,
|
||||
showLocationSelectionDialog: true,
|
||||
mimeType: "application/json",
|
||||
},
|
||||
);
|
||||
|
||||
// Handle the result
|
||||
if (!result.saved) {
|
||||
throw new Error(result.error || "Failed to save file");
|
||||
}
|
||||
} else {
|
||||
throw new Error("This platform does not support file downloads.");
|
||||
}
|
||||
@@ -175,10 +201,19 @@ export default class DataExportSection extends Vue {
|
||||
title: "Export Successful",
|
||||
text: this.platformCapabilities.hasFileDownload
|
||||
? "See your downloads directory for the backup."
|
||||
: "The backup file has been saved.",
|
||||
: "Backup saved to persistent storage that survives app installations. Use the share dialog to access your file and choose where to save it permanently.",
|
||||
},
|
||||
3000,
|
||||
5000,
|
||||
);
|
||||
|
||||
// Refresh the backup files list
|
||||
const backupFilesList = this.$refs.backupFilesList as any;
|
||||
if (
|
||||
backupFilesList &&
|
||||
typeof backupFilesList.refreshAfterSave === "function"
|
||||
) {
|
||||
await backupFilesList.refreshAfterSave();
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("Export Error:", error);
|
||||
this.$notify(
|
||||
@@ -212,5 +247,18 @@ export default class DataExportSection extends Vue {
|
||||
hidden: !this.downloadUrl || !this.platformCapabilities.hasFileDownload,
|
||||
};
|
||||
}
|
||||
|
||||
async mounted() {
|
||||
// Ensure permissions are requested and refresh backup files list on mount
|
||||
if (this.platformCapabilities.hasFileSystem) {
|
||||
const backupFilesList = this.$refs.backupFilesList as any;
|
||||
if (
|
||||
backupFilesList &&
|
||||
typeof backupFilesList.refreshFiles === "function"
|
||||
) {
|
||||
await backupFilesList.refreshFiles();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -321,7 +321,7 @@ export default class GiftedDialog extends Vue {
|
||||
);
|
||||
|
||||
if (!result.success) {
|
||||
const errorMessage = result.error;
|
||||
const errorMessage = this.getGiveCreationErrorMessage(result);
|
||||
logger.error("Error with give creation result:", result);
|
||||
this.$notify(
|
||||
{
|
||||
@@ -367,6 +367,19 @@ export default class GiftedDialog extends Vue {
|
||||
|
||||
// Helper functions for readability
|
||||
|
||||
/**
|
||||
* @param result direct response eg. ErrorResult or SuccessResult (potentially with embedded "data")
|
||||
* @returns best guess at an error message
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
getGiveCreationErrorMessage(result: any) {
|
||||
return (
|
||||
result.error?.userMessage ||
|
||||
result.error?.error ||
|
||||
result.response?.data?.error?.message
|
||||
);
|
||||
}
|
||||
|
||||
explainData() {
|
||||
this.$notify(
|
||||
{
|
||||
|
||||
@@ -48,15 +48,12 @@
|
||||
<span>
|
||||
{{ didInfo(visDid) }}
|
||||
<span v-if="!serverUtil.isEmptyOrHiddenDid(visDid)">
|
||||
<router-link
|
||||
:to="{ path: '/did/' + encodeURIComponent(visDid) }"
|
||||
class="text-blue-500"
|
||||
>
|
||||
<a :href="`/did/${visDid}`" class="text-blue-500">
|
||||
<font-awesome
|
||||
icon="arrow-up-right-from-square"
|
||||
class="fa-fw"
|
||||
/>
|
||||
</router-link>
|
||||
</a>
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
<template>
|
||||
<svg
|
||||
v-if="iconData"
|
||||
:class="svgClass"
|
||||
:fill="fill"
|
||||
:stroke="stroke"
|
||||
:viewBox="viewBox"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path v-for="(path, index) in iconData.paths" :key="index" v-bind="path" />
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from "vue-facing-decorator";
|
||||
import icons from "../assets/icons.json";
|
||||
import { logger } from "../utils/logger";
|
||||
|
||||
/**
|
||||
* Icon path interface
|
||||
*/
|
||||
interface IconPath {
|
||||
d: string;
|
||||
fillRule?: string;
|
||||
clipRule?: string;
|
||||
strokeLinecap?: string;
|
||||
strokeLinejoin?: string;
|
||||
strokeWidth?: string | number;
|
||||
fill?: string;
|
||||
stroke?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Icon data interface
|
||||
*/
|
||||
interface IconData {
|
||||
paths: IconPath[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Icons JSON structure
|
||||
*/
|
||||
interface IconsJson {
|
||||
[key: string]: IconPath | IconData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Icon Renderer Component
|
||||
*
|
||||
* This component loads SVG icon definitions from a JSON file and renders them
|
||||
* as SVG elements. It provides a clean way to use icons without cluttering
|
||||
* templates with long SVG path definitions.
|
||||
*
|
||||
* @author Matthew Raymer
|
||||
* @version 1.0.0
|
||||
* @since 2024
|
||||
*/
|
||||
@Component({
|
||||
name: "IconRenderer",
|
||||
})
|
||||
export default class IconRenderer extends Vue {
|
||||
@Prop({ required: true }) readonly iconName!: string;
|
||||
@Prop({ default: "h-5 w-5" }) readonly svgClass!: string;
|
||||
@Prop({ default: "none" }) readonly fill!: string;
|
||||
@Prop({ default: "currentColor" }) readonly stroke!: string;
|
||||
@Prop({ default: "0 0 24 24" }) readonly viewBox!: string;
|
||||
|
||||
/**
|
||||
* Get the icon data for the specified icon name
|
||||
*
|
||||
* @returns {IconData | null} The icon data object or null if not found
|
||||
*/
|
||||
get iconData(): IconData | null {
|
||||
const icon = (icons as IconsJson)[this.iconName];
|
||||
if (!icon) {
|
||||
logger.warn(`Icon "${this.iconName}" not found in icons.json`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Convert single path to array format for consistency
|
||||
if ("d" in icon) {
|
||||
return {
|
||||
paths: [icon as IconPath],
|
||||
};
|
||||
}
|
||||
|
||||
return icon as IconData;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -268,7 +268,7 @@ import {
|
||||
} from "../constants/app";
|
||||
import { retrieveSettingsForActiveAccount } from "../db/index";
|
||||
import { accessToken } from "../libs/crypto";
|
||||
import { logger } from "../utils/logger";
|
||||
import { logger, getTimestampForFilename } from "../utils/logger";
|
||||
import { PlatformServiceFactory } from "../services/PlatformServiceFactory";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
|
||||
@@ -576,7 +576,7 @@ export default class ImageMethodDialog extends Vue {
|
||||
(blob) => {
|
||||
if (blob) {
|
||||
this.blob = blob;
|
||||
this.fileName = `photo_${Date.now()}.jpg`;
|
||||
this.fileName = `photo-${getTimestampForFilename()}.jpg`;
|
||||
this.showRetry = true;
|
||||
this.stopCameraPreview();
|
||||
}
|
||||
|
||||
@@ -83,7 +83,10 @@
|
||||
import { Vue, Component, Prop } from "vue-facing-decorator";
|
||||
|
||||
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
|
||||
import { createAndSubmitOffer } from "../libs/endorserServer";
|
||||
import {
|
||||
createAndSubmitOffer,
|
||||
serverMessageForUser,
|
||||
} from "../libs/endorserServer";
|
||||
import * as libsUtil from "../libs/util";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import { retrieveSettingsForActiveAccount } from "../db/index";
|
||||
@@ -247,7 +250,7 @@ export default class OfferDialog extends Vue {
|
||||
);
|
||||
|
||||
if (!result.success) {
|
||||
const errorMessage = result.error;
|
||||
const errorMessage = this.getOfferCreationErrorMessage(result);
|
||||
logger.error("Error with offer creation result:", result);
|
||||
this.$notify(
|
||||
{
|
||||
@@ -287,6 +290,21 @@ export default class OfferDialog extends Vue {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper functions for readability
|
||||
|
||||
/**
|
||||
* @param result direct response eg. ErrorResult or SuccessResult (potentially with embedded "data")
|
||||
* @returns best guess at an error message
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
getOfferCreationErrorMessage(result: any) {
|
||||
return (
|
||||
serverMessageForUser(result) ||
|
||||
result.error?.userMessage ||
|
||||
result.error?.error
|
||||
);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ import {
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import { retrieveSettingsForActiveAccount } from "../db/index";
|
||||
import { accessToken } from "../libs/crypto";
|
||||
import { logger } from "../utils/logger";
|
||||
import { logger, getTimestampForFilename } from "../utils/logger";
|
||||
import { PlatformServiceFactory } from "../services/PlatformServiceFactory";
|
||||
|
||||
@Component({ components: { VuePictureCropper } })
|
||||
@@ -393,7 +393,7 @@ export default class PhotoDialog extends Vue {
|
||||
(blob) => {
|
||||
if (blob) {
|
||||
this.blob = blob;
|
||||
this.fileName = `photo_${Date.now()}.jpg`;
|
||||
this.fileName = `photo-${getTimestampForFilename()}.jpg`;
|
||||
this.stopCameraPreview();
|
||||
}
|
||||
},
|
||||
|
||||
@@ -38,13 +38,14 @@ export default class TopMessage extends Vue {
|
||||
settings.apiServer !== AppString.PROD_ENDORSER_API_SERVER
|
||||
) {
|
||||
const didPrefix = settings.activeDid?.slice(11, 15);
|
||||
this.message = "You're not using prod, user " + didPrefix;
|
||||
this.message = "You're linked to a non-prod server, user " + didPrefix;
|
||||
} else if (
|
||||
settings.warnIfProdServer &&
|
||||
settings.apiServer === AppString.PROD_ENDORSER_API_SERVER
|
||||
) {
|
||||
const didPrefix = settings.activeDid?.slice(11, 15);
|
||||
this.message = "You are using prod, user " + didPrefix;
|
||||
this.message =
|
||||
"You're linked to the production server, user " + didPrefix;
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
this.$notify(
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
registerMigration,
|
||||
runMigrations as runMigrationsService,
|
||||
} from "../services/migrationService";
|
||||
import migrationService from "../services/migrationService";
|
||||
import { DEFAULT_ENDORSER_API_SERVER } from "@/constants/app";
|
||||
import { arrayBufferToBase64 } from "@/libs/crypto";
|
||||
|
||||
@@ -126,12 +123,16 @@ const MIGRATIONS = [
|
||||
* @param extractMigrationNames - A function that extracts the names (string array) from "select name from migrations"
|
||||
*/
|
||||
export async function runMigrations<T>(
|
||||
sqlExec: (sql: string, params?: unknown[]) => Promise<unknown>,
|
||||
sqlQuery: (sql: string, params?: unknown[]) => Promise<T>,
|
||||
sqlExec: (sql: string) => Promise<unknown>,
|
||||
sqlQuery: (sql: string) => Promise<T>,
|
||||
extractMigrationNames: (result: T) => Set<string>,
|
||||
): Promise<void> {
|
||||
for (const migration of MIGRATIONS) {
|
||||
registerMigration(migration);
|
||||
migrationService.registerMigration(migration);
|
||||
}
|
||||
await runMigrationsService(sqlExec, sqlQuery, extractMigrationNames);
|
||||
await migrationService.runMigrations(
|
||||
sqlExec,
|
||||
sqlQuery,
|
||||
extractMigrationNames,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -227,28 +227,10 @@ export async function logConsoleAndDb(
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates SQL INSERT statement and parameters from a model object
|
||||
*
|
||||
* This helper function creates a parameterized SQL INSERT statement
|
||||
* from a JavaScript object. It filters out undefined values and
|
||||
* creates the appropriate SQL syntax with placeholders.
|
||||
*
|
||||
* The function is used internally by the migration functions to
|
||||
* safely insert data into the SQLite database.
|
||||
*
|
||||
* @function generateInsertStatement
|
||||
* @param {Record<string, unknown>} model - The model object containing fields to insert
|
||||
* @param {string} tableName - The name of the table to insert into
|
||||
* @returns {Object} Object containing the SQL statement and parameters array
|
||||
* @returns {string} returns.sql - The SQL INSERT statement
|
||||
* @returns {unknown[]} returns.params - Array of parameter values
|
||||
* @example
|
||||
* ```typescript
|
||||
* const contact = { did: 'did:example:123', name: 'John Doe' };
|
||||
* const { sql, params } = generateInsertStatement(contact, 'contacts');
|
||||
* // sql: "INSERT INTO contacts (did, name) VALUES (?, ?)"
|
||||
* // params: ['did:example:123', 'John Doe']
|
||||
* ```
|
||||
* Generates an SQL INSERT statement and parameters from a model object.
|
||||
* @param model The model object containing fields to update
|
||||
* @param tableName The name of the table to update
|
||||
* @returns Object containing the SQL statement and parameters array
|
||||
*/
|
||||
export function generateInsertStatement(
|
||||
model: Record<string, unknown>,
|
||||
@@ -266,30 +248,12 @@ export function generateInsertStatement(
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates SQL UPDATE statement and parameters from a model object
|
||||
*
|
||||
* This helper function creates a parameterized SQL UPDATE statement
|
||||
* from a JavaScript object. It filters out undefined values and
|
||||
* creates the appropriate SQL syntax with placeholders.
|
||||
*
|
||||
* The function is used internally by the migration functions to
|
||||
* safely update data in the SQLite database.
|
||||
*
|
||||
* @function generateUpdateStatement
|
||||
* @param {Record<string, unknown>} model - The model object containing fields to update
|
||||
* @param {string} tableName - The name of the table to update
|
||||
* @param {string} whereClause - The WHERE clause for the update (e.g. "id = ?")
|
||||
* @param {unknown[]} [whereParams=[]] - Parameters for the WHERE clause
|
||||
* @returns {Object} Object containing the SQL statement and parameters array
|
||||
* @returns {string} returns.sql - The SQL UPDATE statement
|
||||
* @returns {unknown[]} returns.params - Array of parameter values
|
||||
* @example
|
||||
* ```typescript
|
||||
* const contact = { name: 'Jane Doe' };
|
||||
* const { sql, params } = generateUpdateStatement(contact, 'contacts', 'did = ?', ['did:example:123']);
|
||||
* // sql: "UPDATE contacts SET name = ? WHERE did = ?"
|
||||
* // params: ['Jane Doe', 'did:example:123']
|
||||
* ```
|
||||
* Generates an SQL UPDATE statement and parameters from a model object.
|
||||
* @param model The model object containing fields to update
|
||||
* @param tableName The name of the table to update
|
||||
* @param whereClause The WHERE clause for the update (e.g. "id = ?")
|
||||
* @param whereParams Parameters for the WHERE clause
|
||||
* @returns Object containing the SQL statement and parameters array
|
||||
*/
|
||||
export function generateUpdateStatement(
|
||||
model: Record<string, unknown>,
|
||||
|
||||
@@ -1 +1 @@
|
||||
# Check the contact & settings export to see whether you want your new table to be included in it
|
||||
Check the contact & settings export to see whether you want your new table to be included in it.
|
||||
|
||||
@@ -19,10 +19,6 @@ export interface Contact {
|
||||
registered?: boolean; // cached value of the server setting
|
||||
}
|
||||
|
||||
export type ContactWithJsonStrings = Contact & {
|
||||
contactMethods?: string;
|
||||
};
|
||||
|
||||
export const ContactSchema = {
|
||||
contacts: "&did, name", // no need to key by other things
|
||||
};
|
||||
|
||||
@@ -64,11 +64,6 @@ export type Settings = {
|
||||
webPushServer?: string; // Web Push server URL
|
||||
};
|
||||
|
||||
// type of settings where the searchBoxes are JSON strings instead of objects
|
||||
export type SettingsWithJsonStrings = Settings & {
|
||||
searchBoxes: string;
|
||||
};
|
||||
|
||||
export function checkIsAnyFeedFilterOn(settings: Settings): boolean {
|
||||
return !!(settings?.filterFeedByNearby || settings?.filterFeedByVisible);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { AxiosResponse } from "axios";
|
||||
import { GiverReceiverInputInfo } from "../libs/util";
|
||||
import { ErrorResult, ResultWithType } from "./common";
|
||||
|
||||
export interface GiverOutputInfo {
|
||||
action: string;
|
||||
@@ -45,3 +47,12 @@ export interface ProviderInfo {
|
||||
*/
|
||||
linkConfirmed: boolean;
|
||||
}
|
||||
|
||||
// Type for createAndSubmitClaim result
|
||||
export type CreateAndSubmitClaimResult = SuccessResult | ErrorResult;
|
||||
|
||||
// Update SuccessResult to use ClaimResult
|
||||
export interface SuccessResult extends ResultWithType {
|
||||
type: "success";
|
||||
response: AxiosResponse<ClaimResult>;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,10 @@ export interface GenericCredWrapper<T extends GenericVerifiableCredential> {
|
||||
publicUrls?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface ResultWithType {
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface ErrorResponse {
|
||||
error?: {
|
||||
message?: string;
|
||||
@@ -26,6 +30,11 @@ export interface InternalError {
|
||||
userMessage?: string;
|
||||
}
|
||||
|
||||
export interface ErrorResult extends ResultWithType {
|
||||
type: "error";
|
||||
error: InternalError;
|
||||
}
|
||||
|
||||
export interface KeyMeta {
|
||||
did: string;
|
||||
publicKeyHex: string;
|
||||
|
||||
@@ -30,7 +30,7 @@ import { z } from "zod";
|
||||
// Add a union type of all valid route paths
|
||||
export const VALID_DEEP_LINK_ROUTES = [
|
||||
"user-profile",
|
||||
"project",
|
||||
"project-details",
|
||||
"onboard-meeting-setup",
|
||||
"invite-one-accept",
|
||||
"contact-import",
|
||||
@@ -61,7 +61,7 @@ export const deepLinkSchemas = {
|
||||
"user-profile": z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
project: z.object({
|
||||
"project-details": z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
"onboard-meeting-setup": z.object({
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
export type {
|
||||
// From common.ts
|
||||
CreateAndSubmitClaimResult,
|
||||
GenericCredWrapper,
|
||||
GenericVerifiableCredential,
|
||||
KeyMeta,
|
||||
@@ -19,6 +18,11 @@ export type {
|
||||
RegisterActionClaim,
|
||||
} from "./claims";
|
||||
|
||||
export type {
|
||||
// From claims-result.ts
|
||||
CreateAndSubmitClaimResult,
|
||||
} from "./claims-result";
|
||||
|
||||
export type {
|
||||
// From records.ts
|
||||
PlanSummaryRecord,
|
||||
|
||||
@@ -12,6 +12,14 @@ import type { PluginListenerHandle } from "@capacitor/core";
|
||||
* Supports 'backButton' and 'appUrlOpen' events from Capacitor
|
||||
*/
|
||||
interface AppInterface {
|
||||
/**
|
||||
* Force exit the app. This should only be used in conjunction with the `backButton` handler for Android to
|
||||
* exit the app when navigation is complete.
|
||||
*
|
||||
* @returns Promise that resolves when the app has been exited
|
||||
*/
|
||||
exitApp(): Promise<void>;
|
||||
|
||||
/**
|
||||
* Add listener for back button events
|
||||
* @param eventName - Must be 'backButton'
|
||||
@@ -38,8 +46,19 @@ interface AppInterface {
|
||||
/**
|
||||
* App wrapper for Capacitor functionality
|
||||
* Provides type-safe event listeners for back button and URL open events
|
||||
* and app exit functionality
|
||||
*/
|
||||
export const App: AppInterface = {
|
||||
/**
|
||||
* Force exit the app. This should only be used in conjunction with the `backButton` handler for Android to
|
||||
* exit the app when navigation is complete.
|
||||
*
|
||||
* @returns Promise that resolves when the app has been exited
|
||||
*/
|
||||
exitApp(): Promise<void> {
|
||||
return CapacitorApp.exitApp();
|
||||
},
|
||||
|
||||
addListener(
|
||||
eventName: "backButton" | "appUrlOpen",
|
||||
listenerFunc: BackButtonListener | ((data: AppLaunchUrl) => void),
|
||||
|
||||
@@ -979,7 +979,7 @@ export const createAndSubmitConfirmation = async (
|
||||
handleId: string | undefined,
|
||||
apiServer: string,
|
||||
axios: Axios,
|
||||
): Promise<CreateAndSubmitClaimResult> => {
|
||||
) => {
|
||||
const goodClaim = removeSchemaContext(
|
||||
removeVisibleToDids(
|
||||
addLastClaimOrHandleAsIdIfMissing(claim, lastClaimId, handleId),
|
||||
|
||||
101
src/libs/util.ts
101
src/libs/util.ts
@@ -45,7 +45,6 @@ import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
import { sha256 } from "ethereum-cryptography/sha256";
|
||||
import { IIdentifier } from "@veramo/core";
|
||||
import { insertDidSpecificSettings, parseJsonField } from "../db/databaseUtil";
|
||||
import { DEFAULT_ROOT_DERIVATION_PATH } from "./crypto";
|
||||
|
||||
export interface GiverReceiverInputInfo {
|
||||
did?: string;
|
||||
@@ -883,71 +882,6 @@ export const contactToCsvLine = (contact: Contact): string => {
|
||||
return fields.join(",");
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses a CSV line into a Contact object. See contactToCsvLine for the format.
|
||||
* @param lineRaw - The CSV line to parse
|
||||
* @returns A Contact object
|
||||
*/
|
||||
export const csvLineToContact = (lineRaw: string): Contact => {
|
||||
// Note that Endorser Mobile puts name first, then did, etc.
|
||||
let line = lineRaw.trim();
|
||||
let did, publicKeyInput, seesMe, registered;
|
||||
let name;
|
||||
let commaPos1 = -1;
|
||||
if (line.startsWith('"')) {
|
||||
let doubleDoubleQuotePos = line.lastIndexOf('""') + 2;
|
||||
if (doubleDoubleQuotePos === -1) {
|
||||
doubleDoubleQuotePos = 1;
|
||||
}
|
||||
const quote2Pos = line.indexOf('"', doubleDoubleQuotePos);
|
||||
if (quote2Pos > -1) {
|
||||
commaPos1 = line.indexOf(",", quote2Pos);
|
||||
name = line.substring(1, quote2Pos).trim();
|
||||
name = name.replace(/""/g, '"');
|
||||
} else {
|
||||
// something is weird with one " to start, so ignore it and start after "
|
||||
line = line.substring(1);
|
||||
commaPos1 = line.indexOf(",");
|
||||
name = line.substring(0, commaPos1).trim();
|
||||
}
|
||||
} else {
|
||||
commaPos1 = line.indexOf(",");
|
||||
name = line.substring(0, commaPos1).trim();
|
||||
}
|
||||
if (commaPos1 > -1) {
|
||||
did = line.substring(commaPos1 + 1).trim();
|
||||
const commaPos2 = line.indexOf(",", commaPos1 + 1);
|
||||
if (commaPos2 > -1) {
|
||||
did = line.substring(commaPos1 + 1, commaPos2).trim();
|
||||
publicKeyInput = line.substring(commaPos2 + 1).trim();
|
||||
const commaPos3 = line.indexOf(",", commaPos2 + 1);
|
||||
if (commaPos3 > -1) {
|
||||
publicKeyInput = line.substring(commaPos2 + 1, commaPos3).trim();
|
||||
seesMe = line.substring(commaPos3 + 1).trim() == "true";
|
||||
const commaPos4 = line.indexOf(",", commaPos3 + 1);
|
||||
if (commaPos4 > -1) {
|
||||
seesMe = line.substring(commaPos3 + 1, commaPos4).trim() == "true";
|
||||
registered = line.substring(commaPos4 + 1).trim() == "true";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// help with potential mistakes while this sharing requires copy-and-paste
|
||||
let publicKeyBase64 = publicKeyInput;
|
||||
if (publicKeyBase64 && /^[0-9A-Fa-f]{66}$/i.test(publicKeyBase64)) {
|
||||
// it must be all hex (compressed public key), so convert
|
||||
publicKeyBase64 = Buffer.from(publicKeyBase64, "hex").toString("base64");
|
||||
}
|
||||
const newContact: Contact = {
|
||||
did: did || "",
|
||||
name,
|
||||
publicKeyBase64,
|
||||
seesMe,
|
||||
registered,
|
||||
};
|
||||
return newContact;
|
||||
};
|
||||
|
||||
/**
|
||||
* Interface for the JSON export format of database tables
|
||||
*/
|
||||
@@ -999,38 +933,3 @@ export const contactsToExportJson = (contacts: Contact[]): DatabaseExport => {
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Imports an account from a mnemonic phrase
|
||||
* @param mnemonic - The seed phrase to import from
|
||||
* @param derivationPath - The derivation path to use (defaults to DEFAULT_ROOT_DERIVATION_PATH)
|
||||
* @param shouldErase - Whether to erase existing accounts before importing
|
||||
* @returns Promise that resolves when import is complete
|
||||
* @throws Error if mnemonic is invalid or import fails
|
||||
*/
|
||||
export async function importFromMnemonic(
|
||||
mnemonic: string,
|
||||
derivationPath: string = DEFAULT_ROOT_DERIVATION_PATH,
|
||||
shouldErase: boolean = false,
|
||||
): Promise<void> {
|
||||
const mne: string = mnemonic.trim().toLowerCase();
|
||||
|
||||
// Derive address and keys from mnemonic
|
||||
const [address, privateHex, publicHex] = deriveAddress(mne, derivationPath);
|
||||
|
||||
// Create new identifier
|
||||
const newId = newIdentifier(address, publicHex, privateHex, derivationPath);
|
||||
|
||||
// Handle erasures
|
||||
if (shouldErase) {
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
await platformService.dbExec("DELETE FROM accounts");
|
||||
if (USE_DEXIE_DB) {
|
||||
const accountsDB = await accountsDBPromise;
|
||||
await accountsDB.accounts.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Save the new identity
|
||||
await saveNewIdentity(newId, mne, derivationPath);
|
||||
}
|
||||
|
||||
@@ -143,11 +143,6 @@ const routes: Array<RouteRecordRaw> = [
|
||||
name: "logs",
|
||||
component: () => import("../views/LogView.vue"),
|
||||
},
|
||||
{
|
||||
path: "/database-migration",
|
||||
name: "database-migration",
|
||||
component: () => import("../views/DatabaseMigration.vue"),
|
||||
},
|
||||
{
|
||||
path: "/new-activity",
|
||||
name: "new-activity",
|
||||
|
||||
@@ -65,9 +65,21 @@ export interface PlatformService {
|
||||
* Writes content to a file at the specified path and shares it.
|
||||
* @param fileName - The filename of the file to write
|
||||
* @param content - The content to write to the file
|
||||
* @returns Promise that resolves when the write is complete
|
||||
* @param options - Optional parameters for file saving behavior
|
||||
* @returns Promise that resolves to save/share result
|
||||
*/
|
||||
writeAndShareFile(fileName: string, content: string): Promise<void>;
|
||||
writeAndShareFile(
|
||||
fileName: string,
|
||||
content: string,
|
||||
options?: {
|
||||
allowLocationSelection?: boolean;
|
||||
saveToDownloads?: boolean;
|
||||
saveToPrivateStorage?: boolean;
|
||||
mimeType?: string;
|
||||
showShareDialog?: boolean;
|
||||
showLocationSelectionDialog?: boolean;
|
||||
},
|
||||
): Promise<{ saved: boolean; uri?: string; shared: boolean; error?: string }>;
|
||||
|
||||
/**
|
||||
* Deletes a file at the specified path.
|
||||
@@ -83,6 +95,48 @@ export interface PlatformService {
|
||||
*/
|
||||
listFiles(directory: string): Promise<string[]>;
|
||||
|
||||
/**
|
||||
* Tests the file sharing functionality by creating and sharing a test file.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
testFileSharing(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Tests saving a file without showing the share dialog.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
testFileSaveOnly(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Tests the location selection functionality using the file picker.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
testLocationSelection(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Tests location selection without showing the dialog (restores original behavior).
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
testLocationSelectionSilent(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Tests listing user-accessible files saved by the app.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
testListUserFiles(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Tests listing backup files specifically saved by the app.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
testBackupFiles(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Tests opening the backup directory in the device's file explorer.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
testOpenBackupDirectory(): Promise<string>;
|
||||
|
||||
// Camera operations
|
||||
/**
|
||||
* Activates the device camera to take a picture.
|
||||
@@ -130,4 +184,92 @@ export interface PlatformService {
|
||||
sql: string,
|
||||
params?: unknown[],
|
||||
): Promise<{ changes: number; lastId?: number }>;
|
||||
|
||||
/**
|
||||
* Lists user-accessible files saved by the app.
|
||||
* Returns files from Downloads (Android) or Documents (iOS) directories.
|
||||
* @returns Promise resolving to array of file information
|
||||
*/
|
||||
listUserAccessibleFiles(): Promise<
|
||||
Array<{ name: string; uri: string; size?: number }>
|
||||
>;
|
||||
|
||||
/**
|
||||
* Lists backup files specifically saved by the app.
|
||||
* Filters for files that appear to be TimeSafari backups.
|
||||
* @returns Promise resolving to array of backup file information
|
||||
*/
|
||||
listBackupFiles(): Promise<
|
||||
Array<{
|
||||
name: string;
|
||||
uri: string;
|
||||
size?: number;
|
||||
type: "contacts" | "seed" | "other";
|
||||
path?: string;
|
||||
}>
|
||||
>;
|
||||
|
||||
/**
|
||||
* Opens a file in the device's default file viewer/app.
|
||||
* Uses the native share dialog to provide options for opening the file.
|
||||
* @param fileUri - URI of the file to open
|
||||
* @param fileName - Name of the file (for display purposes)
|
||||
* @returns Promise resolving to success status
|
||||
*/
|
||||
openFile(
|
||||
fileUri: string,
|
||||
fileName: string,
|
||||
): Promise<{ success: boolean; error?: string }>;
|
||||
|
||||
/**
|
||||
* Opens the directory containing backup files in the device's file explorer.
|
||||
* Uses the native share dialog to provide options for accessing the directory.
|
||||
* @returns Promise resolving to success status
|
||||
*/
|
||||
openBackupDirectory(): Promise<{ success: boolean; error?: string }>;
|
||||
|
||||
/**
|
||||
* Creates a test backup file to verify file writing and reading functionality.
|
||||
* This is useful for debugging file visibility issues.
|
||||
* @returns Promise resolving to success status and file information
|
||||
*/
|
||||
createTestBackupFile(): Promise<{
|
||||
success: boolean;
|
||||
fileName?: string;
|
||||
uri?: string;
|
||||
error?: string;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* Tests different directory contexts to see what files are available.
|
||||
* This helps debug file visibility issues across different storage contexts.
|
||||
* @returns Promise resolving to debug information about file discovery across contexts
|
||||
*/
|
||||
testDirectoryContexts(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Lists files and folders in a specific directory for directory browsing
|
||||
* @param path - The directory path to list
|
||||
* @param debugShowAll - Debug flag to treat all entries as files
|
||||
* @returns Promise resolving to array of directory entries
|
||||
*/
|
||||
listFilesInDirectory(
|
||||
path: string,
|
||||
debugShowAll?: boolean,
|
||||
): Promise<
|
||||
Array<{
|
||||
name: string;
|
||||
uri: string;
|
||||
size?: number;
|
||||
path: string;
|
||||
type: "file" | "folder";
|
||||
}>
|
||||
>;
|
||||
|
||||
/**
|
||||
* Debug method to check what's actually in the TimeSafari directory
|
||||
* This helps identify if the directory exists but is empty or has permission issues
|
||||
* @returns Promise resolving to debug information about the TimeSafari directory
|
||||
*/
|
||||
debugTimeSafariDirectory(): Promise<string>;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
*
|
||||
* Supported Routes:
|
||||
* - user-profile: View user profile
|
||||
* - project: View project details
|
||||
* - project-details: View project details
|
||||
* - onboard-meeting-setup: Setup onboarding meeting
|
||||
* - invite-one-accept: Accept invitation
|
||||
* - contact-import: Import contacts
|
||||
@@ -81,16 +81,18 @@ export class DeepLinkHandler {
|
||||
string,
|
||||
{ name: string; paramKey?: string }
|
||||
> = {
|
||||
claim: { name: "claim" },
|
||||
"claim-add-raw": { name: "claim-add-raw" },
|
||||
"claim-cert": { name: "claim-cert" },
|
||||
"confirm-gift": { name: "confirm-gift" },
|
||||
did: { name: "did", paramKey: "did" },
|
||||
"invite-one-accept": { name: "invite-one-accept", paramKey: "jwt" },
|
||||
"onboard-meeting-members": { name: "onboard-meeting-members" },
|
||||
"onboard-meeting-setup": { name: "onboard-meeting-setup" },
|
||||
project: { name: "project" },
|
||||
"user-profile": { name: "user-profile" },
|
||||
"project-details": { name: "project-details" },
|
||||
"onboard-meeting-setup": { name: "onboard-meeting-setup" },
|
||||
"invite-one-accept": { name: "invite-one-accept" },
|
||||
"contact-import": { name: "contact-import" },
|
||||
"confirm-gift": { name: "confirm-gift" },
|
||||
claim: { name: "claim" },
|
||||
"claim-cert": { name: "claim-cert" },
|
||||
"claim-add-raw": { name: "claim-add-raw" },
|
||||
"contact-edit": { name: "contact-edit", paramKey: "did" },
|
||||
contacts: { name: "contacts" },
|
||||
did: { name: "did", paramKey: "did" },
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,150 +1,60 @@
|
||||
/**
|
||||
* Manage database migrations as people upgrade their app over time
|
||||
*/
|
||||
|
||||
import { logger } from "../utils/logger";
|
||||
|
||||
/**
|
||||
* Migration interface for database schema migrations
|
||||
*/
|
||||
interface Migration {
|
||||
name: string;
|
||||
sql: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Migration registry to store and manage database migrations
|
||||
*/
|
||||
class MigrationRegistry {
|
||||
export class MigrationService {
|
||||
private static instance: MigrationService;
|
||||
private migrations: Migration[] = [];
|
||||
|
||||
/**
|
||||
* Register a migration with the registry
|
||||
*
|
||||
* @param migration - The migration to register
|
||||
*/
|
||||
registerMigration(migration: Migration): void {
|
||||
private constructor() {}
|
||||
|
||||
static getInstance(): MigrationService {
|
||||
if (!MigrationService.instance) {
|
||||
MigrationService.instance = new MigrationService();
|
||||
}
|
||||
return MigrationService.instance;
|
||||
}
|
||||
|
||||
registerMigration(migration: Migration) {
|
||||
this.migrations.push(migration);
|
||||
logger.info(`[MigrationService] Registered migration: ${migration.name}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered migrations
|
||||
*
|
||||
* @returns Array of registered migrations
|
||||
* @param sqlExec - A function that executes a SQL statement and returns some update result
|
||||
* @param sqlQuery - A function that executes a SQL query and returns the result in some format
|
||||
* @param extractMigrationNames - A function that extracts the names (string array) from a "select name from migrations" query
|
||||
*/
|
||||
getMigrations(): Migration[] {
|
||||
return this.migrations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all registered migrations
|
||||
*/
|
||||
clearMigrations(): void {
|
||||
this.migrations = [];
|
||||
logger.info("[MigrationService] Cleared all registered migrations");
|
||||
}
|
||||
}
|
||||
|
||||
// Create a singleton instance of the migration registry
|
||||
const migrationRegistry = new MigrationRegistry();
|
||||
|
||||
/**
|
||||
* Register a migration with the migration service
|
||||
*
|
||||
* This function is used by the migration system to register database
|
||||
* schema migrations that need to be applied to the database.
|
||||
*
|
||||
* @param migration - The migration to register
|
||||
*/
|
||||
export function registerMigration(migration: Migration): void {
|
||||
migrationRegistry.registerMigration(migration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run all registered migrations against the database
|
||||
*
|
||||
* This function executes all registered migrations in order, checking
|
||||
* which ones have already been applied to avoid duplicate execution.
|
||||
* It creates a migrations table if it doesn't exist to track applied
|
||||
* migrations.
|
||||
*
|
||||
* @param sqlExec - Function to execute SQL statements
|
||||
* @param sqlQuery - Function to query SQL data
|
||||
* @param extractMigrationNames - Function to extract migration names from query results
|
||||
* @returns Promise that resolves when all migrations are complete
|
||||
*/
|
||||
export async function runMigrations<T>(
|
||||
sqlExec: (sql: string, params?: unknown[]) => Promise<unknown>,
|
||||
sqlQuery: (sql: string, params?: unknown[]) => Promise<T>,
|
||||
extractMigrationNames: (result: T) => Set<string>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
async runMigrations<T>(
|
||||
// note that this does not take parameters because the Capacitor SQLite 'execute' is different
|
||||
sqlExec: (sql: string) => Promise<unknown>,
|
||||
sqlQuery: (sql: string) => Promise<T>,
|
||||
extractMigrationNames: (result: T) => Set<string>,
|
||||
): Promise<void> {
|
||||
// Create migrations table if it doesn't exist
|
||||
await sqlExec(`
|
||||
CREATE TABLE IF NOT EXISTS migrations (
|
||||
name TEXT PRIMARY KEY,
|
||||
applied_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`);
|
||||
|
||||
// Get list of already applied migrations
|
||||
const appliedMigrationsResult = await sqlQuery(
|
||||
"SELECT name FROM migrations",
|
||||
);
|
||||
const appliedMigrations = extractMigrationNames(appliedMigrationsResult);
|
||||
// Get list of executed migrations
|
||||
const result1: T = await sqlQuery("SELECT name FROM migrations;");
|
||||
const executedMigrations = extractMigrationNames(result1);
|
||||
|
||||
logger.info(
|
||||
`[MigrationService] Found ${appliedMigrations.size} applied migrations`,
|
||||
);
|
||||
|
||||
// Get all registered migrations
|
||||
const migrations = migrationRegistry.getMigrations();
|
||||
|
||||
if (migrations.length === 0) {
|
||||
logger.warn("[MigrationService] No migrations registered");
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`[MigrationService] Running ${migrations.length} registered migrations`,
|
||||
);
|
||||
|
||||
// Run each migration that hasn't been applied yet
|
||||
for (const migration of migrations) {
|
||||
if (appliedMigrations.has(migration.name)) {
|
||||
logger.info(
|
||||
`[MigrationService] Skipping already applied migration: ${migration.name}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
logger.info(`[MigrationService] Applying migration: ${migration.name}`);
|
||||
|
||||
try {
|
||||
// Execute the migration SQL
|
||||
// Run pending migrations in order
|
||||
for (const migration of this.migrations) {
|
||||
if (!executedMigrations.has(migration.name)) {
|
||||
await sqlExec(migration.sql);
|
||||
|
||||
// Record that the migration was applied
|
||||
await sqlExec("INSERT INTO migrations (name) VALUES (?)", [
|
||||
migration.name,
|
||||
]);
|
||||
|
||||
logger.info(
|
||||
`[MigrationService] Successfully applied migration: ${migration.name}`,
|
||||
await sqlExec(
|
||||
`INSERT INTO migrations (name) VALUES ('${migration.name}')`,
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[MigrationService] Failed to apply migration ${migration.name}:`,
|
||||
error,
|
||||
);
|
||||
throw new Error(`Migration ${migration.name} failed: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("[MigrationService] All migrations completed successfully");
|
||||
} catch (error) {
|
||||
logger.error("[MigrationService] Migration process failed:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export default MigrationService.getInstance();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -205,6 +205,7 @@ export class ElectronPlatformService implements PlatformService {
|
||||
isIOS: false,
|
||||
hasFileDownload: false, // Not implemented yet
|
||||
needsFileHandlingInstructions: false,
|
||||
isNativeApp: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -234,11 +235,32 @@ export class ElectronPlatformService implements PlatformService {
|
||||
* Writes content to a file and opens the system share dialog.
|
||||
* @param _fileName - Name of the file to create
|
||||
* @param _content - Content to write to the file
|
||||
* @param _options - Options for file saving behavior
|
||||
* @throws Error with "Not implemented" message
|
||||
* @todo Implement using Electron's dialog and file system APIs
|
||||
*/
|
||||
async writeAndShareFile(_fileName: string, _content: string): Promise<void> {
|
||||
throw new Error("Not implemented");
|
||||
async writeAndShareFile(
|
||||
_fileName: string,
|
||||
_content: string,
|
||||
_options?: {
|
||||
allowLocationSelection?: boolean;
|
||||
saveToDownloads?: boolean;
|
||||
saveToPrivateStorage?: boolean;
|
||||
mimeType?: string;
|
||||
showShareDialog?: boolean;
|
||||
showLocationSelectionDialog?: boolean;
|
||||
},
|
||||
): Promise<{
|
||||
saved: boolean;
|
||||
uri?: string;
|
||||
shared: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
return {
|
||||
saved: false,
|
||||
shared: false,
|
||||
error: "Not implemented in Electron platform",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -284,6 +306,17 @@ export class ElectronPlatformService implements PlatformService {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* Should rotate the camera between front and back cameras.
|
||||
* @returns Promise that resolves when the camera is rotated
|
||||
* @throws Error with "Not implemented" message
|
||||
* @todo Implement camera rotation using Electron's media APIs
|
||||
*/
|
||||
async rotateCamera(): Promise<void> {
|
||||
logger.error("rotateCamera not implemented in Electron platform");
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* Should handle deep link URLs for the desktop application.
|
||||
* @param _url - The deep link URL to handle
|
||||
@@ -345,4 +378,173 @@ export class ElectronPlatformService implements PlatformService {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the file sharing functionality.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testFileSharing(): Promise<string> {
|
||||
return "File sharing not available in Electron platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests saving a file without showing the share dialog.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testFileSaveOnly(): Promise<string> {
|
||||
return "File save only not available in Electron platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the location selection functionality using the file picker.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testLocationSelection(): Promise<string> {
|
||||
return "Location selection not available in Electron platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests location selection without showing the dialog (restores original behavior).
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testLocationSelectionSilent(): Promise<string> {
|
||||
return "Location selection not available in Electron platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests listing user-accessible files saved by the app.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testListUserFiles(): Promise<string> {
|
||||
return "File listing not available in Electron platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests listing backup files specifically saved by the app.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testBackupFiles(): Promise<string> {
|
||||
return "Backup file listing not available in Electron platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests opening the backup directory in the device's file explorer.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testOpenBackupDirectory(): Promise<string> {
|
||||
return "Directory access not available in Electron platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists user-accessible files saved by the app.
|
||||
* Not implemented in Electron platform.
|
||||
* @returns Promise resolving to empty array
|
||||
*/
|
||||
async listUserAccessibleFiles(): Promise<
|
||||
Array<{ name: string; uri: string; size?: number }>
|
||||
> {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists backup files specifically saved by the app.
|
||||
* Not implemented for Electron platform.
|
||||
* @returns Promise resolving to empty array
|
||||
*/
|
||||
async listBackupFiles(): Promise<
|
||||
Array<{
|
||||
name: string;
|
||||
uri: string;
|
||||
size?: number;
|
||||
type: "contacts" | "seed" | "other";
|
||||
path?: string;
|
||||
}>
|
||||
> {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a file in the device's default file viewer/app.
|
||||
* Not implemented in Electron platform.
|
||||
* @param _fileUri - URI of the file to open
|
||||
* @param _fileName - Name of the file (for display purposes)
|
||||
* @returns Promise resolving to error status
|
||||
*/
|
||||
async openFile(
|
||||
_fileUri: string,
|
||||
_fileName: string,
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
return {
|
||||
success: false,
|
||||
error: "File opening not implemented in Electron platform",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the directory containing backup files in the device's file explorer.
|
||||
* Not implemented in Electron platform.
|
||||
* @returns Promise resolving to error status
|
||||
*/
|
||||
async openBackupDirectory(): Promise<{ success: boolean; error?: string }> {
|
||||
return {
|
||||
success: false,
|
||||
error: "Directory access not implemented in Electron platform",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists files and folders in a specific directory for directory browsing.
|
||||
* Not implemented for Electron platform.
|
||||
* @returns Promise resolving to empty array
|
||||
*/
|
||||
async listFilesInDirectory(
|
||||
_path: string,
|
||||
_debugShowAll?: boolean,
|
||||
): Promise<
|
||||
Array<{
|
||||
name: string;
|
||||
uri: string;
|
||||
size?: number;
|
||||
path: string;
|
||||
type: "file" | "folder";
|
||||
}>
|
||||
> {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug method to check what's actually in the TimeSafari directory.
|
||||
* Not implemented for Electron platform.
|
||||
* @returns Promise resolving to debug information
|
||||
*/
|
||||
async debugTimeSafariDirectory(): Promise<string> {
|
||||
return "Electron platform does not support file system access for debugging TimeSafari directory.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a test backup file to verify file writing and reading functionality.
|
||||
* Not implemented for Electron platform.
|
||||
* @returns Promise resolving to error status
|
||||
*/
|
||||
async createTestBackupFile(): Promise<{
|
||||
success: boolean;
|
||||
fileName?: string;
|
||||
uri?: string;
|
||||
error?: string;
|
||||
}> {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
"Electron platform does not support file system access for creating test backup files.",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method to try different directory contexts and see what files are available.
|
||||
* Not implemented for Electron platform.
|
||||
* @returns Promise resolving to debug information
|
||||
*/
|
||||
async testDirectoryContexts(): Promise<string> {
|
||||
return "Electron platform does not support file system access for testing directory contexts.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ export class PyWebViewPlatformService implements PlatformService {
|
||||
isIOS: false,
|
||||
hasFileDownload: false, // Not implemented yet
|
||||
needsFileHandlingInstructions: false,
|
||||
isNativeApp: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -122,14 +123,211 @@ export class PyWebViewPlatformService implements PlatformService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Should write and share a file using the Python backend.
|
||||
* @param _fileName - Name of the file to write and share
|
||||
* @param _content - Content to write to the file
|
||||
* @throws Error with "Not implemented" message
|
||||
* @todo Implement file writing and sharing through pywebview's Python-JavaScript bridge
|
||||
* Writes content to a file at the specified path and shares it.
|
||||
* Not implemented in PyWebView platform.
|
||||
* @param _fileName - The filename of the file to write
|
||||
* @param _content - The content to write to the file
|
||||
* @param _options - Optional parameters for file saving behavior
|
||||
* @returns Promise that resolves to save/share result
|
||||
*/
|
||||
async writeAndShareFile(_fileName: string, _content: string): Promise<void> {
|
||||
logger.error("writeAndShareFile not implemented in PyWebView platform");
|
||||
throw new Error("Not implemented");
|
||||
async writeAndShareFile(
|
||||
_fileName: string,
|
||||
_content: string,
|
||||
_options?: {
|
||||
allowLocationSelection?: boolean;
|
||||
saveToDownloads?: boolean;
|
||||
saveToPrivateStorage?: boolean;
|
||||
mimeType?: string;
|
||||
showShareDialog?: boolean;
|
||||
showLocationSelectionDialog?: boolean;
|
||||
},
|
||||
): Promise<{
|
||||
saved: boolean;
|
||||
uri?: string;
|
||||
shared: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
return {
|
||||
saved: false,
|
||||
shared: false,
|
||||
error: "File sharing not implemented in PyWebView platform",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists user-accessible files saved by the app.
|
||||
* Not implemented in PyWebView platform.
|
||||
* @returns Promise resolving to empty array
|
||||
*/
|
||||
async listUserAccessibleFiles(): Promise<
|
||||
Array<{ name: string; uri: string; size?: number }>
|
||||
> {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists backup files specifically saved by the app.
|
||||
* Not implemented for PyWebView platform.
|
||||
* @returns Promise resolving to empty array
|
||||
*/
|
||||
async listBackupFiles(): Promise<
|
||||
Array<{
|
||||
name: string;
|
||||
uri: string;
|
||||
size?: number;
|
||||
type: "contacts" | "seed" | "other";
|
||||
path?: string;
|
||||
}>
|
||||
> {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a file in the device's default file viewer/app.
|
||||
* Not implemented in PyWebView platform.
|
||||
* @param _fileUri - URI of the file to open
|
||||
* @param _fileName - Name of the file (for display purposes)
|
||||
* @returns Promise resolving to error status
|
||||
*/
|
||||
async openFile(
|
||||
_fileUri: string,
|
||||
_fileName: string,
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
return {
|
||||
success: false,
|
||||
error: "File opening not implemented in PyWebView platform",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the directory containing backup files in the device's file explorer.
|
||||
* Not implemented in PyWebView platform.
|
||||
* @returns Promise resolving to error status
|
||||
*/
|
||||
async openBackupDirectory(): Promise<{ success: boolean; error?: string }> {
|
||||
return {
|
||||
success: false,
|
||||
error: "Directory access not implemented in PyWebView platform",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests listing user-accessible files saved by the app.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testListUserFiles(): Promise<string> {
|
||||
return "File listing not available in PyWebView platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests listing backup files specifically saved by the app.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testBackupFiles(): Promise<string> {
|
||||
return "Backup file listing not available in PyWebView platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests opening the backup directory in the device's file explorer.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testOpenBackupDirectory(): Promise<string> {
|
||||
return "Directory access not available in PyWebView platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the file sharing functionality.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testFileSharing(): Promise<string> {
|
||||
return "File sharing not available in PyWebView platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests saving a file without showing the share dialog.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testFileSaveOnly(): Promise<string> {
|
||||
return "File saving not available in PyWebView platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the location selection functionality.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testLocationSelection(): Promise<string> {
|
||||
return "Location selection not available in PyWebView platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests location selection without showing the dialog.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testLocationSelectionSilent(): Promise<string> {
|
||||
return "Silent location selection not available in PyWebView platform - not implemented";
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates the camera between front and back.
|
||||
* Not implemented in PyWebView platform.
|
||||
*/
|
||||
async rotateCamera(): Promise<void> {
|
||||
// Not implemented
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists files and folders in a specific directory for directory browsing.
|
||||
* Not implemented for PyWebView platform.
|
||||
* @returns Promise resolving to empty array
|
||||
*/
|
||||
async listFilesInDirectory(
|
||||
_path: string,
|
||||
_debugShowAll?: boolean,
|
||||
): Promise<
|
||||
Array<{
|
||||
name: string;
|
||||
uri: string;
|
||||
size?: number;
|
||||
path: string;
|
||||
type: "file" | "folder";
|
||||
}>
|
||||
> {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug method to check what's actually in the TimeSafari directory.
|
||||
* Not implemented for PyWebView platform.
|
||||
* @returns Promise resolving to debug information
|
||||
*/
|
||||
async debugTimeSafariDirectory(): Promise<string> {
|
||||
return "PyWebView platform does not support file system access for debugging TimeSafari directory.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a test backup file to verify file writing and reading functionality.
|
||||
* Not implemented for PyWebView platform.
|
||||
* @returns Promise resolving to error status
|
||||
*/
|
||||
async createTestBackupFile(): Promise<{
|
||||
success: boolean;
|
||||
fileName?: string;
|
||||
uri?: string;
|
||||
error?: string;
|
||||
}> {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
"PyWebView platform does not support file system access for creating test backup files.",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method to try different directory contexts and see what files are available.
|
||||
* Not implemented for PyWebView platform.
|
||||
* @returns Promise resolving to debug information
|
||||
*/
|
||||
async testDirectoryContexts(): Promise<string> {
|
||||
return "PyWebView platform does not support file system access for testing directory contexts.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
PlatformService,
|
||||
PlatformCapabilities,
|
||||
} from "../PlatformService";
|
||||
import { logger } from "../../utils/logger";
|
||||
import { logger, getTimestampForFilename } from "../../utils/logger";
|
||||
import { QueryExecResult } from "@/interfaces/database";
|
||||
import databaseService from "../AbsurdSqlDatabaseService";
|
||||
|
||||
@@ -29,10 +29,14 @@ export class WebPlatformService implements PlatformService {
|
||||
return {
|
||||
hasFileSystem: false,
|
||||
hasCamera: true, // Through file input with capture
|
||||
isMobile: /iPhone|iPad|iPod|Android/i.test(navigator.userAgent),
|
||||
isMobile:
|
||||
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
|
||||
navigator.userAgent,
|
||||
),
|
||||
isIOS: /iPad|iPhone|iPod/.test(navigator.userAgent),
|
||||
hasFileDownload: true,
|
||||
needsFileHandlingInstructions: false,
|
||||
isNativeApp: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -190,7 +194,7 @@ export class WebPlatformService implements PlatformService {
|
||||
if (blob) {
|
||||
resolve({
|
||||
blob,
|
||||
fileName: `photo_${Date.now()}.jpg`,
|
||||
fileName: `photo-${getTimestampForFilename()}.jpg`,
|
||||
});
|
||||
} else {
|
||||
reject(new Error("Failed to capture image from webcam"));
|
||||
@@ -356,10 +360,31 @@ export class WebPlatformService implements PlatformService {
|
||||
* Not supported in web platform.
|
||||
* @param _fileName - Unused fileName parameter
|
||||
* @param _content - Unused content parameter
|
||||
* @throws Error indicating file system access is not available
|
||||
* @param _options - Unused options parameter
|
||||
* @returns Promise that resolves to a failure result
|
||||
*/
|
||||
async writeAndShareFile(_fileName: string, _content: string): Promise<void> {
|
||||
throw new Error("File system access not available in web platform");
|
||||
async writeAndShareFile(
|
||||
_fileName: string,
|
||||
_content: string,
|
||||
_options?: {
|
||||
allowLocationSelection?: boolean;
|
||||
saveToDownloads?: boolean;
|
||||
saveToPrivateStorage?: boolean;
|
||||
mimeType?: string;
|
||||
showShareDialog?: boolean;
|
||||
showLocationSelectionDialog?: boolean;
|
||||
},
|
||||
): Promise<{
|
||||
saved: boolean;
|
||||
uri?: string;
|
||||
shared: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
return {
|
||||
saved: false,
|
||||
shared: false,
|
||||
error: "File system access not available in web platform",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -390,4 +415,183 @@ export class WebPlatformService implements PlatformService {
|
||||
.query(sql, params)
|
||||
.then((result: QueryExecResult[]) => result[0]?.values[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the file sharing functionality.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testFileSharing(): Promise<string> {
|
||||
return "File sharing not available in web platform - use download instead";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests saving a file without showing the share dialog.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testFileSaveOnly(): Promise<string> {
|
||||
return "File saving not available in web platform - use download instead";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the location selection functionality using the file picker.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testLocationSelection(): Promise<string> {
|
||||
return "Location selection not available in web platform - use download instead";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests location selection without showing the dialog (restores original behavior).
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testLocationSelectionSilent(): Promise<string> {
|
||||
return "Location selection not available in web platform - use download instead";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests listing user-accessible files saved by the app.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testListUserFiles(): Promise<string> {
|
||||
return "File listing not available in web platform - files are downloaded directly";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests listing backup files specifically saved by the app.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testBackupFiles(): Promise<string> {
|
||||
return "Backup file listing not available in web platform - files are downloaded directly";
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests opening the backup directory in the device's file explorer.
|
||||
* @returns Promise resolving to a test result message
|
||||
*/
|
||||
async testOpenBackupDirectory(): Promise<string> {
|
||||
return "Directory access not available in web platform - files are downloaded directly";
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists user-accessible files saved by the app.
|
||||
* Not supported in web platform.
|
||||
* @returns Promise resolving to empty array
|
||||
*/
|
||||
async listUserAccessibleFiles(): Promise<
|
||||
Array<{ name: string; uri: string; size?: number }>
|
||||
> {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists backup files specifically saved by the app.
|
||||
* Not supported in web platform.
|
||||
* @returns Promise resolving to empty array
|
||||
*/
|
||||
async listBackupFiles(): Promise<
|
||||
Array<{
|
||||
name: string;
|
||||
uri: string;
|
||||
size?: number;
|
||||
type: "contacts" | "seed" | "other";
|
||||
path?: string;
|
||||
}>
|
||||
> {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a file in the device's default file viewer/app.
|
||||
* Not supported in web platform.
|
||||
* @param _fileUri - URI of the file to open
|
||||
* @param _fileName - Name of the file (for display purposes)
|
||||
* @returns Promise resolving to error status
|
||||
*/
|
||||
async openFile(
|
||||
_fileUri: string,
|
||||
_fileName: string,
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
return {
|
||||
success: false,
|
||||
error: "File opening not available in web platform",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the directory containing backup files in the device's file explorer.
|
||||
* Not supported in web platform.
|
||||
* @returns Promise resolving to error status
|
||||
*/
|
||||
async openBackupDirectory(): Promise<{ success: boolean; error?: string }> {
|
||||
return {
|
||||
success: false,
|
||||
error: "Directory access not available in web platform",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates the camera between front and back cameras.
|
||||
* Not supported in web platform.
|
||||
* @returns Promise that resolves immediately
|
||||
*/
|
||||
async rotateCamera(): Promise<void> {
|
||||
// Not supported in web platform
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists files and folders in a specific directory for directory browsing.
|
||||
* Not supported in web platform.
|
||||
* @returns Promise resolving to empty array
|
||||
*/
|
||||
async listFilesInDirectory(
|
||||
_path: string,
|
||||
_debugShowAll?: boolean,
|
||||
): Promise<
|
||||
Array<{
|
||||
name: string;
|
||||
uri: string;
|
||||
size?: number;
|
||||
path: string;
|
||||
type: "file" | "folder";
|
||||
}>
|
||||
> {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug method to check what's actually in the TimeSafari directory.
|
||||
* Not supported in web platform.
|
||||
* @returns Promise resolving to debug information
|
||||
*/
|
||||
async debugTimeSafariDirectory(): Promise<string> {
|
||||
return "Web platform does not support file system access for debugging TimeSafari directory.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a test backup file to verify file writing and reading functionality.
|
||||
* Not supported in web platform.
|
||||
* @returns Promise resolving to error status
|
||||
*/
|
||||
async createTestBackupFile(): Promise<{
|
||||
success: boolean;
|
||||
fileName?: string;
|
||||
uri?: string;
|
||||
error?: string;
|
||||
}> {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
"Web platform does not support file system access for creating test backup files.",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method to try different directory contexts and see what files are available.
|
||||
* Not supported in web platform.
|
||||
* @returns Promise resolving to debug information
|
||||
*/
|
||||
async testDirectoryContexts(): Promise<string> {
|
||||
return "Web platform does not support file system access for testing directory contexts.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,3 +79,22 @@ if (typeof module !== "undefined" && module.exports) {
|
||||
|
||||
// Add default export for ESM
|
||||
export default { logger };
|
||||
|
||||
/**
|
||||
* Formats current timestamp for use in filenames.
|
||||
* Returns ISO string with colons and periods replaced with hyphens, truncated to seconds.
|
||||
* Format: 2024-01-15T14-30-45
|
||||
* @returns Formatted timestamp string safe for filenames
|
||||
*/
|
||||
export function getTimestampForFilename(): string {
|
||||
return new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats current timestamp for use in filenames with date only.
|
||||
* Format: 2024-01-15
|
||||
* @returns Date-only timestamp string safe for filenames
|
||||
*/
|
||||
export function getDateForFilename(): string {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
@@ -198,7 +198,7 @@ export default class ClaimAddRawView extends Vue {
|
||||
this.apiServer,
|
||||
this.axios,
|
||||
);
|
||||
if (result.success) {
|
||||
if (result.type === "success") {
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
|
||||
@@ -46,7 +46,6 @@
|
||||
</h2>
|
||||
<div class="flex justify-center w-full">
|
||||
<router-link
|
||||
v-if="veriClaim.id"
|
||||
:to="'/claim-cert/' + encodeURIComponent(veriClaim.id)"
|
||||
class="text-blue-500 mt-2"
|
||||
title="Printable Certificate"
|
||||
@@ -293,17 +292,12 @@
|
||||
<div class="text-sm">
|
||||
{{ didInfo(confirmerId) }}
|
||||
<span v-if="!serverUtil.isEmptyOrHiddenDid(confirmerId)">
|
||||
<router-link
|
||||
:to="{
|
||||
path: '/did/' + encodeURIComponent(confirmerId),
|
||||
}"
|
||||
class="text-blue-500"
|
||||
>
|
||||
<a :href="`/did/${confirmerId}`" class="text-blue-500">
|
||||
<font-awesome
|
||||
icon="arrow-up-right-from-square"
|
||||
class="fa-fw"
|
||||
/>
|
||||
</router-link>
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -335,17 +329,12 @@
|
||||
<div class="text-sm">
|
||||
{{ didInfo(confsVisibleTo) }}
|
||||
<span v-if="!serverUtil.isEmptyOrHiddenDid(confsVisibleTo)">
|
||||
<router-link
|
||||
:to="{
|
||||
path: '/did/' + encodeURIComponent(confsVisibleTo),
|
||||
}"
|
||||
class="text-blue-500"
|
||||
>
|
||||
<a :href="`/did/${confsVisibleTo}`" class="text-blue-500">
|
||||
<font-awesome
|
||||
icon="arrow-up-right-from-square"
|
||||
class="fa-fw"
|
||||
/>
|
||||
</router-link>
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -454,17 +443,12 @@
|
||||
<span>
|
||||
{{ didInfo(visDid) }}
|
||||
<span v-if="!serverUtil.isEmptyOrHiddenDid(visDid)">
|
||||
<router-link
|
||||
:to="{
|
||||
path: '/did/' + encodeURIComponent(visDid),
|
||||
}"
|
||||
class="text-blue-500"
|
||||
>
|
||||
<a :href="`/did/${visDid}`" class="text-blue-500">
|
||||
<font-awesome
|
||||
icon="arrow-up-right-from-square"
|
||||
class="fa-fw"
|
||||
/>
|
||||
</router-link>
|
||||
</a>
|
||||
</span>
|
||||
<span v-if="veriClaim.publicUrls?.[visDid]"
|
||||
>, found at <a
|
||||
@@ -941,7 +925,7 @@ export default class ClaimView extends Vue {
|
||||
this.apiServer,
|
||||
this.axios,
|
||||
);
|
||||
if (result.success) {
|
||||
if (result.type === "success") {
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
|
||||
@@ -407,14 +407,14 @@
|
||||
</a>
|
||||
</div>
|
||||
<div class="mt-2 ml-2">
|
||||
<router-link
|
||||
<a
|
||||
v-if="isRegistered"
|
||||
class="text-blue-500 cursor-pointer"
|
||||
:to="urlForNewGive"
|
||||
:href="urlForNewGive"
|
||||
>
|
||||
<font-awesome icon="file-lines" />
|
||||
Record a Give Similar to the Original
|
||||
</router-link>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -831,7 +831,7 @@ export default class ConfirmGiftView extends Vue {
|
||||
this.apiServer,
|
||||
this.axios,
|
||||
);
|
||||
if (result.success) {
|
||||
if (result.type === "success") {
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
|
||||
@@ -566,7 +566,7 @@ export default class ContactImportView extends Vue {
|
||||
this.checkingImports = true;
|
||||
|
||||
try {
|
||||
const jwt: string = getContactJwtFromJwtUrl(jwtInput) || "";
|
||||
const jwt: string = getContactJwtFromJwtUrl(jwtInput);
|
||||
const payload = decodeEndorserJwt(jwt).payload;
|
||||
|
||||
if (Array.isArray(payload.contacts)) {
|
||||
|
||||
@@ -104,7 +104,6 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Buffer } from "buffer/";
|
||||
import QRCodeVue3 from "qr-code-generator-vue3";
|
||||
import { Component, Vue } from "vue-facing-decorator";
|
||||
import { Router } from "vue-router";
|
||||
@@ -118,15 +117,11 @@ import { db } from "../db/index";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
import { getContactJwtFromJwtUrl } from "../libs/crypto";
|
||||
import { decodeEndorserJwt, ETHR_DID_PREFIX } from "../libs/crypto/vc";
|
||||
import * as libsUtil from "../libs/util";
|
||||
import { retrieveSettingsForActiveAccount } from "../db/index";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import {
|
||||
CONTACT_CSV_HEADER,
|
||||
CONTACT_IMPORT_CONFIRM_URL_PATH_TIME_SAFARI,
|
||||
setVisibilityUtil,
|
||||
} from "../libs/endorserServer";
|
||||
import { setVisibilityUtil } from "../libs/endorserServer";
|
||||
import UserNameDialog from "../components/UserNameDialog.vue";
|
||||
import { generateEndorserJwtUrlForAccount } from "../libs/endorserServer";
|
||||
import { retrieveAccountMetadata } from "../libs/util";
|
||||
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
import { parseJsonField } from "../db/databaseUtil";
|
||||
@@ -147,7 +142,7 @@ interface IUserNameDialog {
|
||||
UserNameDialog,
|
||||
},
|
||||
})
|
||||
export default class ContactQRScanFull extends Vue {
|
||||
export default class ContactQRScan extends Vue {
|
||||
$notify!: (notification: NotificationIface, timeout?: number) => void;
|
||||
$router!: Router;
|
||||
|
||||
@@ -156,7 +151,6 @@ export default class ContactQRScanFull extends Vue {
|
||||
activeDid = "";
|
||||
apiServer = "";
|
||||
givenName = "";
|
||||
isRegistered = false;
|
||||
qrValue = "";
|
||||
ETHR_DID_PREFIX = ETHR_DID_PREFIX;
|
||||
|
||||
@@ -178,21 +172,19 @@ export default class ContactQRScanFull extends Vue {
|
||||
this.activeDid = settings.activeDid || "";
|
||||
this.apiServer = settings.apiServer || "";
|
||||
this.givenName = settings.firstName || "";
|
||||
this.isRegistered = !!settings.isRegistered;
|
||||
|
||||
const account = await retrieveAccountMetadata(this.activeDid);
|
||||
if (account) {
|
||||
const name =
|
||||
(settings.firstName || "") +
|
||||
(settings.lastName ? ` ${settings.lastName}` : "");
|
||||
const publicKeyBase64 = Buffer.from(
|
||||
account.publicKeyHex,
|
||||
"hex",
|
||||
).toString("base64");
|
||||
this.qrValue =
|
||||
CONTACT_CSV_HEADER +
|
||||
"\n" +
|
||||
`"${name}",${account.did},${publicKeyBase64},false,${this.isRegistered}`;
|
||||
this.qrValue = await generateEndorserJwtUrlForAccount(
|
||||
account,
|
||||
!!settings.isRegistered,
|
||||
name,
|
||||
settings.profileImageUrl || "",
|
||||
false,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("Error initializing component:", {
|
||||
@@ -344,69 +336,57 @@ export default class ContactQRScanFull extends Vue {
|
||||
|
||||
logger.info("Processing QR code scan result:", rawValue);
|
||||
|
||||
let contact: Contact;
|
||||
if (rawValue.includes(CONTACT_IMPORT_CONFIRM_URL_PATH_TIME_SAFARI)) {
|
||||
// Extract JWT
|
||||
const jwt = getContactJwtFromJwtUrl(rawValue);
|
||||
if (!jwt) {
|
||||
logger.warn("Invalid QR code format - no JWT found in URL");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Invalid QR Code",
|
||||
text: "This QR code does not contain valid contact information. Scan a TimeSafari contact QR code.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Process JWT and contact info
|
||||
logger.info("Decoding JWT payload from QR code");
|
||||
const decodedJwt = await decodeEndorserJwt(jwt);
|
||||
if (!decodedJwt?.payload?.own) {
|
||||
logger.warn("Invalid JWT payload - missing 'own' field");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Invalid Contact Info",
|
||||
text: "The contact information is incomplete or invalid.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const contactInfo = decodedJwt.payload.own;
|
||||
const did = contactInfo.did || decodedJwt.payload.iss;
|
||||
if (!did) {
|
||||
logger.warn("Invalid contact info - missing DID");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Invalid Contact",
|
||||
text: "The contact DID is missing.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Create contact object
|
||||
contact = {
|
||||
did: did,
|
||||
name: contactInfo.name || "",
|
||||
publicKeyBase64: contactInfo.publicKeyBase64 || "",
|
||||
seesMe: contactInfo.seesMe || false,
|
||||
registered: contactInfo.registered || false,
|
||||
};
|
||||
} else if (rawValue.startsWith(CONTACT_CSV_HEADER)) {
|
||||
const lines = rawValue.split(/\n/);
|
||||
contact = libsUtil.csvLineToContact(lines[1]);
|
||||
} else {
|
||||
// Extract JWT
|
||||
const jwt = getContactJwtFromJwtUrl(rawValue);
|
||||
if (!jwt) {
|
||||
logger.warn("Invalid QR code format - no JWT found in URL");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Error",
|
||||
text: "Could not determine the type of contact info. Try again, or tap the QR code to copy it and send it to them.",
|
||||
title: "Invalid QR Code",
|
||||
text: "This QR code does not contain valid contact information. Please scan a TimeSafari contact QR code.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Process JWT and contact info
|
||||
logger.info("Decoding JWT payload from QR code");
|
||||
const decodedJwt = await decodeEndorserJwt(jwt);
|
||||
if (!decodedJwt?.payload?.own) {
|
||||
logger.warn("Invalid JWT payload - missing 'own' field");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Invalid Contact Info",
|
||||
text: "The contact information is incomplete or invalid.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const contactInfo = decodedJwt.payload.own;
|
||||
const did = contactInfo.did || decodedJwt.payload.iss;
|
||||
if (!did) {
|
||||
logger.warn("Invalid contact info - missing DID");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Invalid Contact",
|
||||
text: "The contact DID is missing.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Create contact object
|
||||
const contact = {
|
||||
did: did,
|
||||
name: contactInfo.name || "",
|
||||
email: contactInfo.email || "",
|
||||
phone: contactInfo.phone || "",
|
||||
company: contactInfo.company || "",
|
||||
title: contactInfo.title || "",
|
||||
notes: contactInfo.notes || "",
|
||||
};
|
||||
|
||||
// Add contact but keep scanning
|
||||
logger.info("Adding new contact to database:", {
|
||||
did: contact.did,
|
||||
@@ -488,7 +468,7 @@ export default class ContactQRScanFull extends Vue {
|
||||
title: "Contact Exists",
|
||||
text: "This contact has already been added to your list.",
|
||||
},
|
||||
5000,
|
||||
3000,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -159,7 +159,6 @@
|
||||
|
||||
<script lang="ts">
|
||||
import { AxiosError } from "axios";
|
||||
import { Buffer } from "buffer/";
|
||||
import QRCodeVue3 from "qr-code-generator-vue3";
|
||||
import { Component, Vue } from "vue-facing-decorator";
|
||||
import { useClipboard } from "@vueuse/core";
|
||||
@@ -175,13 +174,12 @@ import * as databaseUtil from "../db/databaseUtil";
|
||||
import { parseJsonField } from "../db/databaseUtil";
|
||||
import { getContactJwtFromJwtUrl } from "../libs/crypto";
|
||||
import {
|
||||
CONTACT_CSV_HEADER,
|
||||
CONTACT_IMPORT_CONFIRM_URL_PATH_TIME_SAFARI,
|
||||
generateEndorserJwtUrlForAccount,
|
||||
register,
|
||||
setVisibilityUtil,
|
||||
} from "../libs/endorserServer";
|
||||
import { decodeEndorserJwt, ETHR_DID_PREFIX } from "../libs/crypto/vc";
|
||||
import * as libsUtil from "../libs/util";
|
||||
import { retrieveAccountMetadata } from "../libs/util";
|
||||
import { Router } from "vue-router";
|
||||
import { logger } from "../utils/logger";
|
||||
import { QRScannerFactory } from "@/services/QRScanner/QRScannerFactory";
|
||||
@@ -254,19 +252,18 @@ export default class ContactQRScanShow extends Vue {
|
||||
!!settings.hideRegisterPromptOnNewContact;
|
||||
this.isRegistered = !!settings.isRegistered;
|
||||
|
||||
const account = await libsUtil.retrieveAccountMetadata(this.activeDid);
|
||||
const account = await retrieveAccountMetadata(this.activeDid);
|
||||
if (account) {
|
||||
const name =
|
||||
(settings.firstName || "") +
|
||||
(settings.lastName ? ` ${settings.lastName}` : "");
|
||||
const publicKeyBase64 = Buffer.from(
|
||||
account.publicKeyHex,
|
||||
"hex",
|
||||
).toString("base64");
|
||||
this.qrValue =
|
||||
CONTACT_CSV_HEADER +
|
||||
"\n" +
|
||||
`"${name}",${account.did},${publicKeyBase64},false,${this.isRegistered}`;
|
||||
this.qrValue = await generateEndorserJwtUrlForAccount(
|
||||
account,
|
||||
!!settings.isRegistered,
|
||||
name,
|
||||
settings.profileImageUrl || "",
|
||||
false,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("Error initializing component:", {
|
||||
@@ -277,7 +274,7 @@ export default class ContactQRScanShow extends Vue {
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Initialization Error",
|
||||
text: "Failed to initialize QR renderer or scanner. Please try again.",
|
||||
text: "Failed to initialize QR scanner. Please try again.",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -464,68 +461,53 @@ export default class ContactQRScanShow extends Vue {
|
||||
|
||||
logger.info("Processing QR code scan result:", rawValue);
|
||||
|
||||
let contact: Contact;
|
||||
if (rawValue.includes(CONTACT_IMPORT_CONFIRM_URL_PATH_TIME_SAFARI)) {
|
||||
const jwt = getContactJwtFromJwtUrl(rawValue);
|
||||
if (!jwt) {
|
||||
logger.warn("Invalid QR code format - no JWT found in URL");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Invalid QR Code",
|
||||
text: "This QR code does not contain valid contact information. Scan a TimeSafari contact QR code.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
logger.info("Decoding JWT payload from QR code");
|
||||
const decodedJwt = await decodeEndorserJwt(jwt);
|
||||
|
||||
// Process JWT and contact info
|
||||
if (!decodedJwt?.payload?.own) {
|
||||
logger.warn("Invalid JWT payload - missing 'own' field");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Invalid Contact Info",
|
||||
text: "The contact information is incomplete or invalid.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const contactInfo = decodedJwt.payload.own;
|
||||
const did = contactInfo.did || decodedJwt.payload.iss;
|
||||
if (!did) {
|
||||
logger.warn("Invalid contact info - missing DID");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Invalid Contact",
|
||||
text: "The contact DID is missing.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Create contact object
|
||||
contact = {
|
||||
did: did,
|
||||
name: contactInfo.name || "",
|
||||
publicKeyBase64: contactInfo.publicKeyBase64 || "",
|
||||
seesMe: contactInfo.seesMe || false,
|
||||
registered: contactInfo.registered || false,
|
||||
};
|
||||
} else if (rawValue.startsWith(CONTACT_CSV_HEADER)) {
|
||||
const lines = rawValue.split(/\n/);
|
||||
contact = libsUtil.csvLineToContact(lines[1]);
|
||||
} else {
|
||||
// Extract JWT
|
||||
const jwt = getContactJwtFromJwtUrl(rawValue);
|
||||
if (!jwt) {
|
||||
logger.warn("Invalid QR code format - no JWT found in URL");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Error",
|
||||
text: "Could not determine the type of contact info. Try again, or tap the QR code to copy it and send it to them.",
|
||||
title: "Invalid QR Code",
|
||||
text: "This QR code does not contain valid contact information. Please scan a TimeSafari contact QR code.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Process JWT and contact info
|
||||
logger.info("Decoding JWT payload from QR code");
|
||||
const decodedJwt = await decodeEndorserJwt(jwt);
|
||||
if (!decodedJwt?.payload?.own) {
|
||||
logger.warn("Invalid JWT payload - missing 'own' field");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Invalid Contact Info",
|
||||
text: "The contact information is incomplete or invalid.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const contactInfo = decodedJwt.payload.own;
|
||||
const did = contactInfo.did || decodedJwt.payload.iss;
|
||||
if (!did) {
|
||||
logger.warn("Invalid contact info - missing DID");
|
||||
this.$notify({
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Invalid Contact",
|
||||
text: "The contact DID is missing.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Create contact object
|
||||
const contact = {
|
||||
did: did,
|
||||
name: contactInfo.name || "",
|
||||
notes: contactInfo.notes || "",
|
||||
};
|
||||
|
||||
// Add contact but keep scanning
|
||||
logger.info("Adding new contact to database:", {
|
||||
did: contact.did,
|
||||
@@ -672,6 +654,7 @@ export default class ContactQRScanShow extends Vue {
|
||||
useClipboard()
|
||||
.copy(this.qrValue)
|
||||
.then(() => {
|
||||
// console.log("Contact URL:", this.qrValue);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
@@ -789,7 +772,7 @@ export default class ContactQRScanShow extends Vue {
|
||||
title: "Contact Exists",
|
||||
text: "This contact has already been added to your list.",
|
||||
},
|
||||
5000,
|
||||
3000,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -935,9 +935,45 @@ export default class ContactsView extends Vue {
|
||||
}
|
||||
|
||||
private async addContactFromEndorserMobileLine(
|
||||
lineRaw: string,
|
||||
line: string,
|
||||
): Promise<IndexableType> {
|
||||
const newContact = libsUtil.csvLineToContact(lineRaw);
|
||||
// Note that Endorser Mobile puts name first, then did, etc.
|
||||
let name = line;
|
||||
let did = "";
|
||||
let publicKeyInput, seesMe, registered;
|
||||
const commaPos1 = line.indexOf(",");
|
||||
if (commaPos1 > -1) {
|
||||
name = line.substring(0, commaPos1).trim();
|
||||
did = line.substring(commaPos1 + 1).trim();
|
||||
const commaPos2 = line.indexOf(",", commaPos1 + 1);
|
||||
if (commaPos2 > -1) {
|
||||
did = line.substring(commaPos1 + 1, commaPos2).trim();
|
||||
publicKeyInput = line.substring(commaPos2 + 1).trim();
|
||||
const commaPos3 = line.indexOf(",", commaPos2 + 1);
|
||||
if (commaPos3 > -1) {
|
||||
publicKeyInput = line.substring(commaPos2 + 1, commaPos3).trim();
|
||||
seesMe = line.substring(commaPos3 + 1).trim() == "true";
|
||||
const commaPos4 = line.indexOf(",", commaPos3 + 1);
|
||||
if (commaPos4 > -1) {
|
||||
seesMe = line.substring(commaPos3 + 1, commaPos4).trim() == "true";
|
||||
registered = line.substring(commaPos4 + 1).trim() == "true";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// help with potential mistakes while this sharing requires copy-and-paste
|
||||
let publicKeyBase64 = publicKeyInput;
|
||||
if (publicKeyBase64 && /^[0-9A-Fa-f]{66}$/i.test(publicKeyBase64)) {
|
||||
// it must be all hex (compressed public key), so convert
|
||||
publicKeyBase64 = Buffer.from(publicKeyBase64, "hex").toString("base64");
|
||||
}
|
||||
const newContact = {
|
||||
did,
|
||||
name,
|
||||
publicKeyBase64,
|
||||
seesMe,
|
||||
registered,
|
||||
};
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const { sql, params } = databaseUtil.generateInsertStatement(
|
||||
newContact as unknown as Record<string, unknown>,
|
||||
@@ -1179,6 +1215,7 @@ export default class ContactsView extends Vue {
|
||||
);
|
||||
if (result.success) {
|
||||
//contact.seesMe = visibility; // why doesn't it affect the UI from here?
|
||||
//console.log("Set result & seesMe", result, contact.seesMe, contact.did);
|
||||
if (showSuccessAlert) {
|
||||
this.$notify(
|
||||
{
|
||||
@@ -1394,6 +1431,10 @@ export default class ContactsView extends Vue {
|
||||
}
|
||||
return contact;
|
||||
});
|
||||
// console.log(
|
||||
// "Array of selected contacts:",
|
||||
// JSON.stringify(selectedContacts),
|
||||
// );
|
||||
const contactsJwt = await createEndorserJwtForDid(this.activeDid, {
|
||||
contacts: selectedContacts,
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -523,7 +523,9 @@ export default class DiscoverView extends Vue {
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (e: any) {
|
||||
logger.error("Error with search all: " + errorStringForLog(e));
|
||||
logger.error("Error with search all:", e);
|
||||
// this sometimes gives different information
|
||||
logger.error("Error with search all (error added): " + e);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
@@ -615,7 +617,7 @@ export default class DiscoverView extends Vue {
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (e: any) {
|
||||
logger.error("Error with search local: " + errorStringForLog(e));
|
||||
logger.error("Error with search local:", e);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
@@ -786,7 +788,7 @@ export default class DiscoverView extends Vue {
|
||||
const route = {
|
||||
path: this.isProjectsActive
|
||||
? "/project/" + encodeURIComponent(id)
|
||||
: "/user-profile/" + encodeURIComponent(id),
|
||||
: "/userProfile/" + encodeURIComponent(id),
|
||||
};
|
||||
this.$router.push(route);
|
||||
}
|
||||
|
||||
@@ -826,7 +826,7 @@ export default class GiftedDetails extends Vue {
|
||||
}
|
||||
|
||||
if (!result.success) {
|
||||
const errorMessage = result.error;
|
||||
const errorMessage = this.getGiveCreationErrorMessage(result);
|
||||
logger.error("Error with give creation result:", result);
|
||||
this.$notify(
|
||||
{
|
||||
@@ -899,6 +899,19 @@ export default class GiftedDetails extends Vue {
|
||||
|
||||
// Helper functions for readability
|
||||
|
||||
/**
|
||||
* @param result direct response eg. ErrorResult or SuccessResult (potentially with embedded "data")
|
||||
* @returns best guess at an error message
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
getGiveCreationErrorMessage(result: any) {
|
||||
return (
|
||||
result.error?.userMessage ||
|
||||
result.error?.error ||
|
||||
result.response?.data?.error?.message
|
||||
);
|
||||
}
|
||||
|
||||
explainData() {
|
||||
this.$notify(
|
||||
{
|
||||
|
||||
@@ -24,11 +24,11 @@
|
||||
<!-- eslint-disable prettier/prettier max-len -->
|
||||
<div>
|
||||
<p>
|
||||
This app focuses on raw gratitude, using it to build cool things together with your network.
|
||||
This app focuses on gifts & gratitude, using them to build cool things together with your network.
|
||||
</p>
|
||||
|
||||
<p class="ml-4">
|
||||
If you'd like to see the page-by-page help again,
|
||||
If you'd like to see the page-by-page help,
|
||||
<span
|
||||
class="text-blue-500 cursor-pointer"
|
||||
@click="unsetFinishedOnboarding()"
|
||||
@@ -37,16 +37,14 @@
|
||||
|
||||
<h2 class="text-xl font-semibold">What is the idea here?</h2>
|
||||
<p>
|
||||
We are building networks of people who want to grow good society from the ground up, using
|
||||
modern technology that connects people peer-to-peer.
|
||||
First of all, let's showcase gratitude: see what people have given, and recognize gifts
|
||||
you've seen. This is done in a way that leaves a permanent record -- one that provably
|
||||
came from you, and one that the recipient can prove they were mentioned.
|
||||
This can be personally gratifying, but it extends to broader work: volunteers get
|
||||
confirmation of activity, and they can selectively show off their contributions and
|
||||
network.
|
||||
This is a way to build trust and reputation. It's a way to build a network of people who
|
||||
are willing to help each other.
|
||||
We are building networks of people who want to grow good society from the ground up, using modern
|
||||
technology that connects people peer-to-peer.
|
||||
First of all, let's showcase gratitude: see what people have given, and recognize
|
||||
gifts you've seen. This is done in a way that leaves a permanent record -- one that
|
||||
came from you, and one that the recipient can prove it was for them. This can be
|
||||
personally gratifying, but it extends to broader work: volunteers get
|
||||
confirmation of activity, and they can selectively show off their contributions
|
||||
and network.
|
||||
</p>
|
||||
<p class="mt-2">
|
||||
With this, you highlight giving and you also offer help --
|
||||
@@ -557,6 +555,9 @@
|
||||
initiative.
|
||||
</p>
|
||||
|
||||
<h2 class="text-xl font-semibold">What app version is this?</h2>
|
||||
<p>{{ package.version }} ({{ commitHash }})</p>
|
||||
|
||||
<h2 class="text-xl font-semibold">
|
||||
I have other questions or feedback, like getting a new profile or removing my data or requesting an improvement.
|
||||
</h2>
|
||||
@@ -566,28 +567,6 @@
|
||||
>info@TimeSafari.app</a
|
||||
>
|
||||
</p>
|
||||
|
||||
<h2 class="text-xl font-semibold">What app version is this?</h2>
|
||||
<p>{{ package.version }} ({{ commitHash }})</p>
|
||||
|
||||
<div v-if="Capacitor.isNativePlatform()">
|
||||
<h2 class="text-xl font-semibold">
|
||||
Do I have the latest version?
|
||||
</h2>
|
||||
<p v-if="Capacitor.getPlatform() === 'ios'">
|
||||
<a href="https://apps.apple.com/us/app/time-safari/id6742664907" target="_blank" class="text-blue-500">
|
||||
Check the App Store.
|
||||
</a>
|
||||
</p>
|
||||
<p v-else-if="Capacitor.getPlatform() === 'android'">
|
||||
<a href="https://timesafari.app/app.apk" target="_blank" class="text-blue-500">
|
||||
Download the latest APK to see.
|
||||
</a>
|
||||
</p>
|
||||
<p v-else>
|
||||
Sorry, your platform of '{{ Capacitor.getPlatform() }}' is not recognized.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<!-- eslint enable -->
|
||||
</section>
|
||||
@@ -624,7 +603,6 @@ export default class HelpView extends Vue {
|
||||
showVerifiable = false;
|
||||
|
||||
APP_SERVER = APP_SERVER;
|
||||
Capacitor = Capacitor;
|
||||
|
||||
// Ideally, we put no functionality in here, especially in the setup,
|
||||
// because we never want this page to have a chance of throwing an error.
|
||||
|
||||
@@ -106,12 +106,12 @@ Raymer * @version 1.0.0 */
|
||||
</button>
|
||||
</div>
|
||||
<UserNameDialog ref="userNameDialog" />
|
||||
<div class="flex justify-end w-full">
|
||||
<div v-if="PASSKEYS_ENABLED" class="flex justify-end w-full">
|
||||
<router-link
|
||||
:to="{ name: 'start' }"
|
||||
class="block text-right text-md font-bold bg-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white mt-2 px-2 py-3 rounded-md"
|
||||
>
|
||||
See advanced options
|
||||
See all your options first
|
||||
</router-link>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1843,7 +1843,7 @@ export default class HomeView extends Vue {
|
||||
this.axios,
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
if (result.type === "success") {
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
|
||||
<div v-if="numAccounts == 1" class="mt-4">
|
||||
<input v-model="shouldErase" type="checkbox" class="mr-2" />
|
||||
<label>Erase previous identifiers.</label>
|
||||
<label>Erase the previous identifier.</label>
|
||||
</div>
|
||||
|
||||
<div v-if="isNotProdServer()" class="mt-4 text-blue-500">
|
||||
@@ -88,9 +88,17 @@ import { Router } from "vue-router";
|
||||
|
||||
import { AppString, NotificationIface, USE_DEXIE_DB } from "../constants/app";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import { retrieveSettingsForActiveAccount } from "../db/index";
|
||||
import { DEFAULT_ROOT_DERIVATION_PATH } from "../libs/crypto";
|
||||
import { retrieveAccountCount, importFromMnemonic } from "../libs/util";
|
||||
import {
|
||||
accountsDBPromise,
|
||||
retrieveSettingsForActiveAccount,
|
||||
} from "../db/index";
|
||||
import {
|
||||
DEFAULT_ROOT_DERIVATION_PATH,
|
||||
deriveAddress,
|
||||
newIdentifier,
|
||||
} from "../libs/crypto";
|
||||
import { retrieveAccountCount, saveNewIdentity } from "../libs/util";
|
||||
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
import { logger } from "../utils/logger";
|
||||
|
||||
@Component({
|
||||
@@ -107,9 +115,12 @@ export default class ImportAccountView extends Vue {
|
||||
$router!: Router;
|
||||
|
||||
apiServer = "";
|
||||
address = "";
|
||||
derivationPath = DEFAULT_ROOT_DERIVATION_PATH;
|
||||
mnemonic = "";
|
||||
numAccounts = 0;
|
||||
privateHex = "";
|
||||
publicHex = "";
|
||||
showAdvanced = false;
|
||||
shouldErase = false;
|
||||
|
||||
@@ -132,16 +143,33 @@ export default class ImportAccountView extends Vue {
|
||||
}
|
||||
|
||||
public async fromMnemonic() {
|
||||
const mne: string = this.mnemonic.trim().toLowerCase();
|
||||
try {
|
||||
await importFromMnemonic(
|
||||
this.mnemonic,
|
||||
[this.address, this.privateHex, this.publicHex] = deriveAddress(
|
||||
mne,
|
||||
this.derivationPath,
|
||||
this.shouldErase,
|
||||
);
|
||||
|
||||
const newId = newIdentifier(
|
||||
this.address,
|
||||
this.publicHex,
|
||||
this.privateHex,
|
||||
this.derivationPath,
|
||||
);
|
||||
|
||||
const accountsDB = await accountsDBPromise;
|
||||
if (this.shouldErase) {
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
await platformService.dbExec("DELETE FROM accounts");
|
||||
if (USE_DEXIE_DB) {
|
||||
await accountsDB.accounts.clear();
|
||||
}
|
||||
}
|
||||
await saveNewIdentity(newId, mne, this.derivationPath);
|
||||
this.$router.push({ name: "account" });
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (err: any) {
|
||||
logger.error("Error importing from mnemonic:", err);
|
||||
logger.error("Error saving mnemonic & updating settings:", err);
|
||||
if (err == "Error: invalid mnemonic") {
|
||||
this.$notify(
|
||||
{
|
||||
|
||||
@@ -83,7 +83,7 @@
|
||||
<span
|
||||
v-else
|
||||
class="text-center text-slate-500 cursor-pointer"
|
||||
:title="invite.inviteIdentifier"
|
||||
:title="inviteLink(invite.jwt)"
|
||||
@click="
|
||||
showInvite(
|
||||
invite.inviteIdentifier,
|
||||
@@ -324,7 +324,7 @@ export default class InviteOneView extends Vue {
|
||||
);
|
||||
await axios.post(
|
||||
this.apiServer + "/api/userUtil/invite",
|
||||
{ inviteJwt, notes, expiresAt },
|
||||
{ inviteIdentifier, inviteJwt, notes, expiresAt },
|
||||
{ headers },
|
||||
);
|
||||
const newInvite = {
|
||||
|
||||
@@ -52,24 +52,16 @@
|
||||
icon="user"
|
||||
class="fa-fw text-slate-400"
|
||||
></font-awesome>
|
||||
<span class="truncate inline-block max-w-[calc(100%-2rem)]">
|
||||
{{ issuerInfoObject?.displayName }}
|
||||
</span>
|
||||
<span class="inline-flex items-center">
|
||||
<router-link
|
||||
:to="{
|
||||
path: '/did/' + encodeURIComponent(issuer),
|
||||
}"
|
||||
class="text-blue-500 ml-1"
|
||||
title="See more about this person"
|
||||
>
|
||||
{{ issuerInfoObject?.displayName }}
|
||||
<span v-if="!serverUtil.isEmptyOrHiddenDid(issuer)">
|
||||
<a :href="`/did/${issuer}`" class="text-blue-500">
|
||||
<font-awesome
|
||||
icon="arrow-up-right-from-square"
|
||||
class="fa-fw"
|
||||
/>
|
||||
</router-link>
|
||||
</a>
|
||||
</span>
|
||||
<span v-if="serverUtil.isHiddenDid(issuer)" class="ml-1">
|
||||
<span v-else-if="serverUtil.isHiddenDid(issuer)">
|
||||
<font-awesome
|
||||
icon="info-circle"
|
||||
class="fa-fw text-blue-500 cursor-pointer"
|
||||
@@ -1433,7 +1425,7 @@ export default class ProjectViewView extends Vue {
|
||||
this.apiServer,
|
||||
this.axios,
|
||||
);
|
||||
if (result.success) {
|
||||
if (result.type === "success") {
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
|
||||
@@ -155,7 +155,7 @@ import { Contact } from "../db/tables/contacts";
|
||||
import {
|
||||
GenericCredWrapper,
|
||||
GenericVerifiableCredential,
|
||||
CreateAndSubmitClaimResult,
|
||||
ErrorResult,
|
||||
} from "../interfaces";
|
||||
import {
|
||||
BVC_MEETUPS_PROJECT_CLAIM_ID,
|
||||
@@ -298,29 +298,28 @@ export default class QuickActionBvcBeginView extends Vue {
|
||||
}
|
||||
|
||||
// in parallel, make a confirmation for each selected claim and send them all to the server
|
||||
const confirmResults: PromiseSettledResult<CreateAndSubmitClaimResult>[] =
|
||||
await Promise.allSettled(
|
||||
this.claimsToConfirmSelected.map(async (jwtId) => {
|
||||
const record = this.claimsToConfirm.find(
|
||||
(claim) => claim.id === jwtId,
|
||||
);
|
||||
if (!record) {
|
||||
return { success: false, error: "Record not found." };
|
||||
}
|
||||
return createAndSubmitConfirmation(
|
||||
this.activeDid,
|
||||
record.claim as GenericVerifiableCredential,
|
||||
record.id,
|
||||
record.handleId,
|
||||
this.apiServer,
|
||||
axios,
|
||||
);
|
||||
}),
|
||||
);
|
||||
const confirmResults = await Promise.allSettled(
|
||||
this.claimsToConfirmSelected.map(async (jwtId) => {
|
||||
const record = this.claimsToConfirm.find(
|
||||
(claim) => claim.id === jwtId,
|
||||
);
|
||||
if (!record) {
|
||||
return { type: "error", error: "Record not found." };
|
||||
}
|
||||
return createAndSubmitConfirmation(
|
||||
this.activeDid,
|
||||
record.claim as GenericVerifiableCredential,
|
||||
record.id,
|
||||
record.handleId,
|
||||
this.apiServer,
|
||||
axios,
|
||||
);
|
||||
}),
|
||||
);
|
||||
// check for any rejected confirmations
|
||||
const confirmsSucceeded = confirmResults.filter(
|
||||
// 'fulfilled' is the status in a successful PromiseFulfilledResult
|
||||
(result) => result.status === "fulfilled" && result.value.success,
|
||||
(result) =>
|
||||
result.status === "fulfilled" && result.value.type === "success",
|
||||
);
|
||||
if (confirmsSucceeded.length < this.claimsToConfirmSelected.length) {
|
||||
logger.error("Error sending confirmations:", confirmResults);
|
||||
@@ -354,7 +353,7 @@ export default class QuickActionBvcBeginView extends Vue {
|
||||
undefined,
|
||||
BVC_MEETUPS_PROJECT_CLAIM_ID,
|
||||
);
|
||||
giveSucceeded = giveResult.success;
|
||||
giveSucceeded = giveResult.type === "success";
|
||||
if (!giveSucceeded) {
|
||||
logger.error("Error sending give:", giveResult);
|
||||
this.$notify(
|
||||
@@ -363,7 +362,7 @@ export default class QuickActionBvcBeginView extends Vue {
|
||||
type: "danger",
|
||||
title: "Error",
|
||||
text:
|
||||
(giveResult as CreateAndSubmitClaimResult)?.error ||
|
||||
(giveResult as ErrorResult)?.error?.userMessage ||
|
||||
"There was an error sending that give.",
|
||||
},
|
||||
5000,
|
||||
|
||||
@@ -82,18 +82,6 @@
|
||||
Derive new address from existing seed
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- Database Migration Section -->
|
||||
<div class="mt-8 pt-6 border-t border-gray-200">
|
||||
<div class="flex justify-center">
|
||||
<router-link
|
||||
:to="{ name: 'database-migration' }"
|
||||
class="block w-fit text-center text-md bg-gradient-to-b from-slate-400 to-slate-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-4 py-2 rounded-md"
|
||||
>
|
||||
Migrate My Old Data
|
||||
</router-link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -182,15 +182,6 @@
|
||||
>
|
||||
Accounts
|
||||
</button>
|
||||
<button
|
||||
class="text-sm text-blue-600 hover:text-blue-800 underline"
|
||||
@click="
|
||||
sqlQuery = 'SELECT * FROM contacts;';
|
||||
executeSql();
|
||||
"
|
||||
>
|
||||
Contacts
|
||||
</button>
|
||||
<button
|
||||
class="text-sm text-blue-600 hover:text-blue-800 underline"
|
||||
@click="
|
||||
@@ -224,6 +215,65 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-8">
|
||||
<h2 class="text-xl font-bold mb-4">File Sharing Test</h2>
|
||||
Test the new file sharing functionality that saves to user-accessible
|
||||
locations.
|
||||
<div>
|
||||
<button
|
||||
class="font-bold capitalize bg-slate-500 text-white px-3 py-2 rounded-md mr-2"
|
||||
@click="testFileSharing()"
|
||||
>
|
||||
Test File Sharing
|
||||
</button>
|
||||
<button
|
||||
class="font-bold capitalize bg-slate-500 text-white px-3 py-2 rounded-md mr-2"
|
||||
@click="testFileSaveOnly()"
|
||||
>
|
||||
Test Save Only (No Share Dialog)
|
||||
</button>
|
||||
<button
|
||||
class="font-bold capitalize bg-slate-500 text-white px-3 py-2 rounded-md mr-2"
|
||||
@click="testLocationSelection()"
|
||||
>
|
||||
Test Location Selection
|
||||
</button>
|
||||
<button
|
||||
class="font-bold capitalize bg-slate-500 text-white px-3 py-2 rounded-md mr-2"
|
||||
@click="testLocationSelectionSilent()"
|
||||
>
|
||||
Test Silent Location Selection
|
||||
</button>
|
||||
<button
|
||||
class="font-bold capitalize bg-slate-500 text-white px-3 py-2 rounded-md mr-2"
|
||||
@click="testListUserFiles()"
|
||||
>
|
||||
List User Files
|
||||
</button>
|
||||
<button
|
||||
class="font-bold capitalize bg-slate-500 text-white px-3 py-2 rounded-md mr-2"
|
||||
@click="testBackupFiles()"
|
||||
>
|
||||
Test Backup Files
|
||||
</button>
|
||||
<button
|
||||
class="font-bold capitalize bg-slate-500 text-white px-3 py-2 rounded-md mr-2"
|
||||
@click="testOpenBackupDirectory()"
|
||||
>
|
||||
Test Open Directory
|
||||
</button>
|
||||
<button
|
||||
class="font-bold capitalize bg-slate-500 text-white px-3 py-2 rounded-md mr-2"
|
||||
@click="testFileDiscoveryDebug()"
|
||||
>
|
||||
Debug File Discovery
|
||||
</button>
|
||||
<div v-if="fileSharingResult" class="mt-2 p-2 bg-gray-100 rounded">
|
||||
<strong>Result:</strong> {{ fileSharingResult }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-8">
|
||||
<h2 class="text-xl font-bold mb-4">Image Sharing</h2>
|
||||
Populates the "shared-photo" view as if they used "share_target".
|
||||
@@ -396,6 +446,9 @@ export default class Help extends Vue {
|
||||
sqlQuery = "";
|
||||
sqlResult: unknown = null;
|
||||
|
||||
// for file sharing test
|
||||
fileSharingResult = "";
|
||||
|
||||
cryptoLib = cryptoLib;
|
||||
|
||||
async mounted() {
|
||||
@@ -629,5 +682,174 @@ export default class Help extends Vue {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async testFileSharing() {
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
try {
|
||||
const result = await platformService.testFileSharing();
|
||||
this.fileSharingResult = result;
|
||||
logger.log("File Sharing Test Result:", this.fileSharingResult);
|
||||
} catch (error) {
|
||||
logger.error("File Sharing Test Error:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "File Sharing Error",
|
||||
text: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
5000,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async testFileSaveOnly() {
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
try {
|
||||
const result = await platformService.testFileSaveOnly();
|
||||
this.fileSharingResult = result;
|
||||
logger.log("File Save Only Test Result:", this.fileSharingResult);
|
||||
} catch (error) {
|
||||
logger.error("File Save Only Test Error:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "File Save Only Error",
|
||||
text: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
5000,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async testLocationSelection() {
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
try {
|
||||
const result = await platformService.testLocationSelection();
|
||||
this.fileSharingResult = result;
|
||||
logger.log("Location Selection Test Result:", this.fileSharingResult);
|
||||
} catch (error) {
|
||||
logger.error("Location Selection Test Error:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Location Selection Error",
|
||||
text: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
5000,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async testLocationSelectionSilent() {
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
try {
|
||||
const result = await platformService.testLocationSelectionSilent();
|
||||
this.fileSharingResult = result;
|
||||
logger.log(
|
||||
"Silent Location Selection Test Result:",
|
||||
this.fileSharingResult,
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error("Silent Location Selection Test Error:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Silent Location Selection Error",
|
||||
text: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
5000,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async testListUserFiles() {
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
try {
|
||||
const result = await platformService.testListUserFiles();
|
||||
this.fileSharingResult = result;
|
||||
logger.log("List User Files Test Result:", this.fileSharingResult);
|
||||
} catch (error) {
|
||||
logger.error("List User Files Test Error:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "List User Files Error",
|
||||
text: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
5000,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async testBackupFiles() {
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
try {
|
||||
const result = await platformService.testBackupFiles();
|
||||
this.fileSharingResult = result;
|
||||
logger.log("Backup Files Test Result:", this.fileSharingResult);
|
||||
} catch (error) {
|
||||
logger.error("Backup Files Test Error:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Backup Files Error",
|
||||
text: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
5000,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async testOpenBackupDirectory() {
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
try {
|
||||
const result = await platformService.testOpenBackupDirectory();
|
||||
this.fileSharingResult = result;
|
||||
logger.log("Open Backup Directory Test Result:", this.fileSharingResult);
|
||||
} catch (error) {
|
||||
logger.error("Open Backup Directory Test Error:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Open Backup Directory Error",
|
||||
text: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
5000,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async testFileDiscoveryDebug() {
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
try {
|
||||
if ("debugFileDiscoveryStepByStep" in platformService) {
|
||||
const result = await (
|
||||
platformService as any
|
||||
).debugFileDiscoveryStepByStep();
|
||||
this.fileSharingResult = result;
|
||||
logger.log("File Discovery Debug Test Result:", this.fileSharingResult);
|
||||
} else {
|
||||
this.fileSharingResult = "Debug method not available on this platform";
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("File Discovery Debug Test Error:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "File Discovery Debug Error",
|
||||
text: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
5000,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user