Files
BadNote/lib/services/vault_service.dart
Akiba So 2f0fda5f95
All checks were successful
CI / Windows build (push) Successful in 14m14s
feat(import): one Import-file entry + vault notebooks
Phase 3. Import becomes a single top-level action beside "Create
notebook" and the library is vault-backed.

- VaultService.createNotebook copies a picked file into a fresh
  (de-duplicated) notebook folder under the vault; its sidecar lives
  beside it, so annotations travel with the file.
- Home screen: one "Import file" action with a multi-extension picker
  (pdf / docx / pptx); routes to the editor by extension.
- The document list is now a vault scan (folders with a source file),
  not the SQLite documents table — no cache, always correct.
- PPTX soffice detection fix; DOCX convert-on-import is best-effort
  and fails gracefully when LibreOffice is unavailable.

analyze clean, tests green.
2026-06-24 21:12:38 +08:00

220 lines
8.3 KiB
Dart

import 'dart:io';
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:path/path.dart' as p;
import 'package:shared_preferences/shared_preferences.dart';
/// Suffix appended to a source-file path to form its sidecar path. Kept in sync
/// with [SidecarRepository.kSidecarSuffix]; duplicated here to avoid a layering
/// dependency from the service onto the editor.
const String kVaultSidecarSuffix = '.badnote.json';
/// A notebook discovered by scanning the vault: one folder holding a source
/// file (and, optionally, its sidecar). This is the file-backed source of truth
/// for the home screen list (the SQLite `documents` table is no longer read).
class VaultNotebook {
const VaultNotebook({
required this.folderPath,
required this.sourceFilePath,
required this.filename,
required this.docType,
required this.modified,
this.hasSidecar = false,
});
/// Absolute path to the notebook folder.
final String folderPath;
/// Absolute path to the annotatable source file inside the folder.
final String sourceFilePath;
/// Source filename including extension, e.g. `Calculus Lecture 3.pdf`.
final String filename;
/// Lowercased extension without the dot: `pdf` / `pptx` / `ppt` / `docx`.
final String docType;
/// Last-modified time of the source file (used for recency sorting).
final DateTime modified;
/// Whether a `<file>.badnote.json` sidecar exists next to the source file.
final bool hasSidecar;
}
/// Records the user-picked vault root folder (an Obsidian-style vault) and
/// gates app startup behind a valid choice.
///
/// The vault root is the single folder under which all notebooks will live.
/// Phase 0 only persists the path and validates it exists; no data is moved
/// into the vault yet (later phases do that).
///
/// Persistence is SharedPreferences-backed under [vaultRootKey]. The service is
/// easily mockable: inject a [SharedPreferences] (e.g. from
/// `SharedPreferences.setMockInitialValues`) via the constructor for tests.
class VaultService {
/// SharedPreferences key under which the vault root path is stored.
static const String vaultRootKey = 'vaultRoot';
final SharedPreferences _prefs;
VaultService._(this._prefs);
static VaultService? _instance;
/// Singleton accessor, mirroring [DatabaseService.getInstance]. Lazily reads
/// the shared [SharedPreferences] instance.
static Future<VaultService> getInstance() async {
if (_instance != null) return _instance!;
final prefs = await SharedPreferences.getInstance();
final service = VaultService._(prefs);
_instance = service;
return service;
}
/// Test-only constructor: inject a (typically mock) [SharedPreferences] so
/// the vault root can be exercised without platform channels.
@visibleForTesting
VaultService.forTest(SharedPreferences prefs) : _prefs = prefs;
/// Test-only: drop the cached singleton so the next [getInstance] rebuilds.
@visibleForTesting
static void resetForTest() {
_instance = null;
}
/// The currently stored vault root path, or null if none has been chosen.
String? get vaultRoot => _prefs.getString(vaultRootKey);
/// Persist [path] as the vault root.
Future<void> setVaultRoot(String path) async {
await _prefs.setString(vaultRootKey, path);
}
/// Forget the stored vault root (e.g. to re-prompt the user).
Future<void> clearVaultRoot() async {
await _prefs.remove(vaultRootKey);
}
/// True iff a vault root is set AND that directory currently exists.
///
/// Returns false when no path is stored or when the stored path no longer
/// resolves to a directory (external drive unplugged, folder deleted) — the
/// caller then re-prompts rather than silently scattering data elsewhere.
Future<bool> vaultRootValid() async {
final path = vaultRoot;
if (path == null || path.isEmpty) return false;
return Directory(path).exists();
}
/// Source-file extensions BadNote can import as notebooks.
static const Set<String> importableExtensions = {'pdf', 'docx', 'pptx', 'ppt'};
/// Create a notebook FOLDER under the vault root, COPY the source file at
/// [sourceFilePath] into it, and return the path of the in-vault copy.
///
/// The folder name is the sanitized source basename (without extension),
/// de-duplicated with a numeric suffix on collision (`Lecture`, `Lecture 2`,
/// …). The sidecar (`<file>.badnote.json`) will live next to the copy — the
/// [SidecarRepository] keys off the returned path, so nothing else is needed.
///
/// Throws [StateError] if no valid vault root is set.
Future<String> createNotebook(String sourceFilePath) async {
final root = vaultRoot;
if (root == null || root.isEmpty) {
throw StateError('No vault root is set; cannot create a notebook.');
}
final source = File(sourceFilePath);
final filename = p.basename(sourceFilePath);
final baseName = _sanitizeFolderName(p.basenameWithoutExtension(filename));
final folder = await _uniqueNotebookFolder(root, baseName);
await folder.create(recursive: true);
final destPath = p.join(folder.path, filename);
await source.copy(destPath);
return destPath;
}
/// Scan the vault root for notebook folders. A notebook is a direct
/// subfolder (excluding the hidden `.badnote` metadata folder) that contains
/// at least one importable source file. Returns the notebooks sorted by
/// source-file mtime, most-recent first. An empty / missing vault yields an
/// empty list (never throws).
Future<List<VaultNotebook>> scanNotebooks() async {
final root = vaultRoot;
if (root == null || root.isEmpty) return const [];
final dir = Directory(root);
if (!await dir.exists()) return const [];
final notebooks = <VaultNotebook>[];
await for (final entity in dir.list(followLinks: false)) {
if (entity is! Directory) continue;
final folderName = p.basename(entity.path);
if (folderName.startsWith('.')) continue; // skip .badnote etc.
final notebook = await _readNotebookFolder(entity);
if (notebook != null) notebooks.add(notebook);
}
notebooks.sort((a, b) => b.modified.compareTo(a.modified));
return notebooks;
}
/// Inspect a single notebook folder, returning a [VaultNotebook] when it
/// holds an importable source file, else null. Picks the first importable
/// file (prefers a `.pdf` so a DOCX→PDF-converted notebook opens as its PDF).
Future<VaultNotebook?> _readNotebookFolder(Directory folder) async {
File? chosen;
String? chosenExt;
await for (final entity in folder.list(followLinks: false)) {
if (entity is! File) continue;
final name = p.basename(entity.path);
if (name.endsWith(kVaultSidecarSuffix)) continue;
final ext = p.extension(name).replaceFirst('.', '').toLowerCase();
if (!importableExtensions.contains(ext)) continue;
// Prefer a PDF artifact when present (DOCX-converted notebooks keep both).
if (chosen == null || (ext == 'pdf' && chosenExt != 'pdf')) {
chosen = entity;
chosenExt = ext;
}
}
if (chosen == null || chosenExt == null) return null;
final stat = await chosen.stat();
final sidecar = File('${chosen.path}$kVaultSidecarSuffix');
return VaultNotebook(
folderPath: folder.path,
sourceFilePath: chosen.path,
filename: p.basename(chosen.path),
docType: chosenExt,
modified: stat.modified,
hasSidecar: await sidecar.exists(),
);
}
/// Find an unused notebook folder under [root] for [baseName], appending a
/// ` 2`, ` 3`, … suffix on collision.
Future<Directory> _uniqueNotebookFolder(String root, String baseName) async {
final safeBase = baseName.isEmpty ? 'Untitled' : baseName;
var candidate = Directory(p.join(root, safeBase));
var n = 2;
while (await candidate.exists()) {
candidate = Directory(p.join(root, '$safeBase $n'));
n++;
}
return candidate;
}
/// Sanitize a basename into a safe folder name: strip characters illegal on
/// Windows/POSIX (`\ / : * ? " < > |`) and control chars, collapse
/// whitespace, and trim trailing dots/spaces (illegal on Windows).
static String _sanitizeFolderName(String name) {
final cleaned = name
.replaceAll(RegExp(r'[\\/:*?"<>|\x00-\x1f]'), ' ')
.replaceAll(RegExp(r'\s+'), ' ')
.trim()
.replaceAll(RegExp(r'[. ]+$'), '');
return cleaned;
}
}