Compare commits

...

91 Commits

Author SHA1 Message Date
Matthew Raymer
a1b6add178 chore: linting; more non-errors need fixing 2025-06-14 11:10:37 +00:00
Matthew Raymer
d3a26a54d4 feat: optimize permission checking and reduce logging verbosity
- Add 30-second cache for storage permission status to prevent redundant checks
- Reduce excessive logging during file discovery operations
- Only log file discovery results when files are actually found
- Optimize backup files listing to reduce console noise
- Maintain essential debugging information while improving performance
- Eliminate redundant permission checks during app initialization
- Improve app startup performance with cached permission status

Performance improvements:
- Faster permission checks with caching mechanism
- Reduced console noise for better debugging experience
- Maintained all functionality while optimizing logging
- Better user experience with less redundant operations

Security: No changes to security model, only performance optimizations
Platforms: Android and iOS file handling improvements
2025-06-14 10:18:10 +00:00
Matthew Raymer
122b5b1a06 feat: implement comprehensive directory creation for Android 10+
- Add 4-strategy directory creation system for Android 10+ compatibility
- Strategy 1: Recursive file creation with temporary files
- Strategy 2: Parent-by-parent directory creation for nested paths
- Strategy 3: Simple file test creation in target directory
- Strategy 4: App-specific external directory creation
- Enhanced testing and user guidance for directory creation capabilities
- Comprehensive logging for debugging directory creation issues
- Guaranteed file saves with graceful fallback to app data directory
2025-06-14 10:09:08 +00:00
Matthew Raymer
9e8f08aa49 feat: improve backup file discovery and user guidance
- Add enhanced logging for debugging when no backup files found
- Improve "no backup files" UI with helpful guidance for users
- Better file filtering to exclude system files from backup lists
- Enhanced user experience for first-time users and permission-denied scenarios
2025-06-14 09:50:59 +00:00
Matthew Raymer
1529cc9689 fix: improve file discovery to find files in app data directory
- Fix listUserAccessibleFilesEnhanced to properly check app data directory
- Add detailed logging for file discovery results
- Ensure files saved to app data directory are discoverable
- Improve file discovery logging with file details

Resolves issue where saved backup files were not appearing in file list
Files saved to app data directory are now properly discoverable
2025-06-14 09:44:07 +00:00
Matthew Raymer
f7ed05d13f fix: implement permission request lock and optimize file access
- Add permission request lock to prevent concurrent requests
- Implement permission state tracking to avoid redundant checks
- Optimize file discovery with single permission check
- Enhance error handling for permission denials
- Add graceful degradation when permissions are denied
- Improve structured logging for better debugging

Resolves "Can request only one set of permissions at a time" warnings
Reduces redundant permission checks and file system operations
Ensures app continues to function with limited permissions
2025-06-14 09:41:24 +00:00
Matthew Raymer
7c8a6d0666 fix: improve Android file export with version-aware storage handling
- Add Android version detection from user agent
- Implement tiered storage strategy for Android 10+ restrictions
- Enhance directory creation logic with better error handling
- Add comprehensive fallback chain for file saving
- Improve permission denial handling for graceful degradation
- Add structured logging for better debugging

Resolves "Parent folder doesn't exist" errors on Android 10+
Ensures files are always saved with multiple fallback levels
2025-06-14 09:30:15 +00:00
Matthew Raymer
1aa285be55 WIP: Debug backup file discovery system - Fixed recursive directory search in CapacitorPlatformService to properly search subdirectories instead of excluding them - Added missing listFilesInDirectory method to all platform services for directory browsing functionality - Added debug methods (debugTimeSafariDirectory, createTestBackupFile, testDirectoryContexts) to help diagnose file visibility issues - Enhanced logging for backup file discovery process - Current issue: TimeSafari directory exists in Download but shows 'Directory does not exist' when trying to read contents - Need to investigate why JSON backup files are not being found despite directory existence 2025-06-13 13:58:14 +00:00
Matthew Raymer
2635c22c33 feat(backup-browser): add folder navigation, breadcrumbs, and debug mode for file discovery
- Implement folder navigation with breadcrumbs in BackupFilesList
- Distinguish files and folders in UI, allow folder navigation
- Add debug mode to forcibly treat all entries as files for diagnosis
- Add detailed debug logging to file discovery (readdir, stat, entries)
- Show warning in UI when debug mode is active
- Prepare for further improvements to handle stat failures gracefully

Co-authored-by: Matthew Raymer
2025-06-12 13:14:41 +00:00
Matthew Raymer
2d516b90b0 feat: implement user-accessible file storage with improved share dialog handling
- Add timeout mechanism for share dialogs to prevent hanging (15s timeout)
- Implement centralized share dialog handling with robust error handling
- Update file storage to use app's external storage (accessible via file managers)
- Add directory picker functionality for custom save locations
- Add listUserAccessibleFiles method to show saved files
- Add testListUserFiles functionality for debugging
- Improve logging and error handling throughout file operations
- Ensure compatibility with Android 11+ storage restrictions

Files are now saved to:
- Android: /storage/emulated/0/Android/data/app.timesafari.app/files/TimeSafari/
- iOS: /Documents/ (accessible via Files app)

Users can access files through file managers, app's file listing,
or use share dialog to save to Downloads folder.
2025-06-11 13:03:42 +00:00
Matthew Raymer
7a1329e1a4 feat: enhance file save and share with location selection options
- Add enhanced writeAndShareFile method with flexible save options
- Support save to Downloads folder (Android) and Documents (iOS)
- Add framework for file picker location selection
- Improve error handling with detailed result objects
- Update PlatformService interface for new options
- Add writeFile method for basic app storage operations
- Update DataExportSection to use enhanced API with location selection
- Maintain backward compatibility with existing implementations
- Add comprehensive logging for debugging and monitoring

This provides users with better control over where files are saved
while maintaining the existing share functionality and adding
multiple fallback strategies for improved reliability.
2025-06-11 08:40:33 +00:00
f255ea389b bump to build 26 and version 0.5.1 2025-06-11 00:46:46 -06:00
0d343b9877 Merge pull request 'fix creation of did-specific settings (with a rename)' (#138) from fix-did-specifics into master
Reviewed-on: #138
2025-06-11 02:14:41 -04:00
df06100c32 remove more debugging 2025-06-10 23:49:14 -06:00
Matthew Raymer
ac5ddfc6f2 style: fix line length in ContactsView ternary operator
- Break long CSS class strings into multiple concatenated lines
- Ensure all lines are under 100 characters for better readability
- Maintain same functionality and styling behavior
- Improve code maintainability and readability

Fixes: Long lines in conditional CSS class assignment
2025-06-11 05:45:58 +00:00
Matthew Raymer
89b3f30466 fix: debug and clean up GiftedPrompts contact retrieval logic
- Add comprehensive debug logging to identify contact list population issues
- Fix array indexing bug in contact mapping (someContactDbIndex -> 0)
- Clean up all console.log statements for production readiness
- Improve contact retrieval debugging for SQLite and Dexie databases
- Maintain core functionality while adding diagnostic capabilities

Debugging: Contact list population issues in GiftedPrompts component
Cleanup: Remove debug console.log statements
2025-06-11 05:40:05 +00:00
Matthew Raymer
3cb5cc096b refactor: use databaseUtil.updateDefaultSettings for feed filter settings
- Replace direct platform service calls with databaseUtil.updateDefaultSettings
- Remove manual SQL query construction in favor of centralized utility
- Improve code consistency and maintainability
- Add proper error handling through databaseUtil's built-in mechanisms
- Remove unused PlatformServiceFactory import
- Fix SQL syntax errors in clearAll and setAll methods (AND -> comma)
- Ensure both SQLite and Dexie databases are updated consistently

Improves: FeedFilters component architecture and error handling
Fixes: isNearby and filterFeedByVisible settings not being saved properly
2025-06-11 05:19:15 +00:00
Matthew Raymer
5df560154f fix: resolve cross-platform contactMethods JSON parsing inconsistencies
- Add platform-agnostic parseJsonField utility for contactMethods handling
- Update contact export functions (contactsToExportJson, contactToCsvLine)
- Fix contact storage in QR scan views (ContactQRScanShowView, ContactQRScanFullView)
- Ensure consistent JSON string storage across web SQLite and Capacitor SQLite
- Prevents "[object Object] is not valid JSON" errors when switching platforms
- Maintains compatibility between auto-parsing web SQLite and raw string Capacitor SQLite

Fixes: contactMethods parsing errors in export and QR scan functionality
Related: searchBoxes field had similar issue (already fixed)
2025-06-11 04:17:38 +00:00
Matthew Raymer
c1aa522e6c fix: resolve cross-platform SQLite JSON parsing inconsistencies
- Add platform-agnostic parseJsonField utility to handle different SQLite implementations
- Web SQLite (wa-sqlite/absurd-sql) auto-parses JSON strings to objects
- Capacitor SQLite returns raw strings requiring manual parsing
- Update searchBoxes parsing to use new utility for consistent behavior
- Fixes "[object Object] is not valid JSON" error when switching platforms
- Ensures compatibility between web and mobile SQLite implementations

Fixes: searchBoxes parsing errors in databaseUtil.ts
Related: contactMethods field has similar issue (needs same treatment)
2025-06-11 03:44:28 +00:00
a082469a01 fix creation of did-specific settings (with a rename) 2025-06-10 20:51:22 -06:00
Jose Olarte III
3544d7278d Optimized item actions
- Edited button labels for brevity
- Repositioned Totals toggle
- Restyled note about recent hours
- Various text size and spacing changes
2025-06-10 19:54:05 +08:00
Jose Olarte III
d3110506ea Optimized per-item layout
- Stacked contact name and DID
- Text truncates to leave room for action buttons when visible
- Separated "from / to" heading from buttons to minimize width
- Various spacing and alignment adjustments
2025-06-10 18:42:49 +08:00
8609f8458d bump to build 25 & version 0.5.0 2025-06-09 09:26:21 -06:00
8f5c34bc5f fix linting 2025-06-09 09:09:54 -06:00
b0d61b95ea Merge branch 'ui-fixes-2025-06-w2' 2025-06-09 08:44:42 -06:00
af7bd236a3 fix check for successful gift submission 2025-06-09 08:41:47 -06:00
d719338bcc fix problem setting 'loading' flag 2025-06-09 08:37:42 -06:00
6ddf2d1012 fix problem switching IDs (creating too many settings) 2025-06-09 08:33:33 -06:00
Jose Olarte III
1b2d4b623a Turned off automatic safe area in iOS
- Safe area implementations will solely depend on CSS styles for full control
- Eliminates doubled top and bottom padding in iOS
2025-06-09 20:20:17 +08:00
Jose Olarte III
16d5c917d2 Updated QR scanner call
- Searched for all other (outdated) calls to QR scanner dialog and updated them
- Fixed vite HTML spec warning
2025-06-09 19:36:06 +08:00
5976a4995e fix problem clicking on offer-delivery, plus some other hardening and phrasing 2025-06-08 20:13:32 -06:00
dcd0cc4c20 fix import for derived accounts and hopefully make other account-access code more robust 2025-06-08 19:14:41 -06:00
b3ca6c9d91 remove relative URL references in different target because mobile chokes 2025-06-08 16:55:03 -06:00
e9d800f601 fix a web test (all passing now) 2025-06-07 21:41:43 -06:00
b939a5e592 bump build to 23 and version to 0.4.8 2025-06-07 18:54:56 -06:00
aa62037fae bump to build 22 version 0.4.7 (though I think the android capacitor.config.json appId is wrong) 2025-06-07 18:45:24 -06:00
722020ea86 fix linting 2025-06-07 18:09:04 -06:00
96aa3f4a54 add Python dependency for electron on Mac 2025-06-07 17:54:31 -06:00
c0c5f9842b fix some errors and correct recent type duplications & bloat (cherry-picked from d8f2587d1c) 2025-06-07 17:53:36 -06:00
be27ca1855 fix more logic for tests (cherry-picked from 83acb028c7) 2025-06-07 17:42:06 -06:00
92e4570672 fix some incorrect logic & things AI hallucinated 2025-06-07 17:39:10 -06:00
820ae727ed fix linting 2025-06-07 17:19:01 -06:00
dbeb1c6b4b Merge branch 'sql-absurd-sql-back' 2025-06-07 17:18:10 -06:00
573e4b206a Merge branch 'search-map-fix' 2025-06-07 16:43:49 -06:00
abc05d426e update messaging for unknown icons on home feed 2025-06-07 16:23:07 -06:00
2ea7479d75 fix verbiage and fix the contact actions to be on the right-hand side 2025-06-07 16:03:47 -06:00
9ac9713172 fix linting 2025-06-07 15:40:52 -06:00
41dad3254d fix a non-existent description, move the description right below the image 2025-06-07 15:33:29 -06:00
485eac59a0 remove unnecessary data element from export 2025-06-07 14:02:22 -06:00
Matthew Raymer
73fc32b75d fix(import): ensure contact import works for both Dexie and absurd-sql backends
- Refactor importContacts to handle both Dexie and absurd-sql (SQLite) storage
- Add ContactDbRecord interface with all string fields strictly typed (never null)
- Add helper functions to coerce null/undefined to empty string for all string fields
- Guarantee contactMethods is always stored as a JSON string (never null)
- Add runtime validation for required fields (e.g., did)
- Ensure imported/updated contacts are type-safe and compatible with both backends
- Improve code documentation and maintainability

Security:
- No sensitive data exposed
- All fields validated and sanitized before database write
- Consistent data structure across storage backends

Testing:
- Import tested with both Dexie and absurd-sql backends
- Null/undefined fields correctly handled and coerced
- No linter/type errors remain
2025-06-07 06:01:17 +00:00
Matthew Raymer
3d8e40e92b feat(export): Replace CSV export with standardized JSON format
- Add contactsToExportJson utility function for standardized data export
- Replace CSV export with JSON format in DataExportSection
- Update file extension and MIME type to application/json
- Remove Dexie-specific export logic in favor of unified SQLite/Dexie approach
- Update success notifications to reflect JSON format
- Add TypeScript interfaces for export data structure

This change improves data portability and standardization by:
- Using a consistent JSON format for data export/import
- Supporting both SQLite and Dexie databases
- Including all contact fields in export
- Properly handling contactMethods as stringified JSON
- Maintaining backward compatibility with existing import tools

Security: No sensitive data exposure, maintains existing access controls
2025-06-07 05:02:33 +00:00
38e67f3533 update a DB save to match others, ie. first SQL then maybe Dexie 2025-06-06 19:50:16 -06:00
7f63ee7c80 add another way to fix the privacy policy manifest for third parties like GoogleToolboxForMac 2025-06-06 19:45:41 -06:00
6a47f0d3e7 format total numbers better 2025-06-06 19:40:53 -06:00
fc50a9d4c6 fix problem finding offer identifiers 2025-06-06 19:06:29 -06:00
Jose Olarte III
45f43ff363 Updated icon and splash assets 2025-06-06 18:15:42 +08:00
Jose Olarte III
7b1d4c4849 Adjusted iOS-specific paddings
- Switched to CSS max() for proper conditional padding when dealing with screens that have a notch, dynamic island, gesture bar, etc.
- Top padding should now appear more compact in iOS
2025-06-06 18:14:56 +08:00
Matthew Raymer
c1f2c3951a feat(db): improve settings retrieval resilience and logging
Enhance retrieveSettingsForActiveAccount with better error handling and logging
while maintaining core functionality. Changes focus on making the system more
debuggable and resilient without overcomplicating the logic.

Key improvements:
- Add structured error handling with specific try-catch blocks
- Implement detailed logging with [databaseUtil] prefix for easy filtering
- Add graceful fallbacks for searchBoxes parsing and missing settings
- Improve error recovery paths with safe defaults
- Maintain existing security model and data integrity

Security:
- No sensitive data in logs
- Safe JSON parsing with fallbacks
- Proper error boundaries
- Consistent state management
- Clear fallback paths

Testing:
- Verify settings retrieval works with/without active DID
- Check error handling for invalid searchBoxes
- Confirm logging provides clear debugging context
- Validate fallback to default settings works
2025-06-06 09:22:35 +00:00
9d4f726c31 bump to build # 19 version 0.4.7 for mobile packages 2025-06-05 20:30:27 -06:00
1d7f626645 fix SQL references to bad "key" -> "id" 2025-06-05 20:11:32 -06:00
c5228ba7ec fix retrieval of column names -- so now most ops are working (but not all, eg. set name) 2025-06-05 20:06:32 -06:00
6e1fcd8dee remove unused DB methods (for now) 2025-06-05 20:00:51 -06:00
5bb563d694 fix extraction of values from SQLite queries 2025-06-05 19:57:59 -06:00
a3951c9d66 refactor for clarity (no logic changes) 2025-06-05 18:30:25 -06:00
aa177a9b8c fix extraction of migration names for SQLite via Capacitor 2025-06-05 18:13:33 -06:00
03cb4720b8 fix Capacitor to use the same migrations (migrations run but accounts aren't created) 2025-06-04 22:01:14 -06:00
Jose Olarte III
0e65431f43 Map z-index fix + adjustments
- Set map z-index lower than nav
- Relocated search box to account for conditional visibility
- Various conditional fixes
- Spacing adjustments
2025-06-04 18:41:49 +08:00
297c5a2dbb disable SQLite in Java & Swift (since they don't compile) & add SQL queueing on startup
At this point, the app compiles and runs in Android & iOS but DB operations fail.
2025-06-03 19:59:28 -06:00
Jose Olarte III
92b9c9334c Clickable person & project icons
- Known entities get routed to their corresponding detail views
- Unknown entities pop up a notification
2025-06-02 21:35:15 +08:00
Jose Olarte III
706182ca0c Icon for hidden DID entity
- Display EntityIcon for known entities, eye-slash icon for hidden entities, and the person-question icon for unknown entities
- Design tweaks (spacings, mostly)
2025-06-02 17:44:37 +08:00
Matthew Raymer
68e0fc4976 merge(master): big merge for qrcode-reboot 2025-06-02 03:57:00 +00:00
504056eb90 add some time to test 30 (but shrink the per-loop timeout) 2025-06-01 15:08:32 -06:00
5a1007c49c add iOS development team ID 2025-06-01 14:29:32 -06:00
Jose Olarte III
cbc14e21ec Look in .own.did for DID, as well 2025-05-30 17:34:50 +08:00
Jose Olarte III
3e02b3924a Look for DID in .iss field instead of .own.did 2025-05-28 19:08:15 +08:00
Jose Olarte III
8b03789941 Change heading based on crop flag 2025-05-28 16:32:41 +08:00
Jose Olarte III
b4a6b99301 Better error handling for image upload 2025-05-28 16:17:49 +08:00
Jose Olarte III
e839997f91 TEST: platform- and camera-specific mirroring 2025-05-27 18:58:35 +08:00
Jose Olarte III
d8d054a0e1 Streamlined QR scanner web camera
- No need to stop and start camera preview
2025-05-27 18:57:12 +08:00
Jose Olarte III
efc720e47f Mobile native to use web camera
- Ensure consistent UI experience for uploading photos across mobile web and native
2025-05-27 17:46:19 +08:00
Jose Olarte III
0a85bea533 Feature: context-based default camera
- Specify the default camera (front / back) to use
2025-05-27 15:37:45 +08:00
Jose Olarte III
47501ae917 Linting 2025-05-26 19:23:41 +08:00
Jose Olarte III
28634839ec Feature: front/back camera toggle
- Added to gifting and profile dialog camera for now. Toggle button is hidden in desktop.
- WIP: same feature for QR scanner camera.
- WIP: ability to specify default camera depending on where it's called.
2025-05-26 19:23:28 +08:00
1b7c96ed9b don't highlight profile Advanced link in blue 2025-05-13 19:37:47 -06:00
41365fab8f add projectLink to onboarding meeting, plus enhancements to setup usability 2025-05-13 19:36:23 -06:00
5cc42be58a fix some test scripts 2025-04-08 20:31:47 -06:00
3d1a2eeb8d adjust to app.timesafari.app in more places 2025-04-08 20:29:08 -06:00
7b0ee2e44e more ios folders to ignore (until we figure out the right way to dance with capacitor-assets) 2025-04-06 19:52:44 -06:00
ac018997e8 adjust instructions for capacitor-assets and more files 2025-04-06 19:48:45 -06:00
6f449e9c1f restore important file from previous cleanup 2025-04-06 19:15:00 -06:00
543599a6a1 remove icon files that are generated by capacitor-assets 2025-04-06 19:02:01 -06:00
133 changed files with 8494 additions and 2411 deletions

View File

@@ -1,101 +0,0 @@
VM5:29 [Preload] Preload script starting...
VM5:29 [Preload] Preload script completed successfully
main.common-DiOUyXe7.js:27 Platform Object
error @ main.common-DiOUyXe7.js:27
main.common-DiOUyXe7.js:27 PWA enabled Object
error @ main.common-DiOUyXe7.js:27
main.common-DiOUyXe7.js:27 [Web] PWA enabled Object
error @ main.common-DiOUyXe7.js:27
main.common-DiOUyXe7.js:27 [Web] Platform Object
error @ main.common-DiOUyXe7.js:27
main.common-DiOUyXe7.js:29 Opened!
main.common-DiOUyXe7.js:2552 Failed to log to database: Error: no such column: value
at E.handleError (main.common-DiOUyXe7.js:27:21133)
at E.exec (main.common-DiOUyXe7.js:27:19785)
at Rc.processQueue (main.common-DiOUyXe7.js:2379:2368)
F7 @ main.common-DiOUyXe7.js:2552
main.common-DiOUyXe7.js:2552 Original message: PWA enabled - [{"pwa_enabled":false}]
F7 @ main.common-DiOUyXe7.js:2552
main.common-DiOUyXe7.js:2552 Failed to log to database: Error: no such column: value
at E.handleError (main.common-DiOUyXe7.js:27:21133)
at E.exec (main.common-DiOUyXe7.js:27:19785)
at Rc.processQueue (main.common-DiOUyXe7.js:2379:2368)
at main.common-DiOUyXe7.js:2379:2816
at new Promise (<anonymous>)
at Rc.queueOperation (main.common-DiOUyXe7.js:2379:2685)
at Rc.query (main.common-DiOUyXe7.js:2379:3378)
at async F7 (main.common-DiOUyXe7.js:2552:117)
F7 @ main.common-DiOUyXe7.js:2552
main.common-DiOUyXe7.js:2552 Original message: [Web] PWA enabled - [{"pwa_enabled":false}]
F7 @ main.common-DiOUyXe7.js:2552
main.common-DiOUyXe7.js:2552 Failed to log to database: Error: no such column: value
at E.handleError (main.common-DiOUyXe7.js:27:21133)
at E.exec (main.common-DiOUyXe7.js:27:19785)
at Rc.processQueue (main.common-DiOUyXe7.js:2379:2368)
at main.common-DiOUyXe7.js:2379:2816
at new Promise (<anonymous>)
at Rc.queueOperation (main.common-DiOUyXe7.js:2379:2685)
at Rc.query (main.common-DiOUyXe7.js:2379:3378)
at async F7 (main.common-DiOUyXe7.js:2552:117)
F7 @ main.common-DiOUyXe7.js:2552
main.common-DiOUyXe7.js:2552 Original message: [Web] Platform - [{"platform":"web"}]
F7 @ main.common-DiOUyXe7.js:2552
main.common-DiOUyXe7.js:2552 Failed to log to database: Error: no such column: value
at E.handleError (main.common-DiOUyXe7.js:27:21133)
at E.exec (main.common-DiOUyXe7.js:27:19785)
at Rc.processQueue (main.common-DiOUyXe7.js:2379:2368)
at main.common-DiOUyXe7.js:2379:2816
at new Promise (<anonymous>)
at Rc.queueOperation (main.common-DiOUyXe7.js:2379:2685)
at Rc.query (main.common-DiOUyXe7.js:2379:3378)
at async F7 (main.common-DiOUyXe7.js:2552:117)
F7 @ main.common-DiOUyXe7.js:2552
main.common-DiOUyXe7.js:2552 Original message: Platform - [{"platform":"web"}]
F7 @ main.common-DiOUyXe7.js:2552
main.common-DiOUyXe7.js:2100
GET https://api.endorser.ch/api/report/rateLimits 400 (Bad Request)
(anonymous) @ main.common-DiOUyXe7.js:2100
xhr @ main.common-DiOUyXe7.js:2100
p6 @ main.common-DiOUyXe7.js:2102
_request @ main.common-DiOUyXe7.js:2103
request @ main.common-DiOUyXe7.js:2102
Yc.<computed> @ main.common-DiOUyXe7.js:2103
(anonymous) @ main.common-DiOUyXe7.js:2098
dJ @ main.common-DiOUyXe7.js:2295
main.common-DiOUyXe7.js:2100
GET https://api.endorser.ch/api/report/rateLimits 400 (Bad Request)
(anonymous) @ main.common-DiOUyXe7.js:2100
xhr @ main.common-DiOUyXe7.js:2100
p6 @ main.common-DiOUyXe7.js:2102
_request @ main.common-DiOUyXe7.js:2103
request @ main.common-DiOUyXe7.js:2102
Yc.<computed> @ main.common-DiOUyXe7.js:2103
(anonymous) @ main.common-DiOUyXe7.js:2098
dJ @ main.common-DiOUyXe7.js:2295
await in dJ
checkRegistrationStatus @ HomeView-DJMSCuMg.js:1
mounted @ HomeView-DJMSCuMg.js:1
XMLHttpRequest.send
(anonymous) @ main.common-DiOUyXe7.js:2100
xhr @ main.common-DiOUyXe7.js:2100
p6 @ main.common-DiOUyXe7.js:2102
_request @ main.common-DiOUyXe7.js:2103
request @ main.common-DiOUyXe7.js:2102
Yc.<computed> @ main.common-DiOUyXe7.js:2103
(anonymous) @ main.common-DiOUyXe7.js:2098
ZG @ main.common-DiOUyXe7.js:2295
await in ZG
initializeIdentity @ HomeView-DJMSCuMg.js:1
XMLHttpRequest.send
(anonymous) @ main.common-DiOUyXe7.js:2100
xhr @ main.common-DiOUyXe7.js:2100
p6 @ main.common-DiOUyXe7.js:2102
_request @ main.common-DiOUyXe7.js:2103
request @ main.common-DiOUyXe7.js:2102
Yc.<computed> @ main.common-DiOUyXe7.js:2103
(anonymous) @ main.common-DiOUyXe7.js:2098
dJ @ main.common-DiOUyXe7.js:2295

View File

@@ -2,7 +2,7 @@
# iOS doesn't like spaces in the app title.
TIME_SAFARI_APP_TITLE="TimeSafari_Dev"
VITE_APP_SERVER=http://localhost:3000
VITE_APP_SERVER=http://localhost:8080
# This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not production).
VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F
VITE_DEFAULT_ENDORSER_API_SERVER=http://localhost:3000

6
.gitignore vendored
View File

@@ -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
@@ -51,6 +52,7 @@ vendor/
# Build logs
build_logs/
android/app/src/main/assets/public
android/app/src/main/res
# PWA icon files generated by capacitor-assets
icons

View File

@@ -9,19 +9,6 @@ For a quick dev environment setup, use [pkgx](https://pkgx.dev).
- Node.js (LTS version recommended)
- npm (comes with Node.js)
- Git
- For Android builds: Android Studio with SDK installed
- For iOS builds: macOS with Xcode and ruby gems & bundle
- `pkgx +rubygems.org sh`
- ... and you may have to fix these, especially with pkgx
```bash
gem_path=$(which gem)
shortened_path="${gem_path:h:h}"
export GEM_HOME=$shortened_path
export GEM_PATH=$shortened_path
```
- For desktop builds: Additional build tools based on your OS
## Forks
@@ -326,6 +313,32 @@ npm run build:electron-prod && npm run electron:start
Prerequisites: macOS with Xcode installed
#### First-time iOS Configuration
- Generate certificates inside XCode.
- Right-click on App and under Signing & Capabilities set the Team.
#### Each Release
0. First time (or if XCode dependencies change):
- `pkgx +rubygems.org sh`
- ... and you may have to fix these, especially with pkgx
```bash
gem_path=$(which gem)
shortened_path="${gem_path:h:h}"
export GEM_HOME=$shortened_path
export GEM_PATH=$shortened_path
```
```bash
cd ios/App
pod install
```
1. Build the web assets:
```bash
@@ -334,6 +347,7 @@ Prerequisites: macOS with Xcode installed
npm run build:capacitor
```
2. Update iOS project with latest build:
```bash
@@ -345,7 +359,11 @@ Prerequisites: macOS with Xcode installed
3. Copy the assets:
```bash
# It makes no sense why capacitor-assets will not run without these but it actually changes the contents.
mkdir -p ios/App/App/Assets.xcassets/AppIcon.appiconset
echo '{"images":[]}' > ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json
mkdir -p ios/App/App/Assets.xcassets/Splash.imageset
echo '{"images":[]}' > ios/App/App/Assets.xcassets/Splash.imageset/Contents.json
npx capacitor-assets generate --ios
```
@@ -353,10 +371,10 @@ Prerequisites: macOS with Xcode installed
```
cd ios/App
xcrun agvtool new-version 15
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.4.5;/g" > temp
cat App.xcodeproj/project.pbxproj | sed "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 0.5.1;/g" > temp
mv temp App.xcodeproj/project.pbxproj
cd -
```
@@ -369,28 +387,25 @@ Prerequisites: macOS with Xcode installed
6. Use Xcode to build and run on simulator or device.
* Select Product -> Destination with some Simulator version. Then click the run arrow.
7. Release
* Under "General" renamed a bunch of things to "Time Safari"
* Choose Product -> Destination -> Build Any iOS
* Someday: Under "General" we want to rename a bunch of things to "Time Safari"
* Choose Product -> Destination -> Any iOS Device
* Choose Product -> Archive
* This will trigger a build and take time, needing user's "login" keychain password which is just their login password, repeatedly.
* This will trigger a build and take time, needing user's "login" keychain password (user's login password), repeatedly.
* If it fails with `building for 'iOS', but linking in dylib (.../.pkgx/zlib.net/v1.3.0/lib/libz.1.3.dylib) built for 'macOS'` then run XCode outside that terminal (ie. not with `npx cap open ios`).
* Click Distribute -> App Store Connect
* In AppStoreConnect, add the build to the distribution: remove the current build with the "-" when you hover over it, then "Add Build" with the new build.
* May have to go to App Review, click Submission, then hover over the build and click "-".
* It can take 15 minutes for the build to show up in the list of builds.
* You'll probably have to "Manage" something about encryption, disallowed in France.
* Then "Save" and "Add to Review" and "Resubmit to App Review".
#### First-time iOS Configuration
- Generate certificates inside XCode.
- Right-click on App and under Signing & Capabilities set the Team.
### Android Build
Prerequisites: Android Studio with SDK installed
Prerequisites: Android Studio with Java SDK installed
1. Build the web assets:
@@ -445,7 +460,9 @@ Prerequisites: Android Studio with SDK installed
* Then `bundleRelease`:
```bash
cd android
./gradlew bundleRelease -Dlint.baselines.continue=true
cd -
```
... and find your `aab` file at app/build/outputs/bundle/release
@@ -458,6 +475,8 @@ At play.google.com/console:
- Hit "Next".
- Save, go to "Publishing Overview" as prompted, and click "Send changes for review".
- 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.
## First-time Android Configuration for deep links

View File

@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [0.4.7]
### Fixed
- Cameras everywhere
### Changed
- IndexedDB -> SQLite
## [0.4.5] - 2025.02.23
### Added
- Total amounts of gives on project page

533
CONTACT_BACKUP_SYSTEM.md Normal file
View 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.

View File

@@ -31,8 +31,8 @@ android {
applicationId "app.timesafari.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 18
versionName "0.4.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.

View File

@@ -32,7 +32,7 @@
}
},
"ios": {
"contentInset": "always",
"contentInset": "never",
"allowsLinkPreview": true,
"scrollEnabled": true,
"limitsNavigationsToAppBoundDomains": true,

View File

@@ -2,7 +2,7 @@ package app.timesafari;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.community.sqlite.SQLite;
//import com.getcapacitor.community.sqlite.SQLite;
public class MainActivity extends BridgeActivity {
@Override
@@ -10,6 +10,6 @@ public class MainActivity extends BridgeActivity {
super.onCreate(savedInstanceState);
// Initialize SQLite
registerPlugin(SQLite.class);
//registerPlugin(SQLite.class);
}
}

View File

@@ -1,5 +0,0 @@
package timesafari.app;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

View File

@@ -1,5 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background>
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
</background>
<foreground>
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
</foreground>
</adaptive-icon>

View File

@@ -1,5 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background>
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
</background>
<foreground>
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
</foreground>
</adaptive-icon>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

BIN
assets/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 279 KiB

BIN
assets/splash-dark.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

BIN
assets/splash.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

View File

@@ -32,7 +32,7 @@
}
},
"ios": {
"contentInset": "always",
"contentInset": "never",
"allowsLinkPreview": true,
"scrollEnabled": true,
"limitsNavigationsToAppBoundDomains": true,

13
ios/.gitignore vendored
View File

@@ -11,3 +11,16 @@ capacitor-cordova-ios-plugins
# Generated Config files
App/App/capacitor.config.json
App/App/config.xml
# User-specific Xcode files
App/App.xcodeproj/xcuserdata/*.xcuserdatad/
App/App.xcodeproj/*.xcuserstate
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
# Generated Icons from capacitor-assets (also Contents.json which is confusing; see BUILDING.md)
App/App/Assets.xcassets/AppIcon.appiconset
App/App/Assets.xcassets/Splash.imageset

View File

@@ -14,7 +14,7 @@
504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; };
504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; };
50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; };
A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */; };
97EF2DC6FD76C3643D680B8D /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 90DCAFB4D8948F7A50C13800 /* Pods_App.framework */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -27,9 +27,9 @@
504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = "<group>"; };
AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_App.framework; sourceTree = BUILT_PRODUCTS_DIR; };
AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.release.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig"; sourceTree = "<group>"; };
FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.debug.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.debug.xcconfig"; sourceTree = "<group>"; };
90DCAFB4D8948F7A50C13800 /* Pods_App.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_App.framework; sourceTree = BUILT_PRODUCTS_DIR; };
E2E9297D5D02C549106C77F9 /* Pods-App.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.release.xcconfig"; path = "Target Support Files/Pods-App/Pods-App.release.xcconfig"; sourceTree = "<group>"; };
EAEC6436E595F7CD3A1C9E96 /* Pods-App.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.debug.xcconfig"; path = "Target Support Files/Pods-App/Pods-App.debug.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -37,17 +37,17 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */,
97EF2DC6FD76C3643D680B8D /* Pods_App.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
27E2DDA53C4D2A4D1A88CE4A /* Frameworks */ = {
4B546315E668C7A13939F417 /* Frameworks */ = {
isa = PBXGroup;
children = (
AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */,
90DCAFB4D8948F7A50C13800 /* Pods_App.framework */,
);
name = Frameworks;
sourceTree = "<group>";
@@ -57,8 +57,8 @@
children = (
504EC3061FED79650016851F /* App */,
504EC3051FED79650016851F /* Products */,
7F8756D8B27F46E3366F6CEA /* Pods */,
27E2DDA53C4D2A4D1A88CE4A /* Frameworks */,
BA325FFCDCE8D334E5C7AEBE /* Pods */,
4B546315E668C7A13939F417 /* Frameworks */,
);
sourceTree = "<group>";
};
@@ -85,13 +85,13 @@
path = App;
sourceTree = "<group>";
};
7F8756D8B27F46E3366F6CEA /* Pods */ = {
BA325FFCDCE8D334E5C7AEBE /* Pods */ = {
isa = PBXGroup;
children = (
FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */,
AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */,
EAEC6436E595F7CD3A1C9E96 /* Pods-App.debug.xcconfig */,
E2E9297D5D02C549106C77F9 /* Pods-App.release.xcconfig */,
);
name = Pods;
path = Pods;
sourceTree = "<group>";
};
/* End PBXGroup section */
@@ -101,12 +101,13 @@
isa = PBXNativeTarget;
buildConfigurationList = 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */;
buildPhases = (
6634F4EFEBD30273BCE97C65 /* [CP] Check Pods Manifest.lock */,
92977BEA1068CC097A57FC77 /* [CP] Check Pods Manifest.lock */,
504EC3001FED79650016851F /* Sources */,
504EC3011FED79650016851F /* Frameworks */,
504EC3021FED79650016851F /* Resources */,
9592DBEFFC6D2A0C8D5DEB22 /* [CP] Embed Pods Frameworks */,
012076E8FFE4BF260A79B034 /* Fix Privacy Manifest */,
3525031ED1C96EF4CF6E9959 /* [CP] Embed Pods Frameworks */,
96A7EF592DF3366D00084D51 /* Fix Privacy Manifest */,
);
buildRules = (
);
@@ -186,28 +187,10 @@
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PROJECT_DIR}/app_privacy_manifest_fixer/fixer.sh\" ";
shellScript = "\"${PROJECT_DIR}/app_privacy_manifest_fixer/fixer.sh\" \n";
showEnvVarsInLog = 0;
};
6634F4EFEBD30273BCE97C65 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-App-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
9592DBEFFC6D2A0C8D5DEB22 /* [CP] Embed Pods Frameworks */ = {
3525031ED1C96EF4CF6E9959 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
@@ -222,6 +205,47 @@
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-App/Pods-App-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
92977BEA1068CC097A57FC77 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-App-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
96A7EF592DF3366D00084D51 /* Fix Privacy Manifest */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = "Fix Privacy Manifest";
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "$PROJECT_DIR/app_privacy_manifest_fixer/fixer.sh\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
@@ -375,11 +399,12 @@
};
504EC3171FED79650016851F /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */;
baseConfigurationReference = EAEC6436E595F7CD3A1C9E96 /* Pods-App.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 18;
CURRENT_PROJECT_VERSION = 26;
DEVELOPMENT_TEAM = GM3FS5JQPH;
ENABLE_APP_SANDBOX = NO;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
INFOPLIST_FILE = App/Info.plist;
@@ -388,7 +413,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.4.7;
MARKETING_VERSION = 0.5.1;
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -401,11 +426,12 @@
};
504EC3181FED79650016851F /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */;
baseConfigurationReference = E2E9297D5D02C549106C77F9 /* Pods-App.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 18;
CURRENT_PROJECT_VERSION = 26;
DEVELOPMENT_TEAM = GM3FS5JQPH;
ENABLE_APP_SANDBOX = NO;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
INFOPLIST_FILE = App/Info.plist;
@@ -414,7 +440,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.4.7;
MARKETING_VERSION = 0.5.1;
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";

View File

@@ -9,8 +9,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Initialize SQLite
let sqlite = SQLite()
sqlite.initialize()
//let sqlite = SQLite()
//sqlite.initialize()
// Override point for customization after application launch.
return true

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

View File

@@ -1,14 +0,0 @@
{
"images": [
{
"idiom": "universal",
"size": "1024x1024",
"filename": "AppIcon-512@2x.png",
"platform": "ios"
}
],
"info": {
"author": "xcode",
"version": 1
}
}

View File

@@ -1,23 +0,0 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "splash-2732x2732-2.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "splash-2732x2732-1.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "splash-2732x2732.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

View File

@@ -27,4 +27,9 @@ end
post_install do |installer|
assertDeploymentTarget(installer)
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64'
end
end
end

View File

@@ -5,6 +5,10 @@ PODS:
- Capacitor
- CapacitorCamera (6.1.2):
- Capacitor
- CapacitorCommunitySqlite (6.0.2):
- Capacitor
- SQLCipher
- ZIPFoundation
- CapacitorCordova (6.2.1)
- CapacitorFilesystem (6.0.3):
- Capacitor
@@ -73,11 +77,18 @@ PODS:
- nanopb/decode (2.30910.0)
- nanopb/encode (2.30910.0)
- PromisesObjC (2.4.0)
- SQLCipher (4.9.0):
- SQLCipher/standard (= 4.9.0)
- SQLCipher/common (4.9.0)
- SQLCipher/standard (4.9.0):
- SQLCipher/common
- ZIPFoundation (0.9.19)
DEPENDENCIES:
- "Capacitor (from `../../node_modules/@capacitor/ios`)"
- "CapacitorApp (from `../../node_modules/@capacitor/app`)"
- "CapacitorCamera (from `../../node_modules/@capacitor/camera`)"
- "CapacitorCommunitySqlite (from `../../node_modules/@capacitor-community/sqlite`)"
- "CapacitorCordova (from `../../node_modules/@capacitor/ios`)"
- "CapacitorFilesystem (from `../../node_modules/@capacitor/filesystem`)"
- "CapacitorMlkitBarcodeScanning (from `../../node_modules/@capacitor-mlkit/barcode-scanning`)"
@@ -98,6 +109,8 @@ SPEC REPOS:
- MLKitVision
- nanopb
- PromisesObjC
- SQLCipher
- ZIPFoundation
EXTERNAL SOURCES:
Capacitor:
@@ -106,6 +119,8 @@ EXTERNAL SOURCES:
:path: "../../node_modules/@capacitor/app"
CapacitorCamera:
:path: "../../node_modules/@capacitor/camera"
CapacitorCommunitySqlite:
:path: "../../node_modules/@capacitor-community/sqlite"
CapacitorCordova:
:path: "../../node_modules/@capacitor/ios"
CapacitorFilesystem:
@@ -121,6 +136,7 @@ SPEC CHECKSUMS:
Capacitor: c95400d761e376be9da6be5a05f226c0e865cebf
CapacitorApp: e1e6b7d05e444d593ca16fd6d76f2b7c48b5aea7
CapacitorCamera: 9bc7b005d0e6f1d5f525b8137045b60cffffce79
CapacitorCommunitySqlite: 0299d20f4b00c2e6aa485a1d8932656753937b9b
CapacitorCordova: 8d93e14982f440181be7304aa9559ca631d77fff
CapacitorFilesystem: 59270a63c60836248812671aa3b15df673fbaf74
CapacitorMlkitBarcodeScanning: 7652be9c7922f39203a361de735d340ae37e134e
@@ -138,7 +154,9 @@ SPEC CHECKSUMS:
MLKitVision: 90922bca854014a856f8b649d1f1f04f63fd9c79
nanopb: 438bc412db1928dac798aa6fd75726007be04262
PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47
SQLCipher: 31878d8ebd27e5c96db0b7cb695c96e9f8ad77da
ZIPFoundation: b8c29ea7ae353b309bc810586181fd073cb3312c
PODFILE CHECKSUM: 7e7e09e6937de7f015393aecf2cf7823645689b3
PODFILE CHECKSUM: f987510f7383b04a1b09ea8472bdadcd88b6c924
COCOAPODS: 1.16.2

1175
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "timesafari",
"version": "0.4.6",
"version": "0.5.1",
"description": "Time Safari Application",
"author": {
"name": "Time Safari Team"
@@ -46,7 +46,7 @@
"electron:build-mac-universal": "npm run build:electron-prod && electron-builder --mac --universal"
},
"dependencies": {
"@capacitor-community/sqlite": "^6.0.2",
"@capacitor-community/sqlite": "6.0.2",
"@capacitor-mlkit/barcode-scanning": "^6.0.0",
"@capacitor/android": "^6.2.0",
"@capacitor/app": "^6.0.0",
@@ -171,7 +171,7 @@
},
"main": "./dist-electron/main.js",
"build": {
"appId": "app.timesafari",
"appId": "app.timesafari.app",
"productName": "TimeSafari",
"directories": {
"output": "dist-electron-packages"

View File

@@ -2,5 +2,6 @@ dependencies:
- gradle
- java
- pod
- rubygems.org
# other dependencies are discovered via package.json & requirements.txt & Gemfile (I'm guessing).

View File

@@ -1,5 +1,6 @@
eth_keys
pywebview
pyinstaller>=6.12.0
setuptools>=69.0.0 # Required for distutils for electron-builder on macOS
# For development
watchdog>=3.0.0 # For file watching support

View File

@@ -51,7 +51,7 @@ const { existsSync } = require('fs');
*/
function checkCommand(command, errorMessage) {
try {
execSync(command + ' --version', { stdio: 'ignore' });
execSync(command, { stdio: 'ignore' });
return true;
} catch (e) {
console.error(`${errorMessage}`);
@@ -164,10 +164,10 @@ function main() {
// Check required command line tools
// These are essential for building and testing the application
success &= checkCommand('node', 'Node.js is required');
success &= checkCommand('npm', 'npm is required');
success &= checkCommand('gradle', 'Gradle is required for Android builds');
success &= checkCommand('xcodebuild', 'Xcode is required for iOS builds');
success &= checkCommand('node --version', 'Node.js is required');
success &= checkCommand('npm --version', 'npm is required');
success &= checkCommand('gradle --version', 'Gradle is required for Android builds');
success &= checkCommand('xcodebuild --help', 'Xcode is required for iOS builds');
// Check platform-specific development environments
success &= checkAndroidSetup();

View File

@@ -170,7 +170,7 @@ const executeDeeplink = async (url, description, log) => {
try {
// Stop the app before executing the deep link
execSync('adb shell am force-stop app.timesafari');
execSync('adb shell am force-stop app.timesafari.app');
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1s
execSync(`adb shell am start -W -a android.intent.action.VIEW -d "${url}" -c android.intent.category.BROWSABLE`);

View File

@@ -4,7 +4,7 @@
<!-- Messages in the upper-right - https://github.com/emmanuelsw/notiwind -->
<NotificationGroup group="alert">
<div
class="fixed top-[calc(env(safe-area-inset-top)+1rem)] right-4 left-4 sm:left-auto sm:w-full sm:max-w-sm flex flex-col items-start justify-end"
class="fixed z-[90] top-[max(1rem,env(safe-area-inset-top))] right-4 left-4 sm:left-auto sm:w-full sm:max-w-sm flex flex-col items-start justify-end"
>
<Notification
v-slot="{ notifications, close }"
@@ -548,13 +548,13 @@ export default class App extends Vue {
<style>
#Content {
padding-left: 1.5rem;
padding-right: 1.5rem;
padding-top: calc(env(safe-area-inset-top) + 1.5rem);
padding-bottom: calc(env(safe-area-inset-bottom) + 1.5rem);
padding-left: max(1.5rem, env(safe-area-inset-left));
padding-right: max(1.5rem, env(safe-area-inset-right));
padding-top: max(1.5rem, env(safe-area-inset-top));
padding-bottom: max(1.5rem, env(safe-area-inset-bottom));
}
#QuickNav ~ #Content {
padding-bottom: calc(env(safe-area-inset-bottom) + 6rem);
padding-bottom: calc(env(safe-area-inset-bottom) + 6.333rem);
}
</style>

View File

@@ -14,22 +14,34 @@
class="flex items-center justify-between gap-2 text-lg bg-slate-200 border border-slate-300 border-b-0 rounded-t-md px-3 sm:px-4 py-1 sm:py-2"
>
<div class="flex items-center gap-2">
<div v-if="record.issuerDid">
<router-link
v-if="record.issuerDid && !isHiddenDid(record.issuerDid)"
:to="{
path: '/did/' + encodeURIComponent(record.issuerDid),
}"
title="More details about this person"
>
<EntityIcon
:entity-id="record.issuerDid"
class="rounded-full bg-white overflow-hidden !size-[2rem] object-cover"
/>
</div>
<div v-else>
<font-awesome
icon="person-circle-question"
class="text-slate-300 text-[2rem]"
/>
</div>
</router-link>
<font-awesome
v-else-if="isHiddenDid(record.issuerDid)"
icon="eye-slash"
class="text-slate-400 !size-[2rem] cursor-pointer"
@click="notifyHiddenPerson"
/>
<font-awesome
v-else
icon="person-circle-question"
class="text-slate-400 !size-[2rem] cursor-pointer"
@click="notifyUnknownPerson"
/>
<div>
<h3 class="font-semibold">
{{ record.issuer.known ? record.issuer.displayName : "" }}
<h3 v-if="record.issuer.known" class="font-semibold leading-tight">
{{ record.issuer.displayName }}
</h3>
<p class="ms-auto text-xs text-slate-500 italic">
{{ friendlyDate }}
@@ -37,7 +49,11 @@
</div>
</div>
<a class="cursor-pointer" @click="$emit('loadClaim', record.jwtId)">
<a
class="cursor-pointer"
data-testid="circle-info-link"
@click="$emit('loadClaim', record.jwtId)"
>
<font-awesome icon="circle-info" class="fa-fw text-slate-500" />
</a>
</div>
@@ -46,7 +62,7 @@
<!-- Record Image -->
<div
v-if="record.image"
class="bg-cover mb-6 -mt-3 sm:-mt-4 -mx-3 sm:-mx-4"
class="bg-cover mb-2 -mt-3 sm:-mt-4 -mx-3 sm:-mx-4"
:style="`background-image: url(${record.image});`"
>
<a
@@ -62,29 +78,59 @@
</a>
</div>
<!-- Description -->
<p class="font-medium">
<a class="cursor-pointer" @click="$emit('loadClaim', record.jwtId)">
{{ description }}
</a>
</p>
<div
class="relative flex justify-between gap-4 max-w-[40rem] mx-auto mb-5"
class="relative flex justify-between gap-4 max-w-[40rem] mx-auto mt-4"
>
<!-- Source -->
<div
class="w-[8rem] sm:w-[12rem] text-center bg-white border border-slate-200 rounded p-2 sm:p-3"
class="w-[7rem] sm:w-[12rem] text-center bg-white border border-slate-200 rounded p-2 sm:p-3"
>
<div class="relative w-fit mx-auto">
<div>
<!-- Project Icon -->
<div v-if="record.providerPlanName">
<ProjectIcon
:entity-id="record.providerPlanName"
:icon-size="48"
class="rounded size-[3rem] sm:size-[4rem] *:w-full *:h-full"
/>
<router-link
:to="{
path:
'/project/' +
encodeURIComponent(record.providerPlanHandleId || ''),
}"
title="View project details"
>
<ProjectIcon
:entity-id="record.providerPlanHandleId || ''"
:icon-size="48"
class="rounded size-[3rem] sm:size-[4rem] *:w-full *:h-full"
/>
</router-link>
</div>
<!-- Identicon for DIDs -->
<div v-else-if="record.agentDid">
<EntityIcon
:entity-id="record.agentDid"
:profile-image-url="record.issuer.profileImageUrl"
class="rounded-full bg-slate-100 overflow-hidden !size-[3rem] sm:!size-[4rem]"
<router-link
v-if="!isHiddenDid(record.agentDid)"
:to="{
path: '/did/' + encodeURIComponent(record.agentDid),
}"
title="More details about this person"
>
<EntityIcon
:entity-id="record.agentDid"
:profile-image-url="record.issuer.profileImageUrl"
class="rounded-full bg-slate-100 overflow-hidden !size-[3rem] sm:!size-[4rem]"
/>
</router-link>
<font-awesome
v-else
icon="eye-slash"
class="text-slate-300 !size-[3rem] sm:!size-[4rem]"
@click="notifyHiddenPerson"
/>
</div>
<!-- Unknown Person -->
@@ -92,6 +138,7 @@
<font-awesome
icon="person-circle-question"
class="text-slate-300 text-[3rem] sm:text-[4rem]"
@click="notifyUnknownPerson"
/>
</div>
</div>
@@ -110,9 +157,11 @@
<!-- Arrow -->
<div
class="absolute inset-x-[8rem] sm:inset-x-[12rem] mx-2 top-1/2 -translate-y-1/2"
class="absolute inset-x-[7rem] sm:inset-x-[12rem] mx-2 top-1/2 -translate-y-1/2"
>
<div class="text-sm text-center leading-none font-semibold pe-[15px]">
<div
class="text-sm text-center leading-none font-semibold pe-2 sm:pe-4"
>
{{ fetchAmount }}
</div>
@@ -129,24 +178,47 @@
<!-- Destination -->
<div
class="w-[8rem] sm:w-[12rem] text-center bg-white border border-slate-200 rounded p-2 sm:p-3"
class="w-[7rem] sm:w-[12rem] text-center bg-white border border-slate-200 rounded p-2 sm:p-3"
>
<div class="relative w-fit mx-auto">
<div>
<!-- Project Icon -->
<div v-if="record.recipientProjectName">
<ProjectIcon
:entity-id="record.recipientProjectName"
:icon-size="48"
class="rounded size-[3rem] sm:size-[4rem] *:w-full *:h-full"
/>
<router-link
:to="{
path:
'/project/' +
encodeURIComponent(record.fulfillsPlanHandleId || ''),
}"
title="View project details"
>
<ProjectIcon
:entity-id="record.fulfillsPlanHandleId || ''"
:icon-size="48"
class="rounded size-[3rem] sm:size-[4rem] *:w-full *:h-full"
/>
</router-link>
</div>
<!-- Identicon for DIDs -->
<div v-else-if="record.recipientDid">
<EntityIcon
:entity-id="record.recipientDid"
:profile-image-url="record.receiver.profileImageUrl"
class="rounded-full bg-slate-100 overflow-hidden !size-[3rem] sm:!size-[4rem]"
<router-link
v-if="!isHiddenDid(record.recipientDid)"
:to="{
path: '/did/' + encodeURIComponent(record.recipientDid),
}"
title="More details about this person"
>
<EntityIcon
:entity-id="record.recipientDid"
:profile-image-url="record.receiver.profileImageUrl"
class="rounded-full bg-slate-100 overflow-hidden !size-[3rem] sm:!size-[4rem]"
/>
</router-link>
<font-awesome
v-else
icon="eye-slash"
class="text-slate-300 !size-[3rem] sm:!size-[4rem]"
@click="notifyHiddenPerson"
/>
</div>
<!-- Unknown Person -->
@@ -154,6 +226,7 @@
<font-awesome
icon="person-circle-question"
class="text-slate-300 text-[3rem] sm:text-[4rem]"
@click="notifyUnknownPerson"
/>
</div>
</div>
@@ -170,13 +243,6 @@
</div>
</div>
</div>
<!-- Description -->
<p class="font-medium">
<a class="cursor-pointer" @click="$emit('loadClaim', record.jwtId)">
{{ description }}
</a>
</p>
</div>
</li>
</template>
@@ -186,8 +252,9 @@ import { Component, Prop, Vue, Emit } from "vue-facing-decorator";
import { GiveRecordWithContactInfo } from "../types";
import EntityIcon from "./EntityIcon.vue";
import { isGiveClaimType, notifyWhyCannotConfirm } from "../libs/util";
import { containsHiddenDid } from "../libs/endorserServer";
import { containsHiddenDid, isHiddenDid } from "../libs/endorserServer";
import ProjectIcon from "./ProjectIcon.vue";
import { NotificationIface } from "../constants/app";
@Component({
components: {
@@ -202,6 +269,33 @@ export default class ActivityListItem extends Vue {
@Prop() activeDid!: string;
@Prop() confirmerIdList?: string[];
isHiddenDid = isHiddenDid;
$notify!: (notification: NotificationIface, timeout?: number) => void;
notifyHiddenPerson() {
this.$notify(
{
group: "alert",
type: "warning",
title: "Person Outside Your Network",
text: "This person is not visible to you.",
},
3000,
);
}
notifyUnknownPerson() {
this.$notify(
{
group: "alert",
type: "warning",
title: "Unidentified Person",
text: "Nobody specific was recognized.",
},
3000,
);
}
@Emit()
cacheImage(image: string) {
return image;
@@ -222,7 +316,7 @@ export default class ActivityListItem extends Vue {
const claim =
(this.record.fullClaim as unknown).claim || this.record.fullClaim;
return `${claim.description}`;
return `${claim?.description || ""}`;
}
private displayAmount(code: string, amt: number) {

View 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>

View File

@@ -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" />
* ``` */
@@ -24,9 +25,7 @@ backup and database export, with platform-specific download instructions. * *
class="block w-full text-center text-md bg-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-1.5 py-2 rounded-md"
@click="exportDatabase()"
>
Download Settings & Contacts
<br />
(excluding Identifier Data)
Download Contacts
</button>
<a
ref="downloadLink"
@@ -45,38 +44,52 @@ 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>
<script lang="ts">
import { Component, Prop, Vue } from "vue-facing-decorator";
import { AppString, NotificationIface, USE_DEXIE_DB } from "../constants/app";
import { db } from "../db/index";
import { logger } from "../utils/logger";
import { AppString, NotificationIface } from "../constants/app";
import { Contact } from "../db/tables/contacts";
import * as databaseUtil from "../db/databaseUtil";
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
@@ -131,24 +144,27 @@ export default class DataExportSection extends Vue {
*/
public async exportDatabase() {
try {
if (!USE_DEXIE_DB) {
throw new Error("Not implemented");
let allContacts: Contact[] = [];
const platformService = PlatformServiceFactory.getInstance();
const result = await platformService.dbQuery(`SELECT * FROM contacts`);
if (result) {
allContacts = databaseUtil.mapQueryResultToValues(
result,
) as unknown as Contact[];
}
const blob = await db.export({
prettyJson: true,
transform: (table, value, key) => {
if (table === "contacts") {
// Dexie inserts a number 0 when some are undefined, so we need to totally remove them.
Object.keys(value).forEach((prop) => {
if (value[prop] === undefined) {
delete value[prop];
}
});
}
return { value, key };
},
});
const fileName = `${AppString.APP_NAME_NO_SPACES}-backup.json`;
// if (USE_DEXIE_DB) {
// await db.open();
// allContacts = await db.contacts.toArray();
// }
// Convert contacts to export format
const exportData = contactsToExportJson(allContacts);
const jsonStr = JSON.stringify(exportData, null, 2);
const blob = new Blob([jsonStr], { type: "application/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
@@ -159,9 +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
const content = await blob.text();
await this.platformService.writeAndShareFile(fileName, content);
// 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.");
}
@@ -172,11 +200,20 @@ export default class DataExportSection extends Vue {
type: "success",
title: "Export Successful",
text: this.platformCapabilities.hasFileDownload
? "See your downloads directory for the backup. It is in the Dexie format."
: "You should have been prompted to save your backup file.",
? "See your downloads directory for the backup."
: "Backup saved to persistent storage that survives app installations. Use the share dialog to access your file and choose where to save it permanently.",
},
-1,
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(
@@ -210,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>

View File

@@ -104,7 +104,6 @@ import { USE_DEXIE_DB } from "@/constants/app";
import * as databaseUtil from "../db/databaseUtil";
import { MASTER_SETTINGS_KEY } from "../db/tables/settings";
import { db, retrieveSettingsForActiveAccount } from "../db/index";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
@Component({
components: {
@@ -143,19 +142,23 @@ export default class FeedFilters extends Vue {
async toggleHasVisibleDid() {
this.settingChanged = true;
this.hasVisibleDid = !this.hasVisibleDid;
await db.settings.update(MASTER_SETTINGS_KEY, {
await databaseUtil.updateDefaultSettings({
filterFeedByVisible: this.hasVisibleDid,
});
if (USE_DEXIE_DB) {
await db.settings.update(MASTER_SETTINGS_KEY, {
filterFeedByVisible: this.hasVisibleDid,
});
}
}
async toggleNearby() {
this.settingChanged = true;
this.isNearby = !this.isNearby;
const platformService = PlatformServiceFactory.getInstance();
await platformService.dbExec(
`UPDATE settings SET filterFeedByNearby = ? WHERE id = ?`,
[this.isNearby, MASTER_SETTINGS_KEY],
);
await databaseUtil.updateDefaultSettings({
filterFeedByNearby: this.isNearby,
});
if (USE_DEXIE_DB) {
await db.settings.update(MASTER_SETTINGS_KEY, {
@@ -169,11 +172,10 @@ export default class FeedFilters extends Vue {
this.settingChanged = true;
}
const platformService = PlatformServiceFactory.getInstance();
await platformService.dbExec(
`UPDATE settings SET filterFeedByNearby = ? AND filterFeedByVisible = ? WHERE id = ?`,
[false, false, MASTER_SETTINGS_KEY],
);
await databaseUtil.updateDefaultSettings({
filterFeedByNearby: false,
filterFeedByVisible: false,
});
if (USE_DEXIE_DB) {
await db.settings.update(MASTER_SETTINGS_KEY, {
@@ -191,11 +193,10 @@ export default class FeedFilters extends Vue {
this.settingChanged = true;
}
const platformService = PlatformServiceFactory.getInstance();
await platformService.dbExec(
`UPDATE settings SET filterFeedByNearby = ? AND filterFeedByVisible = ? WHERE id = ?`,
[true, true, MASTER_SETTINGS_KEY],
);
await databaseUtil.updateDefaultSettings({
filterFeedByNearby: true,
filterFeedByVisible: true,
});
if (USE_DEXIE_DB) {
await db.settings.update(MASTER_SETTINGS_KEY, {

View File

@@ -320,10 +320,7 @@ export default class GiftedDialog extends Vue {
this.fromProjectId,
);
if (
result.type === "error" ||
this.isGiveCreationError(result.response)
) {
if (!result.success) {
const errorMessage = this.getGiveCreationErrorMessage(result);
logger.error("Error with give creation result:", result);
this.$notify(
@@ -370,15 +367,6 @@ export default class GiftedDialog extends Vue {
// Helper functions for readability
/**
* @param result response "data" from the server
* @returns true if the result indicates an error
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
isGiveCreationError(result: any) {
return result.status !== 201 || result.data?.error;
}
/**
* @param result direct response eg. ErrorResult or SuccessResult (potentially with embedded "data")
* @returns best guess at an error message

View File

@@ -227,6 +227,7 @@ export default class GivenPrompts extends Vue {
let someContactDbIndex = Math.floor(Math.random() * this.numContacts);
let count = 0;
// as long as the index has an entry, loop
while (
this.shownContactDbIndices[someContactDbIndex] != null &&
@@ -245,9 +246,8 @@ export default class GivenPrompts extends Vue {
[someContactDbIndex],
);
if (result) {
this.currentContact = databaseUtil.mapQueryResultToValues(result)[
someContactDbIndex
] as unknown as Contact;
const mappedContacts = databaseUtil.mapQueryResultToValues(result);
this.currentContact = mappedContacts[0] as unknown as Contact;
}
if (USE_DEXIE_DB) {
await db.open();

View File

@@ -48,11 +48,7 @@
<span>
{{ didInfo(visDid) }}
<span v-if="!serverUtil.isEmptyOrHiddenDid(visDid)">
<a
:href="`/did/${visDid}`"
target="_blank"
class="text-blue-500"
>
<a :href="`/did/${visDid}`" class="text-blue-500">
<font-awesome
icon="arrow-up-right-from-square"
class="fa-fw"

View File

@@ -4,7 +4,9 @@
<div class="text-lg text-center font-bold relative">
<h1 id="ViewHeading" class="text-center font-bold">
<span v-if="uploading">Uploading Image&hellip;</span>
<span v-else-if="blob">Crop Image</span>
<span v-else-if="blob">{{
crop ? "Crop Image" : "Preview Image"
}}</span>
<span v-else-if="showCameraPreview">Upload Image</span>
<span v-else>Add Photo</span>
</h1>
@@ -119,12 +121,23 @@
playsinline
muted
></video>
<button
class="absolute bottom-4 left-1/2 -translate-x-1/2 bg-white text-slate-800 p-3 rounded-full text-2xl leading-none"
@click="capturePhoto"
<div
class="absolute bottom-4 inset-x-0 flex items-center justify-center gap-4"
>
<font-awesome icon="camera" class="w-[1em]" />
</button>
<button
class="bg-white text-slate-800 p-3 rounded-full text-2xl leading-none"
@click="capturePhoto"
>
<font-awesome icon="camera" class="w-[1em]" />
</button>
<button
v-if="platformCapabilities.isMobile"
class="bg-white text-slate-800 p-3 rounded-full text-2xl leading-none"
@click="rotateCamera"
>
<font-awesome icon="rotate" class="w-[1em]" />
</button>
</div>
</div>
</div>
<div
@@ -229,12 +242,12 @@
<p class="mb-2">
Before you can upload a photo, a friend needs to register you.
</p>
<router-link
:to="{ name: 'contact-qr' }"
<button
class="inline-block text-md uppercase bg-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-4 py-2 rounded-md"
@click="handleQRCodeClick"
>
Share Your Info
</router-link>
</button>
</div>
</template>
</div>
@@ -247,6 +260,7 @@ import axios from "axios";
import { ref } from "vue";
import { Component, Vue } from "vue-facing-decorator";
import VuePictureCropper, { cropper } from "vue-picture-cropper";
import { Capacitor } from "@capacitor/core";
import {
DEFAULT_IMAGE_API_SERVER,
NotificationIface,
@@ -254,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";
@@ -267,6 +281,11 @@ const inputImageFileNameRef = ref<Blob>();
type: Boolean,
default: true,
},
defaultCameraMode: {
type: String,
default: "environment",
validator: (value: string) => ["environment", "user"].includes(value),
},
},
})
export default class ImageMethodDialog extends Vue {
@@ -308,6 +327,9 @@ export default class ImageMethodDialog extends Vue {
/** Camera stream reference */
private cameraStream: MediaStream | null = null;
/** Current camera facing mode */
private currentFacingMode: "environment" | "user" = "environment";
private platformService = PlatformServiceFactory.getInstance();
URL = window.URL || window.webkitURL;
@@ -369,15 +391,16 @@ export default class ImageMethodDialog extends Vue {
}
open(setImageFn: (arg: string) => void, claimType: string, crop?: boolean) {
logger.debug("ImageMethodDialog.open called");
this.claimType = claimType;
this.crop = !!crop;
this.imageCallback = setImageFn;
this.visible = true;
this.currentFacingMode = this.defaultCameraMode as "environment" | "user";
// Start camera preview immediately if not on mobile
if (!this.platformCapabilities.isNativeApp) {
this.startCameraPreview();
}
// Start camera preview immediately
logger.debug("Starting camera preview from open()");
this.startCameraPreview();
}
async uploadImageFile(event: Event) {
@@ -446,46 +469,24 @@ export default class ImageMethodDialog extends Vue {
logger.debug("startCameraPreview called");
logger.debug("Current showCameraPreview state:", this.showCameraPreview);
logger.debug("Platform capabilities:", this.platformCapabilities);
logger.debug("MediaDevices available:", !!navigator.mediaDevices);
logger.debug(
"getUserMedia available:",
!!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
);
if (this.platformCapabilities.isNativeApp) {
logger.debug("Using platform service for mobile device");
this.cameraState = "initializing";
this.cameraStateMessage = "Using platform camera service...";
try {
const result = await this.platformService.takePicture();
this.blob = result.blob;
this.fileName = result.fileName;
this.cameraState = "ready";
this.cameraStateMessage = "Photo captured successfully";
} catch (error) {
logger.error("Error taking picture:", error);
this.cameraState = "error";
this.cameraStateMessage =
error instanceof Error ? error.message : "Failed to take picture";
this.error =
error instanceof Error ? error.message : "Failed to take picture";
this.$notify(
{
group: "alert",
type: "danger",
title: "Error",
text: "Failed to take picture. Please try again.",
},
5000,
);
}
return;
}
logger.debug("Starting camera preview for desktop browser");
try {
this.cameraState = "initializing";
this.cameraStateMessage = "Requesting camera access...";
this.showCameraPreview = true;
await this.$nextTick();
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
throw new Error("Camera API not available in this browser");
}
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: "environment" },
video: { facingMode: this.currentFacingMode },
});
logger.debug("Camera access granted");
this.cameraStream = stream;
@@ -499,25 +500,36 @@ export default class ImageMethodDialog extends Vue {
videoElement.srcObject = stream;
await new Promise((resolve) => {
videoElement.onloadedmetadata = () => {
videoElement.play().then(() => {
resolve(true);
});
videoElement
.play()
.then(() => {
logger.debug("Video element started playing");
resolve(true);
})
.catch((error) => {
logger.error("Error playing video:", error);
throw error;
});
};
});
} else {
logger.error("Video element not found");
throw new Error("Video element not found");
}
} catch (error) {
logger.error("Error starting camera preview:", error);
let errorMessage =
error instanceof Error ? error.message : "Failed to access camera";
if (
error.name === "NotReadableError" ||
error.name === "TrackStartError"
error instanceof Error &&
(error.name === "NotReadableError" || error.name === "TrackStartError")
) {
errorMessage =
"Camera is in use by another application. Please close any other apps or browser tabs using the camera and try again.";
} else if (
error.name === "NotAllowedError" ||
error.name === "PermissionDeniedError"
error instanceof Error &&
(error.name === "NotAllowedError" ||
error.name === "PermissionDeniedError")
) {
errorMessage =
"Camera access was denied. Please allow camera access in your browser settings.";
@@ -525,6 +537,7 @@ export default class ImageMethodDialog extends Vue {
this.cameraState = "error";
this.cameraStateMessage = errorMessage;
this.error = errorMessage;
this.showCameraPreview = false;
this.$notify(
{
group: "alert",
@@ -534,7 +547,6 @@ export default class ImageMethodDialog extends Vue {
},
5000,
);
this.showCameraPreview = false;
}
}
@@ -564,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();
}
@@ -586,6 +598,21 @@ export default class ImageMethodDialog extends Vue {
}
}
async rotateCamera() {
// Toggle between front and back cameras
this.currentFacingMode =
this.currentFacingMode === "environment" ? "user" : "environment";
// Stop current stream
if (this.cameraStream) {
this.cameraStream.getTracks().forEach((track) => track.stop());
this.cameraStream = null;
}
// Start new stream with updated facing mode
await this.startCameraPreview();
}
private createBlobURL(blob: Blob): string {
return URL.createObjectURL(blob);
}
@@ -620,6 +647,7 @@ export default class ImageMethodDialog extends Vue {
5000,
);
this.uploading = false;
this.close();
return;
}
formData.append("image", this.blob, this.fileName || "photo.jpg");
@@ -674,6 +702,7 @@ export default class ImageMethodDialog extends Vue {
);
this.uploading = false;
this.blob = undefined;
this.close();
}
}
@@ -681,6 +710,14 @@ export default class ImageMethodDialog extends Vue {
toggleDiagnostics() {
this.showDiagnostics = !this.showDiagnostics;
}
private handleQRCodeClick() {
if (Capacitor.isNativePlatform()) {
this.$router.push({ name: "contact-qr-scan-full" });
} else {
this.$router.push({ name: "contact-qr" });
}
}
}
</script>

View File

@@ -301,7 +301,7 @@ export default class MembersList extends Vue {
this.decryptedMembers.length === 0 ||
this.decryptedMembers[0].member.memberId !== this.members[0].memberId
) {
return "Your password is not the same as the organizer. Reload or have them check their password.";
return "Your password is not the same as the organizer. Retry or have them check their password.";
} else {
// the first (organizer) member was decrypted OK
return "";
@@ -342,7 +342,7 @@ export default class MembersList extends Vue {
group: "alert",
type: "info",
title: "Contact Exists",
text: "They are in your contacts. If you want to remove them, you must do that from the contacts screen.",
text: "They are in your contacts. To remove them, use the contacts page.",
},
10000,
);
@@ -352,7 +352,7 @@ export default class MembersList extends Vue {
group: "alert",
type: "info",
title: "Contact Available",
text: "This is to add them to your contacts. If you want to remove them later, you must do that from the contacts screen.",
text: "This is to add them to your contacts. To remove them later, use the contacts page.",
},
10000,
);

View File

@@ -249,10 +249,7 @@ export default class OfferDialog extends Vue {
this.projectId,
);
if (
result.type === "error" ||
this.isOfferCreationError(result.response)
) {
if (!result.success) {
const errorMessage = this.getOfferCreationErrorMessage(result);
logger.error("Error with offer creation result:", result);
this.$notify(
@@ -296,15 +293,6 @@ export default class OfferDialog extends Vue {
// Helper functions for readability
/**
* @param result response "data" from the server
* @returns true if the result indicates an error
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
isOfferCreationError(result: any) {
return result.status !== 201 || result.data?.error;
}
/**
* @param result direct response eg. ErrorResult or SuccessResult (potentially with embedded "data")
* @returns best guess at an error message

View File

@@ -5,7 +5,7 @@
<h1 class="text-xl font-bold text-center mb-4 relative">
Welcome to Time Safari
<br />
- Showcasing Gratitude & Magnifying Time
- Showcase Impact & Magnify Time
<div
class="text-lg text-center leading-none absolute right-0 -top-1"
@click="onClickClose(true)"
@@ -14,6 +14,9 @@
</div>
</h1>
The feed underneath this pop-up shows the latest contributions, some from
people and some from projects.
<p v-if="isRegistered" class="mt-4">
You can now log things that you've seen:
<span v-if="numContacts > 0">
@@ -23,14 +26,10 @@
<span class="bg-green-600 text-white rounded-full">
<font-awesome icon="plus" class="fa-fw" />
</span>
button to express your appreciation for... whatever -- maybe thanks for
showing you all these fascinating stories of
<em>gratitude</em>.
button to express your appreciation for... whatever.
</p>
<p v-else class="mt-4">
The feed underneath this pop-up shows the latest gifts that others have
recognized. Once someone registers you, you can log your appreciation,
too.
<p class="mt-4">
Once someone registers you, you can log your appreciation, too.
</p>
<p class="mt-4">
@@ -260,7 +259,7 @@ export default class OnboardingDialog extends Vue {
this.visible = true;
if (this.page === OnboardPage.Create) {
// we'll assume that they've been through all the other pages
await databaseUtil.updateAccountSettings(this.activeDid, {
await databaseUtil.updateDidSpecificSettings(this.activeDid, {
finishedOnboarding: true,
});
if (USE_DEXIE_DB) {
@@ -274,7 +273,7 @@ export default class OnboardingDialog extends Vue {
async onClickClose(done?: boolean, goHome?: boolean) {
this.visible = false;
if (done) {
await databaseUtil.updateAccountSettings(this.activeDid, {
await databaseUtil.updateDidSpecificSettings(this.activeDid, {
finishedOnboarding: true,
});
if (USE_DEXIE_DB) {

View File

@@ -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();
}
},

View File

@@ -1,18 +1,14 @@
<!-- eslint-disable vue/no-v-html -->
<template>
<a
v-if="linkToFull && imageUrl"
v-if="linkToFullImage && imageUrl"
:href="imageUrl"
target="_blank"
class="h-full w-full object-contain"
>
<div class="h-full w-full object-contain" v-html="generateIdenticon()" />
<div class="h-full w-full object-contain" v-html="generateIcon()" />
</a>
<div
v-else
class="h-full w-full object-contain"
v-html="generateIdenticon()"
/>
<div v-else class="h-full w-full object-contain" v-html="generateIcon()" />
</template>
<script lang="ts">
import { toSvg } from "jdenticon";
@@ -35,9 +31,9 @@ export default class ProjectIcon extends Vue {
@Prop entityId = "";
@Prop iconSize = 0;
@Prop imageUrl = "";
@Prop linkToFull = false;
@Prop linkToFullImage = false;
generateIdenticon() {
generateIcon() {
if (this.imageUrl) {
return `<img src="${this.imageUrl}" class="w-full h-full object-contain" />`;
} else {

View File

@@ -1,5 +1,5 @@
<template>
<div class="absolute right-5 top-[calc(env(safe-area-inset-top)+0.75rem)]">
<div class="absolute right-5 top-[max(0.75rem,env(safe-area-inset-top))]">
<span class="align-center text-red-500 mr-2">{{ message }}</span>
<span class="ml-2">
<router-link

View File

@@ -74,7 +74,7 @@ export default class UserNameDialog extends Vue {
async onClickSaveChanges() {
const platformService = PlatformServiceFactory.getInstance();
await platformService.dbExec(
"UPDATE settings SET firstName = ? WHERE key = ?",
"UPDATE settings SET firstName = ? WHERE id = ?",
[this.givenName, MASTER_SETTINGS_KEY],
);
if (USE_DEXIE_DB) {

View File

@@ -33,18 +33,18 @@ export const APP_SERVER =
export const DEFAULT_ENDORSER_API_SERVER =
import.meta.env.VITE_DEFAULT_ENDORSER_API_SERVER ||
AppString.TEST_ENDORSER_API_SERVER;
AppString.PROD_ENDORSER_API_SERVER;
export const DEFAULT_IMAGE_API_SERVER =
import.meta.env.VITE_DEFAULT_IMAGE_API_SERVER ||
AppString.TEST_IMAGE_API_SERVER;
AppString.PROD_IMAGE_API_SERVER;
export const DEFAULT_PARTNER_API_SERVER =
import.meta.env.VITE_DEFAULT_PARTNER_API_SERVER ||
AppString.TEST_PARTNER_API_SERVER;
AppString.PROD_PARTNER_API_SERVER;
export const DEFAULT_PUSH_SERVER =
import.meta.env.VITE_DEFAULT_PUSH_SERVER || "https://timesafari.app";
import.meta.env.VITE_DEFAULT_PUSH_SERVER || AppString.PROD_PUSH_SERVER;
export const IMAGE_TYPE_PROFILE = "profile";

View File

@@ -1,5 +1,4 @@
import migrationService from "../services/migrationService";
import type { QueryExecResult } from "../interfaces/database";
import { DEFAULT_ENDORSER_API_SERVER } from "@/constants/app";
import { arrayBufferToBase64 } from "@/libs/crypto";
@@ -119,16 +118,21 @@ const MIGRATIONS = [
},
];
export async function registerMigrations(): Promise<void> {
// Register all migrations
for (const migration of MIGRATIONS) {
await migrationService.registerMigration(migration);
}
}
export async function runMigrations(
sqlExec: (sql: string, params?: unknown[]) => Promise<Array<QueryExecResult>>,
/**
* @param sqlExec - A function that executes a SQL statement and returns the result
* @param extractMigrationNames - A function that extracts the names (string array) from "select name from migrations"
*/
export async function runMigrations<T>(
sqlExec: (sql: string) => Promise<unknown>,
sqlQuery: (sql: string) => Promise<T>,
extractMigrationNames: (result: T) => Set<string>,
): Promise<void> {
await registerMigrations();
await migrationService.runMigrations(sqlExec);
for (const migration of MIGRATIONS) {
migrationService.registerMigration(migration);
}
await migrationService.runMigrations(
sqlExec,
sqlQuery,
extractMigrationNames,
);
}

View File

@@ -37,7 +37,20 @@ export async function updateDefaultSettings(
}
}
export async function updateAccountSettings(
export async function insertDidSpecificSettings(
did: string,
settings: Partial<Settings> = {},
): Promise<boolean> {
const platform = PlatformServiceFactory.getInstance();
const { sql, params } = generateInsertStatement(
{ ...settings, accountDid: did }, // make sure accountDid is set to the given value
"settings",
);
const result = await platform.dbExec(sql, params);
return result.changes === 1;
}
export async function updateDidSpecificSettings(
accountDid: string,
settingsChanges: Settings,
): Promise<boolean> {
@@ -55,20 +68,7 @@ export async function updateAccountSettings(
);
const updateResult = await platform.dbExec(updateSql, updateParams);
// If no record was updated, insert a new one
if (updateResult.changes === 1) {
return true;
} else {
const columns = Object.keys(settingsChanges);
const values = Object.values(settingsChanges);
const placeholders = values.map(() => "?").join(", ");
const insertSql = `INSERT INTO settings (${columns.join(", ")}) VALUES (${placeholders})`;
const result = await platform.dbExec(insertSql, values);
return result.changes === 1;
}
return updateResult.changes === 1;
}
const DEFAULT_SETTINGS: Settings = {
@@ -80,9 +80,8 @@ const DEFAULT_SETTINGS: Settings = {
// retrieves default settings
export async function retrieveSettingsForDefaultAccount(): Promise<Settings> {
const platform = PlatformServiceFactory.getInstance();
const result = await platform.dbQuery("SELECT * FROM settings WHERE id = ?", [
MASTER_SETTINGS_KEY,
]);
const sql = "SELECT * FROM settings WHERE id = ?";
const result = await platform.dbQuery(sql, [MASTER_SETTINGS_KEY]);
if (!result) {
return DEFAULT_SETTINGS;
} else {
@@ -98,32 +97,77 @@ export async function retrieveSettingsForDefaultAccount(): Promise<Settings> {
}
}
/**
* Retrieves settings for the active account, merging with default settings
*
* @returns Promise<Settings> Combined settings with account-specific overrides
* @throws Will log specific errors for debugging but returns default settings on failure
*/
export async function retrieveSettingsForActiveAccount(): Promise<Settings> {
const defaultSettings = await retrieveSettingsForDefaultAccount();
if (!defaultSettings.activeDid) {
return defaultSettings;
} else {
const platform = PlatformServiceFactory.getInstance();
const result = await platform.dbQuery(
"SELECT * FROM settings WHERE accountDid = ?",
[defaultSettings.activeDid],
);
const overrideSettings = result
? (mapColumnsToValues(result.columns, result.values)[0] as Settings)
: {};
const overrideSettingsFiltered = Object.fromEntries(
Object.entries(overrideSettings).filter(([_, v]) => v !== null),
);
const settings = { ...defaultSettings, ...overrideSettingsFiltered };
if (settings.searchBoxes) {
// @ts-expect-error - the searchBoxes field is a string in the DB
settings.searchBoxes = JSON.parse(settings.searchBoxes);
try {
// Get default settings first
const defaultSettings = await retrieveSettingsForDefaultAccount();
// If no active DID, return defaults
if (!defaultSettings.activeDid) {
return defaultSettings;
}
return settings;
// Get account-specific settings
try {
const platform = PlatformServiceFactory.getInstance();
const result = await platform.dbQuery(
"SELECT * FROM settings WHERE accountDid = ?",
[defaultSettings.activeDid],
);
if (!result?.values?.length) {
// we created DID-specific settings when generated or imported, so this shouldn't happen
return defaultSettings;
}
// Map and filter settings
const overrideSettings = mapColumnsToValues(
result.columns,
result.values,
)[0] as Settings;
const overrideSettingsFiltered = Object.fromEntries(
Object.entries(overrideSettings).filter(([_, v]) => v !== null),
);
// Merge settings
const settings = { ...defaultSettings, ...overrideSettingsFiltered };
// Handle searchBoxes parsing
if (settings.searchBoxes) {
settings.searchBoxes = parseJsonField(settings.searchBoxes, []);
}
return settings;
} catch (error) {
logConsoleAndDb(
`[databaseUtil] Failed to retrieve account settings for ${defaultSettings.activeDid}: ${error}`,
true,
);
// Return defaults on error
return defaultSettings;
}
} catch (error) {
logConsoleAndDb(
`[databaseUtil] Failed to retrieve default settings: ${error}`,
true,
);
// Return minimal default settings on complete failure
return {
id: MASTER_SETTINGS_KEY,
activeDid: undefined,
apiServer: DEFAULT_ENDORSER_API_SERVER,
};
}
}
let lastCleanupDate: string | null = null;
export let memoryLogs: string[] = [];
/**
* Logs a message to the database with proper handling of concurrent writes
@@ -136,6 +180,7 @@ export async function logToDb(message: string): Promise<void> {
const nowKey = new Date().toISOString();
try {
memoryLogs.push(`${new Date().toISOString()} ${message}`);
// Try to insert first, if it fails due to UNIQUE constraint, update instead
await platform.dbExec("INSERT INTO logs (date, message) VALUES (?, ?)", [
nowKey,
@@ -148,6 +193,9 @@ export async function logToDb(message: string): Promise<void> {
const sevenDaysAgo = new Date(
new Date().getTime() - 7 * 24 * 60 * 60 * 1000,
);
memoryLogs = memoryLogs.filter(
(log) => log.split(" ")[0] > sevenDaysAgo.toDateString(),
);
await platform.dbExec("DELETE FROM logs WHERE date < ?", [
sevenDaysAgo.toDateString(),
]);
@@ -192,6 +240,7 @@ export function generateInsertStatement(
const values = Object.values(model).filter((value) => value !== undefined);
const placeholders = values.map(() => "?").join(", ");
const insertSql = `INSERT INTO ${tableName} (${columns.join(", ")}) VALUES (${placeholders})`;
return {
sql: insertSql,
params: values,
@@ -217,10 +266,8 @@ export function generateUpdateStatement(
const params: unknown[] = [];
Object.entries(model).forEach(([key, value]) => {
if (value !== undefined) {
setClauses.push(`${key} = ?`);
params.push(value);
}
setClauses.push(`${key} = ?`);
params.push(value ?? null);
});
if (setClauses.length === 0) {
@@ -265,3 +312,115 @@ export function mapColumnsToValues(
return obj;
});
}
/**
* Debug function to inspect raw settings data in the database
* This helps diagnose issues with data corruption or malformed JSON
* @param did Optional DID to inspect specific account settings
* @author Matthew Raymer
*/
export async function debugSettingsData(did?: string): Promise<void> {
try {
const platform = PlatformServiceFactory.getInstance();
// Get all settings records
const allSettings = await platform.dbQuery("SELECT * FROM settings");
logConsoleAndDb(
`[DEBUG] Total settings records: ${allSettings?.values?.length || 0}`,
false,
);
if (allSettings?.values?.length) {
allSettings.values.forEach((row, index) => {
const settings = mapColumnsToValues(allSettings.columns, [row])[0];
logConsoleAndDb(`[DEBUG] Settings record ${index + 1}:`, false);
logConsoleAndDb(`[DEBUG] - ID: ${settings.id}`, false);
logConsoleAndDb(`[DEBUG] - accountDid: ${settings.accountDid}`, false);
logConsoleAndDb(`[DEBUG] - activeDid: ${settings.activeDid}`, false);
if (settings.searchBoxes) {
logConsoleAndDb(
`[DEBUG] - searchBoxes type: ${typeof settings.searchBoxes}`,
false,
);
logConsoleAndDb(
`[DEBUG] - searchBoxes value: ${String(settings.searchBoxes)}`,
false,
);
// Try to parse it
try {
const parsed = JSON.parse(String(settings.searchBoxes));
logConsoleAndDb(
`[DEBUG] - searchBoxes parsed successfully: ${JSON.stringify(parsed)}`,
false,
);
} catch (parseError) {
logConsoleAndDb(
`[DEBUG] - searchBoxes parse error: ${parseError}`,
true,
);
}
}
logConsoleAndDb(
`[DEBUG] - Full record: ${JSON.stringify(settings, null, 2)}`,
false,
);
});
}
// If specific DID provided, also check accounts table
if (did) {
const account = await platform.dbQuery(
"SELECT * FROM accounts WHERE did = ?",
[did],
);
logConsoleAndDb(
`[DEBUG] Account for ${did}: ${JSON.stringify(account, null, 2)}`,
false,
);
}
} catch (error) {
logConsoleAndDb(`[DEBUG] Error inspecting settings data: ${error}`, true);
}
}
/**
* Platform-agnostic JSON parsing utility
* Handles different SQLite implementations:
* - Web SQLite (wa-sqlite/absurd-sql): Auto-parses JSON strings to objects
* - Capacitor SQLite: Returns raw strings that need manual parsing
*
* @param value The value to parse (could be string or already parsed object)
* @param defaultValue Default value if parsing fails
* @returns Parsed object or default value
* @author Matthew Raymer
*/
export function parseJsonField<T>(value: unknown, defaultValue: T): T {
try {
// If already an object (web SQLite auto-parsed), return as-is
if (typeof value === "object" && value !== null) {
return value as T;
}
// If it's a string (Capacitor SQLite or fallback), parse it
if (typeof value === "string") {
return JSON.parse(value) as T;
}
// If it's null/undefined, return default
if (value === null || value === undefined) {
return defaultValue;
}
return defaultValue;
} catch (error) {
logConsoleAndDb(
`[databaseUtil] Failed to parse JSON field: ${error}`,
true,
);
return defaultValue;
}
}

View File

@@ -1,14 +1,24 @@
import { GenericVerifiableCredential } from "./common";
/**
* Types of Claims
*
* Note that these are for the claims that get signed.
* Records that are the latest edited entities are in the records.ts file.
*
*/
export interface AgreeVerifiableCredential {
"@context": string;
import { ClaimObject } from "./common";
export interface AgreeActionClaim extends ClaimObject {
"@context": "https://schema.org";
"@type": string;
object: Record<string, unknown>;
}
// Note that previous VCs may have additional fields.
// https://endorser.ch/doc/html/transactions.html#id4
export interface GiveVerifiableCredential extends GenericVerifiableCredential {
export interface GiveActionClaim extends ClaimObject {
// context is optional because it might be embedded in another claim, eg. an AgreeAction
"@context"?: "https://schema.org";
"@type": "GiveAction";
agent?: { identifier: string };
description?: string;
@@ -16,43 +26,21 @@ export interface GiveVerifiableCredential extends GenericVerifiableCredential {
identifier?: string;
image?: string;
object?: { amountOfThisGood: number; unitCode: string };
provider?: GenericVerifiableCredential;
provider?: ClaimObject;
recipient?: { identifier: string };
type: string[];
issuer: string;
issuanceDate: string;
credentialSubject: {
id: string;
type: "GiveAction";
offeredBy?: {
type: "Person";
identifier: string;
};
offeredTo?: {
type: "Person";
identifier: string;
};
offeredToProject?: {
type: "Project";
identifier: string;
};
offeredToProjectVisibleToDids?: string[];
offeredToVisibleToDids?: string[];
offeredByVisibleToDids?: string[];
amount: {
type: "QuantitativeValue";
value: number;
unitCode: string;
};
startTime?: string;
endTime?: string;
};
}
export interface JoinActionClaim extends ClaimObject {
agent?: { identifier: string };
event?: { organizer?: { name: string }; name?: string; startTime?: string };
}
// Note that previous VCs may have additional fields.
// https://endorser.ch/doc/html/transactions.html#id8
export interface OfferVerifiableCredential extends GenericVerifiableCredential {
export interface OfferClaim extends ClaimObject {
"@context": "https://schema.org";
"@type": "Offer";
agent?: { identifier: string };
description?: string;
fulfills?: { "@type": string; identifier?: string; lastClaimId?: string }[];
identifier?: string;
@@ -67,43 +55,18 @@ export interface OfferVerifiableCredential extends GenericVerifiableCredential {
name?: string;
};
};
provider?: GenericVerifiableCredential;
offeredBy?: {
type?: "Person";
identifier: string;
};
provider?: ClaimObject;
recipient?: { identifier: string };
validThrough?: string;
type: string[];
issuer: string;
issuanceDate: string;
credentialSubject: {
id: string;
type: "Offer";
offeredBy?: {
type: "Person";
identifier: string;
};
offeredTo?: {
type: "Person";
identifier: string;
};
offeredToProject?: {
type: "Project";
identifier: string;
};
offeredToProjectVisibleToDids?: string[];
offeredToVisibleToDids?: string[];
offeredByVisibleToDids?: string[];
amount: {
type: "QuantitativeValue";
value: number;
unitCode: string;
};
startTime?: string;
endTime?: string;
};
}
// Note that previous VCs may have additional fields.
// https://endorser.ch/doc/html/transactions.html#id7
export interface PlanVerifiableCredential extends GenericVerifiableCredential {
export interface PlanActionClaim extends ClaimObject {
"@context": "https://schema.org";
"@type": "PlanAction";
name: string;
@@ -117,11 +80,18 @@ export interface PlanVerifiableCredential extends GenericVerifiableCredential {
}
// AKA Registration & RegisterAction
export interface RegisterVerifiableCredential {
"@context": string;
export interface RegisterActionClaim extends ClaimObject {
"@context": "https://schema.org";
"@type": "RegisterAction";
agent: { identifier: string };
identifier?: string;
object: string;
object?: string;
participant?: { identifier: string };
}
export interface TenureClaim extends ClaimObject {
"@context": "https://endorser.ch";
"@type": "Tenure";
party?: { identifier: string };
spatialUnit?: { geo?: { polygon?: string } };
}

View File

@@ -1,6 +1,6 @@
// similar to VerifiableCredentialSubject... maybe rename this
export interface GenericVerifiableCredential {
"@context": string | string[];
"@context"?: string;
"@type": string;
[key: string]: unknown;
}
@@ -37,23 +37,26 @@ export interface ErrorResult extends ResultWithType {
export interface KeyMeta {
did: string;
name?: string;
publicKeyHex: string;
mnemonic: string;
derivationPath: string;
registered?: boolean;
profileImageUrl?: string;
identity?: string; // Stringified IIdentifier object from Veramo
derivationPath?: string;
passkeyCredIdHex?: string; // The Webauthn credential ID in hex, if this is from a passkey
[key: string]: unknown;
}
export interface KeyMetaMaybeWithPrivate extends KeyMeta {
mnemonic?: string; // 12 or 24 words encoding the seed
identity?: string; // Stringified IIdentifier object from Veramo
}
export interface KeyMetaWithPrivate extends KeyMeta {
mnemonic: string; // 12 or 24 words encoding the seed
identity: string; // Stringified IIdentifier object from Veramo
}
export interface QuantitativeValue extends GenericVerifiableCredential {
"@type": "QuantitativeValue";
"@context": string | string[];
"@context"?: string;
amountOfThisGood: number;
unitCode: string;
[key: string]: unknown;
}
export interface AxiosErrorResponse {
@@ -87,94 +90,21 @@ export interface CreateAndSubmitClaimResult {
handleId?: string;
}
export interface PlanSummaryRecord {
handleId: string;
issuer: string;
claim: GenericVerifiableCredential;
[key: string]: unknown;
}
export interface Agent {
identifier?: string;
did?: string;
[key: string]: unknown;
}
export interface ClaimObject {
"@type": string;
"@context"?: string | string[];
fulfills?: Array<{
"@type": string;
identifier?: string;
[key: string]: unknown;
}>;
object?: GenericVerifiableCredential;
agent?: Agent;
participant?: {
identifier?: string;
[key: string]: unknown;
};
identifier?: string;
"@context"?: string;
[key: string]: unknown;
}
export interface VerifiableCredentialClaim {
"@context": string | string[];
"@context"?: string;
"@type": string;
type: string[];
credentialSubject: ClaimObject;
[key: string]: unknown;
}
export interface GiveVerifiableCredential extends GenericVerifiableCredential {
"@type": "GiveAction";
"@context": string | string[];
object?: GenericVerifiableCredential;
agent?: Agent;
participant?: {
identifier?: string;
[key: string]: unknown;
};
fulfills?: Array<{
"@type": string;
identifier?: string;
[key: string]: unknown;
}>;
[key: string]: unknown;
}
export interface OfferVerifiableCredential extends GenericVerifiableCredential {
"@type": "OfferAction";
"@context": string | string[];
object?: GenericVerifiableCredential;
agent?: Agent;
participant?: {
identifier?: string;
[key: string]: unknown;
};
itemOffered?: {
description?: string;
isPartOf?: {
"@type": string;
identifier: string;
[key: string]: unknown;
};
[key: string]: unknown;
};
[key: string]: unknown;
}
export interface RegisterVerifiableCredential
extends GenericVerifiableCredential {
"@type": "RegisterAction";
"@context": string | string[];
agent: {
identifier: string;
};
object: string;
participant?: {
identifier: string;
};
identifier?: string;
[key: string]: unknown;
}

View File

@@ -12,6 +12,4 @@ export interface DatabaseService {
sql: string,
params?: unknown[],
): Promise<{ changes: number; lastId?: number }>;
getOneRow(sql: string, params?: unknown[]): Promise<unknown[] | undefined>;
getAll(sql: string, params?: unknown[]): Promise<unknown[][]>;
}

View File

@@ -1,13 +1,17 @@
/**
* Interfaces for the give records with limited contact information, good to show on a feed.
**/
import { GiveSummaryRecord } from "./records";
// Common interface for contact information
// Common interface for views with summary contact information
export interface ContactInfo {
known: boolean;
displayName: string;
profileImageUrl?: string;
}
// Define the contact information fields
// Define a subset of contact information fields
interface GiveContactInfo {
giver: ContactInfo;
issuer: ContactInfo;
@@ -17,5 +21,5 @@ interface GiveContactInfo {
image?: string;
}
// Combine GiveSummaryRecord with contact information using intersection type
// Combine GiveSummaryRecord with contact information
export type GiveRecordWithContactInfo = GiveSummaryRecord & GiveContactInfo;

View File

@@ -13,9 +13,9 @@ export type {
export type {
// From claims.ts
GiveVerifiableCredential,
OfferVerifiableCredential,
RegisterVerifiableCredential,
GiveActionClaim,
OfferClaim,
RegisterActionClaim,
} from "./claims";
export type {

View File

@@ -1,14 +1,14 @@
import { GiveVerifiableCredential, OfferVerifiableCredential } from "./claims";
import { GiveActionClaim, OfferClaim } from "./claims";
// a summary record; the VC is found the fullClaim field
export interface GiveSummaryRecord {
[x: string]: PropertyKey | undefined | GiveVerifiableCredential;
[x: string]: PropertyKey | undefined | GiveActionClaim;
type?: string;
agentDid: string;
amount: number;
amountConfirmed: number;
description: string;
fullClaim: GiveVerifiableCredential;
fullClaim: GiveActionClaim;
fulfillsHandleId: string;
fulfillsPlanHandleId?: string;
fulfillsType?: string;
@@ -26,7 +26,7 @@ export interface OfferSummaryRecord {
amount: number;
amountGiven: number;
amountGivenConfirmed: number;
fullClaim: OfferVerifiableCredential;
fullClaim: OfferClaim;
fulfillsPlanHandleId: string;
handleId: string;
issuerDid: string;

View File

@@ -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),

View File

@@ -32,7 +32,7 @@ export const newIdentifier = (
publicHex: string,
privateHex: string,
derivationPath: string,
): Omit<IIdentifier, keyof "provider"> => {
): IIdentifier => {
return {
did: DEFAULT_DID_PROVIDER_NAME + ":" + address,
keys: [

View File

@@ -17,7 +17,7 @@ import { didEthLocalResolver } from "./did-eth-local-resolver";
import { PEER_DID_PREFIX, verifyPeerSignature } from "./didPeer";
import { base64urlDecodeString, createDidPeerJwt } from "./passkeyDidPeer";
import { urlBase64ToUint8Array } from "./util";
import { KeyMeta } from "../../../interfaces/common";
import { KeyMeta, KeyMetaWithPrivate } from "../../../interfaces/common";
export const ETHR_DID_PREFIX = "did:ethr:";
export const JWT_VERIFY_FAILED_CODE = "JWT_VERIFY_FAILED";
@@ -34,7 +34,7 @@ export function isFromPasskey(keyMeta?: KeyMeta): boolean {
}
export async function createEndorserJwtForKey(
account: KeyMeta,
account: KeyMetaWithPrivate,
payload: object,
expiresIn?: number,
) {

View File

@@ -38,7 +38,14 @@ import {
getPasskeyExpirationSeconds,
} from "../libs/util";
import { createEndorserJwtForKey } from "../libs/crypto/vc";
import { KeyMeta } from "../interfaces/common";
import {
GiveActionClaim,
JoinActionClaim,
OfferClaim,
PlanActionClaim,
RegisterActionClaim,
TenureClaim,
} from "../interfaces/claims";
import {
GenericCredWrapper,
@@ -46,15 +53,13 @@ import {
AxiosErrorResponse,
UserInfo,
CreateAndSubmitClaimResult,
PlanSummaryRecord,
GiveVerifiableCredential,
OfferVerifiableCredential,
RegisterVerifiableCredential,
ClaimObject,
VerifiableCredentialClaim,
Agent,
QuantitativeValue,
KeyMetaWithPrivate,
KeyMetaMaybeWithPrivate,
} from "../interfaces/common";
import { PlanSummaryRecord } from "../interfaces/records";
import { logger } from "../utils/logger";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
@@ -136,7 +141,7 @@ export function isDid(did: string): boolean {
* @param {string} did - The DID to check
* @returns {boolean} True if DID is hidden
*/
export function isHiddenDid(did: string): boolean {
export function isHiddenDid(did: string | undefined): boolean {
return did === HIDDEN_DID;
}
@@ -650,7 +655,7 @@ export async function getNewOffersToUserProjects(
* @param lastClaimId supplied when editing a previous claim
*/
export function hydrateGive(
vcClaimOrig?: GiveVerifiableCredential,
vcClaimOrig?: GiveActionClaim,
fromDid?: string,
toDid?: string,
description?: string,
@@ -662,15 +667,12 @@ export function hydrateGive(
imageUrl?: string,
providerPlanHandleId?: string,
lastClaimId?: string,
): GiveVerifiableCredential {
const vcClaim: GiveVerifiableCredential = vcClaimOrig
): GiveActionClaim {
const vcClaim: GiveActionClaim = vcClaimOrig
? R.clone(vcClaimOrig)
: {
"@context": SCHEMA_ORG_CONTEXT,
"@type": "GiveAction",
object: undefined,
agent: undefined,
fulfills: [],
};
if (lastClaimId) {
@@ -688,8 +690,6 @@ export function hydrateGive(
if (amount && !isNaN(amount)) {
const quantitativeValue: QuantitativeValue = {
"@context": SCHEMA_ORG_CONTEXT,
"@type": "QuantitativeValue",
amountOfThisGood: amount,
unitCode: unitCode || "HUR",
};
@@ -698,7 +698,7 @@ export function hydrateGive(
// Initialize fulfills array if not present
if (!Array.isArray(vcClaim.fulfills)) {
vcClaim.fulfills = [];
vcClaim.fulfills = vcClaim.fulfills ? [vcClaim.fulfills] : [];
}
// Filter and add fulfills elements
@@ -801,7 +801,7 @@ export async function createAndSubmitGive(
export async function editAndSubmitGive(
axios: Axios,
apiServer: string,
fullClaim: GenericCredWrapper<GiveVerifiableCredential>,
fullClaim: GenericCredWrapper<GiveActionClaim>,
issuerDid: string,
fromDid?: string,
toDid?: string,
@@ -842,7 +842,7 @@ export async function editAndSubmitGive(
* @param lastClaimId supplied when editing a previous claim
*/
export function hydrateOffer(
vcClaimOrig?: OfferVerifiableCredential,
vcClaimOrig?: OfferClaim,
fromDid?: string,
toDid?: string,
itemDescription?: string,
@@ -852,24 +852,22 @@ export function hydrateOffer(
fulfillsProjectHandleId?: string,
validThrough?: string,
lastClaimId?: string,
): OfferVerifiableCredential {
const vcClaim: OfferVerifiableCredential = vcClaimOrig
): OfferClaim {
const vcClaim: OfferClaim = vcClaimOrig
? R.clone(vcClaimOrig)
: {
"@context": SCHEMA_ORG_CONTEXT,
"@type": "OfferAction",
object: undefined,
agent: undefined,
itemOffered: {},
"@type": "Offer",
};
if (lastClaimId) {
// this is an edit
vcClaim.lastClaimId = lastClaimId;
delete vcClaim.identifier;
}
if (fromDid) {
vcClaim.agent = { identifier: fromDid };
vcClaim.offeredBy = { identifier: fromDid };
}
if (toDid) {
vcClaim.recipient = { identifier: toDid };
@@ -877,13 +875,10 @@ export function hydrateOffer(
vcClaim.description = conditionDescription || undefined;
if (amount && !isNaN(amount)) {
const quantitativeValue: QuantitativeValue = {
"@context": SCHEMA_ORG_CONTEXT,
"@type": "QuantitativeValue",
vcClaim.includesObject = {
amountOfThisGood: amount,
unitCode: unitCode || "HUR",
};
vcClaim.object = quantitativeValue;
}
if (itemDescription || fulfillsProjectHandleId) {
@@ -936,7 +931,7 @@ export async function createAndSubmitOffer(
undefined,
);
return createAndSubmitClaim(
vcClaim as OfferVerifiableCredential,
vcClaim as OfferClaim,
issuerDid,
apiServer,
axios,
@@ -946,7 +941,7 @@ export async function createAndSubmitOffer(
export async function editAndSubmitOffer(
axios: Axios,
apiServer: string,
fullClaim: GenericCredWrapper<OfferVerifiableCredential>,
fullClaim: GenericCredWrapper<OfferClaim>,
issuerDid: string,
itemDescription: string,
amount?: number,
@@ -969,7 +964,7 @@ export async function editAndSubmitOffer(
fullClaim.id,
);
return createAndSubmitClaim(
vcClaim as OfferVerifiableCredential,
vcClaim as OfferClaim,
issuerDid,
apiServer,
axios,
@@ -1043,7 +1038,7 @@ export async function createAndSubmitClaim(
}
export async function generateEndorserJwtUrlForAccount(
account: KeyMeta,
account: KeyMetaMaybeWithPrivate,
isRegistered: boolean,
givenName: string,
profileImageUrl: string,
@@ -1067,7 +1062,7 @@ export async function generateEndorserJwtUrlForAccount(
}
// Add the next key -- not recommended for the QR code for such a high resolution
if (isContact) {
if (isContact && account.derivationPath && account.mnemonic) {
const newDerivPath = nextDerivationPath(account.derivationPath);
const nextPublicHex = deriveAddress(account.mnemonic, newDerivPath)[2];
const nextPublicEncKey = Buffer.from(nextPublicHex, "hex");
@@ -1089,7 +1084,11 @@ export async function createEndorserJwtForDid(
expiresIn?: number,
) {
const account = await retrieveFullyDecryptedAccount(issuerDid);
return createEndorserJwtForKey(account as KeyMeta, payload, expiresIn);
return createEndorserJwtForKey(
account as KeyMetaWithPrivate,
payload,
expiresIn,
);
}
/**
@@ -1186,102 +1185,118 @@ export const claimSpecialDescription = (
identifiers: Array<string>,
contacts: Array<Contact>,
) => {
let claim = record.claim;
let claim:
| GenericVerifiableCredential
| GenericCredWrapper<GenericVerifiableCredential> = record.claim;
if ("claim" in claim) {
// it's a nested GenericCredWrapper
claim = claim.claim as GenericVerifiableCredential;
}
const issuer = didInfo(record.issuer, activeDid, identifiers, contacts);
const claimObj = claim as ClaimObject;
const type = claimObj["@type"] || "UnknownType";
const type = claim["@type"] || "UnknownType";
if (type === "AgreeAction") {
return (
issuer +
" agreed with " +
claimSummary(claimObj.object as GenericVerifiableCredential)
claimSummary(claim.object as GenericVerifiableCredential)
);
} else if (isAccept(claim)) {
return (
issuer +
" accepted " +
claimSummary(claimObj.object as GenericVerifiableCredential)
claimSummary(claim.object as GenericVerifiableCredential)
);
} else if (type === "GiveAction") {
const giveClaim = claim as GiveVerifiableCredential;
const agent: Agent = giveClaim.agent || {
identifier: undefined,
did: undefined,
};
const agentDid = agent.did || agent.identifier;
const contactInfo = agentDid
? didInfo(agentDid, activeDid, identifiers, contacts)
: "someone";
const offering = giveClaim.object
? " " + claimSummary(giveClaim.object)
const giveClaim = claim as GiveActionClaim;
// @ts-expect-error because .did may be found in legacy data, before March 2023
const legacyGiverDid = giveClaim.agent?.did;
const giver = giveClaim.agent?.identifier || legacyGiverDid;
const giverInfo = didInfo(giver, activeDid, identifiers, contacts);
let gaveAmount = giveClaim.object?.amountOfThisGood
? displayAmount(
giveClaim.object.unitCode as string,
giveClaim.object.amountOfThisGood as number,
)
: "";
const recipient = giveClaim.participant?.identifier;
const recipientInfo = recipient
? " to " + didInfo(recipient, activeDid, identifiers, contacts)
if (giveClaim.description) {
if (gaveAmount) {
gaveAmount = gaveAmount + ", and also: ";
}
gaveAmount = gaveAmount + giveClaim.description;
}
if (!gaveAmount) {
gaveAmount = "something not described";
}
// @ts-expect-error because .did may be found in legacy data, before March 2023
const legacyRecipDid = giveClaim.recipient?.did;
const gaveRecipientId = giveClaim.recipient?.identifier || legacyRecipDid;
const gaveRecipientInfo = gaveRecipientId
? " to " + didInfo(gaveRecipientId, activeDid, identifiers, contacts)
: "";
return contactInfo + " gave" + offering + recipientInfo;
return giverInfo + " gave" + gaveRecipientInfo + ": " + gaveAmount;
} else if (type === "JoinAction") {
const joinClaim = claim as ClaimObject;
const agent: Agent = joinClaim.agent || {
identifier: undefined,
did: undefined,
};
const agentDid = agent.did || agent.identifier;
const contactInfo = agentDid
? didInfo(agentDid, activeDid, identifiers, contacts)
: "someone";
const object = joinClaim.object as GenericVerifiableCredential;
const objectInfo = object ? " " + claimSummary(object) : "";
return contactInfo + " joined" + objectInfo;
const joinClaim = claim as JoinActionClaim;
// @ts-expect-error because .did may be found in legacy data, before March 2023
const legacyDid = joinClaim.agent?.did;
const agent = joinClaim.agent?.identifier || legacyDid;
const contactInfo = didInfo(agent, activeDid, identifiers, contacts);
let eventOrganizer =
joinClaim.event &&
joinClaim.event.organizer &&
joinClaim.event.organizer.name;
eventOrganizer = eventOrganizer || "";
let eventName = joinClaim.event && joinClaim.event.name;
eventName = eventName ? " " + eventName : "";
let fullEvent = eventOrganizer + eventName;
fullEvent = fullEvent ? " attended the " + fullEvent : "";
let eventDate = joinClaim.event && joinClaim.event.startTime;
eventDate = eventDate ? " at " + eventDate : "";
return contactInfo + fullEvent + eventDate;
} else if (isOffer(claim)) {
const offerClaim = claim as OfferVerifiableCredential;
const agent: Agent = offerClaim.agent || {
identifier: undefined,
did: undefined,
};
const agentDid = agent.did || agent.identifier;
const contactInfo = agentDid
? didInfo(agentDid, activeDid, identifiers, contacts)
: "someone";
const offering = offerClaim.object
? " " + claimSummary(offerClaim.object)
: "";
const offerRecipientId = offerClaim.participant?.identifier;
const offerClaim = claim as OfferClaim;
const offerer = offerClaim.offeredBy?.identifier;
const contactInfo = didInfo(offerer, activeDid, identifiers, contacts);
let offering = "";
if (offerClaim.includesObject) {
offering +=
" " +
displayAmount(
offerClaim.includesObject.unitCode,
offerClaim.includesObject.amountOfThisGood,
);
}
if (offerClaim.itemOffered?.description) {
offering += ", saying: " + offerClaim.itemOffered?.description;
}
// @ts-expect-error because .did may be found in legacy data, before March 2023
const legacyDid = offerClaim.recipient?.did;
const offerRecipientId = offerClaim.recipient?.identifier || legacyDid;
const offerRecipientInfo = offerRecipientId
? " to " + didInfo(offerRecipientId, activeDid, identifiers, contacts)
: "";
return contactInfo + " offered" + offering + offerRecipientInfo;
} else if (type === "PlanAction") {
const planClaim = claim as ClaimObject;
const agent: Agent = planClaim.agent || {
identifier: undefined,
did: undefined,
};
const agentDid = agent.did || agent.identifier;
const contactInfo = agentDid
? didInfo(agentDid, activeDid, identifiers, contacts)
: "someone";
const object = planClaim.object as GenericVerifiableCredential;
const objectInfo = object ? " " + claimSummary(object) : "";
return contactInfo + " planned" + objectInfo;
const planClaim = claim as PlanActionClaim;
const claimer = planClaim.agent?.identifier || record.issuer;
const claimerInfo = didInfo(claimer, activeDid, identifiers, contacts);
return claimerInfo + " announced a project: " + planClaim.name;
} else if (type === "Tenure") {
const tenureClaim = claim as ClaimObject;
const agent: Agent = tenureClaim.agent || {
identifier: undefined,
did: undefined,
};
const agentDid = agent.did || agent.identifier;
const contactInfo = agentDid
? didInfo(agentDid, activeDid, identifiers, contacts)
: "someone";
const object = tenureClaim.object as GenericVerifiableCredential;
const objectInfo = object ? " " + claimSummary(object) : "";
return contactInfo + " has tenure" + objectInfo;
const tenureClaim = claim as TenureClaim;
// @ts-expect-error because .did may be found in legacy data, before March 2023
const legacyDid = tenureClaim.party?.did;
const claimer = tenureClaim.party?.identifier || legacyDid;
const contactInfo = didInfo(claimer, activeDid, identifiers, contacts);
const polygon = tenureClaim.spatialUnit?.geo?.polygon || "";
return (
contactInfo +
" possesses [" +
polygon.substring(0, polygon.indexOf(" ")) +
"...]"
);
} else {
return issuer + " declared " + claimSummary(claim);
}
@@ -1323,17 +1338,29 @@ export async function createEndorserJwtVcFromClaim(
return createEndorserJwtForDid(issuerDid, vcPayload);
}
/**
* Create a JWT for a RegisterAction claim.
*
* @param activeDid - The DID of the user creating the invite
* @param contact - The contact to register, with a 'did' field (all optional for invites)
* @param identifier - The identifier for the invite, usually random
* @param expiresIn - The number of seconds until the invite expires
* @returns The JWT for the RegisterAction claim
*/
export async function createInviteJwt(
activeDid: string,
contact: Contact,
contact?: Contact,
identifier?: string,
expiresIn?: number, // in seconds
): Promise<string> {
const vcClaim: RegisterVerifiableCredential = {
const vcClaim: RegisterActionClaim = {
"@context": SCHEMA_ORG_CONTEXT,
"@type": "RegisterAction",
agent: { identifier: activeDid },
object: SERVICE_ID,
identifier: identifier,
};
if (contact) {
if (contact?.did) {
vcClaim.participant = { identifier: contact.did };
}
@@ -1348,7 +1375,7 @@ export async function createInviteJwt(
};
// Create a signature using private key of identity
const vcJwt = await createEndorserJwtForDid(activeDid, vcPayload);
const vcJwt = await createEndorserJwtForDid(activeDid, vcPayload, expiresIn);
return vcJwt;
}

View File

@@ -34,14 +34,17 @@ import { containsHiddenDid } from "../libs/endorserServer";
import {
GenericCredWrapper,
GenericVerifiableCredential,
KeyMetaWithPrivate,
} from "../interfaces/common";
import { GiveSummaryRecord } from "../interfaces/records";
import { OfferVerifiableCredential } from "../interfaces/claims";
import { KeyMeta } from "../interfaces/common";
import { OfferClaim } from "../interfaces/claims";
import { createPeerDid } from "../libs/crypto/vc/didPeer";
import { registerCredential } from "../libs/crypto/vc/passkeyDidPeer";
import { logger } from "../utils/logger";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
import { sha256 } from "ethereum-cryptography/sha256";
import { IIdentifier } from "@veramo/core";
import { insertDidSpecificSettings, parseJsonField } from "../db/databaseUtil";
export interface GiverReceiverInputInfo {
did?: string;
@@ -80,18 +83,24 @@ export const UNIT_LONG: Record<string, string> = {
};
/* eslint-enable prettier/prettier */
const UNIT_CODES: Record<string, Record<string, string>> = {
const UNIT_CODES: Record<
string,
{ name: string; faIcon: string; decimals: number }
> = {
BTC: {
name: "Bitcoin",
faIcon: "bitcoin-sign",
decimals: 4,
},
HUR: {
name: "hours",
faIcon: "clock",
decimals: 0,
},
USD: {
name: "US Dollars",
faIcon: "dollar",
decimals: 2,
},
};
@@ -99,6 +108,13 @@ export function iconForUnitCode(unitCode: string) {
return UNIT_CODES[unitCode]?.faIcon || "question";
}
export function formattedAmount(amount: number, unitCode: string) {
const unit = UNIT_CODES[unitCode];
const amountStr = amount.toFixed(unit?.decimals ?? 4);
const unitName = unit?.name || "?";
return amountStr + " " + unitName;
}
// from https://stackoverflow.com/a/175787/845494
// ... though it appears even this isn't precisely right so keep doing "|| 0" or something in sensitive places
//
@@ -378,17 +394,19 @@ export function base64ToBlob(base64DataUrl: string, sliceSize = 512) {
* @param veriClaim is expected to have fields: claim and issuer
*/
export function offerGiverDid(
veriClaim: GenericCredWrapper<GenericVerifiableCredential>,
veriClaim: GenericCredWrapper<OfferClaim>,
): string | undefined {
let giver;
const claim = veriClaim.claim as OfferVerifiableCredential;
if (
claim.credentialSubject.offeredBy?.identifier &&
!serverUtil.isHiddenDid(claim.credentialSubject.offeredBy.identifier)
) {
giver = claim.credentialSubject.offeredBy.identifier;
} else if (veriClaim.issuer && !serverUtil.isHiddenDid(veriClaim.issuer)) {
giver = veriClaim.issuer;
const innerClaim = veriClaim.claim as OfferClaim;
let giver: string | undefined = undefined;
giver = innerClaim.offeredBy?.identifier;
if (giver && !serverUtil.isHiddenDid(giver)) {
return giver;
}
giver = veriClaim.issuer;
if (giver && !serverUtil.isHiddenDid(giver)) {
return giver;
}
return giver;
}
@@ -399,8 +417,13 @@ export function offerGiverDid(
*/
export const canFulfillOffer = (
veriClaim: GenericCredWrapper<GenericVerifiableCredential>,
isRegistered: boolean,
) => {
return veriClaim.claimType === "Offer" && !!offerGiverDid(veriClaim);
return (
isRegistered &&
veriClaim.claimType === "Offer" &&
!!offerGiverDid(veriClaim as GenericCredWrapper<OfferClaim>)
);
};
// return object with paths and arrays of DIDs for any keys ending in "VisibleToDid"
@@ -469,11 +492,7 @@ export function findAllVisibleToDids(
*
**/
export interface AccountKeyInfo
extends Omit<Account, "derivationPath">,
Omit<KeyMeta, "derivationPath"> {
derivationPath?: string; // Make it optional to match Account type
}
export type AccountKeyInfo = Account & KeyMetaWithPrivate;
export const retrieveAccountCount = async (): Promise<number> => {
let result = 0;
@@ -510,12 +529,16 @@ export const retrieveAccountDids = async (): Promise<string[]> => {
return allDids;
};
// This is provided and recommended when the full key is not necessary so that
// future work could separate this info from the sensitive key material.
/**
* This is provided and recommended when the full key is not necessary so that
* future work could separate this info from the sensitive key material.
*
* If you need the private key data, use retrieveFullyDecryptedAccount instead.
*/
export const retrieveAccountMetadata = async (
activeDid: string,
): Promise<AccountKeyInfo | undefined> => {
let result: AccountKeyInfo | undefined = undefined;
): Promise<Account | undefined> => {
let result: Account | undefined = undefined;
const platformService = PlatformServiceFactory.getInstance();
const dbAccount = await platformService.dbQuery(
`SELECT * FROM accounts WHERE did = ?`,
@@ -547,32 +570,16 @@ export const retrieveAccountMetadata = async (
return result;
};
export const retrieveAllAccountsMetadata = async (): Promise<Account[]> => {
const platformService = PlatformServiceFactory.getInstance();
const dbAccounts = await platformService.dbQuery(`SELECT * FROM accounts`);
const accounts = databaseUtil.mapQueryResultToValues(dbAccounts) as Account[];
let result = accounts.map((account) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { identity, mnemonic, ...metadata } = account;
return metadata as Account;
});
if (USE_DEXIE_DB) {
// one of the few times we use accountsDBPromise directly; try to avoid more usage
const accountsDB = await accountsDBPromise;
const array = await accountsDB.accounts.toArray();
result = array.map((account) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { identity, mnemonic, ...metadata } = account;
return metadata as Account;
});
}
return result;
};
/**
* This contains sensitive data. If possible, use retrieveAccountMetadata instead.
*
* @param activeDid
* @returns account info with private key data decrypted
*/
export const retrieveFullyDecryptedAccount = async (
activeDid: string,
): Promise<AccountKeyInfo | undefined> => {
let result: AccountKeyInfo | undefined = undefined;
): Promise<Account | undefined> => {
let result: Account | undefined = undefined;
const platformService = PlatformServiceFactory.getInstance();
const dbSecrets = await platformService.dbQuery(
`SELECT secretBase64 from secret`,
@@ -620,29 +627,45 @@ export const retrieveFullyDecryptedAccount = async (
return result;
};
// let's try and eliminate this
export const retrieveAllFullyDecryptedAccounts = async (): Promise<
Array<AccountEncrypted>
export const retrieveAllAccountsMetadata = async (): Promise<
AccountEncrypted[]
> => {
const platformService = PlatformServiceFactory.getInstance();
const queryResult = await platformService.dbQuery("SELECT * FROM accounts");
let allAccounts = databaseUtil.mapQueryResultToValues(
queryResult,
) as unknown as AccountEncrypted[];
const dbAccounts = await platformService.dbQuery(`SELECT * FROM accounts`);
const accounts = databaseUtil.mapQueryResultToValues(dbAccounts) as Account[];
let result = accounts.map((account) => {
return account as AccountEncrypted;
});
if (USE_DEXIE_DB) {
// one of the few times we use accountsDBPromise directly; try to avoid more usage
const accountsDB = await accountsDBPromise;
allAccounts = (await accountsDB.accounts.toArray()) as AccountEncrypted[];
const array = await accountsDB.accounts.toArray();
result = array.map((account) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { identity, mnemonic, ...metadata } = account;
// This is not accurate because they can't be decrypted, but we're removing Dexie anyway.
const identityStr = JSON.stringify(identity);
const encryptedAccount = {
identityEncrBase64: sha256(
new TextEncoder().encode(identityStr),
).toString(),
mnemonicEncrBase64: sha256(
new TextEncoder().encode(account.mnemonic),
).toString(),
...metadata,
};
return encryptedAccount as AccountEncrypted;
});
}
return allAccounts;
return result;
};
/**
* Saves a new identity to both SQL and Dexie databases
*/
export async function saveNewIdentity(
identity: string,
identity: IIdentifier,
mnemonic: string,
newId: { did: string; keys: Array<{ publicKeyHex: string }> },
derivationPath: string,
): Promise<void> {
try {
@@ -658,23 +681,24 @@ export async function saveNewIdentity(
}
const secretBase64 = secrets.values[0][0] as string;
const secret = base64ToArrayBuffer(secretBase64);
const encryptedIdentity = await simpleEncrypt(identity, secret);
const identityStr = JSON.stringify(identity);
const encryptedIdentity = await simpleEncrypt(identityStr, secret);
const encryptedMnemonic = await simpleEncrypt(mnemonic, secret);
const encryptedIdentityBase64 = arrayBufferToBase64(encryptedIdentity);
const encryptedMnemonicBase64 = arrayBufferToBase64(encryptedMnemonic);
await platformService.dbExec(
`INSERT INTO accounts (dateCreated, derivationPath, did, identityEncrBase64, mnemonicEncrBase64, publicKeyHex)
VALUES (?, ?, ?, ?, ?, ?)`,
[
new Date().toISOString(),
derivationPath,
newId.did,
encryptedIdentityBase64,
encryptedMnemonicBase64,
newId.keys[0].publicKeyHex,
],
);
await databaseUtil.updateDefaultSettings({ activeDid: newId.did });
const sql = `INSERT INTO accounts (dateCreated, derivationPath, did, identityEncrBase64, mnemonicEncrBase64, publicKeyHex)
VALUES (?, ?, ?, ?, ?, ?)`;
const params = [
new Date().toISOString(),
derivationPath,
identity.did,
encryptedIdentityBase64,
encryptedMnemonicBase64,
identity.keys[0].publicKeyHex,
];
await platformService.dbExec(sql, params);
await databaseUtil.updateDefaultSettings({ activeDid: identity.did });
await databaseUtil.insertDidSpecificSettings(identity.did);
if (USE_DEXIE_DB) {
// one of the few times we use accountsDBPromise directly; try to avoid more usage
@@ -682,12 +706,13 @@ export async function saveNewIdentity(
await accountsDB.accounts.add({
dateCreated: new Date().toISOString(),
derivationPath: derivationPath,
did: newId.did,
identity: identity,
did: identity.did,
identity: identityStr,
mnemonic: mnemonic,
publicKeyHex: newId.keys[0].publicKeyHex,
publicKeyHex: identity.keys[0].publicKeyHex,
});
await updateDefaultSettings({ activeDid: newId.did });
await updateDefaultSettings({ activeDid: identity.did });
await insertDidSpecificSettings(identity.did);
}
} catch (error) {
logger.error("Failed to update default settings:", error);
@@ -708,10 +733,11 @@ export const generateSaveAndActivateIdentity = async (): Promise<string> => {
deriveAddress(mnemonic);
const newId = newIdentifier(address, publicHex, privateHex, derivationPath);
const identity = JSON.stringify(newId);
await saveNewIdentity(identity, mnemonic, newId, derivationPath);
await databaseUtil.updateAccountSettings(newId.did, { isRegistered: false });
await saveNewIdentity(newId, mnemonic, derivationPath);
await databaseUtil.updateDidSpecificSettings(newId.did, {
isRegistered: false,
});
if (USE_DEXIE_DB) {
await updateAccountSettings(newId.did, { isRegistered: false });
}
@@ -753,7 +779,7 @@ export const registerSaveAndActivatePasskey = async (
): Promise<Account> => {
const account = await registerAndSavePasskey(keyName);
await databaseUtil.updateDefaultSettings({ activeDid: account.did });
await databaseUtil.updateAccountSettings(account.did, {
await databaseUtil.updateDidSpecificSettings(account.did, {
isRegistered: false,
});
if (USE_DEXIE_DB) {
@@ -814,3 +840,96 @@ export const sendTestThroughPushServer = async (
logger.log("Got response from web push server:", response);
return response;
};
/**
* Converts a Contact object to a CSV line string following the established format.
* The format matches CONTACT_CSV_HEADER: "name,did,pubKeyBase64,seesMe,registered,contactMethods"
* where contactMethods is stored as a stringified JSON array.
*
* @param contact - The Contact object to convert
* @returns A CSV-formatted string representing the contact
* @throws {Error} If the contact object is missing required fields
*/
export const contactToCsvLine = (contact: Contact): string => {
if (!contact.did) {
throw new Error("Contact must have a did field");
}
// Escape fields that might contain commas or quotes
const escapeField = (field: string | boolean | undefined): string => {
if (field === undefined) return "";
const str = String(field);
if (str.includes(",") || str.includes('"')) {
return `"${str.replace(/"/g, '""')}"`;
}
return str;
};
// Handle contactMethods array by stringifying it
const contactMethodsStr = contact.contactMethods
? escapeField(JSON.stringify(parseJsonField(contact.contactMethods, [])))
: "";
const fields = [
escapeField(contact.name),
escapeField(contact.did),
escapeField(contact.publicKeyBase64),
escapeField(contact.seesMe),
escapeField(contact.registered),
contactMethodsStr,
];
return fields.join(",");
};
/**
* Interface for the JSON export format of database tables
*/
export interface TableExportData {
tableName: string;
rows: Array<Record<string, unknown>>;
}
/**
* Interface for the complete database export format
*/
export interface DatabaseExport {
data: {
data: Array<TableExportData>;
};
}
/**
* Converts an array of contacts to the standardized database export JSON format.
* This format is used for data migration and backup purposes.
*
* @param contacts - Array of Contact objects to convert
* @returns DatabaseExport object in the standardized format
*/
export const contactsToExportJson = (contacts: Contact[]): DatabaseExport => {
// Convert each contact to a plain object and ensure all fields are included
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,
},
],
},
};
};

View File

@@ -13,8 +13,8 @@ import { logger } from "./utils/logger";
const platform = process.env.VITE_PLATFORM;
const pwa_enabled = process.env.VITE_PWA_ENABLED === "true";
logger.error("Platform", { platform });
logger.error("PWA enabled", { pwa_enabled });
logger.log("Platform", JSON.stringify({ platform }));
logger.log("PWA enabled", JSON.stringify({ pwa_enabled }));
// Global Error Handler
function setupGlobalErrorHandler(app: VueApp) {

View File

@@ -5,8 +5,8 @@ import { logger } from "./utils/logger";
const platform = process.env.VITE_PLATFORM;
const pwa_enabled = process.env.VITE_PWA_ENABLED === "true";
logger.error("[Web] PWA enabled", { pwa_enabled });
logger.error("[Web] Platform", { platform });
logger.info("[Web] PWA enabled", { pwa_enabled });
logger.info("[Web] Platform", { platform });
// Only import service worker for web builds
if (platform !== "electron" && pwa_enabled) {

View File

@@ -7,7 +7,7 @@ import type { DatabaseService, QueryExecResult } from "../interfaces/database";
import { logger } from "@/utils/logger";
interface QueuedOperation {
type: "run" | "query" | "getOneRow" | "getAll";
type: "run" | "query";
sql: string;
params: unknown[];
resolve: (value: unknown) => void;
@@ -84,7 +84,7 @@ class AbsurdSqlDatabaseService implements DatabaseService {
SQL.FS.mkdir("/sql");
SQL.FS.mount(sqlFS, {}, "/sql");
const path = "/sql/timesafari.sqlite";
const path = "/sql/timesafari.absurd-sql";
if (typeof SharedArrayBuffer === "undefined") {
const stream = SQL.FS.open(path, "a+");
await stream.node.contents.readIfFallback();
@@ -100,10 +100,20 @@ class AbsurdSqlDatabaseService implements DatabaseService {
// An error is thrown without this pragma: "File has invalid page size. (the first block of a new file must be written first)"
await this.db.exec(`PRAGMA journal_mode=MEMORY;`);
const sqlExec = this.db.exec.bind(this.db);
const sqlExec = this.db.run.bind(this.db);
const sqlQuery = this.db.exec.bind(this.db);
// Extract the migration names for the absurd-sql format
const extractMigrationNames: (result: QueryExecResult[]) => Set<string> = (
result,
) => {
// Even with the "select name" query, the QueryExecResult may be [] (which doesn't make sense to me).
const names = result?.[0]?.values.map((row) => row[0] as string) || [];
return new Set(names);
};
// Run migrations
await runMigrations(sqlExec);
await runMigrations(sqlExec, sqlQuery, extractMigrationNames);
this.initialized = true;
@@ -123,7 +133,6 @@ class AbsurdSqlDatabaseService implements DatabaseService {
if (!operation) continue;
try {
let queryResult: QueryExecResult[] = [];
let result: unknown;
switch (operation.type) {
case "run":
@@ -132,14 +141,6 @@ class AbsurdSqlDatabaseService implements DatabaseService {
case "query":
result = await this.db.exec(operation.sql, operation.params);
break;
case "getOneRow":
queryResult = await this.db.exec(operation.sql, operation.params);
result = queryResult[0]?.values[0];
break;
case "getAll":
queryResult = await this.db.exec(operation.sql, operation.params);
result = queryResult[0]?.values || [];
break;
}
operation.resolve(result);
} catch (error) {
@@ -222,19 +223,6 @@ class AbsurdSqlDatabaseService implements DatabaseService {
await this.waitForInitialization();
return this.queueOperation<QueryExecResult[]>("query", sql, params);
}
async getOneRow(
sql: string,
params: unknown[] = [],
): Promise<unknown[] | undefined> {
await this.waitForInitialization();
return this.queueOperation<unknown[] | undefined>("getOneRow", sql, params);
}
async getAll(sql: string, params: unknown[] = []): Promise<unknown[][]> {
await this.waitForInitialization();
return this.queueOperation<unknown[][]>("getAll", sql, params);
}
}
// Create a singleton instance

View File

@@ -28,6 +28,8 @@ export interface PlatformCapabilities {
hasFileDownload: boolean;
/** Whether the platform requires special file handling instructions */
needsFileHandlingInstructions: boolean;
/** Whether the platform is a native app (Capacitor, Electron, etc.) */
isNativeApp: boolean;
}
/**
@@ -63,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.
@@ -81,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.
@@ -94,6 +150,12 @@ export interface PlatformService {
*/
pickImage(): Promise<ImageResult>;
/**
* Rotates the camera between front and back cameras.
* @returns Promise that resolves when the camera is rotated
*/
rotateCamera(): Promise<void>;
/**
* Handles deep link URLs for the application.
* @param url - The deep link URL to handle
@@ -122,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>;
}

View File

@@ -1,6 +1,3 @@
import { logger } from "@/utils/logger";
import { QueryExecResult } from "../interfaces/database";
interface Migration {
name: string;
sql: string;
@@ -19,15 +16,20 @@ export class MigrationService {
return MigrationService.instance;
}
async registerMigration(migration: Migration): Promise<void> {
registerMigration(migration: Migration) {
this.migrations.push(migration);
}
async runMigrations(
sqlExec: (
sql: string,
params?: unknown[],
) => Promise<Array<QueryExecResult>>,
/**
* @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
*/
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(`
@@ -39,26 +41,17 @@ export class MigrationService {
`);
// Get list of executed migrations
const result: QueryExecResult[] = await sqlExec(
"SELECT name FROM migrations;",
);
let executedMigrations: Set<unknown> = new Set();
// Even with that query, the QueryExecResult may be [] (which doesn't make sense to me).
if (result.length > 0) {
const singleResult = result[0];
executedMigrations = new Set(
singleResult.values.map((row: unknown[]) => row[0]),
);
}
const result1: T = await sqlQuery("SELECT name FROM migrations;");
const executedMigrations = extractMigrationNames(result1);
// Run pending migrations in order
for (const migration of this.migrations) {
if (!executedMigrations.has(migration.name)) {
await sqlExec(migration.sql);
await sqlExec("INSERT INTO migrations (name) VALUES (?)", [
migration.name,
]);
logger.log(`Migration ${migration.name} executed successfully`);
await sqlExec(
`INSERT INTO migrations (name) VALUES ('${migration.name}')`,
);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -60,10 +60,17 @@ export class ElectronPlatformService implements PlatformService {
await this.runMigrations();
this.initialized = true;
logger.log("SQLite database initialized successfully");
logger.log(
"[ElectronPlatformService] SQLite database initialized successfully",
);
} catch (error) {
logger.error("Error initializing SQLite database:", error);
throw new Error("Failed to initialize database");
logger.error(
"[ElectronPlatformService] Error initializing SQLite database:",
error,
);
throw new Error(
"[ElectronPlatformService] Failed to initialize database",
);
}
}
@@ -198,6 +205,7 @@ export class ElectronPlatformService implements PlatformService {
isIOS: false,
hasFileDownload: false, // Not implemented yet
needsFileHandlingInstructions: false,
isNativeApp: true,
};
}
@@ -227,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",
};
}
/**
@@ -277,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
@@ -338,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.";
}
}

View File

@@ -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.";
}
}

View File

@@ -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.";
}
}

View File

@@ -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);
}

Some files were not shown because too many files have changed in this diff Show More