comic page

This commit is contained in:
nyne
2024-10-04 21:56:15 +08:00
parent 2772289a19
commit 07dbf6e6af
7 changed files with 915 additions and 178 deletions

View File

@@ -43,6 +43,8 @@ typedef GetImageLoadingConfigFunc = Map<String, dynamic> Function(
typedef GetThumbnailLoadingConfigFunc = Map<String, dynamic> Function(
String imageKey)?;
typedef ComicThumbnailLoader = Future<Res<List<String>>> Function(String comicId, String? next);
class ComicSource {
static final List<ComicSource> _sources = [];
@@ -140,6 +142,8 @@ class ComicSource {
/// Load comic info.
final LoadComicFunc? loadComicInfo;
final ComicThumbnailLoader? loadComicThumbnail;
/// Load comic pages.
final LoadComicPagesFunc? loadComicPages;
@@ -216,6 +220,7 @@ class ComicSource {
this.searchPageData,
this.settings,
this.loadComicInfo,
this.loadComicThumbnail,
this.loadComicPages,
this.getImageLoadingConfig,
this.getThumbnailLoadingConfig,
@@ -237,6 +242,7 @@ class ComicSource {
searchPageData = null,
settings = [],
loadComicInfo = null,
loadComicThumbnail = null,
loadComicPages = null,
getImageLoadingConfig = null,
getThumbnailLoadingConfig = null,
@@ -338,8 +344,8 @@ class SearchPageData {
/// If this is not null, the default value of search options will be first element.
final List<SearchOptions>? searchOptions;
final Widget Function(BuildContext, List<String> initialValues, void Function(List<String>))?
customOptionsBuilder;
final Widget Function(BuildContext, List<String> initialValues,
void Function(List<String>))? customOptionsBuilder;
final Widget Function(String keyword, List<String> options)?
overrideSearchResultBuilder;
@@ -384,22 +390,23 @@ enum SettingType {
class Comic {
final String title;
final String cover;
final String id;
final String? subtitle;
final List<String>? tags;
final String description;
final String sourceKey;
final int? maxPage;
const Comic(this.title, this.cover, this.id, this.subtitle, this.tags, this.description, this.sourceKey, this.maxPage);
const Comic(this.title, this.cover, this.id, this.subtitle, this.tags,
this.description, this.sourceKey, this.maxPage);
Map<String, dynamic> toJson() {
return {
@@ -443,12 +450,7 @@ class ComicDetails with HistoryMixin {
final List<String>? thumbnails;
final Future<Res<List<String>>> Function(String id, int page)?
thumbnailLoader;
final int thumbnailMaxPage;
final List<Comic>? suggestions;
final List<Comic>? recommend;
final String sourceKey;
@@ -458,36 +460,17 @@ class ComicDetails with HistoryMixin {
final String? subId;
const ComicDetails(
this.title,
this.subTitle,
this.cover,
this.description,
this.tags,
this.chapters,
this.thumbnails,
this.thumbnailLoader,
this.thumbnailMaxPage,
this.suggestions,
this.sourceKey,
this.comicId,
{this.isFavorite,
this.subId});
final bool? isLiked;
Map<String, dynamic> toJson() {
return {
"title": title,
"subTitle": subTitle,
"cover": cover,
"description": description,
"tags": tags,
"chapters": chapters,
"sourceKey": sourceKey,
"comicId": comicId,
"isFavorite": isFavorite,
"subId": subId,
};
}
final int? likesCount;
final int? commentsCount;
final String? uploader;
final String? uploadTime;
final String? updateTime;
static Map<String, List<String>> _generateMap(Map<String, dynamic> map) {
var res = <String, List<String>>{};
@@ -503,15 +486,23 @@ class ComicDetails with HistoryMixin {
cover = json["cover"],
description = json["description"],
tags = _generateMap(json["tags"]),
chapters = Map<String, String>.from(json["chapters"]),
chapters = json["chapters"] == null
? null
: Map<String, String>.from(json["chapters"]),
sourceKey = json["sourceKey"],
comicId = json["comicId"],
thumbnails = null,
thumbnailLoader = null,
thumbnailMaxPage = 0,
suggestions = null,
thumbnails = ListOrNull.from(json["thumbnails"]),
recommend = (json["recommend"] as List?)
?.map((e) => Comic.fromJson(e, json["sourceKey"]))
.toList(),
isFavorite = json["isFavorite"],
subId = json["subId"];
subId = json["subId"],
likesCount = json["likesCount"],
isLiked = json["isLiked"],
commentsCount = json["commentsCount"],
uploader = json["uploader"],
uploadTime = json["uploadTime"],
updateTime = json["updateTime"];
@override
HistoryType get historyType => HistoryType(sourceKey.hashCode);

View File

@@ -55,20 +55,21 @@ class ComicSourceParser {
String? _name;
Future<ComicSource> createAndParse(String js, String fileName) async{
if(!fileName.endsWith("js")){
Future<ComicSource> createAndParse(String js, String fileName) async {
if (!fileName.endsWith("js")) {
fileName = "$fileName.js";
}
var file = File(FilePath.join(App.dataPath, "comic_source", fileName));
if(file.existsSync()){
if (file.existsSync()) {
int i = 0;
while(file.existsSync()){
file = File(FilePath.join(App.dataPath, "comic_source", "${fileName.split('.').first}($i).js"));
while (file.existsSync()) {
file = File(FilePath.join(App.dataPath, "comic_source",
"${fileName.split('.').first}($i).js"));
i++;
}
}
await file.writeAsString(js);
try{
try {
return await parse(js, file.path);
} catch (e) {
await file.delete();
@@ -78,9 +79,12 @@ class ComicSourceParser {
Future<ComicSource> parse(String js, String filePath) async {
js = js.replaceAll("\r\n", "\n");
var line1 = js.split('\n')
var line1 = js
.split('\n')
.firstWhereOrNull((element) => element.removeAllBlank.isNotEmpty);
if(line1 == null || !line1.startsWith("class ") || !line1.contains("extends ComicSource")){
if (line1 == null ||
!line1.startsWith("class ") ||
!line1.contains("extends ComicSource")) {
throw ComicSourceParseException("Invalid Content");
}
var className = line1.split("class")[1].split("extends ComicSource").first;
@@ -91,22 +95,24 @@ class ComicSourceParser {
this['temp'] = new $className()
}).call()
""");
_name = JsEngine().runCode("this['temp'].name")
?? (throw ComicSourceParseException('name is required'));
var key = JsEngine().runCode("this['temp'].key")
?? (throw ComicSourceParseException('key is required'));
var version = JsEngine().runCode("this['temp'].version")
?? (throw ComicSourceParseException('version is required'));
_name = JsEngine().runCode("this['temp'].name") ??
(throw ComicSourceParseException('name is required'));
var key = JsEngine().runCode("this['temp'].key") ??
(throw ComicSourceParseException('key is required'));
var version = JsEngine().runCode("this['temp'].version") ??
(throw ComicSourceParseException('version is required'));
var minAppVersion = JsEngine().runCode("this['temp'].minAppVersion");
var url = JsEngine().runCode("this['temp'].url");
var matchBriefIdRegex = JsEngine().runCode("this['temp'].comic.matchBriefIdRegex");
if(minAppVersion != null){
if(compareSemVer(minAppVersion, App.version.split('-').first)){
throw ComicSourceParseException("minAppVersion $minAppVersion is required");
var matchBriefIdRegex =
JsEngine().runCode("this['temp'].comic.matchBriefIdRegex");
if (minAppVersion != null) {
if (compareSemVer(minAppVersion, App.version.split('-').first)) {
throw ComicSourceParseException(
"minAppVersion $minAppVersion is required");
}
}
for(var source in ComicSource.all()){
if(source.key == key){
for (var source in ComicSource.all()) {
if (source.key == key) {
throw ComicSourceParseException("key($key) already exists");
}
}
@@ -120,10 +126,10 @@ class ComicSourceParser {
final account = _loadAccountConfig();
final explorePageData = _loadExploreData();
final categoryPageData = _loadCategoryData();
final categoryComicsData =
_loadCategoryComicsData();
final categoryComicsData = _loadCategoryComicsData();
final searchData = _loadSearchData();
final loadComicFunc = _parseLoadComicFunc();
final loadComicThumbnailFunc = _parseThumbnailLoader();
final loadComicPagesFunc = _parseLoadComicPagesFunc();
final getImageLoadingConfigFunc = _parseImageLoadingConfigFunc();
final getThumbnailLoadingConfigFunc = _parseThumbnailLoadingConfigFunc();
@@ -131,26 +137,28 @@ class ComicSourceParser {
final commentsLoader = _parseCommentsLoader();
final sendCommentFunc = _parseSendCommentFunc();
var source = ComicSource(
_name!,
key,
account,
categoryPageData,
categoryComicsData,
favoriteData,
explorePageData,
searchData,
[],
loadComicFunc,
loadComicPagesFunc,
getImageLoadingConfigFunc,
getThumbnailLoadingConfigFunc,
matchBriefIdRegex,
filePath,
url ?? "",
version ?? "1.0.0",
commentsLoader,
sendCommentFunc);
var source = ComicSource(
_name!,
key,
account,
categoryPageData,
categoryComicsData,
favoriteData,
explorePageData,
searchData,
[],
loadComicFunc,
loadComicThumbnailFunc,
loadComicPagesFunc,
getImageLoadingConfigFunc,
getThumbnailLoadingConfigFunc,
matchBriefIdRegex,
filePath,
url ?? "",
version ?? "1.0.0",
commentsLoader,
sendCommentFunc,
);
await source.loadData();
@@ -168,7 +176,7 @@ class ComicSourceParser {
}
}
bool _checkExists(String index){
bool _checkExists(String index) {
return JsEngine().runCode("ComicSource.sources.$_key.$index !== null "
"&& ComicSource.sources.$_key.$index !== undefined");
}
@@ -198,16 +206,12 @@ class ComicSourceParser {
}
}
void logout(){
void logout() {
JsEngine().runCode("ComicSource.sources.$_key.account.logout()");
}
return AccountConfig(
login,
_getValue("account.login.website"),
_getValue("account.registerWebsite"),
logout
);
return AccountConfig(login, _getValue("account.login.website"),
_getValue("account.registerWebsite"), logout);
}
List<ExplorePageData> _loadExploreData() {
@@ -216,7 +220,7 @@ class ComicSourceParser {
}
var length = JsEngine().runCode("ComicSource.sources.$_key.explore.length");
var pages = <ExplorePageData>[];
for (int i=0; i<length; i++) {
for (int i = 0; i < length; i++) {
final String title = _getValue("explore[$i].title");
final String type = _getValue("explore[$i].type");
Future<Res<List<ExplorePagePart>>> Function()? loadMultiPart;
@@ -226,12 +230,13 @@ class ComicSourceParser {
try {
var res = await JsEngine()
.runCode("ComicSource.sources.$_key.explore[$i].load()");
return Res(List.from(res.keys.map((e) => ExplorePagePart(
e,
(res[e] as List)
.map<Comic>((e) => Comic.fromJson(e, _key!))
.toList(),
null))
return Res(List.from(res.keys
.map((e) => ExplorePagePart(
e,
(res[e] as List)
.map<Comic>((e) => Comic.fromJson(e, _key!))
.toList(),
null))
.toList()));
} catch (e, s) {
Log.error("Data Analysis", "$e\n$s");
@@ -241,11 +246,11 @@ class ComicSourceParser {
} else if (type == "multiPageComicList") {
loadPage = (int page) async {
try {
var res = await JsEngine()
.runCode("ComicSource.sources.$_key.explore[$i].load(${jsonEncode(page)})");
var res = await JsEngine().runCode(
"ComicSource.sources.$_key.explore[$i].load(${jsonEncode(page)})");
return Res(
List.generate(res["comics"].length,
(index) => Comic.fromJson(res["comics"][index], _key!)),
(index) => Comic.fromJson(res["comics"][index], _key!)),
subData: res["maxPage"]);
} catch (e, s) {
Log.error("Network", "$e\n$s");
@@ -317,18 +322,16 @@ class ComicSourceParser {
var value = split.join("-");
map[key] = value;
}
options.add(
CategoryComicsOptions(
map,
List.from(element["notShowWhen"] ?? []),
element["showWhen"] == null ? null : List.from(element["showWhen"])
));
options.add(CategoryComicsOptions(
map,
List.from(element["notShowWhen"] ?? []),
element["showWhen"] == null ? null : List.from(element["showWhen"])));
}
RankingData? rankingData;
if(_checkExists("categoryComics.ranking")){
if (_checkExists("categoryComics.ranking")) {
var options = <String, String>{};
for(var option in _getValue("categoryComics.ranking.options")){
if(option.isEmpty || !option.contains("-")){
for (var option in _getValue("categoryComics.ranking.options")) {
if (option.isEmpty || !option.contains("-")) {
continue;
}
var split = option.split("-");
@@ -336,7 +339,7 @@ class ComicSourceParser {
var value = split.join("-");
options[key] = value;
}
rankingData = RankingData(options, (option, page) async{
rankingData = RankingData(options, (option, page) async {
try {
var res = await JsEngine().runCode("""
ComicSource.sources.$_key.categoryComics.ranking.load(
@@ -344,7 +347,7 @@ class ComicSourceParser {
""");
return Res(
List.generate(res["comics"].length,
(index) => Comic.fromJson(res["comics"][index], _key!)),
(index) => Comic.fromJson(res["comics"][index], _key!)),
subData: res["maxPage"]);
} catch (e, s) {
Log.error("Network", "$e\n$s");
@@ -412,27 +415,10 @@ class ComicSourceParser {
var res = await JsEngine().runCode("""
ComicSource.sources.$_key.comic.loadInfo(${jsonEncode(id)})
""");
var tags = <String, List<String>>{};
(res["tags"] as Map<String, dynamic>?)
?.forEach((key, value) => tags[key] = List.from(value ?? const []));
return Res(ComicDetails(
res["title"],
res["subTitle"],
res["cover"],
res["description"],
tags,
res["chapters"] == null ? null : Map.from(res["chapters"]),
ListOrNull.from(res["thumbnails"]),
// TODO: implement thumbnailLoader
null,
res["thumbnailMaxPage"] ?? 1,
(res["recommend"] as List?)
?.map((e) => Comic.fromJson(e, _key!))
.toList(),
_key!,
id,
isFavorite: res["isFavorite"],
subId: res["subId"],));
if (res is! Map<String, dynamic>) throw "Invalid data";
res['comicId'] = id;
res['sourceKey'] = _key;
return Res(ComicDetails.fromJson(res));
} catch (e, s) {
Log.error("Network", "$e\n$s");
return Res.error(e.toString());
@@ -459,8 +445,8 @@ class ComicSourceParser {
final bool multiFolder = _getValue("favorites.multiFolder");
Future<Res<T>> retryZone<T>(Future<Res<T>> Function() func) async{
if(!ComicSource.find(_key!)!.isLogged){
Future<Res<T>> retryZone<T>(Future<Res<T>> Function() func) async {
if (!ComicSource.find(_key!)!.isLogged) {
return const Res.error("Not login");
}
var res = await func();
@@ -493,7 +479,7 @@ class ComicSourceParser {
}
Future<Res<List<Comic>>> loadComic(int page, [String? folder]) async {
Future<Res<List<Comic>>> func() async{
Future<Res<List<Comic>>> func() async {
try {
var res = await JsEngine().runCode("""
ComicSource.sources.$_key.favorites.loadComics(
@@ -501,13 +487,14 @@ class ComicSourceParser {
""");
return Res(
List.generate(res["comics"].length,
(index) => Comic.fromJson(res["comics"][index], _key!)),
(index) => Comic.fromJson(res["comics"][index], _key!)),
subData: res["maxPage"]);
} catch (e, s) {
Log.error("Network", "$e\n$s");
return Res.error(e.toString());
}
}
return retryZone(func);
}
@@ -517,15 +504,15 @@ class ComicSourceParser {
Future<Res<bool>> Function(String key)? deleteFolder;
if(multiFolder) {
if (multiFolder) {
loadFolders = ([String? comicId]) async {
Future<Res<Map<String, String>>> func() async{
Future<Res<Map<String, String>>> func() async {
try {
var res = await JsEngine().runCode("""
ComicSource.sources.$_key.favorites.loadFolders(${jsonEncode(comicId)})
""");
List<String>? subData;
if(res["favorited"] != null){
if (res["favorited"] != null) {
subData = List.from(res["favorited"]);
}
return Res(Map.from(res["folders"]), subData: subData);
@@ -562,19 +549,19 @@ class ComicSourceParser {
}
return FavoriteData(
key: _key!,
title: _name!,
multiFolder: multiFolder,
loadComic: loadComic,
loadFolders: loadFolders,
addFolder: addFolder,
deleteFolder: deleteFolder,
addOrDelFavorite: addOrDelFavFunc,
key: _key!,
title: _name!,
multiFolder: multiFolder,
loadComic: loadComic,
loadFolders: loadFolders,
addFolder: addFolder,
deleteFolder: deleteFolder,
addOrDelFavorite: addOrDelFavFunc,
);
}
CommentsLoader? _parseCommentsLoader(){
if(!_checkExists("comic.loadComments")) return null;
CommentsLoader? _parseCommentsLoader() {
if (!_checkExists("comic.loadComments")) return null;
return (id, subId, page, replyTo) async {
try {
var res = await JsEngine().runCode("""
@@ -582,9 +569,10 @@ class ComicSourceParser {
${jsonEncode(id)}, ${jsonEncode(subId)}, ${jsonEncode(page)}, ${jsonEncode(replyTo)})
""");
return Res(
(res["comments"] as List).map((e) => Comment(
e["userName"], e["avatar"], e["content"], e["time"], e["replyCount"], e["id"].toString()
)).toList(),
(res["comments"] as List)
.map((e) => Comment(e["userName"], e["avatar"], e["content"],
e["time"], e["replyCount"], e["id"].toString()))
.toList(),
subData: res["maxPage"]);
} catch (e, s) {
Log.error("Network", "$e\n$s");
@@ -593,10 +581,10 @@ class ComicSourceParser {
};
}
SendCommentFunc? _parseSendCommentFunc(){
if(!_checkExists("comic.sendComment")) return null;
SendCommentFunc? _parseSendCommentFunc() {
if (!_checkExists("comic.sendComment")) return null;
return (id, subId, content, replyTo) async {
Future<Res<bool>> func() async{
Future<Res<bool>> func() async {
try {
await JsEngine().runCode("""
ComicSource.sources.$_key.comic.sendComment(
@@ -608,8 +596,9 @@ class ComicSourceParser {
return Res.error(e.toString());
}
}
var res = await func();
if(res.error && res.errorMessage!.contains("Login expired")){
if (res.error && res.errorMessage!.contains("Login expired")) {
var reLoginRes = await ComicSource.find(_key!)!.reLogin();
if (!reLoginRes) {
return const Res.error("Login expired and re-login failed");
@@ -621,8 +610,8 @@ class ComicSourceParser {
};
}
GetImageLoadingConfigFunc? _parseImageLoadingConfigFunc(){
if(!_checkExists("comic.onImageLoad")){
GetImageLoadingConfigFunc? _parseImageLoadingConfigFunc() {
if (!_checkExists("comic.onImageLoad")) {
return null;
}
return (imageKey, comicId, ep) {
@@ -633,19 +622,36 @@ class ComicSourceParser {
};
}
GetThumbnailLoadingConfigFunc? _parseThumbnailLoadingConfigFunc(){
if(!_checkExists("comic.onThumbnailLoad")){
GetThumbnailLoadingConfigFunc? _parseThumbnailLoadingConfigFunc() {
if (!_checkExists("comic.onThumbnailLoad")) {
return null;
}
return (imageKey) {
var res = JsEngine().runCode("""
ComicSource.sources.$_key.comic.onThumbnailLoad(${jsonEncode(imageKey)})
""");
if(res is! Map) {
if (res is! Map) {
Log.error("Network", "function onThumbnailLoad return invalid data");
throw "function onThumbnailLoad return invalid data";
}
return res as Map<String, dynamic>;
};
}
}
ComicThumbnailLoader? _parseThumbnailLoader() {
if (!_checkExists("comic.loadThumbnail")) {
return null;
}
return (id, next) async {
try {
var res = await JsEngine().runCode("""
ComicSource.sources.$_key.comic.loadThumbnail(${jsonEncode(id)}, ${jsonEncode(next)})
""");
return Res(List<String>.from(res['thumbnails']), subData: res['next']);
} catch (e, s) {
Log.error("Network", "$e\n$s");
return Res.error(e.toString());
}
};
}
}