488 lines
15 KiB
Dart
488 lines
15 KiB
Dart
import 'dart:async';
|
|
import 'dart:io';
|
|
import 'dart:isolate';
|
|
import 'dart:math';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:jni/jni.dart';
|
|
import 'package:unyo_lib/jni_isolate.dart';
|
|
import 'package:unyo_lib/jni_isolate_message.dart';
|
|
import 'package:unyo_lib/models/extension.dart';
|
|
import 'package:logger/logger.dart';
|
|
import 'package:path_provider/path_provider.dart';
|
|
import 'package:path/path.dart' as path;
|
|
import 'package:crypto/crypto.dart';
|
|
import 'package:unyo_lib/jmodels/jvideo.dart';
|
|
import 'package:unyo_lib/jmodels/jsanime.dart';
|
|
import 'package:unyo_lib/jmodels/jsepisode.dart';
|
|
import 'package:unyo_lib/jmodels/jsmanga.dart';
|
|
import 'package:unyo_lib/jmodels/jschapter.dart';
|
|
import 'package:unyo_lib/jmodels/jpage.dart';
|
|
import 'package:unyo_lib/jmodels/jpreferenceitem.dart';
|
|
|
|
class AniyomiBridge {
|
|
// static consts
|
|
static const String _aniyomiBridgeAnimeExtensionsDir = "animeExtensions";
|
|
static const String _aniyomiBridgeMangaExtensionsDir = "mangaExtensions";
|
|
static const String _aniyomiBridgeDir = "aniyomibridge";
|
|
static const String _aniyomiBridgeJarName = "unyo-core.jar";
|
|
static const String _packageAssetsDir =
|
|
"packages/unyo_lib/assets";
|
|
static const Duration _cacheTtl = Duration(minutes: 20);
|
|
|
|
// static variables
|
|
static bool _isReady = false;
|
|
static late final JniIsolate _jniIsolate;
|
|
static late final ReceivePort _jniReceiverPort;
|
|
static late final SendPort _jniSenderPort;
|
|
|
|
// instance variables
|
|
late final String _supportDirectoryPath;
|
|
final Random _random = Random();
|
|
final Logger _logger = Logger(
|
|
printer: PrettyPrinter(methodCount: 9),
|
|
level: Level.debug,
|
|
// output: FileOutput(),
|
|
filter: ProductionFilter(),
|
|
);
|
|
final Map<int, Completer> _pendingRequests = {};
|
|
final Map<String, (int, dynamic)> _responsesCache = {};
|
|
|
|
AniyomiBridge() {
|
|
_initJvm();
|
|
}
|
|
|
|
Future<void> _initJvm() async {
|
|
if (_isReady) {
|
|
return;
|
|
}
|
|
Directory supportDirectory = await getApplicationSupportDirectory();
|
|
_supportDirectoryPath = supportDirectory.path;
|
|
await _loadJarIfNeeded(supportDirectory);
|
|
Jni.setDylibDir(dylibDir: _getDylibDir(supportDirectory));
|
|
|
|
_jniIsolate = JniIsolate();
|
|
final readyPort = ReceivePort();
|
|
_jniReceiverPort = ReceivePort();
|
|
(bool, SendPort) response = await _jniIsolate.initJniIsolate(
|
|
readyPort,
|
|
_jniReceiverPort,
|
|
supportDirectory,
|
|
_getDylibDir(supportDirectory),
|
|
_getClassPath(supportDirectory),
|
|
);
|
|
_jniSenderPort = response.$2;
|
|
_isReady = response.$1;
|
|
_jniReceiverPort.listen((message) {
|
|
if (message is JniIsolateError) {
|
|
final id = message.id;
|
|
final completer = _pendingRequests.remove(id);
|
|
if (completer == null) {
|
|
_logger.w('Received error for unknown request id=$id: ${message.error}');
|
|
return;
|
|
}
|
|
completer.completeError(message.error);
|
|
} else if (message is JniIsolateResponse) {
|
|
final id = message.id;
|
|
final completer = _pendingRequests.remove(id);
|
|
if (completer == null) {
|
|
_logger.w('Received response for unknown request id=$id');
|
|
return;
|
|
}
|
|
if (message.results == null) {
|
|
completer.complete();
|
|
return;
|
|
}
|
|
completer.complete(message.results);
|
|
} else {
|
|
_logger.w('Received unexpected message type: ${message.runtimeType}');
|
|
}
|
|
});
|
|
}
|
|
|
|
bool isReady() {
|
|
return _isReady;
|
|
}
|
|
|
|
Future<List<JSAnime>> getAnimeSearchResults(String query, int page, String packageName) {
|
|
return _sendJniIsolateMessageWithCache<List<JSAnime>>(
|
|
JniIsolateMessageType.getAnimeSearchResults,
|
|
{
|
|
'query': query,
|
|
'page': page,
|
|
'source': packageName,
|
|
},
|
|
);
|
|
}
|
|
|
|
Future<List<JSManga>> getMangaSearchResults(String query, int page, String packageName) {
|
|
return _sendJniIsolateMessageWithCache<List<JSManga>>(
|
|
JniIsolateMessageType.getMangaSearchResults,
|
|
{
|
|
'query': query,
|
|
'page': page,
|
|
'source': packageName,
|
|
},
|
|
);
|
|
}
|
|
|
|
Future<List<JSEpisode>> getEpisodeList(JSAnime sAnime, String packageName) {
|
|
return _sendJniIsolateMessageWithCache<List<JSEpisode>>(
|
|
JniIsolateMessageType.getEpisodeList,
|
|
{
|
|
'sAnime': sAnime,
|
|
'source': packageName,
|
|
},
|
|
);
|
|
}
|
|
|
|
Future<List<JSChapter>> getChapterList(JSManga sManga, String packageName) {
|
|
return _sendJniIsolateMessageWithCache<List<JSChapter>>(
|
|
JniIsolateMessageType.getChapterList,
|
|
{
|
|
'sManga': sManga,
|
|
'source': packageName,
|
|
},
|
|
);
|
|
}
|
|
|
|
Future<List<JVideo>> getVideoList(JSEpisode sEpisode, String packageName) {
|
|
return _sendJniIsolateMessageWithCache<List<JVideo>>(
|
|
JniIsolateMessageType.getVideoList,
|
|
{
|
|
'sEpisode': sEpisode,
|
|
'source': packageName,
|
|
},
|
|
);
|
|
}
|
|
|
|
Future<List<JPage>> getPageList(JSChapter sChapter, String packageName) {
|
|
return _sendJniIsolateMessageWithCache<List<JPage>>(
|
|
JniIsolateMessageType.getPageList,
|
|
{
|
|
'sChapter': sChapter,
|
|
'source': packageName,
|
|
},
|
|
);
|
|
}
|
|
|
|
Future<void> loadAnimeExtension(String extensionUrl, String packageName) async {
|
|
return _sendJniIsolateMessage<void>(
|
|
JniIsolateMessage(
|
|
id: _random.nextInt(1 << 32),
|
|
type: JniIsolateMessageType.loadAnimeExtension,
|
|
args: {
|
|
'extensionUrl': extensionUrl,
|
|
'packageName': packageName,
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> unloadAnimeExtension(String packageName) async {
|
|
return _sendJniIsolateMessage<void>(
|
|
JniIsolateMessage(
|
|
id: _random.nextInt(1 << 32),
|
|
type: JniIsolateMessageType.unloadAnimeExtension,
|
|
args: {
|
|
'packageName': packageName,
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> loadMangaExtension(String extensionUrl, String packageName) async {
|
|
return _sendJniIsolateMessage<void>(
|
|
JniIsolateMessage(
|
|
id: _random.nextInt(1 << 32),
|
|
type: JniIsolateMessageType.loadMangaExtension,
|
|
args: {
|
|
'extensionUrl': extensionUrl,
|
|
'packageName': packageName,
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> unloadMangaExtension(String packageName) async {
|
|
return _sendJniIsolateMessage<void>(
|
|
JniIsolateMessage(
|
|
id: _random.nextInt(1 << 32),
|
|
type: JniIsolateMessageType.unloadMangaExtension,
|
|
args: {
|
|
'packageName': packageName,
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<List<JPreferenceItem>> getAnimePreferences(String packageName) async {
|
|
return _sendJniIsolateMessage<List<JPreferenceItem>>(
|
|
JniIsolateMessage(
|
|
id: _random.nextInt(1 << 32),
|
|
type: JniIsolateMessageType.getAnimePreferences,
|
|
args: {'packageName': packageName},
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> setAnimePreference(String packageName, String key, dynamic value) async {
|
|
return _sendJniIsolateMessage<void>(
|
|
JniIsolateMessage(
|
|
id: _random.nextInt(1 << 32),
|
|
type: JniIsolateMessageType.setAnimePreference,
|
|
args: {'packageName': packageName, 'key': key, 'value': value},
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> setAnimePreferences(String packageName, Map<String, dynamic> values) async {
|
|
return _sendJniIsolateMessage<void>(
|
|
JniIsolateMessage(
|
|
id: _random.nextInt(1 << 32),
|
|
type: JniIsolateMessageType.setAnimePreferences,
|
|
args: {'packageName': packageName, 'values': values},
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<List<String>> getAnimeLoadedExtensions() async {
|
|
return _sendJniIsolateMessage<List<String>>(
|
|
JniIsolateMessage(
|
|
id: _random.nextInt(1 << 32),
|
|
type: JniIsolateMessageType.getAnimeLoadedExtensions,
|
|
args: {},
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<List<String>> getMangaLoadedExtensions() async {
|
|
return _sendJniIsolateMessage<List<String>>(
|
|
JniIsolateMessage(
|
|
id: _random.nextInt(1 << 32),
|
|
type: JniIsolateMessageType.getMangaLoadedExtensions,
|
|
args: {},
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<Set<Extension>> getInstalledAnimeExtensions() async {
|
|
Directory animeExtDir = Directory(
|
|
path.join(_supportDirectoryPath, _aniyomiBridgeAnimeExtensionsDir),
|
|
);
|
|
if (!await animeExtDir.exists()) return {};
|
|
return _scanExtensionsRecursively(animeExtDir);
|
|
}
|
|
|
|
Future<Set<Extension>> getInstalledMangaExtensions() async {
|
|
Directory mangaExtDir = Directory(
|
|
path.join(_supportDirectoryPath, _aniyomiBridgeMangaExtensionsDir),
|
|
);
|
|
if (!await mangaExtDir.exists()) return {};
|
|
return _scanExtensionsRecursively(mangaExtDir);
|
|
}
|
|
|
|
Future<Set<Extension>> _scanExtensionsRecursively(Directory rootDir) async {
|
|
final extensions = <Extension>{};
|
|
await for (final entity in rootDir.list(recursive: true)) {
|
|
if (entity is! File) continue;
|
|
if (path.extension(entity.path) != '.jar') continue;
|
|
|
|
final jarFileName = path.basename(entity.path);
|
|
|
|
final nameWithoutExt = jarFileName.replaceAll('.jar', '');
|
|
final firstDash = nameWithoutExt.indexOf('-');
|
|
final name = firstDash >= 0 ? nameWithoutExt.substring(0, firstDash) : nameWithoutExt;
|
|
final version = firstDash >= 0 ? nameWithoutExt.substring(firstDash + 1) : '';
|
|
|
|
extensions.add(Extension(
|
|
name: name,
|
|
version: version,
|
|
packageName: '', // Still cannot determine from filename alone
|
|
));
|
|
}
|
|
return extensions;
|
|
}
|
|
|
|
Future<T> _sendJniIsolateMessage<T>(JniIsolateMessage message) {
|
|
final completer = Completer<T>();
|
|
_pendingRequests[message.id] = completer;
|
|
_jniSenderPort.send(message);
|
|
return completer.future.timeout(
|
|
const Duration(seconds: 45),
|
|
onTimeout: () => throw TimeoutException("JNI Isolate timed out")
|
|
);
|
|
}
|
|
|
|
Future<T> _sendJniIsolateMessageWithCache<T>(
|
|
JniIsolateMessageType messageType,
|
|
Map<String, dynamic> args,
|
|
) {
|
|
final cachedResult = _getCachedResponse<T>(messageType, args);
|
|
if (cachedResult != null) {
|
|
_logger.d("Cache hit for ${messageType.name}, returning cached result");
|
|
return Future.value(cachedResult);
|
|
}
|
|
final message = JniIsolateMessage(
|
|
id: _random.nextInt(1 << 32),
|
|
type: messageType,
|
|
args: args,
|
|
);
|
|
final future = _sendJniIsolateMessage<T>(message);
|
|
// Only cache on success, never cache errors
|
|
future.then((result) {
|
|
_cacheResponse(result, messageType, args);
|
|
}).catchError((error) {
|
|
_logger.d("Not caching error for ${messageType.name}: $error");
|
|
});
|
|
return future;
|
|
}
|
|
|
|
String _getDylibDir(Directory supportDirectory) {
|
|
String executablePath = File(Platform.resolvedExecutable).parent.path;
|
|
if (Platform.isLinux) {
|
|
return path.join(executablePath, "jre", "customjre", "lib", "server");
|
|
} else if (Platform.isMacOS) {
|
|
return path.join(
|
|
executablePath,
|
|
"..",
|
|
"Resources",
|
|
"jre",
|
|
"customjre",
|
|
"lib",
|
|
"server",
|
|
);
|
|
} else if (Platform.isWindows) {
|
|
return path.join(
|
|
executablePath,
|
|
"..",
|
|
"jre",
|
|
"customjre",
|
|
"lib",
|
|
"server",
|
|
);
|
|
} else {
|
|
throw UnsupportedError("Unsupported platform");
|
|
}
|
|
}
|
|
|
|
List<String> _getClassPath(Directory supportDirectory) {
|
|
return [
|
|
path.join(
|
|
supportDirectory.absolute.path,
|
|
_aniyomiBridgeDir,
|
|
_aniyomiBridgeJarName,
|
|
),
|
|
];
|
|
}
|
|
|
|
Future<void> _loadJarIfNeeded(Directory supportDirectory) async {
|
|
String aniyomiBridgeCorePath = path.join(
|
|
supportDirectory.path,
|
|
_aniyomiBridgeDir,
|
|
_aniyomiBridgeJarName,
|
|
);
|
|
File aniyomiBridgeCore = File(aniyomiBridgeCorePath);
|
|
bool needsCopy = false;
|
|
if (!(await aniyomiBridgeCore.exists())) {
|
|
needsCopy = true;
|
|
} else {
|
|
String assetPath = "$_packageAssetsDir/$_aniyomiBridgeJarName";
|
|
String existingFileHash = await _computeFileHash(aniyomiBridgeCore);
|
|
String assetHash = await _computeAssetHash(assetPath);
|
|
if (existingFileHash != assetHash) {
|
|
needsCopy = true;
|
|
}
|
|
}
|
|
if (needsCopy) {
|
|
_logger.i("Copying new aniyomiBridgeCore binary to $aniyomiBridgeCorePath");
|
|
await _copyAssetToFile(
|
|
"$_packageAssetsDir/$_aniyomiBridgeJarName",
|
|
aniyomiBridgeCorePath,
|
|
);
|
|
}
|
|
}
|
|
|
|
Future<String> _computeFileHash(File file) async {
|
|
final bytes = await file.readAsBytes();
|
|
final digest = sha256.convert(bytes);
|
|
return digest.toString();
|
|
}
|
|
|
|
Future<String> _computeAssetHash(String assetPath) async {
|
|
final byteData = await rootBundle.load(assetPath);
|
|
final bytes = byteData.buffer.asUint8List();
|
|
final digest = sha256.convert(bytes);
|
|
return digest.toString();
|
|
}
|
|
|
|
Future<File> _copyAssetToFile(String assetPath, String outPath) async {
|
|
final byteData = await rootBundle.load(assetPath);
|
|
final buffer = byteData.buffer.asUint8List();
|
|
final file = File(outPath);
|
|
await file.parent.create(recursive: true);
|
|
await file.writeAsBytes(buffer, flush: true);
|
|
return file;
|
|
}
|
|
|
|
T? _getCachedResponse<T>(JniIsolateMessageType messageType, Map<String, dynamic> args) {
|
|
// if (!_isCacheable(messageType)) return null;
|
|
final cacheKey = _generateCacheKey(messageType, args);
|
|
if (_responsesCache.containsKey(cacheKey)) {
|
|
_logger.d("Cached response found for ${messageType.name}");
|
|
try {
|
|
final (expiry, cachedResponse as T) =
|
|
_responsesCache[cacheKey]!;
|
|
if (expiry < DateTime.now().millisecondsSinceEpoch) {
|
|
_logger.d(
|
|
"Cached response for ${messageType.name} with cache key $cacheKey has expired, making new request",
|
|
);
|
|
_responsesCache.remove(cacheKey);
|
|
} else {
|
|
_logger.d("Cached response for ${messageType.name} with cache key $cacheKey is still valid for ${(expiry - DateTime.now().millisecondsSinceEpoch) / 1000}s");
|
|
return cachedResponse;
|
|
}
|
|
} catch (e, stackTrace) {
|
|
_logger.e(
|
|
"Error while retrieving cached response for ${messageType.name}: $e",
|
|
stackTrace: stackTrace,
|
|
);
|
|
_responsesCache.remove(cacheKey);
|
|
return null;
|
|
}
|
|
}
|
|
_logger.d("No cached response found for ${messageType.name} with cache key $cacheKey");
|
|
return null;
|
|
}
|
|
|
|
void _cacheResponse<T>(T response, JniIsolateMessageType messageType, Map<String, dynamic> args) {
|
|
final cacheKey = _generateCacheKey(messageType, args);
|
|
_logger.d("Caching response for ${messageType.name} with cache key $cacheKey");
|
|
_responsesCache[cacheKey] =
|
|
(
|
|
DateTime.now().millisecondsSinceEpoch + _cacheTtl.inMilliseconds,
|
|
response,
|
|
);
|
|
}
|
|
|
|
/// Creates a stable string representation of the args
|
|
String _generateCacheKey(JniIsolateMessageType messageType, Map<String, dynamic> args) {
|
|
final argsString = args.entries
|
|
.map((entry) => "${entry.key}:${_getStableHashCode(entry.value)}")
|
|
.join(":").hashCode;
|
|
return "${messageType.name}_$argsString";
|
|
}
|
|
|
|
int _getStableHashCode(dynamic value) {
|
|
if (value is JSEpisode) {
|
|
return "${value.getUrl().toDartString()}_${value.getEpisode_number()}".hashCode;
|
|
}else if (value is JSAnime) {
|
|
return value.getTitle().toDartString().hashCode;
|
|
} else if (value is JSManga) {
|
|
return value.getTitle().toDartString().hashCode;
|
|
} else if (value is JSChapter) {
|
|
return "${value.getUrl().toDartString().hashCode}_${value.getChapter_number()}".hashCode;
|
|
}
|
|
return value.hashCode;
|
|
}
|
|
}
|