the-mews/app/lib/application/controllers/browser_controller.dart

306 lines
10 KiB
Dart

import 'package:actors/actors.dart';
import 'package:drift/drift.dart' show Value;
import 'package:signals/signals.dart';
import '../../database/database.dart';
import '../../mews/document.dart';
import '../actors/fetch_actor.dart';
import '../internal_actions.dart';
import '../internal_pages.dart';
import '../pages/mews_urls.dart';
/// What went wrong while browsing. The presentation layer maps these to
/// user-facing messages; no raw codes cross into the UI.
sealed class BrowseError {
const BrowseError();
}
class LoadFailed extends BrowseError {
const LoadFailed();
}
class BrokenPage extends BrowseError {
const BrokenPage(this.source);
/// The markup that failed to parse; "show page text" recovers its content.
final String source;
}
/// Coordinates navigation: owns the signals the reader UI observes and
/// dispatches fetch commands to the fetch actor. Local-first: a cached page is
/// revalidated with the server but survives any network failure.
class BrowserController {
BrowserController({
required MewsDatabase db,
required Actor<FetchCommand, FetchResult> fetch,
InternalPages? internalPages,
InternalActions? internalActions,
}) : _db = db,
_fetch = fetch,
_internalPages = internalPages,
_internalActions = internalActions;
final MewsDatabase _db;
final Actor<FetchCommand, FetchResult> _fetch;
final InternalPages? _internalPages;
final InternalActions? _internalActions;
/// The stack of visited pages; the reader is at [_stackIndex].
final List<String> _stack = [];
int _stackIndex = -1;
final currentPage = signal<MewsPage?>(null);
final loading = signal(false);
final error = signal<BrowseError?>(null);
/// Pages opened this session, so links can show the visited color.
final visitedUrls = signal(<String>{});
/// The parsed pages next to the current one in the stack, ready to show
/// while swiping between them.
final backPage = signal<MewsPage?>(null);
final forwardPage = signal<MewsPage?>(null);
bool get canGoBack => _stackIndex > 0;
bool get canGoForward => _stackIndex >= 0 && _stack.length - 1 > _stackIndex;
/// Normalizes what the reader typed into an address: bare domains become
/// https URLs; anything already carrying a scheme (mews:, https:, ...) is
/// left alone.
static String normalizeAddress(String input) {
final trimmed = input.trim();
if (trimmed.isEmpty) return '';
if (_schemePattern.hasMatch(trimmed)) return trimmed;
return 'https://$trimmed';
}
static final _schemePattern = RegExp(r'^[a-zA-Z][a-zA-Z0-9+.-]*:');
/// The wap. subdomain equivalent of [url], or null when the host already
/// starts with it or the address is not a plain web URL.
static String? wapUrlOf(String url) {
final uri = Uri.tryParse(url);
if (uri == null || !uri.hasScheme || uri.host.isEmpty) return null;
if (uri.scheme != 'http' && uri.scheme != 'https') return null;
if (uri.host.startsWith('wap.')) return null;
return uri.replace(host: 'wap.${uri.host}').toString();
}
Future<void> open(String input) async {
final url = MewsUrls.canonical(normalizeAddress(input));
if (url.isEmpty) return;
// Action links change something and stay on the current page instead of
// joining the walk history.
if (MewsUrls.isAction(url)) {
// Only the client's own pages may change the reader's data. A fetched
// page linking to mews:do/... must not act on their behalf (spec 8.1).
if (!_onInternalPage) return;
if (await (_internalActions?.apply(url) ?? Future.value(false))) {
await _loadCurrent();
}
return;
}
_stack.removeRange(_stackIndex + 1, _stack.length);
_stack.add(url);
_stackIndex++;
_updateNeighbors();
await _loadCurrent();
// Mews sites commonly live on a wap. subdomain; try that before showing
// an error when the address as typed does not work out.
if (error.value != null && _stack[_stackIndex] == url) {
final wap = wapUrlOf(url);
if (wap != null) {
final firstError = error.value;
_stack[_stackIndex] = wap;
_updateNeighbors();
await _loadCurrent();
// The address as typed is the closer match; keep its error when the
// wap. attempt does not work either.
if (error.value != null && firstError != null) {
error.value = firstError;
}
}
}
}
Future<void> back() async {
if (!canGoBack) return;
_stackIndex--;
// The neighbor was parsed for the swipe already; show it right away so
// the transition lands on content instead of a blank page while
// _loadCurrent revalidates it against the server.
_showParsedNeighbor(backPage.value);
_updateNeighbors();
await _loadCurrent();
}
Future<void> forward() async {
if (!canGoForward) return;
_stackIndex++;
_showParsedNeighbor(forwardPage.value);
_updateNeighbors();
await _loadCurrent();
}
void _showParsedNeighbor(MewsPage? page) {
if (page == null) return;
currentPage.value = page;
error.value = null;
visitedUrls.value = {...visitedUrls.value, page.url};
}
Future<void> reload() => _loadCurrent();
/// Whether the reader is standing on one of the client's own pages.
bool get _onInternalPage =>
_stackIndex >= 0 && MewsUrls.isInternal(_stack[_stackIndex]);
/// Rebuilds the open page when it is one of ours, so a change made elsewhere
/// shows up without the reader navigating.
Future<void> refreshInternalPage() async {
if (!_onInternalPage) return;
await _loadCurrent();
}
Future<void> submitForm(String action, String method, Map<String, String> fields) async {
// A form on one of our own pages is a navigation or an action, never a
// network request; the fetch client cannot speak the mews scheme.
if (MewsUrls.isInternal(action)) {
final base = Uri.parse(action);
final verb = MewsUrls.verbOf(action);
return open(verb == null
? MewsUrls.page(base, fields)
: MewsUrls.action(verb, {...base.queryParameters, ...fields}));
}
loading.value = true;
error.value = null;
final FetchResult result;
try {
result = await _fetch.send(SubmitForm(url: action, method: method, fields: fields));
} catch (_) {
// A submit that throws out of the actor is still just a failed load.
loading.value = false;
error.value = const LoadFailed();
return;
}
loading.value = false;
switch (result) {
case FetchFormOk(:final page):
_stack.removeRange(_stackIndex + 1, _stack.length);
_stack.add(page.url);
_stackIndex++;
_updateNeighbors();
_show(page);
case _:
error.value = const LoadFailed();
}
}
/// Reopens the most recent page from the previous session, or the hub when
/// there is nothing to return to.
Future<void> restoreLastSession() async {
final url = await _db.lastVisitedUrl() ?? MewsUrls.hub;
_stack.add(url);
_stackIndex = 0;
_updateNeighbors();
await _loadCurrent();
}
/// Parses the stack's neighboring pages in the fetch actor so swipes can
/// show the real content. Results arriving after another navigation are
/// dropped, so rapid navigation never shows a stale neighbor.
void _updateNeighbors() {
_loadNeighbor(_stackIndex - 1, backPage);
_loadNeighbor(_stackIndex + 1, forwardPage);
}
Future<void> _loadNeighbor(int index, Signal<MewsPage?> target) async {
final expectedIndex = _stackIndex;
if (index < 0 || index >= _stack.length) {
target.value = null;
return;
}
final url = _stack[index];
if (_internalPages?.handles(url) ?? false) {
target.value = await _internalPages!.pageFor(url);
return;
}
final cached = await _db.cachedPage(url);
if (_stackIndex != expectedIndex) return;
if (cached == null) {
target.value = null;
return;
}
final result = await _fetch.send(ParseSource(url: url, source: cached.source));
if (_stackIndex != expectedIndex) return;
target.value = result is FetchPageOk ? result.page : null;
}
Future<void> _loadCurrent() async {
if (_stackIndex < 0) return;
final url = _stack[_stackIndex];
loading.value = true;
error.value = null;
// Internal pages are built from the local database, never fetched or
// cached; they join the stack like any other page.
if (_internalPages?.handles(url) ?? false) {
final page = await _internalPages!.pageFor(url);
loading.value = false;
if (page != null) {
currentPage.value = page;
error.value = null;
// Our own addresses stay out of visitedUrls: a sort or filter link
// would otherwise take the visited color after one use.
} else {
currentPage.value = null;
error.value = const LoadFailed();
}
return;
}
final cached = await _db.cachedPage(url);
final result = await _fetch.send(FetchPage(
url: url,
etag: cached?.etag,
lastModified: cached?.lastModified,
cachedSource: cached?.source,
));
loading.value = false;
switch (result) {
case FetchPageOk(:final page, :final source, :final etag, :final lastModified, :final notModified):
currentPage.value = page;
error.value = null;
visitedUrls.value = {...visitedUrls.value, url};
// Opening a post is reading it. Nothing happens when the address is
// not one, so this needs no knowledge of the reader's subscriptions.
await _db.markEntryRead(url);
if (!notModified) {
await _db.saveCachedPage(CachedPagesCompanion.insert(
url: url,
source: source,
title: Value(page.title),
etag: Value(etag),
lastModified: Value(lastModified),
));
await _db.recordVisit(url, page.title);
}
case FetchParseError(:final source):
currentPage.value = null;
error.value = BrokenPage(source);
case _:
currentPage.value = null;
error.value = const LoadFailed();
}
}
void _show(MewsPage page) {
currentPage.value = page;
_db.recordVisit(page.url, page.title);
}
}