Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 35 additions & 11 deletions lib/plugins/bloc/plugin_system_bloc.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:bloc_concurrency/bloc_concurrency.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:http/http.dart' as http;
import 'package:otzaria/plugins/utils/plugin_safe_mode.dart';
import 'package:otzaria/plugins/bloc/plugin_system_event.dart';
import 'package:otzaria/plugins/bloc/plugin_system_state.dart';
Expand Down Expand Up @@ -64,6 +65,7 @@ class PluginSystemBloc extends Bloc<PluginSystemEvent, PluginSystemState> {
final bool _sharedDevWatcher;
StreamSubscription<PluginDevFsChange>? _devWatchSub;
StreamSubscription<TabsState>? _readerStateSub;
Future<void>? _closeFuture;

/// החתימה מונעת קומפילציה ושאילתות חוזרות כשהמניפסט וההרשאות לא השתנו.
String? _lastDeclarativeSyncSignature;
Expand All @@ -85,6 +87,7 @@ class PluginSystemBloc extends Bloc<PluginSystemEvent, PluginSystemState> {
PluginSystemBloc({
required this.repository,
PluginInstallerService? installerService,
// השירות מועבר לבעלות ה-BLoC ומשוחרר בסגירת החלון.
PluginDownloadService? downloadService,
PluginDevLoaderService? devLoader,
PluginDevWatchService? devWatchService,
Expand Down Expand Up @@ -154,18 +157,26 @@ class PluginSystemBloc extends Bloc<PluginSystemEvent, PluginSystemState> {
}

@override
Future<void> close() async {
PluginShortcutRegistry.instance.removeListener(_onPluginShortcutsChanged);
await _devWatchSub?.cancel();
await _readerStateSub?.cancel();
if (_sharedDevWatcher) {
PluginDevWatchService.release();
} else {
devWatchService.dispose();
// _close קוראת ל-super.close ב-finally, גם אם שחרור השירות נכשל.
// ignore: must_call_super
Future<void> close() => _closeFuture ??= _close();

Future<void> _close() async {
try {
_downloadService.dispose();
} finally {
PluginShortcutRegistry.instance.removeListener(_onPluginShortcutsChanged);
await _devWatchSub?.cancel();
await _readerStateSub?.cancel();
if (_sharedDevWatcher) {
PluginDevWatchService.release();
} else {
devWatchService.dispose();
}
declarativeHost?.dispose();
toolbarRegistry?.dispose();
await super.close();
}
declarativeHost?.dispose();
toolbarRegistry?.dispose();
await super.close();
}

Future<void> _handleDevChange(PluginDevFsChange change) async {
Expand Down Expand Up @@ -519,6 +530,7 @@ class PluginSystemBloc extends Bloc<PluginSystemEvent, PluginSystemState> {
InstallRemotePluginRequested event,
Emitter<PluginSystemState> emit,
) async {
if (_closeFuture != null || emit.isDone) return;
String? archivePath;

// אישור קבלה מיידי לאתר החנות — עוד לפני ההורדה ודיאלוג ההרשאות,
Expand All @@ -533,17 +545,23 @@ class PluginSystemBloc extends Bloc<PluginSystemEvent, PluginSystemState> {
try {
appVersion = appReleaseVersion(await PackageInfo.fromPlatform());
} catch (_) {}
if (_closeFuture != null || emit.isDone) return;

archivePath = await _downloadService.downloadPluginArchive(
Uri.parse(event.downloadUrl),
appVersion: appVersion,
storeOnly: event.storeOnly,
);
if (_closeFuture != null || emit.isDone) return;

final prepareInfo = await _installerService.prepareInstall(
archivePath,
forceOverwrite: event.forceOverwrite,
);
if (_closeFuture != null || emit.isDone) {
await _installerService.cancelInstall(prepareInfo.tempDirPath);
return;
}

emit(
PluginSystemInstallRequiresPermissions(
Expand All @@ -555,7 +573,10 @@ class PluginSystemBloc extends Bloc<PluginSystemEvent, PluginSystemState> {
isUserInitiated: event.isUserInitiated,
),
);
} on http.RequestAbortedException {
return;
} on PluginOverwriteException catch (e) {
if (_closeFuture != null || emit.isDone) return;
UiSnack.show(PluginMessages.pluginAlreadyInstalledSameVersion);
debugPrint(
'Plugin overwrite required for "${e.pluginName}" version ${e.version}',
Expand All @@ -567,6 +588,7 @@ class PluginSystemBloc extends Bloc<PluginSystemEvent, PluginSystemState> {
);
add(LoadPlugins());
} on PluginStoreIncompatibleException catch (e) {
if (_closeFuture != null || emit.isDone) return;
// tryParse מבטיח שלפחות אחד הגבולות קיים, לכן maxAppVersion אינו null כאן.
final String message;
if (e.isAboveCeiling || e.minAppVersion.isEmpty) {
Expand All @@ -588,6 +610,7 @@ class PluginSystemBloc extends Bloc<PluginSystemEvent, PluginSystemState> {
);
add(LoadPlugins());
} on PluginNewerVersionInstalledException catch (e) {
if (_closeFuture != null || emit.isDone) return;
UiSnack.show(
PluginMessages.newerVersionInstalled(e.pluginName, e.installedVersion),
);
Expand All @@ -598,6 +621,7 @@ class PluginSystemBloc extends Bloc<PluginSystemEvent, PluginSystemState> {
);
add(LoadPlugins());
} catch (e) {
if (_closeFuture != null || emit.isDone) return;
UiSnack.showError(PluginMessages.installRemotePluginError(e));
_reportInstallResult(
event.reportContext,
Expand Down
189 changes: 142 additions & 47 deletions lib/plugins/services/plugin_download_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,32 @@ import 'package:path/path.dart' as p;

class PluginDownloadService {
final http.Client _client;
final bool _ownsClient;
final _downloads = <Completer<void>>{};
late final FutureOr<void> Function() _closer = dispose;
bool _disposed = false;

/// משך מרבי ללא בייטים (גם בהמתנה לכותרות) לפני [TimeoutException].
final Duration _stallTimeout;

/// [client] מוזרק נשאר באחריות הקורא ואינו נסגר עם השירות.
PluginDownloadService({
http.Client? client,
this._stallTimeout = const Duration(seconds: 60),
}) : _client = client ?? http.Client() {
HttpClientRegistry.register(_client.close);
}) : _client = client ?? http.Client(),
_ownsClient = client == null {
if (_ownsClient) HttpClientRegistry.register(_closer);
}

/// מבטל הורדות פעילות ומשחרר רק את ה-client שבבעלות השירות.
void dispose() {
if (_disposed) return;
_disposed = true;
if (_ownsClient) HttpClientRegistry.unregister(_closer);
for (final download in _downloads) {
if (!download.isCompleted) download.complete();
}
if (_ownsClient) _client.close();
}

/// מורידה את ארכיון התוסף. [appVersion] — גרסת האוצריא הנוכחית; כשהכתובת
Expand All @@ -32,56 +49,76 @@ class PluginDownloadService {
String? appVersion,
bool storeOnly = false,
}) async {
final resolvedUri = PluginStoreLinkParser.appendAppVersion(
downloadUri,
appVersion,
);
var response = await _sendFollowingRedirects(resolvedUri, storeOnly);

if (response.statusCode >= 400 && resolvedUri != downloadUri) {
final body = await utf8.decodeStream(
response.stream.timeout(_stallTimeout),
if (_disposed) throw StateError('PluginDownloadService is disposed');
final abort = Completer<void>();
_downloads.add(abort);
_DownloadResponse? response;
try {
final resolvedUri = PluginStoreLinkParser.appendAppVersion(
downloadUri,
appVersion,
);
// לחנות אין גרסה תואמת — פרטי התאימות כבר בגוף התשובה, ואין טעם
// להוריד ארכיון שממילא ייפסל.
final incompatible = PluginStoreIncompatibleException.tryParse(body);
if (incompatible != null) {
throw incompatible;
}
// סירוב מסיבה אחרת (למשל שילוב פרמטרים שהשרת דוחה) — מנסים שוב
// בכתובת המקורית, כדי לא לשבור התקנה שעבדה לפני הוספת appVersion.
response = await _sendFollowingRedirects(downloadUri, storeOnly);
}
response = await _sendFollowingRedirects(resolvedUri, storeOnly, abort);
_checkActive(abort, downloadUri);

if (response.statusCode < 200 || response.statusCode >= 300) {
throw Exception(
'שגיאה בהורדת התוסף (${response.statusCode})',
);
}
if (response.statusCode >= 400 && resolvedUri != downloadUri) {
final body = await utf8.decodeStream(
response.stream.timeout(_stallTimeout),
);
_checkActive(abort, downloadUri);
final incompatible = PluginStoreIncompatibleException.tryParse(body);
if (incompatible != null) throw incompatible;

final tempDir = await Directory.systemTemp.createTemp(
'otzaria_plugin_download_',
);
final archivePath = p.join(
tempDir.path,
'${_resolveFileStem(downloadUri)}.otzplugin',
);
final targetFile = File(archivePath);
final sink = targetFile.openWrite();
// סירוב שאינו אי-תאימות — מנסים את הכתובת המקורית ללא appVersion.
await response.cancel();
response = await _sendFollowingRedirects(downloadUri, storeOnly, abort);
_checkActive(abort, downloadUri);
}

try {
await sink.addStream(response.stream.timeout(_stallTimeout));
await sink.flush();
await sink.close();
} catch (_) {
if (response.statusCode < 200 || response.statusCode >= 300) {
throw Exception('שגיאה בהורדת התוסף (${response.statusCode})');
}

final tempDir = await Directory.systemTemp.createTemp(
'otzaria_plugin_download_',
);
final archivePath = p.join(
tempDir.path,
'${_resolveFileStem(downloadUri)}.otzplugin',
);
IOSink? sink;
try {
_checkActive(abort, downloadUri);
sink = File(archivePath).openWrite();
await sink.addStream(response.stream.timeout(_stallTimeout));
await sink.flush();
await sink.close();
} catch (_) {}
await _cleanupDirectory(tempDir);
sink = null;
_checkActive(abort, downloadUri);
} catch (_) {
try {
await sink?.close();
} catch (_) {}
await _cleanupDirectory(tempDir);
rethrow;
}

return archivePath;
} catch (error) {
if (abort.isCompleted &&
(error is http.ClientException || error is SocketException)) {
throw http.RequestAbortedException(downloadUri);
}
rethrow;
} finally {
if (!abort.isCompleted) abort.complete();
_downloads.remove(abort);
await response?.cancel();
}
}

return archivePath;
void _checkActive(Completer<void> abort, Uri uri) {
if (abort.isCompleted) throw http.RequestAbortedException(uri);
}

Future<void> cleanupDownloadedArchive(String archivePath) async {
Expand Down Expand Up @@ -109,24 +146,47 @@ class PluginDownloadService {
/// שולחת GET ועוקבת אחרי הפניות **ידנית**. מעקב אוטומטי היה מאפשר
/// ל-redirect מהחנות להוציא את ההורדה לשרת זר, ובכך לרוקן את הגידור
/// שנעשה בנקודת הקריאה.
Future<http.StreamedResponse> _sendFollowingRedirects(
Future<_DownloadResponse> _sendFollowingRedirects(
Uri uri,
bool storeOnly,
Completer<void> abort,
) async {
var current = uri;
for (var hop = 0; hop <= _maxRedirects; hop++) {
_checkActive(abort, current);
if (storeOnly && !PluginStoreLinkParser.isStoreDownloadUri(current)) {
throw Exception('הורדת תוסף מותרת רק מכתובת של חנות התוספים');
}
final request = http.Request('GET', current)..followRedirects = false;
final response = await _client.send(request).timeout(_stallTimeout);
final request = http.AbortableRequest(
'GET',
current,
abortTrigger: abort.future,
)..followRedirects = false;
final response = await _client
.send(request)
.then<_DownloadResponse>((response) {
// רישום סינכרוני לפני החזרת התשובה: ביטול בזמן יצירת התיקייה
// חייב להגיע גם ל-body שעדיין לא התחיל להיכתב.
final body = _DownloadResponse(response);
if (abort.isCompleted) {
return body.cancel().then<_DownloadResponse>(
(_) => throw http.RequestAbortedException(request.url),
);
}
return body;
})
.timeout(_stallTimeout);
final location = response.headers['location'];
final isRedirect =
response.statusCode >= 300 &&
response.statusCode < 400 &&
location != null;
if (!isRedirect) return response;
await response.stream.timeout(_stallTimeout).drain<void>();
try {
await response.stream.timeout(_stallTimeout).drain<void>();
} finally {
await response.cancel();
}
current = current.resolve(location);
}
throw Exception('יותר מדי הפניות בהורדת התוסף');
Expand All @@ -147,6 +207,41 @@ class PluginDownloadService {
}
}

/// מחזיק subscription מיד עם קבלת הכותרות, לפני כל IO נוסף. IOClient אינו
/// מנתק body שטרם האזינו לו אם הביטול כבר הגיע; pause שומר על backpressure
/// עד שהצרכן מוכן, והביטול משחרר את החיבור גם בכשל ביצירת תיקייה או קובץ.
class _DownloadResponse {
_DownloadResponse(this._response) {
_subscription = _response.stream.listen(
_body.add,
onError: _body.addError,
onDone: _body.close,
)..pause();
_body
..onListen = _subscription.resume
..onPause = _subscription.pause
..onResume = _subscription.resume
..onCancel = _subscription.cancel;
}

final http.StreamedResponse _response;
final _body = StreamController<List<int>>(sync: true);
late final StreamSubscription<List<int>> _subscription;

int get statusCode => _response.statusCode;
Map<String, String> get headers => _response.headers;
Stream<List<int>> get stream => _body.stream;

Future<void> cancel() async {
try {
await _subscription.cancel();
} finally {
// בלי מאזין (למשל כש-mkdir נכשל), close ממתינה עד שיאזינו ל-stream.
unawaited(_body.close());
}
}
}

/// לחנות אין גרסה של התוסף שתואמת לגרסת האוצריא המותקנת. נבנית מגוף תשובת
/// ה-404 של החנות, שכולל את פרטי התאימות — כך שאין צורך להוריד ארכיון כדי
/// לדעת מה להציג למשתמש.
Expand Down
Loading
Loading