You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
2.7 KiB
Dart

import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:isekai_wiki/api/base_api.dart';
import 'package:json_annotation/json_annotation.dart';
import '../global.dart';
part 'site_config.g.dart';
@JsonSerializable()
class SiteConfig {
List<String> moduleStyles;
List<String> moduleScripts;
String renderTheme;
SiteConfig({
this.moduleStyles = const [],
this.moduleScripts = const [],
this.renderTheme = Global.renderThemeFallback,
});
factory SiteConfig.fromJson(Map<String, dynamic> json) =>
_$SiteConfigFromJson(json);
Map<String, dynamic> toJson() => _$SiteConfigToJson(this);
}
class AppSettingsController extends GetxController {
bool _ignoreSave = false;
bool isAppActive = false;
List<String> moduleStyles = [];
List<String> moduleScripts = [];
String renderTheme = Global.renderThemeFallback;
@override
void onInit() {
super.onInit();
loadFromStorage();
if (isAppActive) {
// 尝试更新APP配置
loadFromRemote().catchError((err, stack) {
if (kDebugMode) {
print("Cannot update site config: $err");
stack.printError();
}
});
}
}
/// 从本地存储读取
void loadFromStorage() {
try {
final storage = GetStorage();
isAppActive = storage.read<bool>("appActive") ?? false;
var siteConfigJson = storage.read<String>("siteConfigCache");
if (siteConfigJson == null) return;
var siteConfigObject = jsonDecode(siteConfigJson);
if (siteConfigObject == null) return;
var siteConfigData = SiteConfig.fromJson(siteConfigObject);
loadFromEntity(siteConfigData);
} catch (ex, stack) {
if (kDebugMode) {
print(ex);
stack.printError();
}
} finally {
_ignoreSave = false;
}
}
/// 缓存到本地存储
void saveToStorage() {
if (_ignoreSave) return;
final storage = GetStorage();
var siteConfigData = SiteConfig(
moduleScripts: moduleScripts,
moduleStyles: moduleStyles,
renderTheme: renderTheme,
);
var siteConfigJson = jsonEncode(siteConfigData.toJson());
storage.write("siteConfigCache", siteConfigJson);
}
void loadFromEntity(SiteConfig siteConfigData) {
moduleScripts = siteConfigData.moduleScripts;
moduleStyles = siteConfigData.moduleStyles;
renderTheme = siteConfigData.renderTheme;
}
Future<void> loadFromRemote() async {
Uri siteConfigUri = Uri.parse(Global.siteConfigUrl);
var resMap = await BaseApi.getJson(siteConfigUri);
var siteConfigData = SiteConfig.fromJson(resMap);
loadFromEntity(siteConfigData);
}
}