Repo created

This commit is contained in:
Fr4nz D13trich 2025-11-20 13:08:39 +01:00
parent 2fd78f5dc9
commit 489cf0b2ea
148 changed files with 30898 additions and 2 deletions

View file

@ -0,0 +1,136 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:html/parser.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class APKCombo extends AppSource {
APKCombo() {
hosts = ['apkcombo.com'];
showReleaseDateAsVersionToggle = true;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}/+[^/]+/+[^/]+',
caseSensitive: false,
);
var match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
return Uri.parse(standardUrl).pathSegments.last;
}
@override
Future<Map<String, String>?> getRequestHeaders(
Map<String, dynamic> additionalSettings, {
bool forAPKDownload = false,
}) async {
return {
"User-Agent": "curl/8.0.1",
"Accept": "*/*",
"Connection": "keep-alive",
"Host": hosts[0],
};
}
Future<List<MapEntry<String, String>>> getApkUrls(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var res = await sourceRequest('$standardUrl/download/apk', {});
if (res.statusCode != 200) {
throw getObtainiumHttpError(res);
}
var html = parse(res.body);
return html
.querySelectorAll('#variants-tab > div > ul > li')
.map((e) {
String? arch = e
.querySelector('code')
?.text
.trim()
.replaceAll(',', '')
.replaceAll(':', '-')
.replaceAll(' ', '-');
return e.querySelectorAll('a').map((e) {
String? url = e.attributes['href'];
if (url != null &&
!Uri.parse(url).path.toLowerCase().endsWith('.apk')) {
url = null;
}
String verCode =
e.querySelector('.info .header .vercode')?.text.trim() ?? '';
return MapEntry<String, String>(
arch != null ? '$arch-$verCode.apk' : '',
url ?? '',
);
}).toList();
})
.reduce((value, element) => [...value, ...element])
.where((element) => element.value.isNotEmpty)
.toList();
}
@override
Future<String> assetUrlPrefetchModifier(
String assetUrl,
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var freshURLs = await getApkUrls(standardUrl, additionalSettings);
var path2Match = Uri.parse(assetUrl).path;
for (var url in freshURLs) {
if (Uri.parse(url.value).path == path2Match) {
return url.value;
}
}
throw NoAPKError();
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
String appId = (await tryInferringAppId(standardUrl))!;
var preres = await sourceRequest(standardUrl, additionalSettings);
if (preres.statusCode != 200) {
throw getObtainiumHttpError(preres);
}
var res = parse(preres.body);
String? version = res.querySelector('div.version')?.text.trim();
if (version == null) {
throw NoVersionError();
}
String appName = res.querySelector('div.app_name')?.text.trim() ?? appId;
String author = res.querySelector('div.author')?.text.trim() ?? appName;
List<String> infoArray = res
.querySelectorAll('div.information-table > .item > div.value')
.map((e) => e.text.trim())
.toList();
DateTime? releaseDate;
if (infoArray.length >= 2) {
try {
releaseDate = DateFormat('MMMM d, yyyy').parse(infoArray[1]);
} catch (e) {
// ignore
}
}
return APKDetails(
version,
await getApkUrls(standardUrl, additionalSettings),
AppNames(author, appName),
releaseDate: releaseDate,
);
}
}

View file

@ -0,0 +1,138 @@
import 'dart:io';
import 'package:easy_localization/easy_localization.dart';
import 'package:html/parser.dart';
import 'package:http/http.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/apps_provider.dart';
import 'package:obtainium/providers/settings_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
class APKMirror extends AppSource {
APKMirror() {
hosts = ['apkmirror.com'];
enforceTrackOnly = true;
showReleaseDateAsVersionToggle = true;
additionalSourceAppSpecificSettingFormItems = [
[
GeneratedFormSwitch(
'fallbackToOlderReleases',
label: tr('fallbackToOlderReleases'),
defaultValue: true,
),
],
[
GeneratedFormTextField(
'filterReleaseTitlesByRegEx',
label: tr('filterReleaseTitlesByRegEx'),
required: false,
additionalValidators: [
(value) {
return regExValidator(value);
},
],
),
],
];
}
@override
Future<Map<String, String>?> getRequestHeaders(
Map<String, dynamic> additionalSettings, {
bool forAPKDownload = false,
}) async {
return {
"User-Agent":
"Obtainium/${(await getInstalledInfo(obtainiumId))?.versionName ?? '1.0.0'}",
};
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}/apk/[^/]+/[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
String? changeLogPageFromStandardUrl(String standardUrl) =>
'$standardUrl/#whatsnew';
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
bool fallbackToOlderReleases =
additionalSettings['fallbackToOlderReleases'] == true;
String? regexFilter =
(additionalSettings['filterReleaseTitlesByRegEx'] as String?)
?.isNotEmpty ==
true
? additionalSettings['filterReleaseTitlesByRegEx']
: null;
Response res = await sourceRequest(
'$standardUrl/feed/',
additionalSettings,
);
if (res.statusCode == 200) {
var items = parse(res.body).querySelectorAll('item');
dynamic targetRelease;
for (int i = 0; i < items.length; i++) {
if (!fallbackToOlderReleases && i > 0) break;
String? nameToFilter = items[i].querySelector('title')?.innerHtml;
if (regexFilter != null &&
nameToFilter != null &&
!RegExp(regexFilter).hasMatch(nameToFilter.trim())) {
continue;
}
targetRelease = items[i];
break;
}
String? titleString = targetRelease?.querySelector('title')?.innerHtml;
String? dateString = targetRelease
?.querySelector('pubDate')
?.innerHtml
.split(' ')
.sublist(0, 5)
.join(' ');
DateTime? releaseDate = dateString != null
? HttpDate.parse('$dateString GMT')
: null;
String? version = titleString
?.substring(
RegExp('[0-9]').firstMatch(titleString)?.start ?? 0,
RegExp(' by ').allMatches(titleString).last.start,
)
.trim();
if (version == null || version.isEmpty) {
version = titleString;
}
if (version == null || version.isEmpty) {
throw NoVersionError();
}
return APKDetails(
version,
[],
getAppNames(standardUrl),
releaseDate: releaseDate,
);
} else {
throw getObtainiumHttpError(res);
}
}
AppNames getAppNames(String standardUrl) {
String temp = standardUrl.substring(standardUrl.indexOf('://') + 3);
List<String> names = temp.substring(temp.indexOf('/') + 1).split('/');
return AppNames(names[1], names[2]);
}
}

View file

@ -0,0 +1,219 @@
import 'dart:convert';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
extension Unique<E, Id> on List<E> {
List<E> unique([Id Function(E element)? id, bool inplace = true]) {
final ids = <dynamic>{};
var list = inplace ? this : List<E>.from(this);
list.retainWhere((x) => ids.add(id != null ? id(x) : x as Id));
return list;
}
}
class APKPure extends AppSource {
APKPure() {
hosts = ['apkpure.net', 'apkpure.com'];
allowSubDomains = true;
naiveStandardVersionDetection = true;
showReleaseDateAsVersionToggle = true;
additionalSourceAppSpecificSettingFormItems = [
[
GeneratedFormSwitch(
'fallbackToOlderReleases',
label: tr('fallbackToOlderReleases'),
defaultValue: true,
),
],
[
GeneratedFormSwitch(
'stayOneVersionBehind',
label: tr('stayOneVersionBehind'),
defaultValue: false,
),
],
[
GeneratedFormSwitch(
'useFirstApkOfVersion',
label: tr('useFirstApkOfVersion'),
defaultValue: true,
),
],
];
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegExB = RegExp(
'^https?://m.${getSourceRegex(hosts)}(/+[^/]{2})?/+[^/]+/+[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegExB.firstMatch(url);
if (match != null) {
var uri = Uri.parse(url);
url = 'https://${uri.host.substring(2)}${uri.path}';
}
RegExp standardUrlRegExA = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}(/+[^/]{2})?/+[^/]+/+[^/]+',
caseSensitive: false,
);
match = standardUrlRegExA.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
return Uri.parse(standardUrl).pathSegments.last;
}
Future<APKDetails> getDetailsForVersion(
List<Map<String, dynamic>> versionVariants,
List<String> supportedArchs,
Map<String, dynamic> additionalSettings,
) async {
var apkUrls = versionVariants
.map((e) {
String appId = e['package_name'];
String versionCode = e['version_code'];
List<String> architectures = e['native_code']?.cast<String>();
String architectureString = architectures.join(',');
if (architectures.contains("universal") ||
architectures.contains("unlimited")) {
architectures = [];
}
if (additionalSettings['autoApkFilterByArch'] == true &&
architectures.isNotEmpty &&
architectures.where((a) => supportedArchs.contains(a)).isEmpty) {
return null;
}
String type = e['asset']['type'];
String downloadUri = e['asset']['url'];
return MapEntry(
'$appId-$versionCode-$architectureString.${type.toLowerCase()}',
downloadUri,
);
})
.nonNulls
.toList()
.unique((e) => e.key);
if (apkUrls.isEmpty) {
throw NoAPKError();
}
// get version details from first variant
var v = versionVariants.first;
String version = v['version_name'];
String author = v['developer'];
String appName = v['title'];
DateTime releaseDate = DateTime.parse(v['update_date']);
String? changeLog = v['whatsnew'];
if (changeLog != null && changeLog.isEmpty) {
changeLog = null;
}
if (additionalSettings['useFirstApkOfVersion'] == true) {
apkUrls = [apkUrls.first];
}
return APKDetails(
version,
apkUrls,
AppNames(author, appName),
releaseDate: releaseDate,
changeLog: changeLog,
);
}
@override
Future<Map<String, String>?> getRequestHeaders(
Map<String, dynamic> additionalSettings, {
bool forAPKDownload = false,
}) async {
if (forAPKDownload) {
return null;
} else {
return {
"Ual-Access-Businessid": "projecta",
"Ual-Access-ProjectA":
'{"device_info":{"os_ver":"${((await DeviceInfoPlugin().androidInfo).version.sdkInt)}"}}',
};
}
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
String appId = (await tryInferringAppId(standardUrl))!;
List<String> supportedArchs =
(await DeviceInfoPlugin().androidInfo).supportedAbis;
// request versions from API
var res = await sourceRequest(
"https://tapi.pureapk.com/v3/get_app_his_version?package_name=$appId&hl=en",
additionalSettings,
);
if (res.statusCode != 200) {
throw getObtainiumHttpError(res);
}
List<Map<String, dynamic>> apks = jsonDecode(
res.body,
)['version_list'].cast<Map<String, dynamic>>();
// group by version
List<List<Map<String, dynamic>>> versions = apks
.fold<Map<String, List<Map<String, dynamic>>>>({}, (
Map<String, List<Map<String, dynamic>>> val,
Map<String, dynamic> element,
) {
String v = element['version_name'];
if (!val.containsKey(v)) {
val[v] = [];
}
val[v]?.add(element);
return val;
})
.values
.toList();
if (versions.isEmpty) {
throw NoReleasesError();
}
for (var i = 0; i < versions.length; i++) {
var v = versions[i];
try {
if (i == 0 && additionalSettings['stayOneVersionBehind'] == true) {
throw NoReleasesError();
}
return await getDetailsForVersion(
v,
supportedArchs,
additionalSettings,
);
} catch (e) {
if (additionalSettings['fallbackToOlderReleases'] != true ||
i == versions.length - 1) {
rethrow;
}
}
}
throw NoAPKError();
}
}

View file

@ -0,0 +1,94 @@
import 'dart:convert';
import 'package:easy_localization/easy_localization.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class Aptoide extends AppSource {
Aptoide() {
hosts = ['aptoide.com'];
name = 'Aptoide';
allowSubDomains = true;
naiveStandardVersionDetection = true;
showReleaseDateAsVersionToggle = true;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://([^\\.]+\\.){2,}${getSourceRegex(hosts)}',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
return (await getAppDetailsJSON(
standardUrl,
additionalSettings,
))['package'];
}
Future<Map<String, dynamic>> getAppDetailsJSON(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var res = await sourceRequest(standardUrl, additionalSettings);
if (res.statusCode != 200) {
throw getObtainiumHttpError(res);
}
var idMatch = RegExp('"app":{"id":[0-9]+').firstMatch(res.body);
String? id;
if (idMatch != null) {
id = res.body.substring(idMatch.start + 12, idMatch.end);
} else {
throw NoReleasesError();
}
var res2 = await sourceRequest(
'https://ws2.aptoide.com/api/7/getApp/app_id/$id',
additionalSettings,
);
if (res2.statusCode != 200) {
throw getObtainiumHttpError(res);
}
return jsonDecode(res2.body)?['nodes']?['meta']?['data'];
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var appDetails = await getAppDetailsJSON(standardUrl, additionalSettings);
String appName = appDetails['name'] ?? tr('app');
String author = appDetails['developer']?['name'] ?? name;
String? dateStr = appDetails['updated'];
String? version = appDetails['file']?['vername'];
String? apkUrl = appDetails['file']?['path'];
if (version == null) {
throw NoVersionError();
}
if (apkUrl == null) {
throw NoAPKError();
}
DateTime? relDate;
if (dateStr != null) {
relDate = DateTime.parse(dateStr);
}
return APKDetails(
version,
getApkUrlsFromUrls([apkUrl]),
AppNames(author, appName),
releaseDate: relDate,
);
}
}

View file

@ -0,0 +1,65 @@
import 'package:obtainium/app_sources/github.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class Codeberg extends AppSource {
GitHub gh = GitHub(hostChanged: true);
Codeberg() {
name = 'Forgejo (Codeberg)';
hosts = ['codeberg.org'];
additionalSourceAppSpecificSettingFormItems =
gh.additionalSourceAppSpecificSettingFormItems;
canSearch = true;
searchQuerySettingFormItems = gh.searchQuerySettingFormItems;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}/[^/]+/[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
String? changeLogPageFromStandardUrl(String standardUrl) =>
'$standardUrl/releases';
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
return await gh.getLatestAPKDetailsCommon2(standardUrl, additionalSettings, (
bool useTagUrl,
) async {
return 'https://${hosts[0]}/api/v1/repos${standardUrl.substring('https://${hosts[0]}'.length)}/${useTagUrl ? 'tags' : 'releases'}?per_page=100';
}, null);
}
AppNames getAppNames(String standardUrl) {
String temp = standardUrl.substring(standardUrl.indexOf('://') + 3);
List<String> names = temp.substring(temp.indexOf('/') + 1).split('/');
return AppNames(names[0], names[1]);
}
@override
Future<Map<String, List<String>>> search(
String query, {
Map<String, dynamic> querySettings = const {},
}) async {
return gh.searchCommon(
query,
'https://${hosts[0]}/api/v1/repos/search?q=${Uri.encodeQueryComponent(query)}&limit=100',
'data',
querySettings: querySettings,
);
}
}

View file

@ -0,0 +1,193 @@
import 'dart:convert';
import 'package:bcrypt/bcrypt.dart';
import 'package:crypto/crypto.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'dart:math';
// kanged from https://github.com/DUpdateSystem/UpgradeAll/blob/b2f92c9/core-websdk/src/main/java/net/xzos/upgradeall/core/websdk/api/client_proxy/hubs/CoolApk.kt
class CoolApk extends AppSource {
CoolApk() {
name = tr('coolApk');
hosts = ['www.coolapk.com', 'api2.coolapk.com'];
allowSubDomains = true;
naiveStandardVersionDetection = true;
allowOverride = false;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
r'^https?://(www\.)?coolapk\.com/apk/[^/]+',
caseSensitive: false,
);
var match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
String standardizedUrl = match.group(0)!;
return standardizedUrl;
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
String appId = Uri.parse(standardUrl).pathSegments.last;
return appId;
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
String appId = (await tryInferringAppId(standardUrl))!;
String apiUrl = 'https://api2.coolapk.com';
// get latest
var detailUrl = '$apiUrl/v6/apk/detail?id=$appId';
var headers = await getRequestHeaders(additionalSettings);
var res = await sourceRequest(detailUrl, additionalSettings);
if (res.statusCode != 200) {
throw getObtainiumHttpError(res);
}
var json = jsonDecode(res.body);
if (json['status'] == -2 || json['data'] == null) {
throw NoReleasesError();
}
var detail = json['data'];
String version = detail['apkversionname'].toString();
String appName = detail['title'].toString();
String author = detail['developername']?.toString() ?? 'CoolApk';
String changelog = detail['changelog']?.toString() ?? '';
int? releaseDate = detail['lastupdate'] != null
? (detail['lastupdate'] is int
? detail['lastupdate'] * 1000
: int.parse(detail['lastupdate'].toString()) * 1000)
: null;
String aid = detail['id'].toString();
// get apk url
String apkUrl = await _getLatestApkUrl(
apiUrl,
appId,
aid,
version,
headers,
);
if (apkUrl.isEmpty) {
throw NoAPKError();
}
String apkName = '${appId}_$version.apk';
return APKDetails(
version,
[MapEntry(apkName, apkUrl)],
AppNames(author, appName),
releaseDate: releaseDate != null
? DateTime.fromMillisecondsSinceEpoch(releaseDate)
: null,
changeLog: changelog,
);
}
Future<String> _getLatestApkUrl(
String apiUrl,
String appId,
String aid,
String version,
Map<String, String>? headers,
) async {
String url = '$apiUrl/v6/apk/download?pn=$appId&aid=$aid';
var res = await sourceRequest(url, {}, followRedirects: false);
if (res.statusCode >= 300 && res.statusCode < 400) {
String location = res.headers['location'] ?? '';
return location;
}
return '';
}
@override
Future<Map<String, String>?> getRequestHeaders(
Map<String, dynamic> additionalSettings, {
bool forAPKDownload = false,
}) async {
var tokenPair = _getToken();
// CoolAPK header
return {
'User-Agent':
'Dalvik/2.1.0 (Linux; U; Android 9; MI 8 SE MIUI/9.5.9) (#Build; Xiaomi; MI 8 SE; PKQ1.181121.001; 9) +CoolMarket/12.4.2-2208241-universal',
'X-App-Id': 'com.coolapk.market',
'X-Requested-With': 'XMLHttpRequest',
'X-Sdk-Int': '30',
'X-App-Mode': 'universal',
'X-App-Channel': 'coolapk',
'X-Sdk-Locale': 'zh-CN',
'X-App-Version': '12.4.2',
'X-Api-Supported': '2208241',
'X-App-Code': '2208241',
'X-Api-Version': '12',
'X-App-Device': tokenPair['deviceCode']!,
'X-Dark-Mode': '0',
'X-App-Token': tokenPair['token']!,
};
}
Map<String, String> _getToken() {
final rand = Random();
String randHexString(int n) => List.generate(
n,
(_) => rand.nextInt(256).toRadixString(16).padLeft(2, '0'),
).join().toUpperCase();
String randMacAddress() => List.generate(
6,
(_) => rand.nextInt(256).toRadixString(16).padLeft(2, '0'),
).join(':');
// https://github.com/XiaoMengXinX/FuckCoolapkTokenV2https://github.com/Coolapk-UWP/Coolapk-UWP
// device
String aid = randHexString(16);
String mac = randMacAddress();
const manufactor = 'Google';
const brand = 'Google';
const model = 'Pixel 5a';
const buildNumber = 'SQ1D.220105.007';
// generate deviceCode
String deviceCode = base64.encode(
'$aid; ; ; $mac; $manufactor; $brand; $model; $buildNumber'.codeUnits,
);
// generate timestamp
String timeStamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000)
.toString();
String base64TimeStamp = base64.encode(timeStamp.codeUnits);
String md5TimeStamp = md5.convert(timeStamp.codeUnits).toString();
String md5DeviceCode = md5.convert(deviceCode.codeUnits).toString();
// generate token
String token =
'token://com.coolapk.market/dcf01e569c1e3db93a3d0fcf191a622c?$md5TimeStamp\$$md5DeviceCode&com.coolapk.market';
String base64Token = base64.encode(token.codeUnits);
String md5Base64Token = md5.convert(base64Token.codeUnits).toString();
String md5Token = md5.convert(token.codeUnits).toString();
// generate salt and hash
String bcryptSalt =
'\$2a\$10\$${base64TimeStamp.substring(0, 14)}/${md5Token.substring(0, 6)}u';
String bcryptResult = BCrypt.hashpw(md5Base64Token, bcryptSalt);
String reBcryptResult = bcryptResult.replaceRange(0, 3, '\$2y');
String finalToken = 'v2${base64.encode(reBcryptResult.codeUnits)}';
return {'deviceCode': deviceCode, 'token': finalToken};
}
}

View file

@ -0,0 +1,83 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:obtainium/app_sources/html.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class DirectAPKLink extends AppSource {
HTML html = HTML();
DirectAPKLink() {
name = tr('directAPKLink');
additionalSourceAppSpecificSettingFormItems = [
...html.additionalSourceAppSpecificSettingFormItems
.where(
(element) => element
.where((element) => element.key == 'requestHeader')
.isNotEmpty,
)
,
[
GeneratedFormDropdown(
'defaultPseudoVersioningMethod',
[
MapEntry('partialAPKHash', tr('partialAPKHash')),
MapEntry('ETag', 'ETag'),
],
label: tr('defaultPseudoVersioningMethod'),
defaultValue: 'partialAPKHash',
),
],
];
excludeCommonSettingKeys = [
'versionExtractionRegEx',
'matchGroupToUse',
'versionDetection',
'useVersionCodeAsOSVersion',
'apkFilterRegEx',
'autoApkFilterByArch',
];
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
if (!forSelection) {
return url;
}
RegExp standardUrlRegExA = RegExp('.+\\.apk\$', caseSensitive: false);
var match = standardUrlRegExA.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<Map<String, String>?> getRequestHeaders(
Map<String, dynamic> additionalSettings, {
bool forAPKDownload = false,
}) {
return html.getRequestHeaders(
additionalSettings,
forAPKDownload: forAPKDownload,
);
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var additionalSettingsNew = getDefaultValuesFromFormItems(
html.combinedAppSpecificSettingFormItems,
);
for (var s in additionalSettings.keys) {
if (additionalSettingsNew.containsKey(s)) {
additionalSettingsNew[s] = additionalSettings[s];
}
}
additionalSettingsNew['directAPKLink'] = true;
additionalSettingsNew['versionDetection'] = false;
return html.getLatestAPKDetails(standardUrl, additionalSettingsNew);
}
}

View file

@ -0,0 +1,95 @@
import 'dart:convert';
import 'package:easy_localization/easy_localization.dart';
import 'package:html/parser.dart';
import 'package:obtainium/app_sources/html.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class Farsroid extends AppSource {
Farsroid() {
hosts = ['farsroid.com'];
name = 'Farsroid';
naiveStandardVersionDetection = true;
additionalSourceAppSpecificSettingFormItems = [
[
GeneratedFormSwitch(
'useFirstApkOfVersion',
label: tr('useFirstApkOfVersion'),
defaultValue: true,
),
],
];
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://([^\\.]+\\.)${getSourceRegex(hosts)}/[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
String appName = Uri.parse(standardUrl).pathSegments.last;
var res = await sourceRequest(standardUrl, additionalSettings);
if (res.statusCode != 200) {
throw getObtainiumHttpError(res);
}
var html = parse(res.body);
var dlinks = html.querySelectorAll('.download-links');
if (dlinks.isEmpty) {
throw NoReleasesError();
}
var postId = dlinks.first.attributes['data-post-id'] ?? '';
var version = dlinks.first.attributes['data-post-version'] ?? '';
if (postId.isEmpty || version.isEmpty) {
throw NoVersionError();
}
var res2 = await sourceRequest(
Uri.encodeFull(
'https://${hosts[0]}/api/download-box/?post_id=$postId&post_version=$version',
),
additionalSettings,
);
var html2 = jsonDecode(res2.body)?['data']?['content'] as String? ?? '';
if (html2.isEmpty) {
throw NoAPKError();
}
var apkLinks = (await grabLinksCommon(
html2,
res2.request!.url,
additionalSettings,
)).map((l) => MapEntry(Uri.parse(l.key).pathSegments.last, l.key)).toList();
if (additionalSettings['useFirstApkOfVersion'] == true) {
apkLinks = apkLinks
.where(
(l) => l.key.toLowerCase().startsWith(
'$appName-$version'.toLowerCase(),
),
)
.toList();
}
if (apkLinks.isEmpty) {
throw NoAPKError();
}
return APKDetails(version, apkLinks, AppNames(name, appName));
}
}

291
lib/app_sources/fdroid.dart Normal file
View file

@ -0,0 +1,291 @@
import 'dart:convert';
import 'package:easy_localization/easy_localization.dart';
import 'package:html/parser.dart';
import 'package:http/http.dart';
import 'package:obtainium/app_sources/github.dart';
import 'package:obtainium/app_sources/gitlab.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class FDroid extends AppSource {
FDroid() {
hosts = ['f-droid.org'];
name = tr('fdroid');
naiveStandardVersionDetection = true;
canSearch = true;
additionalSourceAppSpecificSettingFormItems = [
[
GeneratedFormTextField(
'filterVersionsByRegEx',
label: tr('filterVersionsByRegEx'),
required: false,
additionalValidators: [
(value) {
return regExValidator(value);
},
],
),
],
[
GeneratedFormSwitch(
'trySelectingSuggestedVersionCode',
label: tr('trySelectingSuggestedVersionCode'),
defaultValue: true,
),
],
[
GeneratedFormSwitch(
'autoSelectHighestVersionCode',
label: tr('autoSelectHighestVersionCode'),
),
],
];
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegExB = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}/+[^/]+/+packages/+[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegExB.firstMatch(url);
if (match != null) {
url =
'https://${Uri.parse(match.group(0)!).host}/packages/${Uri.parse(url).pathSegments.where((s) => s.trim().isNotEmpty).last}';
}
RegExp standardUrlRegExA = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}/+packages/+[^/]+',
caseSensitive: false,
);
match = standardUrlRegExA.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
return Uri.parse(standardUrl).pathSegments.last;
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
String? appId = await tryInferringAppId(standardUrl);
String host = Uri.parse(standardUrl).host;
var details = getAPKUrlsFromFDroidPackagesAPIResponse(
await sourceRequest(
'https://$host/api/v1/packages/$appId',
additionalSettings,
),
'https://$host/repo/$appId',
standardUrl,
name,
additionalSettings: additionalSettings,
);
if (!hostChanged) {
try {
var res = await sourceRequest(
'https://gitlab.com/fdroid/fdroiddata/-/raw/master/metadata/$appId.yml',
additionalSettings,
);
var lines = res.body.split('\n');
var authorLines = lines.where((l) => l.startsWith('AuthorName: '));
if (authorLines.isNotEmpty) {
details.names.author = authorLines.first
.split(': ')
.sublist(1)
.join(': ');
}
var changelogUrls = lines
.where((l) => l.startsWith('Changelog: '))
.map((e) => e.split(' ').sublist(1).join(' '));
if (changelogUrls.isNotEmpty) {
details.changeLog = changelogUrls.first;
bool isGitHub = false;
bool isGitLab = false;
try {
GitHub(
hostChanged: true,
).sourceSpecificStandardizeURL(details.changeLog!);
isGitHub = true;
} catch (e) {
//
}
try {
GitLab(
hostChanged: true,
).sourceSpecificStandardizeURL(details.changeLog!);
isGitLab = true;
} catch (e) {
//
}
if ((isGitHub || isGitLab) &&
(details.changeLog?.indexOf('/blob/') ?? -1) >= 0) {
details.changeLog = (await sourceRequest(
details.changeLog!.replaceFirst('/blob/', '/raw/'),
additionalSettings,
)).body;
}
}
} catch (e) {
// Fail silently
}
if ((details.changeLog?.length ?? 0) > 2048) {
details.changeLog = '${details.changeLog!.substring(0, 2048)}...';
}
}
return details;
}
@override
Future<Map<String, List<String>>> search(
String query, {
Map<String, dynamic> querySettings = const {},
}) async {
Response res = await sourceRequest(
'https://search.${hosts[0]}/?q=${Uri.encodeQueryComponent(query)}',
{},
);
if (res.statusCode == 200) {
Map<String, List<String>> urlsWithDescriptions = {};
parse(res.body).querySelectorAll('.package-header').forEach((e) {
String? url = e.attributes['href'];
if (url != null) {
try {
standardizeUrl(url);
} catch (e) {
url = null;
}
}
if (url != null) {
urlsWithDescriptions[url] = [
e.querySelector('.package-name')?.text.trim() ?? '',
e.querySelector('.package-summary')?.text.trim() ??
tr('noDescription'),
];
}
});
return urlsWithDescriptions;
} else {
throw getObtainiumHttpError(res);
}
}
APKDetails getAPKUrlsFromFDroidPackagesAPIResponse(
Response res,
String apkUrlPrefix,
String standardUrl,
String sourceName, {
Map<String, dynamic> additionalSettings = const {},
}) {
var autoSelectHighestVersionCode =
additionalSettings['autoSelectHighestVersionCode'] == true;
var trySelectingSuggestedVersionCode =
additionalSettings['trySelectingSuggestedVersionCode'] == true;
var filterVersionsByRegEx =
(additionalSettings['filterVersionsByRegEx'] as String?)?.isNotEmpty ==
true
? additionalSettings['filterVersionsByRegEx']
: null;
var apkFilterRegEx =
(additionalSettings['apkFilterRegEx'] as String?)?.isNotEmpty == true
? additionalSettings['apkFilterRegEx']
: null;
if (res.statusCode == 200) {
var response = jsonDecode(res.body);
List<dynamic> releases = response['packages'] ?? [];
if (apkFilterRegEx != null) {
releases = releases.where((rel) {
String apk = '${apkUrlPrefix}_${rel['versionCode']}.apk';
return filterApks(
[MapEntry(apk, apk)],
apkFilterRegEx,
false,
).isNotEmpty;
}).toList();
}
if (releases.isEmpty) {
throw NoReleasesError();
}
String? version;
Iterable<dynamic> releaseChoices = [];
// Grab the versionCode suggested if the user chose to do that
// Only do so at this stage if the user has no release filter
if (trySelectingSuggestedVersionCode &&
response['suggestedVersionCode'] != null &&
filterVersionsByRegEx == null) {
var suggestedReleases = releases.where(
(element) =>
element['versionCode'] == response['suggestedVersionCode'],
);
if (suggestedReleases.isNotEmpty) {
releaseChoices = suggestedReleases;
version = suggestedReleases.first['versionName'];
}
}
// Apply the release filter if any
if (filterVersionsByRegEx?.isNotEmpty == true) {
version = null;
releaseChoices = [];
for (var i = 0; i < releases.length; i++) {
if (RegExp(
filterVersionsByRegEx!,
).hasMatch(releases[i]['versionName'])) {
version = releases[i]['versionName'];
}
}
if (version == null) {
throw NoVersionError();
}
}
// Default to the highest version
version ??= releases[0]['versionName'];
if (version == null) {
throw NoVersionError();
}
// If a suggested release was not already picked, pick all those with the selected version
if (releaseChoices.isEmpty) {
releaseChoices = releases.where(
(element) => element['versionName'] == version,
);
}
// For the remaining releases, use the toggles to auto-select one if possible
if (releaseChoices.length > 1) {
if (autoSelectHighestVersionCode) {
releaseChoices = [releaseChoices.first];
} else if (trySelectingSuggestedVersionCode &&
response['suggestedVersionCode'] != null) {
var suggestedReleases = releaseChoices.where(
(element) =>
element['versionCode'] == response['suggestedVersionCode'],
);
if (suggestedReleases.isNotEmpty) {
releaseChoices = suggestedReleases;
}
}
}
if (releaseChoices.isEmpty) {
throw NoReleasesError();
}
List<String> apkUrls = releaseChoices
.map((e) => '${apkUrlPrefix}_${e['versionCode']}.apk')
.toList();
return APKDetails(
version,
getApkUrlsFromUrls(apkUrls.toSet().toList()),
AppNames(sourceName, Uri.parse(standardUrl).pathSegments.last),
);
} else {
throw getObtainiumHttpError(res);
}
}
}

View file

@ -0,0 +1,275 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:html/parser.dart';
import 'package:http/http.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class FDroidRepo extends AppSource {
FDroidRepo() {
name = tr('fdroidThirdPartyRepo');
canSearch = true;
includeAdditionalOptsInMainSearch = true;
neverAutoSelect = true;
showReleaseDateAsVersionToggle = true;
additionalSourceAppSpecificSettingFormItems = [
[
GeneratedFormTextField(
'appIdOrName',
label: tr('appIdOrName'),
hint: tr('reposHaveMultipleApps'),
required: true,
),
],
[
GeneratedFormSwitch(
'pickHighestVersionCode',
label: tr('pickHighestVersionCode'),
defaultValue: false,
),
],
[
GeneratedFormSwitch(
'trySelectingSuggestedVersionCode',
label: tr('trySelectingSuggestedVersionCode'),
defaultValue: true,
),
],
];
}
String removeQueryParamsFromUrl(String url, {List<String> keep = const []}) {
var uri = Uri.parse(url);
Map<String, dynamic> resultParams = {};
uri.queryParameters.forEach((key, value) {
if (keep.contains(key)) {
resultParams[key] = value;
}
});
url = uri.replace(queryParameters: resultParams).toString();
if (url.endsWith('?')) {
url = url.substring(0, url.length - 1);
}
return url;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
var standardUri = Uri.parse(url);
var pathSegments = standardUri.pathSegments;
if (pathSegments.isNotEmpty && pathSegments.last == 'index.xml') {
pathSegments.removeLast();
standardUri = standardUri.replace(path: pathSegments.join('/'));
}
return removeQueryParamsFromUrl(standardUri.toString(), keep: ['appId']);
}
@override
Future<Map<String, List<String>>> search(
String query, {
Map<String, dynamic> querySettings = const {},
}) async {
String? url = querySettings['url'];
if (url == null) {
throw NoReleasesError();
}
url = removeQueryParamsFromUrl(standardizeUrl(url));
var res = await sourceRequestWithURLVariants(url, {});
if (res.statusCode == 200) {
var body = parse(res.body);
Map<String, List<String>> results = {};
body.querySelectorAll('application').toList().forEach((app) {
String appId = app.attributes['id']!;
String appName = app.querySelector('name')?.innerHtml ?? appId;
String appDesc = app.querySelector('desc')?.innerHtml ?? '';
if (query.isEmpty ||
appId.contains(query) ||
appName.contains(query) ||
appDesc.contains(query)) {
results['${res.request!.url.toString().split('/').reversed.toList().sublist(1).reversed.join('/')}?appId=$appId'] =
[appName, appDesc];
}
});
return results;
} else {
throw getObtainiumHttpError(res);
}
}
@override
void runOnAddAppInputChange(String userInput) {
additionalSourceAppSpecificSettingFormItems =
additionalSourceAppSpecificSettingFormItems.map((row) {
row = row.map((item) {
if (item.key == 'appIdOrName') {
try {
var appId = Uri.parse(userInput).queryParameters['appId'];
if (appId != null && item is GeneratedFormTextField) {
item.required = false;
}
} catch (e) {
//
}
}
return item;
}).toList();
return row;
}).toList();
}
@override
App endOfGetAppChanges(App app) {
var uri = Uri.parse(app.url);
String? appId;
if (!isTempId(app)) {
appId = app.id;
} else if (uri.queryParameters['appId'] != null) {
appId = uri.queryParameters['appId'];
}
if (appId != null) {
app.url = uri
.replace(
queryParameters: Map.fromEntries([
...uri.queryParameters.entries,
MapEntry('appId', appId),
]),
)
.toString();
app.additionalSettings['appIdOrName'] = appId;
app.id = appId;
}
return app;
}
Future<Response> sourceRequestWithURLVariants(
String url,
Map<String, dynamic> additionalSettings,
) async {
var res = await sourceRequest(
'$url${url.endsWith('/index.xml') ? '' : '/index.xml'}',
additionalSettings,
);
if (res.statusCode != 200) {
var base = url.endsWith('/index.xml')
? url.split('/').reversed.toList().sublist(1).reversed.join('/')
: url;
res = await sourceRequest('$base/repo/index.xml', additionalSettings);
if (res.statusCode != 200) {
res = await sourceRequest(
'$base/fdroid/repo/index.xml',
additionalSettings,
);
}
}
return res;
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
String? appIdOrName = additionalSettings['appIdOrName'];
var standardUri = Uri.parse(standardUrl);
if (standardUri.queryParameters['appId'] != null) {
appIdOrName = standardUri.queryParameters['appId'];
}
standardUrl = removeQueryParamsFromUrl(standardUrl);
bool pickHighestVersionCode = additionalSettings['pickHighestVersionCode'];
bool trySelectingSuggestedVersionCode = additionalSettings['trySelectingSuggestedVersionCode'];
if (appIdOrName == null) {
throw NoReleasesError();
}
additionalSettings['appIdOrName'] = appIdOrName;
var res = await sourceRequestWithURLVariants(
standardUrl,
additionalSettings,
);
if (res.statusCode == 200) {
var body = parse(res.body);
var foundApps = body.querySelectorAll('application').where((element) {
return element.attributes['id'] == appIdOrName;
}).toList();
if (foundApps.isEmpty) {
foundApps = body.querySelectorAll('application').where((element) {
return element.querySelector('name')?.innerHtml.toLowerCase() ==
appIdOrName!.toLowerCase();
}).toList();
}
if (foundApps.isEmpty) {
foundApps = body.querySelectorAll('application').where((element) {
return element
.querySelector('name')
?.innerHtml
.toLowerCase()
.contains(appIdOrName!.toLowerCase()) ??
false;
}).toList();
}
if (foundApps.isEmpty) {
throw ObtainiumError(tr('appWithIdOrNameNotFound'));
}
var authorName = body.querySelector('repo')?.attributes['name'] ?? name;
String appId = foundApps[0].attributes['id']!;
foundApps[0].querySelector('name')?.innerHtml ?? appId;
var appName = foundApps[0].querySelector('name')?.innerHtml ?? appId;
var releases = foundApps[0].querySelectorAll('package');
if (releases.isEmpty) {
throw NoReleasesError();
}
String? changeLog = foundApps[0].querySelector('changelog')?.innerHtml;
String? latestVersion = releases[0].querySelector('version')?.innerHtml;
if (latestVersion == null) {
throw NoVersionError();
}
String? marketvercodeStr = foundApps[0].querySelector('marketvercode')?.innerHtml;
int? marketvercode = int.tryParse(marketvercodeStr ?? '');
List selectedReleases = [];
if (trySelectingSuggestedVersionCode && marketvercode != null) {
selectedReleases = releases.where((e) =>
int.tryParse(e.querySelector('versioncode')?.innerHtml ?? '') == marketvercode &&
e.querySelector('apkname') != null
).toList();
}
String? appAuthorName = foundApps[0].querySelector('author')?.innerHtml;
if (appAuthorName != null) {
authorName = appAuthorName;
}
if (selectedReleases.isEmpty) {
selectedReleases = releases.where((e) =>
e.querySelector('version')?.innerHtml == latestVersion &&
e.querySelector('apkname') != null
).toList();
if (selectedReleases.length > 1 && pickHighestVersionCode) {
selectedReleases.sort((e1, e2) {
return int.parse(e2.querySelector('versioncode')!.innerHtml)
.compareTo(int.parse(e1.querySelector('versioncode')!.innerHtml));
});
selectedReleases = [selectedReleases[0]];
}
}
String? selectedVersion = selectedReleases[0].querySelector('version')?.innerHtml;
if (selectedVersion == null) {
throw NoVersionError();
}
String? added = selectedReleases[0].querySelector('added')?.innerHtml;
DateTime? releaseDate = added != null ? DateTime.parse(added) : null;
List<String> apkUrls = selectedReleases
.map(
(e) =>
'${res.request!.url.toString().split('/').reversed.toList().sublist(1).reversed.join('/')}/${e.querySelector('apkname')!.innerHtml}',
)
.toList();
return APKDetails(
selectedVersion,
getApkUrlsFromUrls(apkUrls),
AppNames(authorName, appName),
releaseDate: releaseDate,
changeLog: changeLog,
);
} else {
throw getObtainiumHttpError(res);
}
}
}

769
lib/app_sources/github.dart Normal file
View file

@ -0,0 +1,769 @@
import 'dart:convert';
import 'dart:io';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:obtainium/app_sources/html.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/apps_provider.dart';
import 'package:obtainium/providers/logs_provider.dart';
import 'package:obtainium/providers/settings_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:url_launcher/url_launcher_string.dart';
class GitHub extends AppSource {
GitHub({hostChanged = false}) {
hosts = ['github.com'];
appIdInferIsOptional = true;
showReleaseDateAsVersionToggle = true;
this.hostChanged = hostChanged;
allowIncludeZips = true;
sourceConfigSettingFormItems = [
GeneratedFormTextField(
'github-creds',
label: tr('githubPATLabel'),
password: true,
required: false,
belowWidgets: [
const SizedBox(height: 4),
GestureDetector(
onTap: () {
launchUrlString(
'https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token',
mode: LaunchMode.externalApplication,
);
},
child: Text(
tr('about'),
style: const TextStyle(
decoration: TextDecoration.underline,
fontSize: 12,
),
),
),
const SizedBox(height: 4),
],
),
GeneratedFormTextField(
'GHReqPrefix',
label: tr('GHReqPrefix'),
hint: 'gh-proxy.com',
required: false,
additionalValidators: [
(value) {
try {
if (value != null && Uri.parse(value).scheme.isNotEmpty) {
throw true;
}
if (value != null) {
Uri.parse('https://${value}/api.github.com');
}
} catch (e) {
return tr('invalidInput');
}
return null;
},
],
belowWidgets: [
const SizedBox(height: 4),
GestureDetector(
onTap: () {
launchUrlString(
'https://github.com/sky22333/hubproxy',
mode: LaunchMode.externalApplication,
);
},
child: Text(
tr('about'),
style: const TextStyle(
decoration: TextDecoration.underline,
fontSize: 12,
),
),
),
const SizedBox(height: 4),
],
),
];
additionalSourceAppSpecificSettingFormItems = [
[
GeneratedFormSwitch(
'includePrereleases',
label: tr('includePrereleases'),
defaultValue: false,
),
],
[
GeneratedFormSwitch(
'fallbackToOlderReleases',
label: tr('fallbackToOlderReleases'),
defaultValue: true,
),
],
[
GeneratedFormTextField(
'filterReleaseTitlesByRegEx',
label: tr('filterReleaseTitlesByRegEx'),
required: false,
additionalValidators: [
(value) {
return regExValidator(value);
},
],
),
],
[
GeneratedFormTextField(
'filterReleaseNotesByRegEx',
label: tr('filterReleaseNotesByRegEx'),
required: false,
additionalValidators: [
(value) {
return regExValidator(value);
},
],
),
],
[GeneratedFormSwitch('verifyLatestTag', label: tr('verifyLatestTag'))],
[
GeneratedFormDropdown(
'sortMethodChoice',
[
MapEntry('date', tr('releaseDate')),
MapEntry('smartname', tr('smartname')),
MapEntry('none', tr('none')),
MapEntry(
'smartname-datefallback',
'${tr('smartname')} x ${tr('releaseDate')}',
),
MapEntry('name', tr('name')),
],
label: tr('sortMethod'),
defaultValue: 'date',
),
],
[
GeneratedFormSwitch(
'useLatestAssetDateAsReleaseDate',
label: tr('useLatestAssetDateAsReleaseDate'),
defaultValue: false,
),
],
[
GeneratedFormSwitch(
'releaseTitleAsVersion',
label: tr('releaseTitleAsVersion'),
defaultValue: false,
),
],
];
canSearch = true;
searchQuerySettingFormItems = [
GeneratedFormTextField(
'minStarCount',
label: tr('minStarCount'),
defaultValue: '0',
additionalValidators: [
(value) {
try {
int.parse(value ?? '0');
} catch (e) {
return tr('invalidInput');
}
return null;
},
],
),
];
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
const possibleBuildGradleLocations = [
'/app/build.gradle',
'android/app/build.gradle',
'src/app/build.gradle',
];
for (var path in possibleBuildGradleLocations) {
try {
var res = await sourceRequest(
'${await convertStandardUrlToAPIUrl(standardUrl, additionalSettings)}/contents/$path',
additionalSettings,
);
if (res.statusCode == 200) {
try {
var body = jsonDecode(res.body);
var trimmedLines = utf8
.decode(
base64.decode(
body['content'].toString().split('\n').join(''),
),
)
.split('\n')
.map((e) => e.trim());
var appIds = trimmedLines.where(
(l) =>
l.startsWith('applicationId "') ||
l.startsWith('applicationId \''),
);
appIds = appIds.map(
(appId) => appId.split(
appId.startsWith('applicationId "') ? '"' : '\'',
)[1],
);
appIds = appIds
.map((appId) {
if (appId.startsWith('\${') && appId.endsWith('}')) {
appId = trimmedLines
.where(
(l) => l.startsWith(
'def ${appId.substring(2, appId.length - 1)}',
),
)
.first;
appId = appId.split(appId.contains('"') ? '"' : '\'')[1];
}
return appId;
})
.where((appId) => appId.isNotEmpty);
if (appIds.length == 1) {
return appIds.first;
}
} catch (err) {
LogsProvider().add(
'Error parsing build.gradle from ${res.request!.url.toString()}: ${err.toString()}',
);
}
}
} catch (err) {
// Ignore - ID will be extracted from the APK
}
}
return null;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}/[^/]+/[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<Map<String, String>?> getRequestHeaders(
Map<String, dynamic> additionalSettings, {
bool forAPKDownload = false,
}) async {
var token = await getTokenIfAny(additionalSettings);
var headers = <String, String>{};
if (token != null && token.isNotEmpty) {
headers[HttpHeaders.authorizationHeader] = 'Token $token';
}
if (forAPKDownload == true) {
headers[HttpHeaders.acceptHeader] = 'application/octet-stream';
}
if (headers.isNotEmpty) {
return headers;
} else {
return null;
}
}
Future<String?> getTokenIfAny(Map<String, dynamic> additionalSettings) async {
SettingsProvider settingsProvider = SettingsProvider();
await settingsProvider.initializeSettings();
var sourceConfig = await getSourceConfigValues(
additionalSettings,
settingsProvider,
);
String? creds = sourceConfig['github-creds'];
if ((additionalSettings['GHReqPrefix'] as String? ?? '').isNotEmpty) {
creds = null;
}
if (creds != null) {
var userNameEndIndex = creds.indexOf(':');
if (userNameEndIndex > 0) {
creds = creds.substring(
userNameEndIndex + 1,
); // For old username-included token inputs
}
return creds;
} else {
return null;
}
}
@override
Future<String?> getSourceNote() async {
if (!hostChanged && (await getTokenIfAny({})) == null) {
return '${tr('githubSourceNote')} ${hostChanged ? tr('addInfoBelow') : tr('addInfoInSettings')}';
}
return null;
}
@override
Future<String> generalReqPrefetchModifier(
String reqUrl,
Map<String, dynamic> additionalSettings,
) async {
if ((additionalSettings['GHReqPrefix'] as String? ?? '').isNotEmpty) {
var uri = Uri.parse(reqUrl);
return 'https://${additionalSettings['GHReqPrefix']}/${uri.toString().substring('https://'.length)}';
}
return reqUrl;
}
Future<String> getAPIHost(Map<String, dynamic> additionalSettings) async =>
'https://api.${hosts[0]}';
Future<String> convertStandardUrlToAPIUrl(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async =>
'${await getAPIHost(additionalSettings)}/repos${standardUrl.substring('https://${hosts[0]}'.length)}';
@override
String? changeLogPageFromStandardUrl(String standardUrl) =>
'$standardUrl/releases';
Future<APKDetails> getLatestAPKDetailsCommon(
String requestUrl,
String standardUrl,
Map<String, dynamic> additionalSettings, {
Function(Response)? onHttpErrorCode,
}) async {
SettingsProvider settingsProvider = SettingsProvider();
await settingsProvider.initializeSettings();
var sourceConfigSettingValues = await getSourceConfigValues(
additionalSettings,
settingsProvider,
);
bool includePrereleases = additionalSettings['includePrereleases'] == true;
bool fallbackToOlderReleases =
additionalSettings['fallbackToOlderReleases'] == true;
String? regexFilter =
(additionalSettings['filterReleaseTitlesByRegEx'] as String?)
?.isNotEmpty ==
true
? additionalSettings['filterReleaseTitlesByRegEx']
: null;
String? regexNotesFilter =
(additionalSettings['filterReleaseNotesByRegEx'] as String?)
?.isNotEmpty ==
true
? additionalSettings['filterReleaseNotesByRegEx']
: null;
bool verifyLatestTag = additionalSettings['verifyLatestTag'] == true;
bool useLatestAssetDateAsReleaseDate =
additionalSettings['useLatestAssetDateAsReleaseDate'] == true;
String sortMethod =
additionalSettings['sortMethodChoice'] ?? 'smartname-datefallback';
bool includeZips = additionalSettings['includeZips'] == true;
dynamic latestRelease;
if (verifyLatestTag) {
var temp = requestUrl.split('?');
Response res = await sourceRequest(
'${temp[0]}/latest${temp.length > 1 ? '?${temp.sublist(1).join('?')}' : ''}',
additionalSettings,
);
if (res.statusCode != 200) {
if (onHttpErrorCode != null) {
onHttpErrorCode(res);
}
throw getObtainiumHttpError(res);
}
latestRelease = jsonDecode(res.body);
}
Response res = await sourceRequest(requestUrl, additionalSettings);
if (res.statusCode == 200) {
var releases = jsonDecode(res.body) as List<dynamic>;
if (latestRelease != null) {
var latestTag = latestRelease['tag_name'] ?? latestRelease['name'];
if (releases
.where(
(element) =>
(element['tag_name'] ?? element['name']) == latestTag,
)
.isEmpty) {
releases = [latestRelease, ...releases];
}
}
findReleaseAssetUrls(dynamic release) =>
(release['assets'] as List<dynamic>?)?.map((e) {
var ext = e['name'].toString().toLowerCase().split('.').last;
var url = !(ext == 'apk' || ext == 'xapk' || (includeZips && ext == 'zip'))
? (e['browser_download_url'] ?? e['url'])
: (e['url'] ?? e['browser_download_url']);
url = undoGHProxyMod(url, sourceConfigSettingValues);
e['final_url'] = (e['name'] != null) && (url != null)
? MapEntry(e['name'] as String, url as String)
: const MapEntry('', '');
return e;
}).toList() ??
[];
DateTime? getPublishDateFromRelease(dynamic rel) =>
rel?['published_at'] != null
? DateTime.parse(rel['published_at'])
: rel?['commit']?['created'] != null
? DateTime.parse(rel['commit']['created'])
: null;
DateTime? getNewestAssetDateFromRelease(dynamic rel) {
var allAssets = rel['assets'] as List<dynamic>?;
var filteredAssets = rel['filteredAssets'] as List<dynamic>?;
var t = (filteredAssets ?? allAssets)
?.map((e) {
return e?['updated_at'] != null
? DateTime.parse(e['updated_at'])
: null;
})
.where((e) => e != null)
.toList();
t?.sort((a, b) => b!.compareTo(a!));
if (t?.isNotEmpty == true) {
return t!.first;
}
return null;
}
DateTime? getReleaseDateFromRelease(dynamic rel, bool useAssetDate) =>
!useAssetDate
? getPublishDateFromRelease(rel)
: getNewestAssetDateFromRelease(rel);
if (sortMethod == 'none') {
releases = releases.reversed.toList();
} else {
releases.sort((a, b) {
// See #478 and #534
if (a == b) {
return 0;
} else if (a == null) {
return -1;
} else if (b == null) {
return 1;
} else {
var nameA = a['tag_name'] ?? a['name'];
var nameB = b['tag_name'] ?? b['name'];
var stdFormats = findStandardFormatsForVersion(
nameA,
false,
).intersection(findStandardFormatsForVersion(nameB, false));
if (sortMethod == 'date' ||
(sortMethod == 'smartname-datefallback' &&
stdFormats.isEmpty)) {
return (getReleaseDateFromRelease(
a,
useLatestAssetDateAsReleaseDate,
) ??
DateTime(1))
.compareTo(
getReleaseDateFromRelease(
b,
useLatestAssetDateAsReleaseDate,
) ??
DateTime(0),
);
} else {
if (sortMethod != 'name' && stdFormats.isNotEmpty) {
var reg = RegExp(stdFormats.last);
var matchA = reg.firstMatch(nameA);
var matchB = reg.firstMatch(nameB);
return compareAlphaNumeric(
(nameA as String).substring(matchA!.start, matchA.end),
(nameB as String).substring(matchB!.start, matchB.end),
);
} else {
// 'name'
return compareAlphaNumeric(
(nameA as String),
(nameB as String),
);
}
}
}
});
}
if (latestRelease != null &&
(latestRelease['tag_name'] ?? latestRelease['name']) != null &&
releases.isNotEmpty &&
latestRelease !=
(releases[releases.length - 1]['tag_name'] ??
releases[0]['name'])) {
var ind = releases.indexWhere(
(element) =>
(latestRelease['tag_name'] ?? latestRelease['name']) ==
(element['tag_name'] ?? element['name']),
);
if (ind >= 0) {
releases.add(releases.removeAt(ind));
}
}
releases = releases.reversed.toList();
dynamic targetRelease;
var prerrelsSkipped = 0;
for (int i = 0; i < releases.length; i++) {
if (!fallbackToOlderReleases && i > prerrelsSkipped) break;
if (!includePrereleases && releases[i]['prerelease'] == true) {
prerrelsSkipped++;
continue;
}
if (releases[i]['draft'] == true) {
// Draft releases not supported
continue;
}
var nameToFilter = releases[i]['name'] as String?;
if (nameToFilter == null || nameToFilter.trim().isEmpty) {
// Some leave titles empty so tag is used
nameToFilter = releases[i]['tag_name'] as String;
}
if (regexFilter != null &&
!RegExp(regexFilter).hasMatch(nameToFilter.trim())) {
continue;
}
if (regexNotesFilter != null &&
!RegExp(
regexNotesFilter,
).hasMatch(((releases[i]['body'] as String?) ?? '').trim())) {
continue;
}
var allAssetsWithUrls = findReleaseAssetUrls(releases[i]);
List<MapEntry<String, String>> allAssetUrls = allAssetsWithUrls
.map((e) => e['final_url'] as MapEntry<String, String>)
.toList();
var apkAssetsWithUrls = allAssetsWithUrls.where((element) {
var ext = (element['final_url'] as MapEntry<String, String>).key
.toLowerCase()
.split('.')
.last;
return ext == 'apk' || ext == 'xapk' || (includeZips && ext == 'zip');
}).toList();
var filteredApkUrls = filterApks(
apkAssetsWithUrls
.map((e) => e['final_url'] as MapEntry<String, String>)
.toList(),
additionalSettings['apkFilterRegEx'],
additionalSettings['invertAPKFilter'],
);
var filteredApks = apkAssetsWithUrls
.where(
(e) => filteredApkUrls
.where(
(e2) =>
e2.key ==
(e['final_url'] as MapEntry<String, String>).key,
)
.isNotEmpty,
)
.toList();
if (filteredApks.isEmpty && additionalSettings['trackOnly'] != true) {
continue;
}
targetRelease = releases[i];
targetRelease['apkUrls'] = filteredApkUrls;
targetRelease['filteredAssets'] = filteredApks;
targetRelease['version'] =
additionalSettings['releaseTitleAsVersion'] == true
? nameToFilter
: targetRelease['tag_name'] ?? targetRelease['name'];
if (targetRelease['tarball_url'] != null) {
allAssetUrls.add(
MapEntry(
(targetRelease['version'] ?? 'source') + '.tar.gz',
undoGHProxyMod(
targetRelease['tarball_url'],
sourceConfigSettingValues,
),
),
);
}
if (targetRelease['zipball_url'] != null) {
allAssetUrls.add(
MapEntry(
(targetRelease['version'] ?? 'source') + '.zip',
undoGHProxyMod(
targetRelease['zipball_url'],
sourceConfigSettingValues,
),
),
);
}
targetRelease['allAssetUrls'] = allAssetUrls;
break;
}
if (targetRelease == null) {
throw NoReleasesError();
}
String? version = targetRelease['version'];
DateTime? releaseDate = getReleaseDateFromRelease(
targetRelease,
useLatestAssetDateAsReleaseDate,
);
if (version == null) {
throw NoVersionError();
}
var changeLog = (targetRelease['body'] ?? '').toString();
return APKDetails(
version,
targetRelease['apkUrls'] as List<MapEntry<String, String>>,
getAppNames(standardUrl),
releaseDate: releaseDate,
changeLog: changeLog.isEmpty ? null : changeLog,
allAssetUrls:
targetRelease['allAssetUrls'] as List<MapEntry<String, String>>,
);
} else {
if (onHttpErrorCode != null) {
onHttpErrorCode(res);
}
throw getObtainiumHttpError(res);
}
}
Future<APKDetails> getLatestAPKDetailsCommon2(
String standardUrl,
Map<String, dynamic> additionalSettings,
Future<String> Function(bool) reqUrlGenerator,
dynamic Function(Response)? onHttpErrorCode,
) async {
try {
return await getLatestAPKDetailsCommon(
await reqUrlGenerator(false),
standardUrl,
additionalSettings,
onHttpErrorCode: onHttpErrorCode,
);
} catch (err) {
if (err is NoReleasesError && additionalSettings['trackOnly'] == true) {
return await getLatestAPKDetailsCommon(
await reqUrlGenerator(true),
standardUrl,
additionalSettings,
onHttpErrorCode: onHttpErrorCode,
);
} else {
rethrow;
}
}
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
return await getLatestAPKDetailsCommon2(
standardUrl,
additionalSettings,
(bool useTagUrl) async {
return '${await convertStandardUrlToAPIUrl(standardUrl, additionalSettings)}/${useTagUrl ? 'tags' : 'releases'}?per_page=100';
},
(Response res) {
rateLimitErrorCheck(res);
},
);
}
AppNames getAppNames(String standardUrl) {
String temp = standardUrl.substring(standardUrl.indexOf('://') + 3);
List<String> names = temp.substring(temp.indexOf('/') + 1).split('/');
return AppNames(names[0], names.sublist(1).join('/'));
}
Future<Map<String, List<String>>> searchCommon(
String query,
String requestUrl,
String rootProp, {
Function(Response)? onHttpErrorCode,
Map<String, dynamic> querySettings = const {},
}) async {
Response res = await sourceRequest(requestUrl, {});
if (res.statusCode == 200) {
int minStarCount = querySettings['minStarCount'] != null
? int.parse(querySettings['minStarCount'])
: 0;
Map<String, List<String>> urlsWithDescriptions = {};
for (var e in (jsonDecode(res.body)[rootProp] as List<dynamic>)) {
if ((e['stargazers_count'] ?? e['stars_count'] ?? 0) >= minStarCount) {
urlsWithDescriptions.addAll({
e['html_url'] as String: [
e['full_name'] as String,
((e['archived'] == true ? '[ARCHIVED] ' : '') +
(e['description'] != null
? e['description'] as String
: tr('noDescription'))),
],
});
}
}
return urlsWithDescriptions;
} else {
if (onHttpErrorCode != null) {
onHttpErrorCode(res);
}
throw getObtainiumHttpError(res);
}
}
undoGHProxyMod(
String reqUrl,
Map<String, String> sourceConfigSettingValues,
) => reqUrl.replaceFirst(
'https://${sourceConfigSettingValues['GHReqPrefix']}/',
'',
);
@override
Future<Map<String, List<String>>> search(
String query, {
Map<String, dynamic> querySettings = const {},
}) async {
var sp = SettingsProvider();
await sp.initializeSettings();
var sourceConfigSettingValues = await getSourceConfigValues({}, sp);
var results = await searchCommon(
query,
'${await getAPIHost({})}/search/repositories?q=${Uri.encodeQueryComponent(query)}&per_page=100',
'items',
onHttpErrorCode: (Response res) {
rateLimitErrorCheck(res);
},
querySettings: querySettings,
);
if ((sourceConfigSettingValues['GHReqPrefix'] ?? '').isNotEmpty) {
Map<String, List<String>> results2 = {};
results.forEach((k, v) {
results2[undoGHProxyMod(k, sourceConfigSettingValues)] = v;
});
return results2;
} else {
return results;
}
}
void rateLimitErrorCheck(Response res) {
if (res.headers['x-ratelimit-remaining'] == '0') {
throw RateLimitError(
(int.parse(res.headers['x-ratelimit-reset'] ?? '1800000000') / 60000000)
.round(),
);
}
}
}

260
lib/app_sources/gitlab.dart Normal file
View file

@ -0,0 +1,260 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:obtainium/app_sources/github.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/settings_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:url_launcher/url_launcher_string.dart';
class GitLab extends AppSource {
GitLab({bool hostChanged = false}) {
hosts = ['gitlab.com'];
canSearch = true;
showReleaseDateAsVersionToggle = true;
this.hostChanged = hostChanged;
sourceConfigSettingFormItems = [
GeneratedFormTextField(
'gitlab-creds',
label: tr('gitlabPATLabel'),
password: true,
required: false,
belowWidgets: [
const SizedBox(height: 4),
GestureDetector(
onTap: () {
launchUrlString(
'https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html#create-a-personal-access-token',
mode: LaunchMode.externalApplication,
);
},
child: Text(
tr('about'),
style: const TextStyle(
decoration: TextDecoration.underline,
fontSize: 12,
),
),
),
const SizedBox(height: 4),
],
),
];
additionalSourceAppSpecificSettingFormItems = [
[
GeneratedFormSwitch(
'fallbackToOlderReleases',
label: tr('fallbackToOlderReleases'),
defaultValue: true,
),
],
];
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
var urlSegments = url.split('/');
var cutOffIndex = urlSegments.indexWhere((s) => s == '-');
url = urlSegments
.sublist(0, cutOffIndex <= 0 ? null : cutOffIndex)
.join('/');
RegExp standardUrlRegEx = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}/[^/]+(/[^((\b/\b)|(\b/-/\b))]+){1,20}',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
Future<String?> getPATIfAny(Map<String, dynamic> additionalSettings) async {
SettingsProvider settingsProvider = SettingsProvider();
await settingsProvider.initializeSettings();
var sourceConfig = await getSourceConfigValues(
additionalSettings,
settingsProvider,
);
String? creds = sourceConfig['gitlab-creds'];
return creds != null && creds.isNotEmpty ? creds : null;
}
@override
Future<Map<String, List<String>>> search(
String query, {
Map<String, dynamic> querySettings = const {},
}) async {
var url =
'https://${hosts[0]}/api/v4/projects?search=${Uri.encodeQueryComponent(query)}';
var res = await sourceRequest(url, {});
if (res.statusCode != 200) {
throw getObtainiumHttpError(res);
}
var json = jsonDecode(res.body) as List<dynamic>;
Map<String, List<String>> results = {};
for (var element in json) {
results['https://${hosts[0]}/${element['path_with_namespace']}'] = [
element['name_with_namespace'],
element['description'] ?? tr('noDescription'),
];
}
return results;
}
@override
String? changeLogPageFromStandardUrl(String standardUrl) =>
'$standardUrl/-/releases';
@override
Future<Map<String, String>?> getRequestHeaders(
Map<String, dynamic> additionalSettings, {
bool forAPKDownload = false,
}) async {
// Change headers to pacify, e.g. cloudflare protection
// Related to: (#1397, #1389, #1384, #1382, #1381, #1380, #1359, #854, #785, #697)
var headers = <String, String>{};
headers[HttpHeaders.refererHeader] = 'https://${hosts[0]}';
if (headers.isNotEmpty) {
return headers;
} else {
return null;
}
}
@override
Future<String> assetUrlPrefetchModifier(
String assetUrl,
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
String? PAT = await getPATIfAny(hostChanged ? additionalSettings : {});
String optionalAuth = (PAT != null) ? 'private_token=$PAT' : '';
return '$assetUrl${(Uri.parse(assetUrl).query.isEmpty ? '?' : '&')}$optionalAuth';
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
// Prepare request params
var names = GitHub(hostChanged: true).getAppNames(standardUrl);
String projectUriComponent =
'${Uri.encodeComponent(names.author)}%2F${Uri.encodeComponent(names.name)}';
String? PAT = await getPATIfAny(hostChanged ? additionalSettings : {});
String optionalAuth = (PAT != null) ? 'private_token=$PAT' : '';
bool trackOnly = additionalSettings['trackOnly'] == true;
// Get project ID
Response res0 = await sourceRequest(
'https://${hosts[0]}/api/v4/projects/$projectUriComponent?$optionalAuth',
additionalSettings,
);
if (res0.statusCode != 200) {
throw getObtainiumHttpError(res0);
}
int? projectId = jsonDecode(res0.body)['id'];
if (projectId == null) {
throw NoReleasesError();
}
// Request data from REST API
Response res = await sourceRequest(
'https://${hosts[0]}/api/v4/projects/$projectUriComponent/${trackOnly ? 'repository/tags' : 'releases'}?$optionalAuth',
additionalSettings,
);
if (res.statusCode != 200) {
throw getObtainiumHttpError(res);
}
// Extract .apk details from received data
Iterable<APKDetails> apkDetailsList = [];
var json = jsonDecode(res.body) as List<dynamic>;
apkDetailsList = json.map((e) {
var apkUrlsFromAssets = (e['assets']?['links'] as List<dynamic>? ?? [])
.map((e) {
var url = (e['direct_asset_url'] ?? e['url'] ?? '') as String;
var parsedUrl = url.isNotEmpty ? Uri.parse(url) : null;
return MapEntry(
(e['name'] ??
(parsedUrl != null && parsedUrl.pathSegments.isNotEmpty
? parsedUrl.pathSegments.last
: 'unknown'))
as String,
(e['direct_asset_url'] ?? e['url'] ?? '') as String,
);
})
.where((s) => s.key.isNotEmpty)
.toList();
var uploadedAPKsFromDescription = ((e['description'] ?? '') as String)
.split('](')
.join('\n')
.split('.apk)')
.join('.apk\n')
.split('\n')
.where((s) => s.startsWith('/uploads/') && s.endsWith('apk'))
.map((s) => 'https://${hosts[0]}/-/project/$projectId$s')
.map((l) => MapEntry(Uri.parse(l).pathSegments.last, l))
.toList();
Map<String, String> apkUrls = {};
for (var entry in apkUrlsFromAssets) {
apkUrls[entry.key] = entry.value;
}
for (var entry in uploadedAPKsFromDescription) {
apkUrls[entry.key] = entry.value;
}
var releaseDateString =
e['released_at'] ?? e['created_at'] ?? e['commit']?['created_at'];
DateTime? releaseDate = releaseDateString != null
? DateTime.parse(releaseDateString)
: null;
return APKDetails(
e['tag_name'] ?? e['name'],
apkUrls.entries.toList(),
AppNames(names.author, names.name.split('/').last),
releaseDate: releaseDate,
);
});
if (apkDetailsList.isEmpty) {
throw NoReleasesError();
}
var finalResult = apkDetailsList.first;
// Fallback procedure
bool fallbackToOlderReleases =
additionalSettings['fallbackToOlderReleases'] == true;
if (finalResult.apkUrls.isEmpty && fallbackToOlderReleases && !trackOnly) {
apkDetailsList = apkDetailsList
.where((e) => e.apkUrls.isNotEmpty)
.toList();
finalResult = apkDetailsList.first;
}
if (finalResult.apkUrls.isEmpty && !trackOnly) {
throw NoAPKError();
}
finalResult.apkUrls = finalResult.apkUrls.map((apkUrl) {
if (RegExp(
'^$standardUrl/-/jobs/[0-9]+/artifacts/file/[^/]+',
).hasMatch(apkUrl.value)) {
return MapEntry(
apkUrl.key,
apkUrl.value.replaceFirst('/file/', '/raw/'),
);
} else {
return apkUrl;
}
}).toList();
return finalResult;
}
}

471
lib/app_sources/html.dart Normal file
View file

@ -0,0 +1,471 @@
import 'dart:convert';
import 'package:easy_localization/easy_localization.dart';
import 'package:html/parser.dart';
import 'package:http/http.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/apps_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
String ensureAbsoluteUrl(String ambiguousUrl, Uri referenceAbsoluteUrl) {
try {
if (Uri.parse(ambiguousUrl).isAbsolute) {
return ambiguousUrl; // #2315
}
} catch (e) {
//
}
return referenceAbsoluteUrl.resolve(ambiguousUrl).toString();
}
int compareAlphaNumeric(String a, String b) {
List<String> aParts = _splitAlphaNumeric(a);
List<String> bParts = _splitAlphaNumeric(b);
for (int i = 0; i < aParts.length && i < bParts.length; i++) {
String aPart = aParts[i];
String bPart = bParts[i];
bool aIsNumber = _isNumeric(aPart);
bool bIsNumber = _isNumeric(bPart);
if (aIsNumber && bIsNumber) {
int aNumber = int.parse(aPart);
int bNumber = int.parse(bPart);
int cmp = aNumber.compareTo(bNumber);
if (cmp != 0) {
return cmp;
}
} else if (!aIsNumber && !bIsNumber) {
int cmp = aPart.compareTo(bPart);
if (cmp != 0) {
return cmp;
}
} else {
// Alphanumeric strings come before numeric strings
return aIsNumber ? 1 : -1;
}
}
return aParts.length.compareTo(bParts.length);
}
List<String> collectAllStringsFromJSONObject(dynamic obj) {
List<String> extractor(dynamic obj) {
final results = <String>[];
if (obj is String) {
results.add(obj);
} else if (obj is List) {
for (final item in obj) {
results.addAll(extractor(item));
}
} else if (obj is Map<String, dynamic>) {
for (final value in obj.values) {
results.addAll(extractor(value));
}
}
return results;
}
return extractor(obj);
}
List<String> _splitAlphaNumeric(String s) {
List<String> parts = [];
StringBuffer sb = StringBuffer();
bool isNumeric = _isNumeric(s[0]);
sb.write(s[0]);
for (int i = 1; i < s.length; i++) {
bool currentIsNumeric = _isNumeric(s[i]);
if (currentIsNumeric == isNumeric) {
sb.write(s[i]);
} else {
parts.add(sb.toString());
sb.clear();
sb.write(s[i]);
isNumeric = currentIsNumeric;
}
}
parts.add(sb.toString());
return parts;
}
bool _isNumeric(String s) {
return s.codeUnitAt(0) >= 48 && s.codeUnitAt(0) <= 57;
}
List<MapEntry<String, String>> getLinksInLines(String lines) =>
RegExp(
r'(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?',
)
.allMatches(lines)
.map(
(match) =>
MapEntry(match.group(0)!, match.group(0)?.split('/').last ?? ''),
)
.toList();
// Given an HTTP response, grab some links according to the common additional settings
// (those that apply to intermediate and final steps)
Future<List<MapEntry<String, String>>> grabLinksCommonFromRes(
Response res,
Map<String, dynamic> additionalSettings,
) async {
if (res.statusCode != 200) {
throw getObtainiumHttpError(res);
}
return grabLinksCommon(res.body, res.request!.url, additionalSettings);
}
// Note keys are URLs, values are filenames (opposite to the AppSource apkUrls)
Future<List<MapEntry<String, String>>> grabLinksCommon(
String rawBody,
Uri reqUrl,
Map<String, dynamic> additionalSettings,
) async {
bool matchLinksOutsideATags =
additionalSettings['matchLinksOutsideATags'] == true;
var html = parse(rawBody);
List<MapEntry<String, String>> allLinks = html
.querySelectorAll('a')
.map(
(element) => MapEntry(
element.attributes['href'] ?? '',
element.text.isNotEmpty
? element.text
: (element.attributes['href'] ?? '').split('/').last,
),
)
.where((element) => element.key.isNotEmpty)
.map((e) => MapEntry(ensureAbsoluteUrl(e.key, reqUrl), e.value))
.toList();
if (allLinks.isEmpty || matchLinksOutsideATags) {
// Decode the body if the response is a JSON
try {
var jsonStrings = collectAllStringsFromJSONObject(jsonDecode(rawBody));
allLinks = getLinksInLines(jsonStrings.join('\n'));
if (allLinks.isEmpty) {
allLinks = getLinksInLines(
jsonStrings
.map((l) {
return ensureAbsoluteUrl(l, reqUrl);
})
.join('\n'),
);
}
} catch (e) {
allLinks = getLinksInLines(rawBody);
}
}
List<MapEntry<String, String>> links = [];
bool skipSort = additionalSettings['skipSort'] == true;
bool filterLinkByText = additionalSettings['filterByLinkText'] == true;
if ((additionalSettings['customLinkFilterRegex'] as String?)?.isNotEmpty ==
true) {
var reg = RegExp(additionalSettings['customLinkFilterRegex']);
links = allLinks.where((element) {
var link = element.key;
try {
link = Uri.decodeFull(element.key);
} catch (e) {
// Some links may not have valid encoding
}
return reg.hasMatch(filterLinkByText ? element.value : link);
}).toList();
} else {
links = allLinks.where((element) {
var link = element.key;
try {
link = Uri.decodeFull(element.key);
} catch (e) {
// Some links may not have valid encoding
}
return Uri.parse(
filterLinkByText ? element.value : link,
).path.toLowerCase().endsWith('.apk');
}).toList();
}
if (!skipSort) {
links.sort(
(a, b) => additionalSettings['sortByLastLinkSegment'] == true
? compareAlphaNumeric(
a.key.split('/').where((e) => e.isNotEmpty).last,
b.key.split('/').where((e) => e.isNotEmpty).last,
)
: compareAlphaNumeric(a.key, b.key),
);
}
if (additionalSettings['reverseSort'] == true) {
links = links.reversed.toList();
}
return links;
}
class HTML extends AppSource {
@override
List<List<GeneratedFormItem>> get combinedAppSpecificSettingFormItems {
return super.combinedAppSpecificSettingFormItems.map((r) {
return r.map((e) {
if (e.key == 'versionExtractionRegEx') {
e.label = tr('versionExtractionRegEx');
}
if (e.key == 'matchGroupToUse') {
e.label = tr('matchGroupToUse');
}
return e;
}).toList();
}).toList();
}
var finalStepFormitems = [
[
GeneratedFormTextField(
'customLinkFilterRegex',
label: tr('customLinkFilterRegex'),
hint: 'download/(.*/)?(android|apk|mobile)',
required: false,
additionalValidators: [
(value) {
return regExValidator(value);
},
],
),
],
[
GeneratedFormSwitch(
'versionExtractWholePage',
label: tr('versionExtractWholePage'),
),
],
];
var commonFormItems = [
[GeneratedFormSwitch('filterByLinkText', label: tr('filterByLinkText'))],
[
GeneratedFormSwitch(
'matchLinksOutsideATags',
label: tr('matchLinksOutsideATags')
),
],
[GeneratedFormSwitch('skipSort', label: tr('skipSort'))],
[GeneratedFormSwitch('reverseSort', label: tr('takeFirstLink'))],
[
GeneratedFormSwitch(
'sortByLastLinkSegment',
label: tr('sortByLastLinkSegment'),
),
],
];
var intermediateFormItems = [
[
GeneratedFormTextField(
'customLinkFilterRegex',
label: tr('intermediateLinkRegex'),
hint: '([0-9]+.)*[0-9]+/\$',
required: true,
additionalValidators: [(value) => regExValidator(value)],
),
],
[
GeneratedFormSwitch(
'autoLinkFilterByArch',
label: tr('autoLinkFilterByArch'),
defaultValue: false,
),
],
];
HTML() {
additionalSourceAppSpecificSettingFormItems = [
[
GeneratedFormSubForm('intermediateLink', [
...intermediateFormItems,
...commonFormItems,
], label: tr('intermediateLink')),
],
finalStepFormitems[0],
...commonFormItems,
...finalStepFormitems.sublist(1),
[
GeneratedFormSubForm(
'requestHeader',
[
[
GeneratedFormTextField(
'requestHeader',
label: tr('requestHeader'),
required: false,
additionalValidators: [
(value) {
if ((value ?? 'empty:valid')
.split(':')
.map((e) => e.trim())
.where((e) => e.isNotEmpty)
.length <
2) {
return tr('invalidInput');
}
return null;
},
],
),
],
],
label: tr('requestHeader'),
defaultValue: [
{
'requestHeader':
'User-Agent: Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36',
},
],
),
],
[
GeneratedFormDropdown(
'defaultPseudoVersioningMethod',
[
MapEntry('partialAPKHash', tr('partialAPKHash')),
MapEntry('APKLinkHash', tr('APKLinkHash')),
MapEntry('ETag', 'ETag'),
],
label: tr('defaultPseudoVersioningMethod'),
defaultValue: 'partialAPKHash',
),
],
];
}
@override
Future<Map<String, String>?> getRequestHeaders(
Map<String, dynamic> additionalSettings, {
bool forAPKDownload = false,
}) async {
if (additionalSettings.isNotEmpty) {
if (additionalSettings['requestHeader']?.isNotEmpty != true) {
additionalSettings['requestHeader'] = [];
}
additionalSettings['requestHeader'] = additionalSettings['requestHeader']
.where((l) => l['requestHeader'].isNotEmpty == true)
.toList();
Map<String, String> requestHeaders = {};
for (int i = 0; i < (additionalSettings['requestHeader'].length); i++) {
var temp =
(additionalSettings['requestHeader'][i]['requestHeader'] as String)
.split(':');
requestHeaders[temp[0].trim()] = temp.sublist(1).join(':').trim();
}
return requestHeaders;
}
return null;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
return url;
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var currentUrl = standardUrl;
if (additionalSettings['intermediateLink']?.isNotEmpty != true) {
additionalSettings['intermediateLink'] = [];
}
additionalSettings['intermediateLink'] =
additionalSettings['intermediateLink']
.where((l) => l['customLinkFilterRegex'].isNotEmpty == true)
.toList();
for (int i = 0; i < (additionalSettings['intermediateLink'].length); i++) {
var intLinks = await grabLinksCommonFromRes(
await sourceRequest(currentUrl, additionalSettings),
additionalSettings['intermediateLink'][i],
);
if (intLinks.isEmpty) {
throw NoReleasesError(note: currentUrl);
} else {
if (additionalSettings['intermediateLink'][i]['autoLinkFilterByArch'] ==
true) {
intLinks = await filterApksByArch(intLinks);
}
currentUrl = intLinks.last.key;
}
}
var uri = Uri.parse(currentUrl);
List<MapEntry<String, String>> links = [];
String versionExtractionWholePageString = currentUrl;
if (additionalSettings['directAPKLink'] != true) {
Response res = await sourceRequest(currentUrl, additionalSettings);
versionExtractionWholePageString = res.body
.split('\r\n')
.join('\n')
.split('\n')
.join('\\n');
links = await grabLinksCommonFromRes(res, additionalSettings);
links = filterApks(
links,
additionalSettings['apkFilterRegEx'],
additionalSettings['invertAPKFilter'],
);
if (links.isEmpty) {
throw NoReleasesError(note: currentUrl);
}
} else {
links = [MapEntry(currentUrl, currentUrl)];
}
var rel = links.last.key;
var relDecoded = rel;
try {
relDecoded = Uri.decodeFull(rel);
} catch (e) {
// Some links may not have valid encoding
}
String? version;
version = extractVersion(
additionalSettings['versionExtractionRegEx'] as String?,
additionalSettings['matchGroupToUse'] as String?,
additionalSettings['versionExtractWholePage'] == true
? versionExtractionWholePageString
: relDecoded,
);
var apkReqHeaders = await getRequestHeaders(
additionalSettings,
forAPKDownload: true,
);
if (version == null &&
additionalSettings['defaultPseudoVersioningMethod'] == 'ETag') {
version = await checkETagHeader(
rel,
headers: apkReqHeaders,
allowInsecure: additionalSettings['allowInsecure'] == true,
);
if (version == null) {
throw NoVersionError();
}
}
version ??=
additionalSettings['defaultPseudoVersioningMethod'] == 'APKLinkHash'
? rel.hashCode.toString()
: (await checkPartialDownloadHashDynamic(
rel,
headers: apkReqHeaders,
allowInsecure: additionalSettings['allowInsecure'] == true,
)).toString();
return APKDetails(
version,
[rel].map((e) {
var uri = Uri.parse(e);
var fileName = uri.pathSegments.isNotEmpty
? uri.pathSegments.last
: uri.origin;
return MapEntry('${e.hashCode}-$fileName', e);
}).toList(),
AppNames(uri.host, tr('app')),
);
}
}

View file

@ -0,0 +1,113 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:http/http.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class HuaweiAppGallery extends AppSource {
HuaweiAppGallery() {
name = 'Huawei AppGallery';
hosts = ['appgallery.huawei.com', 'appgallery.cloud.huawei.com'];
versionDetectionDisallowed = true;
showReleaseDateAsVersionToggle = true;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}(/#)?/(app|appdl)/[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
String getDlUrl(String standardUrl) =>
'https://${hosts[0].replaceAll('appgallery.huawei', 'appgallery.cloud.huawei')}/appdl/${standardUrl.split('/').last}';
Future<Response> requestAppdlRedirect(
String dlUrl,
Map<String, dynamic> additionalSettings,
) async {
Response res = await sourceRequest(
dlUrl,
additionalSettings,
followRedirects: false,
);
if (res.statusCode == 200 ||
res.statusCode == 302 ||
res.statusCode == 304) {
return res;
} else {
throw getObtainiumHttpError(res);
}
}
String appIdFromRedirectDlUrl(String redirectDlUrl) {
var parts = redirectDlUrl
.split('?')[0]
.split('/')
.last
.split('.')
.reversed
.toList();
parts.removeAt(0);
parts.removeAt(0);
return parts.reversed.join('.');
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
String dlUrl = getDlUrl(standardUrl);
Response res = await requestAppdlRedirect(dlUrl, additionalSettings);
return res.headers['location'] != null
? appIdFromRedirectDlUrl(res.headers['location']!)
: null;
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
String dlUrl = getDlUrl(standardUrl);
Response res = await requestAppdlRedirect(dlUrl, additionalSettings);
if (res.headers['location'] == null) {
throw NoReleasesError();
}
String appId = appIdFromRedirectDlUrl(res.headers['location']!);
if (appId.isEmpty) {
throw NoReleasesError();
}
var relDateStr = res.headers['location']
?.split('?')[0]
.split('.')
.reversed
.toList()[1];
if (relDateStr == null || relDateStr.length != 10) {
throw NoVersionError();
}
var relDateStrAdj = relDateStr.split('');
var tempLen = relDateStrAdj.length;
var i = 2;
while (i < tempLen) {
relDateStrAdj.insert((i + i ~/ 2 - 1), '-');
i += 2;
}
var relDate = DateFormat(
'yy-MM-dd-HH-mm',
'en_US',
).parse(relDateStrAdj.join(''));
return APKDetails(
relDateStr,
[MapEntry('$appId.apk', dlUrl)],
AppNames(name, appId),
releaseDate: relDate,
);
}
}

View file

@ -0,0 +1,61 @@
import 'package:obtainium/app_sources/fdroid.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class IzzyOnDroid extends AppSource {
late FDroid fd;
IzzyOnDroid() {
hosts = ['izzysoft.de'];
fd = FDroid();
additionalSourceAppSpecificSettingFormItems =
fd.additionalSourceAppSpecificSettingFormItems;
allowSubDomains = true;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegExA = RegExp(
'^https?://android.${getSourceRegex(hosts)}/repo/apk/[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegExA.firstMatch(url);
if (match == null) {
RegExp standardUrlRegExB = RegExp(
'^https?://apt.${getSourceRegex(hosts)}/fdroid/index/apk/[^/]+',
caseSensitive: false,
);
match = standardUrlRegExB.firstMatch(url);
}
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
return fd.tryInferringAppId(standardUrl);
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
String? appId = await tryInferringAppId(standardUrl);
return fd.getAPKUrlsFromFDroidPackagesAPIResponse(
await sourceRequest(
'https://apt.izzysoft.de/fdroid/api/v1/packages/$appId',
additionalSettings,
),
'https://android.izzysoft.de/frepo/$appId',
standardUrl,
name,
additionalSettings: additionalSettings,
);
}
}

View file

@ -0,0 +1,76 @@
import 'dart:convert';
import 'package:http/http.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class Jenkins extends AppSource {
Jenkins() {
versionDetectionDisallowed = true;
neverAutoSelect = true;
showReleaseDateAsVersionToggle = true;
}
String trimJobUrl(String url) {
RegExp standardUrlRegEx = RegExp('.*/job/[^/]+');
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
String? changeLogPageFromStandardUrl(String standardUrl) =>
'$standardUrl/-/releases';
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
standardUrl = trimJobUrl(standardUrl);
Response res = await sourceRequest(
'$standardUrl/lastSuccessfulBuild/api/json',
additionalSettings,
);
if (res.statusCode == 200) {
var json = jsonDecode(res.body);
var releaseDate = json['timestamp'] == null
? null
: DateTime.fromMillisecondsSinceEpoch(json['timestamp'] as int);
var version = json['number'] == null
? null
: (json['number'] as int).toString();
if (version == null) {
throw NoVersionError();
}
var apkUrls = (json['artifacts'] as List<dynamic>)
.map((e) {
var path = (e['relativePath'] as String?);
if (path != null && path.isNotEmpty) {
path = '$standardUrl/lastSuccessfulBuild/artifact/$path';
}
return path == null
? const MapEntry<String, String>('', '')
: MapEntry<String, String>(
(e['fileName'] ?? e['relativePath']) as String,
path,
);
})
.where(
(url) =>
url.value.isNotEmpty && url.key.toLowerCase().endsWith('.apk'),
)
.toList();
return APKDetails(
version,
apkUrls,
releaseDate: releaseDate,
AppNames(Uri.parse(standardUrl).host, standardUrl.split('/').last),
);
} else {
throw getObtainiumHttpError(res);
}
}
}

View file

@ -0,0 +1,87 @@
import 'dart:convert';
import 'package:http/http.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class LiteAPKs extends AppSource {
LiteAPKs() {
hosts = ['liteapks.com'];
name = 'LiteAPKs';
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}/+[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var standardUri = Uri.parse(standardUrl);
var slug = standardUri.path
.split('.')
.reversed
.toList()
.sublist(1)
.reversed
.join('.');
Response res1 = await sourceRequest(
'${standardUri.origin}/wp-json/wp/v2/posts?slug=$slug',
additionalSettings,
);
if (res1.statusCode != 200) {
throw getObtainiumHttpError(res1);
}
var liteAppId = jsonDecode(res1.body)[0]['id'];
if (liteAppId == null) {
throw NoReleasesError();
}
Response res2 = await sourceRequest(
'${standardUri.origin}/wp-json/v2/posts/$liteAppId',
additionalSettings,
);
if (res2.statusCode != 200) {
throw getObtainiumHttpError(res2);
}
var json = jsonDecode(res2.body);
var appName = json['data']?['title'] as String?;
var author = json['data']?['publisher'] as String?;
var version = json['data']?['versions']?[0]?['version'] as String?;
if (version == null) {
throw NoVersionError();
}
var apkUrls =
((json['data']?['versions']?[0]?['version_downloads'] as List<dynamic>?)
?.map((l) => l['version_download_link']) ??
[])
.map(
(l) => MapEntry<String, String>(
Uri.decodeComponent(Uri.parse(l).pathSegments.last),
l,
),
)
.toList();
return APKDetails(
version,
apkUrls,
AppNames(
author ?? Uri.parse(standardUrl).host,
appName ?? standardUrl.split('/').last,
),
);
}
}

View file

@ -0,0 +1,75 @@
import 'package:html/parser.dart';
import 'package:http/http.dart';
import 'package:obtainium/app_sources/github.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class Mullvad extends AppSource {
Mullvad() {
hosts = ['mullvad.net'];
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
String? changeLogPageFromStandardUrl(String standardUrl) =>
'https://github.com/mullvad/mullvadvpn-app/blob/master/CHANGELOG.md';
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
Response res = await sourceRequest(
'$standardUrl/en/download/android',
additionalSettings,
);
if (res.statusCode == 200) {
var versions = parse(res.body)
.querySelectorAll('p')
.map((e) => e.innerHtml)
.where((p) => p.contains('Latest version: '))
.map((e) {
var match = RegExp('[0-9]+(\\.[0-9]+)*').firstMatch(e);
if (match == null) {
return '';
} else {
return e.substring(match.start, match.end);
}
})
.where((element) => element.isNotEmpty)
.toList();
if (versions.isEmpty) {
throw NoVersionError();
}
String? changeLog;
try {
changeLog = (await GitHub(hostChanged: true).getLatestAPKDetails(
'https://github.com/mullvad/mullvadvpn-app',
{'fallbackToOlderReleases': true},
)).changeLog;
} catch (e) {
// Ignore
}
return APKDetails(
versions[0],
getApkUrlsFromUrls(['https://mullvad.net/download/app/apk/latest']),
AppNames(name, 'Mullvad-VPN'),
changeLog: changeLog,
);
} else {
throw getObtainiumHttpError(res);
}
}
}

View file

@ -0,0 +1,122 @@
import 'package:html/parser.dart';
import 'package:http/http.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class NeutronCode extends AppSource {
NeutronCode() {
hosts = ['neutroncode.com'];
showReleaseDateAsVersionToggle = true;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}/downloads/file/[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
String? changeLogPageFromStandardUrl(String standardUrl) => standardUrl;
String monthNameToNumberString(String s) {
switch (s.toLowerCase()) {
case 'january':
return '01';
case 'february':
return '02';
case 'march':
return '03';
case 'april':
return '04';
case 'may':
return '05';
case 'june':
return '06';
case 'july':
return '07';
case 'august':
return '08';
case 'september':
return '09';
case 'october':
return '10';
case 'november':
return '11';
case 'december':
return '12';
default:
throw ArgumentError('Invalid month name: $s');
}
}
String? customDateParse(String dateString) {
List<String> parts = dateString.split(' ');
if (parts.length != 3) {
return null;
}
String result = '';
for (var s in parts.reversed) {
try {
try {
int.parse(s);
result += '$s-';
} catch (e) {
result += '${monthNameToNumberString(s)}-';
}
} catch (e) {
return null;
}
}
return result.substring(0, result.length - 1);
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
Response res = await sourceRequest(standardUrl, additionalSettings);
if (res.statusCode == 200) {
var http = parse(res.body);
var name = http.querySelector('.pd-title')?.innerHtml;
var filename = http.querySelector('.pd-filename .pd-float')?.innerHtml;
if (filename == null) {
throw NoReleasesError();
}
var version = http
.querySelector('.pd-version-txt')
?.nextElementSibling
?.innerHtml;
if (version == null) {
throw NoVersionError();
}
String? apkUrl = 'https://${hosts[0]}/download/$filename';
var dateStringOriginal = http
.querySelector('.pd-date-txt')
?.nextElementSibling
?.innerHtml;
var dateString = dateStringOriginal != null
? (customDateParse(dateStringOriginal))
: null;
var changeLogElements = http.querySelectorAll('.pd-fdesc p');
return APKDetails(
version,
getApkUrlsFromUrls([apkUrl]),
AppNames(runtimeType.toString(), name ?? standardUrl.split('/').last),
releaseDate: dateString != null ? DateTime.parse(dateString) : null,
changeLog: changeLogElements.isNotEmpty
? changeLogElements.last.innerHtml
: null,
);
} else {
throw getObtainiumHttpError(res);
}
}
}

View file

@ -0,0 +1,110 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter_charset_detector/flutter_charset_detector.dart';
import 'package:http/http.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class RuStore extends AppSource {
RuStore() {
hosts = ['rustore.ru'];
name = 'RuStore';
naiveStandardVersionDetection = true;
showReleaseDateAsVersionToggle = true;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}/catalog/app/+[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
return Uri.parse(standardUrl).pathSegments.last;
}
Future<dynamic> decodeJsonBody(Uint8List bytes) async {
try {
return jsonDecode((await CharsetDetector.autoDecode(bytes)).string);
} catch (e) {
try {
return jsonDecode(utf8.decode(bytes));
} catch (_) {
rethrow;
}
}
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
String? appId = await tryInferringAppId(standardUrl);
Response res0 = await sourceRequest(
'https://backapi.rustore.ru/applicationData/overallInfo/$appId',
additionalSettings,
);
if (res0.statusCode != 200) {
throw getObtainiumHttpError(res0);
}
var appDetails = (await decodeJsonBody(res0.bodyBytes))['body'];
if (appDetails['appId'] == null) {
throw NoReleasesError();
}
String appName = appDetails['appName'] ?? tr('app');
String author = appDetails['companyName'] ?? name;
String? dateStr = appDetails['appVerUpdatedAt'];
String? version = appDetails['versionName'];
String? changeLog = appDetails['whatsNew'];
if (version == null) {
throw NoVersionError();
}
DateTime? relDate;
if (dateStr != null) {
relDate = DateTime.parse(dateStr);
}
Response res1 = await sourceRequest(
'https://backapi.rustore.ru/applicationData/v2/download-link',
additionalSettings,
followRedirects: false,
postBody: {"appId": appDetails['appId'], "firstInstall": true},
);
var downloadDetails = (await decodeJsonBody(res1.bodyBytes))['body'];
try {
if (res1.statusCode != 200 || downloadDetails['downloadUrls'][0]['url'] == null) {
throw NoAPKError();
}
} catch (e) {
throw NoAPKError();
}
return APKDetails(
version,
getApkUrlsFromUrls([
(downloadDetails['downloadUrls'][0]['url'] as String).replaceAll(
RegExp('\\.zip\$'),
'.apk',
),
]),
AppNames(author, appName),
releaseDate: relDate,
changeLog: changeLog,
);
}
}

View file

@ -0,0 +1,129 @@
import 'package:html/parser.dart';
import 'package:http/http.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class SourceForge extends AppSource {
SourceForge() {
hosts = ['sourceforge.net'];
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
var sourceRegex = getSourceRegex(hosts);
RegExp standardUrlRegExC = RegExp(
'^https?://(www\\.)?$sourceRegex/p/.+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegExC.firstMatch(url);
if (match != null) {
url =
'https://${Uri.parse(match.group(0)!).host}/projects/${url.substring(Uri.parse(match.group(0)!).host.length + '/projects/'.length + 1)}';
}
RegExp standardUrlRegExB = RegExp(
'^https?://(www\\.)?$sourceRegex/projects/[^/]+',
caseSensitive: false,
);
match = standardUrlRegExB.firstMatch(url);
if (match != null && match.group(0) == url) {
url = '$url/files';
}
RegExp standardUrlRegExA = RegExp(
'^https?://(www\\.)?$sourceRegex/projects/[^/]+/files(/.+)?',
caseSensitive: false,
);
match = standardUrlRegExA.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var standardUri = Uri.parse(standardUrl);
if (standardUri.pathSegments.length == 2) {
standardUrl = '$standardUrl/files';
standardUri = Uri.parse(standardUrl);
}
Response res = await sourceRequest(
'${standardUri.origin}/${standardUri.pathSegments.sublist(0, 2).join('/')}/rss?path=/',
additionalSettings,
);
if (res.statusCode == 200) {
var parsedHtml = parse(res.body);
var allDownloadLinks = parsedHtml
.querySelectorAll('guid')
.map((e) => e.innerHtml)
.where((element) => element.startsWith(standardUrl))
.toList();
getVersion(String url) {
try {
var segments = url
.substring(standardUrl.length)
.split('/')
.where((element) => element.isNotEmpty)
.toList()
.reversed
.toList()
.sublist(1)
.reversed
.toList();
segments = segments.length > 1
? segments.reversed.toList().sublist(1).reversed.toList()
: segments;
var version = segments.isNotEmpty ? segments.join('/') : null;
if (version != null) {
try {
var extractedVersion = extractVersion(
additionalSettings['versionExtractionRegEx'] as String?,
additionalSettings['matchGroupToUse'] as String?,
version,
);
if (extractedVersion != null) {
version = extractedVersion;
}
} catch (e) {
if (e is NoVersionError) {
version = null;
} else {
rethrow;
}
}
}
return version;
} catch (e) {
return null;
}
}
var apkUrlListAllReleases = allDownloadLinks
.where((element) => element.toLowerCase().endsWith('.apk/download'))
.where((element) => getVersion(element) != null)
.toList();
if (apkUrlListAllReleases.isEmpty) {
throw NoReleasesError();
}
String? version = getVersion(apkUrlListAllReleases[0]);
if (version == null) {
throw NoVersionError();
}
var apkUrlList =
apkUrlListAllReleases // This can be used skipped for fallback support later
.where((element) => getVersion(element) == version)
.toList();
var segments = standardUrl.split('/');
return APKDetails(
version,
getApkUrlsFromUrls(apkUrlList),
AppNames(name, segments[segments.indexOf('files') - 1]),
);
} else {
throw getObtainiumHttpError(res);
}
}
}

View file

@ -0,0 +1,142 @@
import 'package:html/parser.dart';
import 'package:http/http.dart';
import 'package:obtainium/app_sources/html.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:easy_localization/easy_localization.dart';
class SourceHut extends AppSource {
SourceHut() {
hosts = ['git.sr.ht'];
showReleaseDateAsVersionToggle = true;
additionalSourceAppSpecificSettingFormItems = [
[
GeneratedFormSwitch(
'fallbackToOlderReleases',
label: tr('fallbackToOlderReleases'),
defaultValue: true,
),
],
];
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://(www\\.)?${getSourceRegex(hosts)}/[^/]+/[^/]+',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
String? changeLogPageFromStandardUrl(String standardUrl) => standardUrl;
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
if (standardUrl.endsWith('/refs')) {
standardUrl = standardUrl
.split('/')
.reversed
.toList()
.sublist(1)
.reversed
.join('/');
}
Uri standardUri = Uri.parse(standardUrl);
String appName = standardUri.pathSegments.last;
bool fallbackToOlderReleases =
additionalSettings['fallbackToOlderReleases'] == true;
Response res = await sourceRequest(
'$standardUrl/refs/rss.xml',
additionalSettings,
);
if (res.statusCode == 200) {
var parsedHtml = parse(res.body);
List<APKDetails> apkDetailsList = [];
int ind = 0;
for (var entry in parsedHtml.querySelectorAll('item').sublist(0, 6)) {
ind++;
String releasePage = // querySelector('link') fails for some reason
entry
.querySelector('guid') // Luckily guid is identical
?.innerHtml
.trim() ??
'';
if (!releasePage.startsWith('$standardUrl/refs')) {
continue;
}
if (!fallbackToOlderReleases && ind > 1) {
break;
}
String? version = entry.querySelector('title')?.text.trim();
if (version == null) {
throw NoVersionError();
}
String? releaseDateString = entry.querySelector('pubDate')?.innerHtml;
DateTime? releaseDate;
try {
releaseDate = releaseDateString != null
? DateFormat('E, dd MMM yyyy HH:mm:ss Z').parse(releaseDateString)
: null;
releaseDate = releaseDateString != null
? DateFormat(
'EEE, dd MMM yyyy HH:mm:ss Z',
).parse(releaseDateString)
: null;
} catch (e) {
// ignore
}
var res2 = await sourceRequest(releasePage, additionalSettings);
List<MapEntry<String, String>> apkUrls = [];
if (res2.statusCode == 200) {
apkUrls = getApkUrlsFromUrls(
parse(res2.body)
.querySelectorAll('a')
.map((e) => e.attributes['href'] ?? '')
.where((e) => e.toLowerCase().endsWith('.apk'))
.map((e) => ensureAbsoluteUrl(e, standardUri))
.toList(),
);
}
apkDetailsList.add(
APKDetails(
version,
apkUrls,
AppNames(
entry.querySelector('author')?.innerHtml.trim() ?? appName,
appName,
),
releaseDate: releaseDate,
),
);
}
if (apkDetailsList.isEmpty) {
throw NoReleasesError();
}
if (fallbackToOlderReleases) {
if (additionalSettings['trackOnly'] != true) {
apkDetailsList = apkDetailsList
.where((e) => e.apkUrls.isNotEmpty)
.toList();
}
if (apkDetailsList.isEmpty) {
throw NoReleasesError();
}
}
return apkDetailsList.first;
} else {
throw getObtainiumHttpError(res);
}
}
}

View file

@ -0,0 +1,46 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:html/parser.dart';
import 'package:http/http.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class TelegramApp extends AppSource {
TelegramApp() {
hosts = ['telegram.org'];
name = 'Telegram ${tr('app')}';
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
return 'https://${hosts[0]}';
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
Response res = await sourceRequest(
'https://t.me/s/TAndroidAPK',
additionalSettings,
);
if (res.statusCode == 200) {
var http = parse(res.body);
var messages = http.querySelectorAll(
'.tgme_widget_message_text.js-message_text',
);
var version = messages.isNotEmpty
? messages.last.innerHtml.split('\n').first.trim().split(' ').first
: null;
if (version == null) {
throw NoVersionError();
}
String? apkUrl = 'https://telegram.org/dl/android/apk';
return APKDetails(version, [
MapEntry<String, String>('telegram-$version.apk', apkUrl),
], AppNames('Telegram', 'Telegram'));
} else {
throw getObtainiumHttpError(res);
}
}
}

View file

@ -0,0 +1,84 @@
import 'dart:convert';
import 'package:easy_localization/easy_localization.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class Tencent extends AppSource {
Tencent() {
name = tr('tencentAppStore');
hosts = ['sj.qq.com'];
naiveStandardVersionDetection = true;
showReleaseDateAsVersionToggle = true;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://${getSourceRegex(hosts)}/appdetail/[^/]+',
caseSensitive: false,
);
var match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return match.group(0)!;
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
return Uri.parse(standardUrl).pathSegments.last;
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
String appId = (await tryInferringAppId(standardUrl))!;
String baseHost = Uri.parse(
standardUrl,
).host.split('.').reversed.toList().sublist(0, 2).reversed.join('.');
var res = await sourceRequest(
'https://upage.html5.$baseHost/wechat-apkinfo',
additionalSettings,
followRedirects: false,
postBody: {"packagename": appId},
);
if (res.statusCode == 200) {
var json = jsonDecode(res.body);
if (json['app_detail_records'][appId] == null) {
throw NoReleasesError();
}
var version =
json['app_detail_records'][appId]['apk_all_data']['version_name'];
var apkUrl = json['app_detail_records'][appId]['apk_all_data']['url'];
if (apkUrl == null) {
throw NoAPKError();
}
var appName = json['app_detail_records'][appId]['app_info']['name'];
var author = json['app_detail_records'][appId]['app_info']['author'];
var releaseDate =
json['app_detail_records'][appId]['app_info']['update_time'];
var apkName =
Uri.parse(apkUrl).queryParameters['fsname'] ??
'${appId}_$version.apk';
return APKDetails(
version,
[MapEntry(apkName, apkUrl)],
AppNames(author, appName),
releaseDate: releaseDate != null
? DateTime.fromMillisecondsSinceEpoch(releaseDate * 1000)
: null,
);
} else {
throw getObtainiumHttpError(res);
}
}
}

View file

@ -0,0 +1,145 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:html/parser.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
DateTime? parseDateTimeMMMddCommayyyy(String? dateString) {
DateTime? releaseDate;
try {
releaseDate = dateString != null
? DateFormat('MMM dd, yyyy').parse(dateString)
: null;
releaseDate = dateString != null && releaseDate == null
? DateFormat('MMMM dd, yyyy').parse(dateString)
: releaseDate;
} catch (err) {
// ignore
}
return releaseDate;
}
class Uptodown extends AppSource {
Uptodown() {
hosts = ['uptodown.com'];
allowSubDomains = true;
naiveStandardVersionDetection = true;
showReleaseDateAsVersionToggle = true;
urlsAlwaysHaveExtension = true;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
RegExp standardUrlRegEx = RegExp(
'^https?://([^\\.]+\\.){2,}${getSourceRegex(hosts)}',
caseSensitive: false,
);
RegExpMatch? match = standardUrlRegEx.firstMatch(url);
if (match == null) {
throw InvalidURLError(name);
}
return '${match.group(0)!}/android/download';
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
return (await getAppDetailsFromPage(
standardUrl,
additionalSettings,
))['appId'];
}
Future<Map<String, String?>> getAppDetailsFromPage(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var res = await sourceRequest(standardUrl, additionalSettings);
if (res.statusCode != 200) {
throw getObtainiumHttpError(res);
}
var html = parse(res.body);
String? version = html.querySelector('div.version')?.innerHtml;
String? name = html.querySelector('#detail-app-name')?.innerHtml.trim();
String? author = html.querySelector('#author-link')?.innerHtml.trim();
var detailElements = html
.querySelectorAll('#technical-information td')
.map((e) => e.innerHtml.trim())
.where((e) => !e.startsWith('<'))
.toList();
String? appId = detailElements.elementAtOrNull(0);
String? dateStr = detailElements.elementAtOrNull(6);
String? fileId = html
.querySelector('#detail-app-name')
?.attributes['data-file-id'];
String? extension = detailElements.elementAtOrNull(7)?.toLowerCase();
return Map.fromEntries([
MapEntry('version', version),
MapEntry('appId', appId),
MapEntry('name', name),
MapEntry('author', author),
MapEntry('dateStr', dateStr),
MapEntry('fileId', fileId),
MapEntry('extension', extension),
]);
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var appDetails = await getAppDetailsFromPage(
standardUrl,
additionalSettings,
);
var version = appDetails['version'];
var appId = appDetails['appId'];
var fileId = appDetails['fileId'];
var extension = appDetails['extension'];
if (version == null) {
throw NoVersionError();
}
if (fileId == null) {
throw NoAPKError();
}
var apkUrl = '$standardUrl/$fileId-x';
if (appId == null) {
throw NoReleasesError();
}
String appName = appDetails['name'] ?? tr('app');
String author = appDetails['author'] ?? name;
String? dateStr = appDetails['dateStr'];
DateTime? relDate;
if (dateStr != null) {
relDate = parseDateTimeMMMddCommayyyy(dateStr);
}
return APKDetails(
version,
[MapEntry('$appId.$extension', apkUrl)],
AppNames(author, appName),
releaseDate: relDate,
);
}
@override
Future<String> assetUrlPrefetchModifier(
String assetUrl,
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var res = await sourceRequest(assetUrl, additionalSettings);
if (res.statusCode != 200) {
throw getObtainiumHttpError(res);
}
var html = parse(res.body);
var finalUrlKey = html
.querySelector('#detail-download-button')
?.attributes['data-url'];
if (finalUrlKey == null) {
throw NoAPKError();
}
return 'https://dw.${hosts[0]}/dwn/$finalUrlKey';
}
}

View file

@ -0,0 +1,111 @@
import 'dart:convert';
import 'package:easy_localization/easy_localization.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class VivoAppStore extends AppSource {
static const appDetailUrl =
'https://h5coml.vivo.com.cn/h5coml/appdetail_h5/browser_v2/index.html?appId=';
VivoAppStore() {
name = tr('vivoAppStore');
hosts = ['h5.appstore.vivo.com.cn', 'h5coml.vivo.com.cn'];
naiveStandardVersionDetection = true;
canSearch = true;
allowOverride = false;
}
@override
String sourceSpecificStandardizeURL(String url, {bool forSelection = false}) {
var vivoAppId = parseVivoAppId(url);
return '$appDetailUrl$vivoAppId';
}
@override
Future<String?> tryInferringAppId(
String standardUrl, {
Map<String, dynamic> additionalSettings = const {},
}) async {
var json = await getDetailJson(standardUrl, additionalSettings);
return json['package_name'];
}
@override
Future<APKDetails> getLatestAPKDetails(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var json = await getDetailJson(standardUrl, additionalSettings);
var appName = json['title_zh'].toString();
var packageName = json['package_name'].toString();
var versionName = json['version_name'].toString();
var versionCode = json['version_code'].toString();
var developer = json['developer'].toString();
var uploadTime = json['upload_time'].toString();
var apkUrl = json['download_url'].toString();
var apkName = '${packageName}_$versionCode.apk';
return APKDetails(
versionName,
[MapEntry(apkName, apkUrl)],
AppNames(developer, appName),
releaseDate: DateTime.parse(uploadTime),
);
}
@override
Future<Map<String, List<String>>> search(
String query, {
Map<String, dynamic> querySettings = const {},
}) async {
var apiBaseUrl =
'https://h5-api.appstore.vivo.com.cn/h5appstore/search/result-list?app_version=2100&page_index=1&apps_per_page=20&target=local&cfrom=2&key=';
var searchUrl = '$apiBaseUrl${Uri.encodeQueryComponent(query)}';
var response = await sourceRequest(searchUrl, {});
if (response.statusCode != 200) {
throw getObtainiumHttpError(response);
}
var json = jsonDecode(response.body);
if (json['code'] != 0 || !json['data']['appSearchResponse']['result']) {
throw NoReleasesError();
}
Map<String, List<String>> results = {};
var resultsJson = json['data']['appSearchResponse']?['value'];
if (resultsJson != null) {
for (var item in (resultsJson as List<dynamic>)) {
results['$appDetailUrl${item['id']}'] = [
item['title_zh'].toString(),
item['developer'].toString(),
];
}
}
return results;
}
Future<Map<String, dynamic>> getDetailJson(
String standardUrl,
Map<String, dynamic> additionalSettings,
) async {
var vivoAppId = parseVivoAppId(standardUrl);
var apiBaseUrl = 'https://h5-api.appstore.vivo.com.cn/detail/';
var params = '?frompage=messageh5&app_version=2100';
var detailUrl = '$apiBaseUrl$vivoAppId$params';
var response = await sourceRequest(detailUrl, additionalSettings);
if (response.statusCode != 200) {
throw getObtainiumHttpError(response);
}
var json = jsonDecode(response.body);
if (json['id'] == null) {
throw NoReleasesError();
}
return json;
}
String parseVivoAppId(String url) {
var appId = Uri.parse(url.replaceAll('/#', '')).queryParameters['appId'];
if (appId == null || appId.isEmpty) {
throw InvalidURLError(name);
}
return appId;
}
}

View file

@ -0,0 +1,30 @@
import 'package:flutter/material.dart';
class CustomAppBar extends StatefulWidget {
const CustomAppBar({super.key, required this.title});
final String title;
@override
State<CustomAppBar> createState() => _CustomAppBarState();
}
class _CustomAppBarState extends State<CustomAppBar> {
@override
Widget build(BuildContext context) {
return SliverAppBar(
pinned: true,
automaticallyImplyLeading: false,
expandedHeight: 100,
flexibleSpace: FlexibleSpaceBar(
titlePadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
title: Text(
widget.title,
style: TextStyle(
color: Theme.of(context).textTheme.bodyMedium!.color,
),
),
),
);
}
}

View file

@ -0,0 +1,850 @@
import 'dart:math';
import 'package:hsluv/hsluv.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:obtainium/components/generated_form_modal.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
abstract class GeneratedFormItem {
late String key;
late String label;
late List<Widget> belowWidgets;
late dynamic defaultValue;
List<dynamic> additionalValidators;
dynamic ensureType(dynamic val);
GeneratedFormItem clone();
GeneratedFormItem(
this.key, {
this.label = 'Input',
this.belowWidgets = const [],
this.defaultValue,
this.additionalValidators = const [],
});
}
class GeneratedFormTextField extends GeneratedFormItem {
late bool required;
late int max;
late String? hint;
late bool password;
late TextInputType? textInputType;
late List<String>? autoCompleteOptions;
GeneratedFormTextField(
super.key, {
super.label,
super.belowWidgets,
String super.defaultValue = '',
List<String? Function(String? value)> super.additionalValidators = const [],
this.required = true,
this.max = 1,
this.hint,
this.password = false,
this.textInputType,
this.autoCompleteOptions,
});
@override
String ensureType(val) {
return val.toString();
}
@override
GeneratedFormTextField clone() {
return GeneratedFormTextField(
key,
label: label,
belowWidgets: belowWidgets,
defaultValue: defaultValue,
additionalValidators: List.from(additionalValidators),
required: required,
max: max,
hint: hint,
password: password,
textInputType: textInputType,
);
}
}
class GeneratedFormDropdown extends GeneratedFormItem {
late List<MapEntry<String, String>>? opts;
List<String>? disabledOptKeys;
GeneratedFormDropdown(
super.key,
this.opts, {
super.label,
super.belowWidgets,
String super.defaultValue = '',
this.disabledOptKeys,
List<String? Function(String? value)> super.additionalValidators = const [],
});
@override
String ensureType(val) {
return val.toString();
}
@override
GeneratedFormDropdown clone() {
return GeneratedFormDropdown(
key,
opts?.map((e) => MapEntry(e.key, e.value)).toList(),
label: label,
belowWidgets: belowWidgets,
defaultValue: defaultValue,
disabledOptKeys: disabledOptKeys != null
? List.from(disabledOptKeys!)
: null,
additionalValidators: List.from(additionalValidators),
);
}
}
class GeneratedFormSwitch extends GeneratedFormItem {
bool disabled = false;
GeneratedFormSwitch(
super.key, {
super.label,
super.belowWidgets,
bool super.defaultValue = false,
bool disabled = false,
List<String? Function(bool value)> super.additionalValidators = const [],
});
@override
bool ensureType(val) {
return val == true || val == 'true';
}
@override
GeneratedFormSwitch clone() {
return GeneratedFormSwitch(
key,
label: label,
belowWidgets: belowWidgets,
defaultValue: defaultValue,
disabled: false,
additionalValidators: List.from(additionalValidators),
);
}
}
class GeneratedFormTagInput extends GeneratedFormItem {
late MapEntry<String, String>? deleteConfirmationMessage;
late bool singleSelect;
late WrapAlignment alignment;
late String emptyMessage;
late bool showLabelWhenNotEmpty;
GeneratedFormTagInput(
super.key, {
super.label,
super.belowWidgets,
Map<String, MapEntry<int, bool>> super.defaultValue = const {},
List<String? Function(Map<String, MapEntry<int, bool>> value)>
super.additionalValidators =
const [],
this.deleteConfirmationMessage,
this.singleSelect = false,
this.alignment = WrapAlignment.start,
this.emptyMessage = 'Input',
this.showLabelWhenNotEmpty = true,
});
@override
Map<String, MapEntry<int, bool>> ensureType(val) {
return val is Map<String, MapEntry<int, bool>> ? val : {};
}
@override
GeneratedFormTagInput clone() {
return GeneratedFormTagInput(
key,
label: label,
belowWidgets: belowWidgets,
defaultValue: defaultValue,
additionalValidators: List.from(additionalValidators),
deleteConfirmationMessage: deleteConfirmationMessage,
singleSelect: singleSelect,
alignment: alignment,
emptyMessage: emptyMessage,
showLabelWhenNotEmpty: showLabelWhenNotEmpty,
);
}
}
typedef OnValueChanges =
void Function(Map<String, dynamic> values, bool valid, bool isBuilding);
class GeneratedForm extends StatefulWidget {
const GeneratedForm({
super.key,
required this.items,
required this.onValueChanges,
});
final List<List<GeneratedFormItem>> items;
final OnValueChanges onValueChanges;
@override
State<GeneratedForm> createState() => _GeneratedFormState();
}
List<List<GeneratedFormItem>> cloneFormItems(
List<List<GeneratedFormItem>> items,
) {
List<List<GeneratedFormItem>> clonedItems = [];
for (var row in items) {
List<GeneratedFormItem> clonedRow = [];
for (var it in row) {
clonedRow.add(it.clone());
}
clonedItems.add(clonedRow);
}
return clonedItems;
}
class GeneratedFormSubForm extends GeneratedFormItem {
final List<List<GeneratedFormItem>> items;
GeneratedFormSubForm(
super.key,
this.items, {
super.label,
super.belowWidgets,
super.defaultValue = const [],
});
@override
ensureType(val) {
return val; // Not easy to validate List<Map<String, dynamic>>
}
@override
GeneratedFormSubForm clone() {
return GeneratedFormSubForm(
key,
cloneFormItems(items),
label: label,
belowWidgets: belowWidgets,
defaultValue: defaultValue,
);
}
}
// Generates a color in the HSLuv (Pastel) color space
// https://pub.dev/documentation/hsluv/latest/hsluv/Hsluv/hpluvToRgb.html
Color generateRandomLightColor() {
final randomSeed = Random().nextInt(120);
// https://en.wikipedia.org/wiki/Golden_angle
final goldenAngle = 180 * (3 - sqrt(5));
// Generate next golden angle hue
final double hue = randomSeed * goldenAngle;
// Map from HPLuv color space to RGB, use constant saturation=100, lightness=70
final List<double> rgbValuesDbl = Hsluv.hpluvToRgb([hue, 100, 70]);
// Map RBG values from 0-1 to 0-255:
final List<int> rgbValues = rgbValuesDbl
.map((rgb) => (rgb * 255).toInt())
.toList();
return Color.fromARGB(255, rgbValues[0], rgbValues[1], rgbValues[2]);
}
int generateRandomNumber(
int seed1, {
int seed2 = 0,
int seed3 = 0,
max = 10000,
}) {
int combinedSeed = seed1.hashCode ^ seed2.hashCode ^ seed3.hashCode;
Random random = Random(combinedSeed);
int randomNumber = random.nextInt(max);
return randomNumber;
}
bool validateTextField(TextFormField tf) =>
(tf.key as GlobalKey<FormFieldState>).currentState?.isValid == true;
class _GeneratedFormState extends State<GeneratedForm> {
final _formKey = GlobalKey<FormState>();
Map<String, dynamic> values = {};
late List<List<Widget>> formInputs;
List<List<Widget>> rows = [];
String? initKey;
int forceUpdateKeyCount = 0;
// If any value changes, call this to update the parent with value and validity
void someValueChanged({bool isBuilding = false, bool forceInvalid = false}) {
Map<String, dynamic> returnValues = values;
var valid = true;
for (int r = 0; r < formInputs.length; r++) {
for (int i = 0; i < formInputs[r].length; i++) {
if (formInputs[r][i] is TextFormField) {
valid = valid && validateTextField(formInputs[r][i] as TextFormField);
}
}
}
if (forceInvalid) {
valid = false;
}
widget.onValueChanges(returnValues, valid, isBuilding);
}
void initForm() {
initKey = widget.key.toString();
// Initialize form values as all empty
values.clear();
for (var row in widget.items) {
for (var e in row) {
values[e.key] = e.defaultValue;
}
}
// Dynamically create form inputs
formInputs = widget.items.asMap().entries.map((row) {
return row.value.asMap().entries.map((e) {
var formItem = e.value;
if (formItem is GeneratedFormTextField) {
final formFieldKey = GlobalKey<FormFieldState>();
var ctrl = TextEditingController(text: values[formItem.key]);
return TypeAheadField<String>(
controller: ctrl,
builder: (context, controller, focusNode) {
return TextFormField(
controller: ctrl,
focusNode: focusNode,
keyboardType: formItem.textInputType,
obscureText: formItem.password,
autocorrect: !formItem.password,
enableSuggestions: !formItem.password,
key: formFieldKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
onChanged: (value) {
setState(() {
values[formItem.key] = value;
someValueChanged();
});
},
decoration: InputDecoration(
helperText: formItem.label + (formItem.required ? ' *' : ''),
hintText: formItem.hint,
),
minLines: formItem.max <= 1 ? null : formItem.max,
maxLines: formItem.max <= 1 ? 1 : formItem.max,
validator: (value) {
if (formItem.required &&
(value == null || value.trim().isEmpty)) {
return '${formItem.label} ${tr('requiredInBrackets')}';
}
for (var validator in formItem.additionalValidators) {
String? result = validator(value);
if (result != null) {
return result;
}
}
return null;
},
);
},
itemBuilder: (context, value) {
return ListTile(title: Text(value));
},
onSelected: (value) {
ctrl.text = value;
setState(() {
values[formItem.key] = value;
someValueChanged();
});
},
suggestionsCallback: (search) {
return formItem.autoCompleteOptions
?.where((t) => t.toLowerCase().contains(search.toLowerCase()))
.toList();
},
hideOnEmpty: true,
);
} else if (formItem is GeneratedFormDropdown) {
if (formItem.opts!.isEmpty) {
return Text(tr('dropdownNoOptsError'));
}
return DropdownButtonFormField(
decoration: InputDecoration(labelText: formItem.label),
value: values[formItem.key],
items: formItem.opts!.map((e2) {
var enabled = formItem.disabledOptKeys?.contains(e2.key) != true;
return DropdownMenuItem(
value: e2.key,
enabled: enabled,
child: Opacity(
opacity: enabled ? 1 : 0.5,
child: Text(e2.value),
),
);
}).toList(),
onChanged: (value) {
setState(() {
values[formItem.key] = value ?? formItem.opts!.first.key;
someValueChanged();
});
},
);
} else if (formItem is GeneratedFormSubForm) {
values[formItem.key] = [];
for (Map<String, dynamic> v
in ((formItem.defaultValue ?? []) as List<dynamic>)) {
var fullDefaults = getDefaultValuesFromFormItems(formItem.items);
for (var element in v.entries) {
fullDefaults[element.key] = element.value;
}
values[formItem.key].add(fullDefaults);
}
return Container();
} else {
return Container(); // Some input types added in build
}
}).toList();
}).toList();
someValueChanged(isBuilding: true);
}
@override
void initState() {
super.initState();
initForm();
}
@override
Widget build(BuildContext context) {
if (widget.key.toString() != initKey) {
initForm();
}
for (var r = 0; r < formInputs.length; r++) {
for (var e = 0; e < formInputs[r].length; e++) {
String fieldKey = widget.items[r][e].key;
if (widget.items[r][e] is GeneratedFormSwitch) {
formInputs[r][e] = Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(child: Text(widget.items[r][e].label)),
const SizedBox(width: 8),
Switch(
value: values[fieldKey],
onChanged: (widget.items[r][e] as GeneratedFormSwitch).disabled
? null
: (value) {
setState(() {
values[fieldKey] = value;
someValueChanged();
});
},
),
],
);
} else if (widget.items[r][e] is GeneratedFormTagInput) {
onAddPressed() {
showDialog<Map<String, dynamic>?>(
context: context,
builder: (BuildContext ctx) {
return GeneratedFormModal(
title: widget.items[r][e].label,
items: [
[GeneratedFormTextField('label', label: tr('label'))],
],
);
},
).then((value) {
String? label = value?['label'];
if (label != null) {
setState(() {
var temp =
values[fieldKey] as Map<String, MapEntry<int, bool>>?;
temp ??= {};
if (temp[label] == null) {
var singleSelect =
(widget.items[r][e] as GeneratedFormTagInput)
.singleSelect;
var someSelected = temp.entries
.where((element) => element.value.value)
.isNotEmpty;
temp[label] = MapEntry(
generateRandomLightColor().value,
!(someSelected && singleSelect),
);
values[fieldKey] = temp;
someValueChanged();
}
});
}
});
}
formInputs[r][e] = Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if ((values[fieldKey] as Map<String, MapEntry<int, bool>>?)
?.isNotEmpty ==
true &&
(widget.items[r][e] as GeneratedFormTagInput)
.showLabelWhenNotEmpty)
Column(
crossAxisAlignment:
(widget.items[r][e] as GeneratedFormTagInput).alignment ==
WrapAlignment.center
? CrossAxisAlignment.center
: CrossAxisAlignment.stretch,
children: [
Text(widget.items[r][e].label),
const SizedBox(height: 8),
],
),
Wrap(
alignment:
(widget.items[r][e] as GeneratedFormTagInput).alignment,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
// (values[fieldKey] as Map<String, MapEntry<int, bool>>?)
// ?.isEmpty ==
// true
// ? Text(
// (widget.items[r][e] as GeneratedFormTagInput)
// .emptyMessage,
// )
// : const SizedBox.shrink(),
...(values[fieldKey] as Map<String, MapEntry<int, bool>>?)
?.entries
.map((e2) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 4,
),
child: ChoiceChip(
label: Text(e2.key),
backgroundColor: Color(
e2.value.key,
).withAlpha(50),
selectedColor: Color(e2.value.key),
visualDensity: VisualDensity.compact,
selected: e2.value.value,
onSelected: (value) {
setState(() {
(values[fieldKey]
as Map<String, MapEntry<int, bool>>)[e2
.key] = MapEntry(
(values[fieldKey]
as Map<
String,
MapEntry<int, bool>
>)[e2.key]!
.key,
value,
);
if ((widget.items[r][e]
as GeneratedFormTagInput)
.singleSelect &&
value == true) {
for (var key
in (values[fieldKey]
as Map<
String,
MapEntry<int, bool>
>)
.keys) {
if (key != e2.key) {
(values[fieldKey]
as Map<
String,
MapEntry<int, bool>
>)[key] = MapEntry(
(values[fieldKey]
as Map<
String,
MapEntry<int, bool>
>)[key]!
.key,
false,
);
}
}
}
someValueChanged();
});
},
),
);
}) ??
[const SizedBox.shrink()],
(values[fieldKey] as Map<String, MapEntry<int, bool>>?)
?.values
.where((e) => e.value)
.length ==
1
? Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: IconButton(
onPressed: () {
setState(() {
var temp =
values[fieldKey]
as Map<String, MapEntry<int, bool>>;
// get selected category str where bool is true
final oldEntry = temp.entries.firstWhere(
(entry) => entry.value.value,
);
// generate new color, ensure it is not the same
int newColor = oldEntry.value.key;
while (oldEntry.value.key == newColor) {
newColor = generateRandomLightColor().value;
}
// Update entry with new color, remain selected
temp.update(
oldEntry.key,
(old) => MapEntry(newColor, old.value),
);
values[fieldKey] = temp;
someValueChanged();
});
},
icon: const Icon(Icons.format_color_fill_rounded),
visualDensity: VisualDensity.compact,
tooltip: tr('colour'),
),
)
: const SizedBox.shrink(),
(values[fieldKey] as Map<String, MapEntry<int, bool>>?)
?.values
.where((e) => e.value)
.isNotEmpty ==
true
? Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: IconButton(
onPressed: () {
fn() {
setState(() {
var temp =
values[fieldKey]
as Map<String, MapEntry<int, bool>>;
temp.removeWhere((key, value) => value.value);
values[fieldKey] = temp;
someValueChanged();
});
}
if ((widget.items[r][e] as GeneratedFormTagInput)
.deleteConfirmationMessage !=
null) {
var message =
(widget.items[r][e]
as GeneratedFormTagInput)
.deleteConfirmationMessage!;
showDialog<Map<String, dynamic>?>(
context: context,
builder: (BuildContext ctx) {
return GeneratedFormModal(
title: message.key,
message: message.value,
items: const [],
);
},
).then((value) {
if (value != null) {
fn();
}
});
} else {
fn();
}
},
icon: const Icon(Icons.remove),
visualDensity: VisualDensity.compact,
tooltip: tr('remove'),
),
)
: const SizedBox.shrink(),
(values[fieldKey] as Map<String, MapEntry<int, bool>>?)
?.isEmpty ==
true
? Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: TextButton.icon(
onPressed: onAddPressed,
icon: const Icon(Icons.add),
label: Text(
(widget.items[r][e] as GeneratedFormTagInput)
.label,
),
),
)
: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: IconButton(
onPressed: onAddPressed,
icon: const Icon(Icons.add),
visualDensity: VisualDensity.compact,
tooltip: tr('add'),
),
),
],
),
],
);
} else if (widget.items[r][e] is GeneratedFormSubForm) {
List<Widget> subformColumn = [];
var compact =
(widget.items[r][e] as GeneratedFormSubForm).items.length == 1 &&
(widget.items[r][e] as GeneratedFormSubForm).items[0].length == 1;
for (int i = 0; i < values[fieldKey].length; i++) {
var internalFormKey = ValueKey(
generateRandomNumber(
values[fieldKey].length,
seed2: i,
seed3: forceUpdateKeyCount,
),
);
subformColumn.add(
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!compact) const SizedBox(height: 16),
if (!compact)
Text(
'${(widget.items[r][e] as GeneratedFormSubForm).label} (${i + 1})',
style: const TextStyle(fontWeight: FontWeight.bold),
),
GeneratedForm(
key: internalFormKey,
items:
cloneFormItems(
(widget.items[r][e] as GeneratedFormSubForm)
.items,
)
.map(
(x) => x.map((y) {
y.defaultValue = values[fieldKey]?[i]?[y.key];
y.key = '${y.key.toString()},$internalFormKey';
return y;
}).toList(),
)
.toList(),
onValueChanges: (values, valid, isBuilding) {
values = values.map(
(key, value) => MapEntry(key.split(',')[0], value),
);
if (valid) {
this.values[fieldKey]?[i] = values;
}
someValueChanged(
isBuilding: isBuilding,
forceInvalid: !valid,
);
},
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton.icon(
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.error,
),
onPressed: (values[fieldKey].length > 0)
? () {
var temp = List.from(values[fieldKey]);
temp.removeAt(i);
values[fieldKey] = List.from(temp);
forceUpdateKeyCount++;
someValueChanged();
}
: null,
label: Text(
'${(widget.items[r][e] as GeneratedFormSubForm).label} (${i + 1})',
),
icon: const Icon(Icons.delete_outline_rounded),
),
],
),
],
),
);
}
subformColumn.add(
Padding(
padding: const EdgeInsets.only(bottom: 0, top: 8),
child: Row(
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: () {
values[fieldKey].add(
getDefaultValuesFromFormItems(
(widget.items[r][e] as GeneratedFormSubForm).items,
),
);
forceUpdateKeyCount++;
someValueChanged();
},
icon: const Icon(Icons.add),
label: Text(
(widget.items[r][e] as GeneratedFormSubForm).label,
),
),
),
],
),
),
);
formInputs[r][e] = Column(children: subformColumn);
}
}
}
rows.clear();
formInputs.asMap().entries.forEach((rowInputs) {
if (rowInputs.key > 0) {
rows.add([
SizedBox(
height: widget.items[rowInputs.key - 1][0] is GeneratedFormSwitch
? 8
: 25,
),
]);
}
List<Widget> rowItems = [];
rowInputs.value.asMap().entries.forEach((rowInput) {
if (rowInput.key > 0) {
rowItems.add(const SizedBox(width: 20));
}
rowItems.add(
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
rowInput.value,
...widget.items[rowInputs.key][rowInput.key].belowWidgets,
],
),
),
);
});
rows.add(rowItems);
});
return Form(
key: _formKey,
child: Column(
children: [
...rows.map(
(row) => Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [...row.map((e) => e)],
),
),
],
),
);
}
}

View file

@ -0,0 +1,99 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:obtainium/components/generated_form.dart';
class GeneratedFormModal extends StatefulWidget {
const GeneratedFormModal({
super.key,
required this.title,
required this.items,
this.initValid = false,
this.message = '',
this.additionalWidgets = const [],
this.singleNullReturnButton,
this.primaryActionColour,
});
final String title;
final String message;
final List<List<GeneratedFormItem>> items;
final bool initValid;
final List<Widget> additionalWidgets;
final String? singleNullReturnButton;
final Color? primaryActionColour;
@override
State<GeneratedFormModal> createState() => _GeneratedFormModalState();
}
class _GeneratedFormModalState extends State<GeneratedFormModal> {
Map<String, dynamic> values = {};
bool valid = false;
@override
void initState() {
super.initState();
valid = widget.initValid || widget.items.isEmpty;
}
@override
Widget build(BuildContext context) {
return AlertDialog(
scrollable: true,
title: Text(widget.title),
content: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.message.isNotEmpty) Text(widget.message),
if (widget.message.isNotEmpty) const SizedBox(height: 16),
GeneratedForm(
items: widget.items,
onValueChanges: (values, valid, isBuilding) {
if (isBuilding) {
this.values = values;
this.valid = valid;
} else {
setState(() {
this.values = values;
this.valid = valid;
});
}
},
),
if (widget.additionalWidgets.isNotEmpty) ...widget.additionalWidgets,
],
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(null);
},
child: Text(
widget.singleNullReturnButton == null
? tr('cancel')
: widget.singleNullReturnButton!,
),
),
widget.singleNullReturnButton == null
? TextButton(
style: widget.primaryActionColour == null
? null
: TextButton.styleFrom(
foregroundColor: widget.primaryActionColour,
),
onPressed: !valid
? null
: () {
if (valid) {
HapticFeedback.selectionClick();
Navigator.of(context).pop(values);
}
},
child: Text(tr('continue')),
)
: const SizedBox.shrink(),
],
);
}
}

178
lib/custom_errors.dart Normal file
View file

@ -0,0 +1,178 @@
import 'dart:io';
import 'package:android_package_installer/android_package_installer.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:obtainium/providers/logs_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:provider/provider.dart';
class ObtainiumError {
late String message;
bool unexpected;
ObtainiumError(this.message, {this.unexpected = false});
@override
String toString() {
return message;
}
}
class RateLimitError extends ObtainiumError {
late int remainingMinutes;
RateLimitError(this.remainingMinutes)
: super(plural('tooManyRequestsTryAgainInMinutes', remainingMinutes));
}
class InvalidURLError extends ObtainiumError {
InvalidURLError(String sourceName)
: super(tr('invalidURLForSource', args: [sourceName]));
}
class CredsNeededError extends ObtainiumError {
CredsNeededError(String sourceName)
: super(tr('requiresCredentialsInSettings', args: [sourceName]));
}
class NoReleasesError extends ObtainiumError {
NoReleasesError({String? note})
: super(
'${tr('noReleaseFound')}${note?.isNotEmpty == true ? '\n\n$note' : ''}',
);
}
class NoAPKError extends ObtainiumError {
NoAPKError() : super(tr('noAPKFound'));
}
class NoVersionError extends ObtainiumError {
NoVersionError() : super(tr('noVersionFound'));
}
class UnsupportedURLError extends ObtainiumError {
UnsupportedURLError() : super(tr('urlMatchesNoSource'));
}
class DowngradeError extends ObtainiumError {
DowngradeError(int currentVersionCode, int newVersionCode)
: super(
'${tr('cantInstallOlderVersion')} (versionCode $currentVersionCode$newVersionCode)',
);
}
class InstallError extends ObtainiumError {
InstallError(int code)
: super(PackageInstallerStatus.byCode(code).name.substring(7));
}
class IDChangedError extends ObtainiumError {
IDChangedError(String newId) : super('${tr('appIdMismatch')} - $newId');
}
class NotImplementedError extends ObtainiumError {
NotImplementedError() : super(tr('functionNotImplemented'));
}
class MultiAppMultiError extends ObtainiumError {
Map<String, dynamic> rawErrors = {};
Map<String, List<String>> idsByErrorString = {};
Map<String, String> appIdNames = {};
MultiAppMultiError() : super(tr('placeholder'), unexpected: true);
void add(String appId, dynamic error, {String? appName}) {
if (error is SocketException) {
error = error.message;
}
rawErrors[appId] = error;
var string = error.toString();
var tempIds = idsByErrorString.remove(string);
tempIds ??= [];
tempIds.add(appId);
idsByErrorString.putIfAbsent(string, () => tempIds!);
if (appName != null) {
appIdNames[appId] = appName;
}
}
String errorString(String appId, {bool includeIdsWithNames = false}) =>
'${appIdNames.containsKey(appId) ? '${appIdNames[appId]}${includeIdsWithNames ? ' ($appId)' : ''}' : appId}: ${rawErrors[appId].toString()}';
String errorsAppsString(
String errString,
List<String> appIds, {
bool includeIdsWithNames = false,
}) =>
'$errString [${list2FriendlyString(appIds.map((id) => appIdNames.containsKey(id) == true ? '${appIdNames[id]}${includeIdsWithNames ? ' ($id)' : ''}' : id).toList())}]';
@override
String toString() => idsByErrorString.entries
.map((e) => errorsAppsString(e.key, e.value))
.join('\n\n');
}
void showMessage(dynamic e, BuildContext context, {bool isError = false}) {
Provider.of<LogsProvider>(
context,
listen: false,
).add(e.toString(), level: isError ? LogLevels.error : LogLevels.info);
if (e is String || (e is ObtainiumError && !e.unexpected)) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(e.toString())));
} else {
showDialog(
context: context,
builder: (BuildContext ctx) {
return AlertDialog(
scrollable: true,
title: Text(
e is MultiAppMultiError
? tr(isError ? 'someErrors' : 'updates')
: tr(isError ? 'unexpectedError' : 'unknown'),
),
content: GestureDetector(
onLongPress: () {
Clipboard.setData(ClipboardData(text: e.toString()));
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(tr('copiedToClipboard'))));
},
child: Text(e.toString()),
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(null);
},
child: Text(tr('ok')),
),
],
);
},
);
}
}
void showError(dynamic e, BuildContext context) {
showMessage(e, context, isError: true);
}
String list2FriendlyString(List<String> list) {
var isUsingEnglish = isEnglish();
return list.length == 2
? '${list[0]} ${tr('and')} ${list[1]}'
: list
.asMap()
.entries
.map(
(e) =>
e.value +
(e.key == list.length - 1
? ''
: e.key == list.length - 2
? '${isUsingEnglish ? ',' : ''} and '
: ', '),
)
.join('');
}

423
lib/main.dart Normal file
View file

@ -0,0 +1,423 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:obtainium/pages/home.dart';
import 'package:obtainium/providers/apps_provider.dart';
import 'package:obtainium/providers/logs_provider.dart';
import 'package:obtainium/providers/native_provider.dart';
import 'package:obtainium/providers/notifications_provider.dart';
import 'package:obtainium/providers/settings_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:provider/provider.dart';
import 'package:dynamic_color/dynamic_color.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:background_fetch/background_fetch.dart';
import 'package:easy_localization/easy_localization.dart';
// ignore: implementation_imports
import 'package:easy_localization/src/easy_localization_controller.dart';
// ignore: implementation_imports
import 'package:easy_localization/src/localization.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
List<MapEntry<Locale, String>> supportedLocales = const [
MapEntry(Locale('en'), 'English'),
MapEntry(Locale('zh'), '简体中文'),
MapEntry(Locale('zh', 'Hant_TW'), '臺灣話'),
MapEntry(Locale('it'), 'Italiano'),
MapEntry(Locale('ja'), '日本語'),
MapEntry(Locale('hu'), 'Magyar'),
MapEntry(Locale('de'), 'Deutsch'),
MapEntry(Locale('fa'), 'فارسی'),
MapEntry(Locale('fr'), 'Français'),
MapEntry(Locale('es'), 'Español'),
MapEntry(Locale('pl'), 'Polski'),
MapEntry(Locale('ru'), 'Русский'),
MapEntry(Locale('bs'), 'Bosanski'),
MapEntry(Locale('pt'), 'Português'),
MapEntry(Locale('pt', 'BR'), 'Brasileiro'),
MapEntry(Locale('cs'), 'Česky'),
MapEntry(Locale('sv'), 'Svenska'),
MapEntry(Locale('nl'), 'Nederlands'),
MapEntry(Locale('vi'), 'Tiếng Việt'),
MapEntry(Locale('tr'), 'Türkçe'),
MapEntry(Locale('uk'), 'Українська'),
MapEntry(Locale('da'), 'Dansk'),
MapEntry(
Locale('en', 'EO'),
'Esperanto',
), // https://github.com/aissat/easy_localization/issues/220#issuecomment-846035493
MapEntry(Locale('in'), 'Bahasa Indonesia'),
MapEntry(Locale('ko'), '한국어'),
MapEntry(Locale('ca'), 'Català'),
MapEntry(Locale('ar'), 'العربية'),
MapEntry(Locale('ml'), 'മലയാളം'),
];
const fallbackLocale = Locale('en');
const localeDir = 'assets/translations';
var fdroid = false;
final globalNavigatorKey = GlobalKey<NavigatorState>();
Future<void> loadTranslations() async {
// See easy_localization/issues/210
await EasyLocalizationController.initEasyLocation();
var s = SettingsProvider();
await s.initializeSettings();
var forceLocale = s.forcedLocale;
final controller = EasyLocalizationController(
saveLocale: true,
forceLocale: forceLocale,
fallbackLocale: fallbackLocale,
supportedLocales: supportedLocales.map((e) => e.key).toList(),
assetLoader: const RootBundleAssetLoader(),
useOnlyLangCode: false,
useFallbackTranslations: true,
path: localeDir,
onLoadError: (FlutterError e) {
throw e;
},
);
await controller.loadTranslations();
Localization.load(
controller.locale,
translations: controller.translations,
fallbackTranslations: controller.fallbackTranslations,
);
}
@pragma('vm:entry-point')
void backgroundFetchHeadlessTask(HeadlessTask task) async {
String taskId = task.taskId;
bool isTimeout = task.timeout;
if (isTimeout) {
print('BG update task timed out.');
BackgroundFetch.finish(taskId);
return;
}
await bgUpdateCheck(taskId, null);
BackgroundFetch.finish(taskId);
}
@pragma('vm:entry-point')
void startCallback() {
FlutterForegroundTask.setTaskHandler(MyTaskHandler());
}
class MyTaskHandler extends TaskHandler {
static const String incrementCountCommand = 'incrementCount';
@override
Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
print('onStart(starter: ${starter.name})');
bgUpdateCheck('bg_check', null);
}
@override
void onRepeatEvent(DateTime timestamp) {
bgUpdateCheck('bg_check', null);
}
@override
Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {
print('Foreground service onDestroy(isTimeout: $isTimeout)');
}
@override
void onReceiveData(Object data) {}
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
try {
ByteData data = await PlatformAssetBundle().load(
'assets/ca/lets-encrypt-r3.pem',
);
SecurityContext.defaultContext.setTrustedCertificatesBytes(
data.buffer.asUint8List(),
);
} catch (e) {
// Already added, do nothing (see #375)
}
await EasyLocalization.ensureInitialized();
if ((await DeviceInfoPlugin().androidInfo).version.sdkInt >= 29) {
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(systemNavigationBarColor: Colors.transparent),
);
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
}
final np = NotificationsProvider();
await np.initialize();
FlutterForegroundTask.initCommunicationPort();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => AppsProvider()),
ChangeNotifierProvider(create: (context) => SettingsProvider()),
Provider(create: (context) => np),
Provider(create: (context) => LogsProvider()),
],
child: EasyLocalization(
supportedLocales: supportedLocales.map((e) => e.key).toList(),
path: localeDir,
fallbackLocale: fallbackLocale,
useOnlyLangCode: false,
child: const Obtainium(),
),
),
);
BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
}
class Obtainium extends StatefulWidget {
const Obtainium({super.key});
@override
State<Obtainium> createState() => _ObtainiumState();
}
class _ObtainiumState extends State<Obtainium> {
var existingUpdateInterval = -1;
@override
void initState() {
super.initState();
initPlatformState();
WidgetsBinding.instance.addPostFrameCallback((_) {
requestNonOptionalPermissions();
});
}
Future<void> requestNonOptionalPermissions() async {
final NotificationPermission notificationPermission =
await FlutterForegroundTask.checkNotificationPermission();
if (notificationPermission != NotificationPermission.granted) {
await FlutterForegroundTask.requestNotificationPermission();
}
if (!await FlutterForegroundTask.isIgnoringBatteryOptimizations) {
await FlutterForegroundTask.requestIgnoreBatteryOptimization();
}
}
void initForegroundService() {
// ignore: invalid_use_of_visible_for_testing_member
if (!FlutterForegroundTask.isInitialized) {
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: 'bg_update',
channelName: tr('foregroundService'),
channelDescription: tr('foregroundService'),
onlyAlertOnce: true,
),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: false,
playSound: false,
),
foregroundTaskOptions: ForegroundTaskOptions(
eventAction: ForegroundTaskEventAction.repeat(900000),
autoRunOnBoot: true,
autoRunOnMyPackageReplaced: true,
allowWakeLock: true,
allowWifiLock: true,
),
);
}
}
Future<ServiceRequestResult?> startForegroundService(bool restart) async {
initForegroundService();
if (await FlutterForegroundTask.isRunningService) {
if (restart) {
return FlutterForegroundTask.restartService();
}
} else {
return FlutterForegroundTask.startService(
serviceTypes: [ForegroundServiceTypes.specialUse],
serviceId: 666,
notificationTitle: tr('foregroundService'),
notificationText: tr('fgServiceNotice'),
notificationIcon: NotificationIcon(
metaDataName: 'dev.imranr.obtainium.service.NOTIFICATION_ICON',
),
callback: startCallback,
);
}
return null;
}
stopForegroundService() async {
if (await FlutterForegroundTask.isRunningService) {
return FlutterForegroundTask.stopService();
}
}
// void onReceiveForegroundServiceData(Object data) {
// print('onReceiveTaskData: $data');
// }
@override
void dispose() {
// Remove a callback to receive data sent from the TaskHandler.
// FlutterForegroundTask.removeTaskDataCallback(onReceiveForegroundServiceData);
super.dispose();
}
Future<void> initPlatformState() async {
await BackgroundFetch.configure(
BackgroundFetchConfig(
minimumFetchInterval: 15,
stopOnTerminate: false,
startOnBoot: true,
enableHeadless: true,
requiresBatteryNotLow: false,
requiresCharging: false,
requiresStorageNotLow: false,
requiresDeviceIdle: false,
requiredNetworkType: NetworkType.ANY,
),
(String taskId) async {
await bgUpdateCheck(taskId, null);
BackgroundFetch.finish(taskId);
},
(String taskId) async {
context.read<LogsProvider>().add('BG update task timed out.');
BackgroundFetch.finish(taskId);
},
);
if (!mounted) return;
}
@override
Widget build(BuildContext context) {
SettingsProvider settingsProvider = context.watch<SettingsProvider>();
AppsProvider appsProvider = context.read<AppsProvider>();
LogsProvider logs = context.read<LogsProvider>();
NotificationsProvider notifs = context.read<NotificationsProvider>();
if (settingsProvider.updateInterval == 0) {
stopForegroundService();
BackgroundFetch.stop();
} else {
if (settingsProvider.useFGService) {
BackgroundFetch.stop();
startForegroundService(false);
} else {
stopForegroundService();
BackgroundFetch.start();
}
}
if (settingsProvider.prefs == null) {
settingsProvider.initializeSettings();
} else {
bool isFirstRun = settingsProvider.checkAndFlipFirstRun();
if (isFirstRun) {
logs.add('This is the first ever run of Obtainium.');
// If this is the first run, add Obtainium to the Apps list
if (!fdroid) {
getInstalledInfo(obtainiumId)
.then((value) {
if (value?.versionName != null) {
appsProvider.saveApps([
App(
obtainiumId,
obtainiumUrl,
'ImranR98',
'Obtainium',
value!.versionName,
value.versionName!,
[],
0,
{
'versionDetection': true,
'apkFilterRegEx': 'fdroid',
'invertAPKFilter': true,
},
null,
false,
),
], onlyIfExists: false);
}
})
.catchError((err) {
print(err);
});
}
}
if (!supportedLocales.map((e) => e.key).contains(context.locale) ||
(settingsProvider.forcedLocale == null &&
context.deviceLocale != context.locale)) {
settingsProvider.resetLocaleSafe(context);
}
}
WidgetsBinding.instance.addPostFrameCallback((_) {
notifs.checkLaunchByNotif();
});
return WithForegroundTask(
child: DynamicColorBuilder(
builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
// Decide on a colour/brightness scheme based on OS and user settings
ColorScheme lightColorScheme;
ColorScheme darkColorScheme;
if (lightDynamic != null &&
darkDynamic != null &&
settingsProvider.useMaterialYou) {
lightColorScheme = lightDynamic.harmonized();
darkColorScheme = darkDynamic.harmonized();
} else {
lightColorScheme = ColorScheme.fromSeed(
seedColor: settingsProvider.themeColor,
);
darkColorScheme = ColorScheme.fromSeed(
seedColor: settingsProvider.themeColor,
brightness: Brightness.dark,
);
}
// set the background and surface colors to pure black in the amoled theme
if (settingsProvider.useBlackTheme) {
darkColorScheme = darkColorScheme
.copyWith(surface: Colors.black)
.harmonized();
}
if (settingsProvider.useSystemFont) NativeFeatures.loadSystemFont();
return MaterialApp(
title: 'Obtainium',
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
navigatorKey: globalNavigatorKey,
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
colorScheme: settingsProvider.theme == ThemeSettings.dark
? darkColorScheme
: lightColorScheme,
fontFamily: settingsProvider.useSystemFont
? 'SystemFont'
: 'Montserrat',
),
darkTheme: ThemeData(
useMaterial3: true,
colorScheme: settingsProvider.theme == ThemeSettings.light
? lightColorScheme
: darkColorScheme,
fontFamily: settingsProvider.useSystemFont
? 'SystemFont'
: 'Montserrat',
),
home: Shortcuts(
shortcuts: <LogicalKeySet, Intent>{
LogicalKeySet(LogicalKeyboardKey.select):
const ActivateIntent(),
},
child: const HomePage(),
),
);
},
),
);
}
}

6
lib/main_fdroid.dart Normal file
View file

@ -0,0 +1,6 @@
import 'main.dart' as m;
void main() async {
m.fdroid = true;
m.main();
}

View file

@ -0,0 +1,67 @@
import 'dart:convert';
import 'package:easy_localization/easy_localization.dart';
import 'package:http/http.dart';
import 'package:obtainium/app_sources/github.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/source_provider.dart';
class GitHubStars implements MassAppUrlSource {
@override
late String name = tr('githubStarredRepos');
@override
late List<String> requiredArgs = [tr('uname')];
Future<Map<String, List<String>>> getOnePageOfUserStarredUrlsWithDescriptions(
String username,
int page,
) async {
Response res = await get(
Uri.parse(
'https://api.github.com/users/$username/starred?per_page=100&page=$page',
),
headers: await GitHub().getRequestHeaders({}),
);
if (res.statusCode == 200) {
Map<String, List<String>> urlsWithDescriptions = {};
for (var e in (jsonDecode(res.body) as List<dynamic>)) {
urlsWithDescriptions.addAll({
e['html_url'] as String: [
e['full_name'] as String,
e['description'] != null
? e['description'] as String
: tr('noDescription'),
],
});
}
return urlsWithDescriptions;
} else {
var gh = GitHub();
gh.rateLimitErrorCheck(res);
throw getObtainiumHttpError(res);
}
}
@override
Future<Map<String, List<String>>> getUrlsWithDescriptions(
List<String> args,
) async {
if (args.length != requiredArgs.length) {
throw ObtainiumError(tr('wrongArgNum'));
}
Map<String, List<String>> urlsWithDescriptions = {};
var page = 1;
while (true) {
var pageUrls = await getOnePageOfUserStarredUrlsWithDescriptions(
args[0],
page++,
);
urlsWithDescriptions.addAll(pageUrls);
if (pageUrls.length < 100) {
break;
}
}
return urlsWithDescriptions;
}
}

771
lib/pages/add_app.dart Normal file
View file

@ -0,0 +1,771 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:obtainium/components/custom_app_bar.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:obtainium/components/generated_form_modal.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/main.dart';
import 'package:obtainium/pages/app.dart';
import 'package:obtainium/pages/import_export.dart';
import 'package:obtainium/pages/settings.dart';
import 'package:obtainium/providers/apps_provider.dart';
import 'package:obtainium/providers/notifications_provider.dart';
import 'package:obtainium/providers/settings_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher_string.dart';
class AddAppPage extends StatefulWidget {
const AddAppPage({super.key});
@override
State<AddAppPage> createState() => AddAppPageState();
}
class AddAppPageState extends State<AddAppPage> {
bool gettingAppInfo = false;
bool searching = false;
String userInput = '';
String searchQuery = '';
String? pickedSourceOverride;
String? previousPickedSourceOverride;
AppSource? pickedSource;
Map<String, dynamic> additionalSettings = {};
bool additionalSettingsValid = true;
bool inferAppIdIfOptional = true;
List<String> pickedCategories = [];
int urlInputKey = 0;
SourceProvider sourceProvider = SourceProvider();
void linkFn(String input) {
try {
if (input.isEmpty) {
throw UnsupportedURLError();
}
sourceProvider.getSource(input);
changeUserInput(input, true, false, updateUrlInput: true);
} catch (e) {
showError(e, context);
}
}
void changeUserInput(
String input,
bool valid,
bool isBuilding, {
bool updateUrlInput = false,
String? overrideSource,
}) {
userInput = input;
if (!isBuilding) {
setState(() {
if (overrideSource != null) {
pickedSourceOverride = overrideSource;
}
bool overrideChanged =
pickedSourceOverride != previousPickedSourceOverride;
previousPickedSourceOverride = pickedSourceOverride;
if (updateUrlInput) {
urlInputKey++;
}
var prevHost = pickedSource?.hosts.isNotEmpty == true
? pickedSource?.hosts[0]
: null;
var source = valid
? sourceProvider.getSource(
userInput,
overrideSource: pickedSourceOverride,
)
: null;
if (pickedSource.runtimeType != source.runtimeType ||
overrideChanged ||
(prevHost != null && prevHost != source?.hosts[0])) {
pickedSource = source;
pickedSource?.runOnAddAppInputChange(userInput);
additionalSettings = source != null
? getDefaultValuesFromFormItems(
source.combinedAppSpecificSettingFormItems,
)
: {};
additionalSettingsValid = source != null
? !sourceProvider.ifRequiredAppSpecificSettingsExist(source)
: true;
inferAppIdIfOptional = true;
}
});
}
}
@override
Widget build(BuildContext context) {
AppsProvider appsProvider = context.read<AppsProvider>();
SettingsProvider settingsProvider = context.watch<SettingsProvider>();
NotificationsProvider notificationsProvider = context
.read<NotificationsProvider>();
bool doingSomething = gettingAppInfo || searching;
Future<bool> getTrackOnlyConfirmationIfNeeded(
bool userPickedTrackOnly, {
bool ignoreHideSetting = false,
}) async {
var useTrackOnly = userPickedTrackOnly || pickedSource!.enforceTrackOnly;
if (useTrackOnly &&
(!settingsProvider.hideTrackOnlyWarning || ignoreHideSetting)) {
// ignore: use_build_context_synchronously
var values = await showDialog(
context: context,
builder: (BuildContext ctx) {
return GeneratedFormModal(
initValid: true,
title: tr(
'xIsTrackOnly',
args: [
pickedSource!.enforceTrackOnly ? tr('source') : tr('app'),
],
),
items: [
[GeneratedFormSwitch('hide', label: tr('dontShowAgain'))],
],
message:
'${pickedSource!.enforceTrackOnly ? tr('appsFromSourceAreTrackOnly') : tr('youPickedTrackOnly')}\n\n${tr('trackOnlyAppDescription')}',
);
},
);
if (values != null) {
settingsProvider.hideTrackOnlyWarning = values['hide'] == true;
}
return useTrackOnly && values != null;
} else {
return true;
}
}
getReleaseDateAsVersionConfirmationIfNeeded(
bool userPickedTrackOnly,
) async {
return (!(additionalSettings['releaseDateAsVersion'] == true &&
// ignore: use_build_context_synchronously
await showDialog(
context: context,
builder: (BuildContext ctx) {
return GeneratedFormModal(
title: tr('releaseDateAsVersion'),
items: const [],
message: tr('releaseDateAsVersionExplanation'),
);
},
) ==
null));
}
addApp({bool resetUserInputAfter = false}) async {
setState(() {
gettingAppInfo = true;
});
try {
var userPickedTrackOnly = additionalSettings['trackOnly'] == true;
App? app;
if ((await getTrackOnlyConfirmationIfNeeded(userPickedTrackOnly)) &&
(await getReleaseDateAsVersionConfirmationIfNeeded(
userPickedTrackOnly,
))) {
var trackOnly = pickedSource!.enforceTrackOnly || userPickedTrackOnly;
app = await sourceProvider.getApp(
pickedSource!,
userInput.trim(),
additionalSettings,
trackOnlyOverride: trackOnly,
sourceIsOverriden: pickedSourceOverride != null,
inferAppIdIfOptional: inferAppIdIfOptional,
);
// Only download the APK here if you need to for the package ID
if (isTempId(app) && app.additionalSettings['trackOnly'] != true) {
// ignore: use_build_context_synchronously
var apkUrl = await appsProvider.confirmAppFileUrl(
app,
context,
false,
);
if (apkUrl == null) {
throw ObtainiumError(tr('cancelled'));
}
app.preferredApkIndex = app.apkUrls
.map((e) => e.value)
.toList()
.indexOf(apkUrl.value);
// ignore: use_build_context_synchronously
var downloadedArtifact = await appsProvider.downloadApp(
app,
globalNavigatorKey.currentContext,
notificationsProvider: notificationsProvider,
);
DownloadedApk? downloadedFile;
DownloadedDir? downloadedDir;
if (downloadedArtifact is DownloadedApk) {
downloadedFile = downloadedArtifact;
} else {
downloadedDir = downloadedArtifact as DownloadedDir;
}
app.id = downloadedFile?.appId ?? downloadedDir!.appId;
}
if (appsProvider.apps.containsKey(app.id)) {
throw ObtainiumError(tr('appAlreadyAdded'));
}
if (app.additionalSettings['trackOnly'] == true ||
app.additionalSettings['versionDetection'] != true) {
app.installedVersion = app.latestVersion;
}
app.categories = pickedCategories;
await appsProvider.saveApps([app], onlyIfExists: false);
}
if (app != null) {
Navigator.push(
globalNavigatorKey.currentContext ?? context,
MaterialPageRoute(builder: (context) => AppPage(appId: app!.id)),
);
}
} catch (e) {
showError(e, context);
} finally {
setState(() {
gettingAppInfo = false;
if (resetUserInputAfter) {
changeUserInput('', false, true);
}
});
}
}
Widget getUrlInputRow() => Row(
children: [
Expanded(
child: GeneratedForm(
key: Key(urlInputKey.toString()),
items: [
[
GeneratedFormTextField(
'appSourceURL',
label: tr('appSourceURL'),
defaultValue: userInput,
additionalValidators: [
(value) {
try {
sourceProvider
.getSource(
value ?? '',
overrideSource: pickedSourceOverride,
)
.standardizeUrl(value ?? '');
} catch (e) {
return e is String
? e
: e is ObtainiumError
? e.toString()
: tr('error');
}
return null;
},
],
),
],
],
onValueChanges: (values, valid, isBuilding) {
changeUserInput(values['appSourceURL']!, valid, isBuilding);
},
),
),
const SizedBox(width: 16),
gettingAppInfo
? const CircularProgressIndicator()
: ElevatedButton(
onPressed:
doingSomething ||
pickedSource == null ||
(pickedSource!
.combinedAppSpecificSettingFormItems
.isNotEmpty &&
!additionalSettingsValid)
? null
: () {
HapticFeedback.selectionClick();
addApp();
},
child: Text(tr('add')),
),
],
);
runSearch({bool filtered = true}) async {
setState(() {
searching = true;
});
var sourceStrings = <String, List<String>>{};
sourceProvider.sources.where((e) => e.canSearch).forEach((s) {
sourceStrings[s.name] = [s.name];
});
try {
var searchSources =
await showDialog<List<String>?>(
context: context,
builder: (BuildContext ctx) {
return SelectionModal(
title: tr(
'selectX',
args: [plural('source', 2).toLowerCase()],
),
entries: sourceStrings,
selectedByDefault: true,
onlyOneSelectionAllowed: false,
titlesAreLinks: false,
deselectThese: settingsProvider.searchDeselected,
);
},
) ??
[];
if (searchSources.isNotEmpty) {
settingsProvider.searchDeselected = sourceStrings.keys
.where((s) => !searchSources.contains(s))
.toList();
List<MapEntry<String, Map<String, List<String>>>?>
results = (await Future.wait(
sourceProvider.sources
.where((e) => searchSources.contains(e.name))
.map((e) async {
try {
Map<String, dynamic>? querySettings = {};
if (e.includeAdditionalOptsInMainSearch) {
querySettings = await showDialog<Map<String, dynamic>?>(
context: context,
builder: (BuildContext ctx) {
return GeneratedFormModal(
title: tr('searchX', args: [e.name]),
items: [
...e.searchQuerySettingFormItems.map((e) => [e]),
[
GeneratedFormTextField(
'url',
label: e.hosts.isNotEmpty
? tr('overrideSource')
: plural('url', 1).substring(2),
autoCompleteOptions: [
...(e.hosts.isNotEmpty ? [e.hosts[0]] : []),
...appsProvider.apps.values
.where(
(a) =>
sourceProvider
.getSource(
a.app.url,
overrideSource:
a.app.overrideSource,
)
.runtimeType ==
e.runtimeType,
)
.map((a) {
var uri = Uri.parse(a.app.url);
return '${uri.origin}${uri.path}';
}),
],
defaultValue: e.hosts.isNotEmpty
? e.hosts[0]
: '',
required: true,
),
],
],
);
},
);
if (querySettings == null) {
return null;
}
}
return MapEntry(
e.runtimeType.toString(),
await e.search(searchQuery, querySettings: querySettings),
);
} catch (err) {
if (err is! CredsNeededError) {
rethrow;
} else {
err.unexpected = true;
showError(err, context);
return null;
}
}
}),
)).where((a) => a != null).toList();
// Interleave results instead of simple reduce
Map<String, MapEntry<String, List<String>>> res = {};
var si = 0;
var done = false;
while (!done) {
done = true;
for (var r in results) {
var sourceName = r!.key;
if (r.value.length > si) {
done = false;
var singleRes = r.value.entries.elementAt(si);
res[singleRes.key] = MapEntry(sourceName, singleRes.value);
}
}
si++;
}
if (res.isEmpty) {
throw ObtainiumError(tr('noResults'));
}
List<String>? selectedUrls = res.isEmpty
? []
// ignore: use_build_context_synchronously
: await showDialog<List<String>?>(
context: context,
builder: (BuildContext ctx) {
return SelectionModal(
entries: res.map((k, v) => MapEntry(k, v.value)),
selectedByDefault: false,
onlyOneSelectionAllowed: true,
);
},
);
if (selectedUrls != null && selectedUrls.isNotEmpty) {
var sourceName = res[selectedUrls[0]]?.key;
changeUserInput(
selectedUrls[0],
true,
false,
updateUrlInput: true,
overrideSource: sourceName,
);
}
}
} catch (e) {
showError(e, context);
} finally {
setState(() {
searching = false;
});
}
}
Widget getHTMLSourceOverrideDropdown() => Column(
children: [
Row(
children: [
Expanded(
child: GeneratedForm(
items: [
[
GeneratedFormDropdown(
'overrideSource',
defaultValue: pickedSourceOverride ?? '',
[
MapEntry('', tr('none')),
...sourceProvider.sources
.where(
(s) =>
s.allowOverride ||
(pickedSource != null &&
pickedSource.runtimeType ==
s.runtimeType),
)
.map(
(s) => MapEntry(s.runtimeType.toString(), s.name),
),
],
label: tr('overrideSource'),
),
],
],
onValueChanges: (values, valid, isBuilding) {
fn() {
pickedSourceOverride =
(values['overrideSource'] == null ||
values['overrideSource'] == '')
? null
: values['overrideSource'];
}
if (!isBuilding) {
setState(() {
fn();
});
} else {
fn();
}
changeUserInput(userInput, valid, isBuilding);
},
),
),
],
),
const SizedBox(height: 16),
],
);
bool shouldShowSearchBar() =>
sourceProvider.sources.where((e) => e.canSearch).isNotEmpty &&
pickedSource == null &&
userInput.isEmpty;
Widget getSearchBarRow() => Row(
children: [
Expanded(
child: GeneratedForm(
items: [
[
GeneratedFormTextField(
'searchSomeSources',
label: tr('searchSomeSourcesLabel'),
required: false,
),
],
],
onValueChanges: (values, valid, isBuilding) {
if (values.isNotEmpty && valid && !isBuilding) {
setState(() {
searchQuery = values['searchSomeSources']!.trim();
});
}
},
),
),
const SizedBox(width: 16),
searching
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: searchQuery.isEmpty || doingSomething
? null
: () {
runSearch();
},
child: Text(tr('search')),
),
],
);
Widget getAdditionalOptsCol() => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 16),
Text(
tr('additionalOptsFor', args: [pickedSource?.name ?? tr('source')]),
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
GeneratedForm(
key: Key(
'${pickedSource.runtimeType.toString()}-${pickedSource?.hostChanged.toString()}-${pickedSource?.hostIdenticalDespiteAnyChange.toString()}',
),
items: [
...pickedSource!.combinedAppSpecificSettingFormItems,
...(pickedSourceOverride != null
? pickedSource!.sourceConfigSettingFormItems.map((e) => [e])
: []),
],
onValueChanges: (values, valid, isBuilding) {
if (!isBuilding) {
setState(() {
additionalSettings = values;
additionalSettingsValid = valid;
});
}
},
),
Column(
children: [
const SizedBox(height: 16),
CategoryEditorSelector(
alignment: WrapAlignment.start,
onSelected: (categories) {
pickedCategories = categories;
},
),
],
),
if (pickedSource != null && pickedSource!.appIdInferIsOptional)
GeneratedForm(
key: const Key('inferAppIdIfOptional'),
items: [
[
GeneratedFormSwitch(
'inferAppIdIfOptional',
label: tr('tryInferAppIdFromCode'),
defaultValue: inferAppIdIfOptional,
),
],
],
onValueChanges: (values, valid, isBuilding) {
if (!isBuilding) {
setState(() {
inferAppIdIfOptional = values['inferAppIdIfOptional'];
});
}
},
),
if (pickedSource != null && pickedSource!.enforceTrackOnly)
GeneratedForm(
key: Key(
'${pickedSource.runtimeType.toString()}-${pickedSource?.hostChanged.toString()}-${pickedSource?.hostIdenticalDespiteAnyChange.toString()}-appId',
),
items: [
[
GeneratedFormTextField(
'appId',
label: '${tr('appId')} - ${tr('custom')}',
required: false,
additionalValidators: [
(value) {
if (value == null || value.isEmpty) {
return null;
}
final isValid = RegExp(
r'^([A-Za-z]{1}[A-Za-z\d_]*\.)+[A-Za-z][A-Za-z\d_]*$',
).hasMatch(value);
if (!isValid) {
return tr('invalidInput');
}
return null;
},
],
),
],
],
onValueChanges: (values, valid, isBuilding) {
if (!isBuilding) {
setState(() {
additionalSettings['appId'] = values['appId'];
});
}
},
),
],
);
Widget getSourcesListWidget() => Padding(
padding: const EdgeInsets.all(16),
child: Wrap(
direction: Axis.horizontal,
alignment: WrapAlignment.spaceBetween,
spacing: 12,
children: [
GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (context) {
return GeneratedFormModal(
singleNullReturnButton: tr('ok'),
title: tr('supportedSources'),
items: const [],
additionalWidgets: [
...sourceProvider.sources.map(
(e) => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: GestureDetector(
onTap: e.hosts.isNotEmpty
? () {
launchUrlString(
'https://${e.hosts[0]}',
mode: LaunchMode.externalApplication,
);
}
: null,
child: Text(
'${e.name}${e.enforceTrackOnly ? ' ${tr('trackOnlyInBrackets')}' : ''}${e.canSearch ? ' ${tr('searchableInBrackets')}' : ''}',
style: TextStyle(
decoration: e.hosts.isNotEmpty
? TextDecoration.underline
: TextDecoration.none,
),
),
),
),
),
const SizedBox(height: 16),
Text(
'${tr('note')}:',
style: const TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
Text(tr('selfHostedNote', args: [tr('overrideSource')])),
],
);
},
);
},
child: Text(
tr('supportedSources'),
style: const TextStyle(
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline,
fontStyle: FontStyle.italic,
),
),
),
GestureDetector(
onTap: () {
launchUrlString(
'https://apps.obtainium.imranr.dev/',
mode: LaunchMode.externalApplication,
);
},
child: Text(
tr('crowdsourcedConfigsShort'),
style: const TextStyle(
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline,
fontStyle: FontStyle.italic,
),
),
),
],
),
);
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.surface,
bottomNavigationBar: pickedSource == null ? getSourcesListWidget() : null,
body: CustomScrollView(
shrinkWrap: true,
slivers: <Widget>[
CustomAppBar(title: tr('addApp')),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
getUrlInputRow(),
const SizedBox(height: 16),
if (pickedSource != null) getHTMLSourceOverrideDropdown(),
if (shouldShowSearchBar()) getSearchBarRow(),
if (pickedSource != null)
FutureBuilder(
builder: (ctx, val) {
return val.data != null && val.data!.isNotEmpty
? Text(
val.data!,
style: Theme.of(context).textTheme.bodySmall,
)
: const SizedBox();
},
future: pickedSource?.getSourceNote(),
),
if (pickedSource != null) getAdditionalOptsCol(),
],
),
),
),
],
),
);
}
}

695
lib/pages/app.dart Normal file
View file

@ -0,0 +1,695 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:obtainium/components/generated_form_modal.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/main.dart';
import 'package:obtainium/pages/apps.dart';
import 'package:obtainium/pages/settings.dart';
import 'package:obtainium/providers/apps_provider.dart';
import 'package:obtainium/providers/settings_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:provider/provider.dart';
import 'package:markdown/markdown.dart' as md;
class AppPage extends StatefulWidget {
const AppPage({
super.key,
required this.appId,
this.showOppositeOfPreferredView = false,
});
final String appId;
final bool showOppositeOfPreferredView;
@override
State<AppPage> createState() => _AppPageState();
}
class _AppPageState extends State<AppPage> {
late final WebViewController _webViewController;
bool _wasWebViewOpened = false;
AppInMemory? prevApp;
bool updating = false;
@override
void initState() {
super.initState();
_webViewController = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(
onWebResourceError: (WebResourceError error) {
if (error.isForMainFrame == true) {
showError(
ObtainiumError(error.description, unexpected: true),
context,
);
}
},
onNavigationRequest: (NavigationRequest request) =>
!(request.url.startsWith("http://") ||
request.url.startsWith("https://") ||
request.url.startsWith("ftp://") ||
request.url.startsWith("ftps://"))
? NavigationDecision.prevent
: NavigationDecision.navigate,
),
);
}
@override
Widget build(BuildContext context) {
var appsProvider = context.watch<AppsProvider>();
var settingsProvider = context.watch<SettingsProvider>();
var showAppWebpageFinal =
(settingsProvider.showAppWebpage &&
!widget.showOppositeOfPreferredView) ||
(!settingsProvider.showAppWebpage &&
widget.showOppositeOfPreferredView);
getUpdate(String id, {bool resetVersion = false}) async {
try {
setState(() {
updating = true;
});
await appsProvider.checkUpdate(id);
if (resetVersion) {
appsProvider.apps[id]?.app.additionalSettings['versionDetection'] =
true;
if (appsProvider.apps[id]?.app.installedVersion != null) {
appsProvider.apps[id]?.app.installedVersion =
appsProvider.apps[id]?.app.latestVersion;
}
appsProvider.saveApps([appsProvider.apps[id]!.app]);
}
} catch (err) {
// ignore: use_build_context_synchronously
showError(err, context);
} finally {
setState(() {
updating = false;
});
}
}
bool areDownloadsRunning = appsProvider.areDownloadsRunning();
var sourceProvider = SourceProvider();
AppInMemory? app = appsProvider.apps[widget.appId]?.deepCopy();
var source = app != null
? sourceProvider.getSource(
app.app.url,
overrideSource: app.app.overrideSource,
)
: null;
if (!areDownloadsRunning &&
prevApp == null &&
app != null &&
settingsProvider.checkUpdateOnDetailPage) {
prevApp = app;
getUpdate(app.app.id);
}
var trackOnly = app?.app.additionalSettings['trackOnly'] == true;
bool isVersionDetectionStandard =
app?.app.additionalSettings['versionDetection'] == true;
bool installedVersionIsEstimate = app?.app != null
? isVersionPseudo(app!.app)
: false;
if (app != null && !_wasWebViewOpened) {
_wasWebViewOpened = true;
_webViewController.loadRequest(Uri.parse(app.app.url));
}
getInfoColumn() {
String versionLines = '';
bool installed = app?.app.installedVersion != null;
bool upToDate = app?.app.installedVersion == app?.app.latestVersion;
if (installed) {
versionLines = '${app?.app.installedVersion} ${tr('installed')}';
if (upToDate) {
versionLines += '/${tr('latest')}';
}
} else {
versionLines = tr('notInstalled');
}
if (!upToDate) {
versionLines += '\n${app?.app.latestVersion} ${tr('latest')}';
}
String infoLines = tr(
'lastUpdateCheckX',
args: [
app?.app.lastUpdateCheck == null
? tr('never')
: '${app?.app.lastUpdateCheck?.toLocal()}',
],
);
if (trackOnly) {
infoLines = '${tr('xIsTrackOnly', args: [tr('app')])}\n$infoLines';
}
if (installedVersionIsEstimate) {
infoLines = '${tr('pseudoVersionInUse')}\n$infoLines';
}
if ((app?.app.apkUrls.length ?? 0) > 0) {
infoLines =
'$infoLines\n${app?.app.apkUrls.length == 1 ? app?.app.apkUrls[0].key : plural('apk', app?.app.apkUrls.length ?? 0)}';
}
var changeLogFn = app != null ? getChangeLogFn(context, app.app) : null;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 24),
child: Column(
children: [
const SizedBox(height: 8),
Text(
versionLines,
textAlign: TextAlign.start,
style: Theme.of(
context,
).textTheme.bodyLarge!.copyWith(fontWeight: FontWeight.bold),
),
changeLogFn != null || app?.app.releaseDate != null
? GestureDetector(
onTap: changeLogFn,
child: Text(
app?.app.releaseDate == null
? tr('changes')
: app!.app.releaseDate!.toLocal().toString(),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.labelSmall!
.copyWith(
decoration: changeLogFn != null
? TextDecoration.underline
: null,
fontStyle: changeLogFn != null
? FontStyle.italic
: null,
),
),
)
: const SizedBox.shrink(),
const SizedBox(height: 8),
],
),
),
Text(
infoLines,
textAlign: TextAlign.center,
style: const TextStyle(fontStyle: FontStyle.italic, fontSize: 12),
),
if (app?.app.apkUrls.isNotEmpty == true ||
app?.app.otherAssetUrls.isNotEmpty == true)
GestureDetector(
onTap: app?.app == null || updating
? null
: () async {
try {
await appsProvider.downloadAppAssets([
app!.app.id,
], context);
} catch (e) {
showError(e, context);
}
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: settingsProvider.highlightTouchTargets
? (Theme.of(context).brightness == Brightness.light
? Theme.of(context).primaryColor
: Theme.of(context).primaryColorLight)
.withAlpha(
Theme.of(context).brightness ==
Brightness.light
? 20
: 40,
)
: null,
),
padding: settingsProvider.highlightTouchTargets
? const EdgeInsetsDirectional.fromSTEB(12, 6, 12, 6)
: const EdgeInsetsDirectional.fromSTEB(0, 6, 0, 6),
margin: const EdgeInsetsDirectional.fromSTEB(0, 6, 0, 0),
child: Text(
tr(
'downloadX',
args: [lowerCaseIfEnglish(tr('releaseAsset'))],
),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.labelSmall!.copyWith(
decoration: TextDecoration.underline,
fontStyle: FontStyle.italic,
),
),
),
],
),
),
const SizedBox(height: 48),
CategoryEditorSelector(
alignment: WrapAlignment.center,
preselected: app?.app.categories != null
? app!.app.categories.toSet()
: {},
onSelected: (categories) {
if (app != null) {
app.app.categories = categories;
appsProvider.saveApps([app.app]);
}
},
),
if (app?.app.additionalSettings['about'] is String &&
app?.app.additionalSettings['about'].isNotEmpty)
Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 48),
GestureDetector(
onLongPress: () {
Clipboard.setData(
ClipboardData(
text: app?.app.additionalSettings['about'] ?? '',
),
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(tr('copiedToClipboard'))),
);
},
child: Markdown(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
styleSheet: MarkdownStyleSheet(
blockquoteDecoration: BoxDecoration(
color: Theme.of(context).cardColor,
),
textAlign: WrapAlignment.center,
),
data: app?.app.additionalSettings['about'],
onTapLink: (text, href, title) {
if (href != null) {
launchUrlString(
href,
mode: LaunchMode.externalApplication,
);
}
},
extensionSet: md.ExtensionSet(
md.ExtensionSet.gitHubFlavored.blockSyntaxes,
[
md.EmojiSyntax(),
...md.ExtensionSet.gitHubFlavored.inlineSyntaxes,
],
),
),
),
],
),
],
);
}
getFullInfoColumn({bool small = false}) => Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(height: small ? 5 : 20),
FutureBuilder(
future: appsProvider.updateAppIcon(app?.app.id, ignoreCache: true),
builder: (ctx, val) {
return app?.icon != null
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
onTap: app == null
? null
: () => pm.openApp(app.app.id),
child: Image.memory(
app!.icon!,
height: small ? 70 : 150,
gaplessPlayback: true,
),
),
],
)
: Container();
},
),
SizedBox(height: small ? 10 : 25),
Text(
app?.name ?? tr('app'),
textAlign: TextAlign.center,
style: small
? Theme.of(context).textTheme.displaySmall
: Theme.of(context).textTheme.displayLarge,
),
Text(
tr('byX', args: [app?.author ?? tr('unknown')]),
textAlign: TextAlign.center,
style: small
? Theme.of(context).textTheme.headlineSmall
: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 24),
GestureDetector(
onTap: () {
if (app?.app.url != null) {
launchUrlString(
app?.app.url ?? '',
mode: LaunchMode.externalApplication,
);
}
},
onLongPress: () {
Clipboard.setData(ClipboardData(text: app?.app.url ?? ''));
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(tr('copiedToClipboard'))));
},
child: Text(
app?.app.url ?? '',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.labelSmall!.copyWith(
decoration: TextDecoration.underline,
fontStyle: FontStyle.italic,
),
),
),
Text(
app?.app.id ?? '',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.labelSmall,
),
getInfoColumn(),
const SizedBox(height: 150),
],
);
getAppWebView() => app != null
? WebViewWidget(
key: ObjectKey(_webViewController),
controller: _webViewController
..setBackgroundColor(Theme.of(context).colorScheme.surface),
)
: Container();
showMarkUpdatedDialog() {
return showDialog(
context: context,
builder: (BuildContext ctx) {
return AlertDialog(
title: Text(tr('alreadyUpToDateQuestion')),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(tr('no')),
),
TextButton(
onPressed: () {
HapticFeedback.selectionClick();
var updatedApp = app?.app;
if (updatedApp != null) {
updatedApp.installedVersion = updatedApp.latestVersion;
appsProvider.saveApps([updatedApp]);
}
Navigator.of(context).pop();
},
child: Text(tr('yesMarkUpdated')),
),
],
);
},
);
}
showAdditionalOptionsDialog() async {
return await showDialog<Map<String, dynamic>?>(
context: context,
builder: (BuildContext ctx) {
var items = (source?.combinedAppSpecificSettingFormItems ?? []).map((
row,
) {
row = row.map((e) {
if (app?.app.additionalSettings[e.key] != null) {
e.defaultValue = app?.app.additionalSettings[e.key];
}
return e;
}).toList();
return row;
}).toList();
return GeneratedFormModal(
title: tr('additionalOptions'),
items: items,
);
},
);
}
handleAdditionalOptionChanges(Map<String, dynamic>? values) {
if (app != null && values != null) {
Map<String, dynamic> originalSettings = app.app.additionalSettings;
app.app.additionalSettings = values;
if (source?.enforceTrackOnly == true) {
app.app.additionalSettings['trackOnly'] = true;
// ignore: use_build_context_synchronously
showMessage(tr('appsFromSourceAreTrackOnly'), context);
}
var versionDetectionEnabled =
app.app.additionalSettings['versionDetection'] == true &&
originalSettings['versionDetection'] != true;
var releaseDateVersionEnabled =
app.app.additionalSettings['releaseDateAsVersion'] == true &&
originalSettings['releaseDateAsVersion'] != true;
var releaseDateVersionDisabled =
app.app.additionalSettings['releaseDateAsVersion'] != true &&
originalSettings['releaseDateAsVersion'] == true;
if (releaseDateVersionEnabled) {
if (app.app.releaseDate != null) {
bool isUpdated = app.app.installedVersion == app.app.latestVersion;
app.app.latestVersion = app.app.releaseDate!.microsecondsSinceEpoch
.toString();
if (isUpdated) {
app.app.installedVersion = app.app.latestVersion;
}
}
} else if (releaseDateVersionDisabled) {
app.app.installedVersion =
app.installedInfo?.versionName ?? app.app.installedVersion;
}
if (versionDetectionEnabled) {
app.app.additionalSettings['versionDetection'] = true;
app.app.additionalSettings['releaseDateAsVersion'] = false;
}
appsProvider.saveApps([app.app]).then((value) {
getUpdate(app.app.id, resetVersion: versionDetectionEnabled);
});
}
}
getInstallOrUpdateButton() => TextButton(
onPressed:
!updating &&
(app?.app.installedVersion == null ||
app?.app.installedVersion != app?.app.latestVersion) &&
!areDownloadsRunning
? () async {
try {
var successMessage = app?.app.installedVersion == null
? tr('installed')
: tr('appsUpdated');
HapticFeedback.heavyImpact();
var res = await appsProvider.downloadAndInstallLatestApps(
app?.app.id != null ? [app!.app.id] : [],
globalNavigatorKey.currentContext,
);
if (res.isNotEmpty && !trackOnly) {
// ignore: use_build_context_synchronously
showMessage(successMessage, context);
}
if (res.isNotEmpty && mounted) {
Navigator.of(context).pop();
}
} catch (e) {
// ignore: use_build_context_synchronously
showError(e, context);
}
}
: null,
child: Text(
app?.app.installedVersion == null
? !trackOnly
? tr('install')
: tr('markInstalled')
: !trackOnly
? tr('update')
: tr('markUpdated'),
),
);
getBottomSheetMenu() => Padding(
padding: EdgeInsets.fromLTRB(
0,
0,
0,
MediaQuery.of(context).padding.bottom,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
if (source != null &&
source.combinedAppSpecificSettingFormItems.isNotEmpty)
IconButton(
onPressed: app?.downloadProgress != null || updating
? null
: () async {
var values = await showAdditionalOptionsDialog();
handleAdditionalOptionChanges(values);
},
tooltip: tr('additionalOptions'),
icon: const Icon(Icons.edit),
),
if (app != null && app.installedInfo != null)
IconButton(
onPressed: () {
appsProvider.openAppSettings(app.app.id);
},
icon: const Icon(Icons.settings),
tooltip: tr('settings'),
),
if (app != null && showAppWebpageFinal)
IconButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext ctx) {
return AlertDialog(
scrollable: true,
content: getFullInfoColumn(small: true),
title: Text(app.name),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(tr('continue')),
),
],
);
},
);
},
icon: const Icon(Icons.more_horiz),
tooltip: tr('more'),
),
if (app?.app.installedVersion != null &&
app?.app.installedVersion != app?.app.latestVersion &&
!isVersionDetectionStandard &&
!trackOnly)
IconButton(
onPressed: app?.downloadProgress != null || updating
? null
: showMarkUpdatedDialog,
tooltip: tr('markUpdated'),
icon: const Icon(Icons.done),
),
if ((!isVersionDetectionStandard || trackOnly) &&
app?.app.installedVersion != null &&
app?.app.installedVersion == app?.app.latestVersion)
IconButton(
onPressed: app?.app == null || updating
? null
: () {
app!.app.installedVersion = null;
appsProvider.saveApps([app.app]);
},
icon: const Icon(Icons.restore_rounded),
tooltip: tr('resetInstallStatus'),
),
const SizedBox(width: 16.0),
Expanded(child: getInstallOrUpdateButton()),
const SizedBox(width: 16.0),
IconButton(
onPressed: app?.downloadProgress != null || updating
? null
: () {
appsProvider
.removeAppsWithModal(
context,
app != null ? [app.app] : [],
)
.then((value) {
if (value == true) {
Navigator.of(context).pop();
}
});
},
tooltip: tr('remove'),
icon: const Icon(Icons.delete_outline),
),
],
),
),
if (app?.downloadProgress != null)
Padding(
padding: const EdgeInsets.fromLTRB(0, 8, 0, 0),
child: LinearProgressIndicator(
value: app!.downloadProgress! >= 0
? app.downloadProgress! / 100
: null,
),
),
],
),
);
appScreenAppBar() => AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
},
),
);
return Scaffold(
appBar: showAppWebpageFinal ? AppBar() : appScreenAppBar(),
backgroundColor: Theme.of(context).colorScheme.surface,
body: RefreshIndicator(
child: showAppWebpageFinal
? getAppWebView()
: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: Column(children: [getFullInfoColumn()]),
),
],
),
onRefresh: () async {
if (app != null) {
getUpdate(app.app.id);
}
},
),
bottomSheet: getBottomSheetMenu(),
);
}
}

1372
lib/pages/apps.dart Normal file

File diff suppressed because it is too large Load diff

351
lib/pages/home.dart Normal file
View file

@ -0,0 +1,351 @@
import 'dart:async';
import 'package:android_intent_plus/android_intent.dart';
import 'package:animations/animations.dart';
import 'package:app_links/app_links.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:obtainium/components/generated_form_modal.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/pages/add_app.dart';
import 'package:obtainium/pages/apps.dart';
import 'package:obtainium/pages/import_export.dart';
import 'package:obtainium/pages/settings.dart';
import 'package:obtainium/providers/apps_provider.dart';
import 'package:obtainium/providers/settings_provider.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher_string.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class NavigationPageItem {
late String title;
late IconData icon;
late Widget widget;
NavigationPageItem(this.title, this.icon, this.widget);
}
class _HomePageState extends State<HomePage> {
List<int> selectedIndexHistory = [];
bool isReversing = false;
int prevAppCount = -1;
bool prevIsLoading = true;
late AppLinks _appLinks;
StreamSubscription<Uri>? _linkSubscription;
bool isLinkActivity = false;
List<NavigationPageItem> pages = [
NavigationPageItem(
tr('appsString'),
Icons.apps,
AppsPage(key: GlobalKey<AppsPageState>()),
),
NavigationPageItem(
tr('addApp'),
Icons.add,
AddAppPage(key: GlobalKey<AddAppPageState>()),
),
NavigationPageItem(
tr('importExport'),
Icons.import_export,
const ImportExportPage(),
),
NavigationPageItem(tr('settings'), Icons.settings, const SettingsPage()),
];
@override
void initState() {
super.initState();
initDeepLinks();
WidgetsBinding.instance.addPostFrameCallback((_) async {
var sp = context.read<SettingsProvider>();
if (!sp.welcomeShown) {
await showDialog(
context: context,
builder: (BuildContext ctx) {
return AlertDialog(
title: Text(tr('welcome')),
content: Column(
mainAxisSize: MainAxisSize.min,
spacing: 20,
children: [
Text(tr('documentationLinksNote')),
GestureDetector(
onTap: () {
launchUrlString(
'https://github.com/ImranR98/Obtainium/blob/main/README.md',
mode: LaunchMode.externalApplication,
);
},
child: Text(
'https://github.com/ImranR98/Obtainium/blob/main/README.md',
style: const TextStyle(
decoration: TextDecoration.underline,
fontWeight: FontWeight.bold,
),
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(tr('batteryOptimizationNote')),
GestureDetector(
onTap: () {
final intent = AndroidIntent(
action:
'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS',
package:
obtainiumId, // Replace with your app's package name
);
intent.launch();
},
child: Text(
tr('settings'),
style: const TextStyle(
decoration: TextDecoration.underline,
fontWeight: FontWeight.bold,
),
),
),
],
),
],
),
actions: [
TextButton(
onPressed: () {
sp.welcomeShown = true;
Navigator.of(context).pop(null);
},
child: Text(tr('ok')),
),
],
);
},
);
}
});
}
Future<void> initDeepLinks() async {
_appLinks = AppLinks();
goToAddApp(String data) async {
switchToPage(1);
while ((pages[1].widget.key as GlobalKey<AddAppPageState>?)
?.currentState ==
null) {
await Future.delayed(const Duration(microseconds: 1));
}
(pages[1].widget.key as GlobalKey<AddAppPageState>?)?.currentState
?.linkFn(data);
}
interpretLink(Uri uri) async {
isLinkActivity = true;
var action = uri.host;
var data = uri.path.length > 1 ? uri.path.substring(1) : "";
try {
if (action == 'add') {
await goToAddApp(data);
} else if (action == 'app' || action == 'apps') {
var dataStr = Uri.decodeComponent(data);
if (await showDialog(
context: context,
builder: (BuildContext ctx) {
return GeneratedFormModal(
title: tr(
'importX',
args: [
(action == 'app' ? tr('app') : tr('appsString'))
.toLowerCase(),
],
),
items: const [],
additionalWidgets: [
ExpansionTile(
title: const Text('Raw JSON'),
children: [
Text(
dataStr,
style: const TextStyle(fontFamily: 'monospace'),
),
],
),
],
);
},
) !=
null) {
// ignore: use_build_context_synchronously
var appsProvider = context.read<AppsProvider>();
var result = await appsProvider.import(
action == 'app'
? '{ "apps": [$dataStr] }'
: '{ "apps": $dataStr }',
);
// ignore: use_build_context_synchronously
showMessage(
tr(
'importedX',
args: [plural('apps', result.key.length).toLowerCase()],
),
context,
);
}
} else {
throw ObtainiumError(tr('unknown'));
}
} catch (e) {
showError(e, context);
}
}
// Check initial link if app was in cold state (terminated)
final appLink = await _appLinks.getInitialLink();
var initLinked = false;
if (appLink != null) {
await interpretLink(appLink);
initLinked = true;
}
// Handle link when app is in warm state (front or background)
_linkSubscription = _appLinks.uriLinkStream.listen((uri) async {
if (!initLinked) {
await interpretLink(uri);
} else {
initLinked = false;
}
});
}
void setIsReversing(int targetIndex) {
bool reversing =
selectedIndexHistory.isNotEmpty &&
selectedIndexHistory.last > targetIndex;
setState(() {
isReversing = reversing;
});
}
Future<void> switchToPage(int index) async {
setIsReversing(index);
if (index == 0) {
while ((pages[0].widget.key as GlobalKey<AppsPageState>).currentState !=
null) {
// Avoid duplicate GlobalKey error
await Future.delayed(const Duration(microseconds: 1));
}
setState(() {
selectedIndexHistory.clear();
});
} else if (selectedIndexHistory.isEmpty ||
(selectedIndexHistory.isNotEmpty &&
selectedIndexHistory.last != index)) {
setState(() {
int existingInd = selectedIndexHistory.indexOf(index);
if (existingInd >= 0) {
selectedIndexHistory.removeAt(existingInd);
}
selectedIndexHistory.add(index);
});
}
}
@override
Widget build(BuildContext context) {
AppsProvider appsProvider = context.watch<AppsProvider>();
SettingsProvider settingsProvider = context.watch<SettingsProvider>();
if (!prevIsLoading &&
prevAppCount >= 0 &&
appsProvider.apps.length > prevAppCount &&
selectedIndexHistory.isNotEmpty &&
selectedIndexHistory.last == 1 &&
!isLinkActivity) {
switchToPage(0);
}
prevAppCount = appsProvider.apps.length;
prevIsLoading = appsProvider.loadingApps;
return WillPopScope(
child: Scaffold(
backgroundColor: Theme.of(context).colorScheme.surface,
body: PageTransitionSwitcher(
duration: Duration(
milliseconds: settingsProvider.disablePageTransitions ? 0 : 300,
),
reverse: settingsProvider.reversePageTransitions
? !isReversing
: isReversing,
transitionBuilder:
(
Widget child,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
return SharedAxisTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
transitionType: SharedAxisTransitionType.horizontal,
child: child,
);
},
child: pages
.elementAt(
selectedIndexHistory.isEmpty ? 0 : selectedIndexHistory.last,
)
.widget,
),
bottomNavigationBar: NavigationBar(
destinations: pages
.map(
(e) =>
NavigationDestination(icon: Icon(e.icon), label: e.title),
)
.toList(),
onDestinationSelected: (int index) async {
HapticFeedback.selectionClick();
switchToPage(index);
},
selectedIndex: selectedIndexHistory.isEmpty
? 0
: selectedIndexHistory.last,
),
),
onWillPop: () async {
if (isLinkActivity &&
selectedIndexHistory.length == 1 &&
selectedIndexHistory.last == 1) {
return true;
}
setIsReversing(
selectedIndexHistory.length >= 2
? selectedIndexHistory.reversed.toList()[1]
: 0,
);
if (selectedIndexHistory.isNotEmpty) {
setState(() {
selectedIndexHistory.removeLast();
});
return false;
}
return !(pages[0].widget.key as GlobalKey<AppsPageState>).currentState!
.clearSelected();
},
);
}
@override
void dispose() {
super.dispose();
_linkSubscription?.cancel();
}
}

View file

@ -0,0 +1,969 @@
import 'dart:convert';
import 'dart:io';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:obtainium/app_sources/fdroidrepo.dart';
import 'package:obtainium/components/custom_app_bar.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:obtainium/components/generated_form_modal.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/providers/apps_provider.dart';
import 'package:obtainium/providers/settings_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:provider/provider.dart';
import 'package:file_picker/file_picker.dart';
import 'package:url_launcher/url_launcher_string.dart';
class ImportExportPage extends StatefulWidget {
const ImportExportPage({super.key});
@override
State<ImportExportPage> createState() => _ImportExportPageState();
}
class _ImportExportPageState extends State<ImportExportPage> {
bool importInProgress = false;
@override
Widget build(BuildContext context) {
SourceProvider sourceProvider = SourceProvider();
var appsProvider = context.watch<AppsProvider>();
var settingsProvider = context.watch<SettingsProvider>();
var outlineButtonStyle = ButtonStyle(
shape: WidgetStateProperty.all(
StadiumBorder(
side: BorderSide(
width: 1,
color: Theme.of(context).colorScheme.primary,
),
),
),
);
urlListImport({String? initValue, bool overrideInitValid = false}) {
showDialog<Map<String, dynamic>?>(
context: context,
builder: (BuildContext ctx) {
return GeneratedFormModal(
initValid: overrideInitValid,
title: tr('importFromURLList'),
items: [
[
GeneratedFormTextField(
'appURLList',
defaultValue: initValue ?? '',
label: tr('appURLList'),
max: 7,
additionalValidators: [
(dynamic value) {
if (value != null && value.isNotEmpty) {
var lines = value.trim().split('\n');
for (int i = 0; i < lines.length; i++) {
try {
sourceProvider.getSource(lines[i]);
} catch (e) {
return '${tr('line')} ${i + 1}: $e';
}
}
}
return null;
},
],
),
],
],
);
},
).then((values) {
if (values != null) {
var urls = (values['appURLList'] as String).split('\n');
setState(() {
importInProgress = true;
});
appsProvider
.addAppsByURL(urls)
.then((errors) {
if (errors.isEmpty) {
showMessage(
tr(
'importedX',
args: [plural('apps', urls.length).toLowerCase()],
),
context,
);
} else {
showDialog(
context: context,
builder: (BuildContext ctx) {
return ImportErrorDialog(
urlsLength: urls.length,
errors: errors,
);
},
);
}
})
.catchError((e) {
showError(e, context);
})
.whenComplete(() {
setState(() {
importInProgress = false;
});
});
}
});
}
runObtainiumExport({bool pickOnly = false}) async {
HapticFeedback.selectionClick();
appsProvider
.export(
pickOnly:
pickOnly || (await settingsProvider.getExportDir()) == null,
sp: settingsProvider,
)
.then((String? result) {
if (result != null) {
showMessage(tr('exportedTo', args: [result]), context);
}
})
.catchError((e) {
showError(e, context);
});
}
runObtainiumImport() {
HapticFeedback.selectionClick();
FilePicker.platform
.pickFiles()
.then((result) {
setState(() {
importInProgress = true;
});
if (result != null) {
String data = File(result.files.single.path!).readAsStringSync();
try {
jsonDecode(data);
} catch (e) {
throw ObtainiumError(tr('invalidInput'));
}
appsProvider.import(data).then((value) {
var cats = settingsProvider.categories;
appsProvider.apps.forEach((key, value) {
for (var c in value.app.categories) {
if (!cats.containsKey(c)) {
cats[c] = generateRandomLightColor().value;
}
}
});
appsProvider.addMissingCategories(settingsProvider);
showMessage(
'${tr('importedX', args: [plural('apps', value.key.length).toLowerCase()])}${value.value ? ' + ${tr('settings').toLowerCase()}' : ''}',
context,
);
});
} else {
// User canceled the picker
}
})
.catchError((e) {
showError(e, context);
})
.whenComplete(() {
setState(() {
importInProgress = false;
});
});
}
runUrlImport() {
FilePicker.platform.pickFiles().then((result) {
if (result != null) {
urlListImport(
overrideInitValid: true,
initValue: RegExp('https?://[^"]+')
.allMatches(File(result.files.single.path!).readAsStringSync())
.map((e) => e.input.substring(e.start, e.end))
.toSet()
.toList()
.where((url) {
try {
sourceProvider.getSource(url);
return true;
} catch (e) {
return false;
}
})
.join('\n'),
);
}
});
}
runSourceSearch(AppSource source) {
() async {
var values = await showDialog<Map<String, dynamic>?>(
context: context,
builder: (BuildContext ctx) {
return GeneratedFormModal(
title: tr('searchX', args: [source.name]),
items: [
[
GeneratedFormTextField(
'searchQuery',
label: tr('searchQuery'),
required: source.name != FDroidRepo().name,
),
],
...source.searchQuerySettingFormItems.map((e) => [e]),
[
GeneratedFormTextField(
'url',
label: source.hosts.isNotEmpty
? tr('overrideSource')
: plural('url', 1).substring(2),
defaultValue: source.hosts.isNotEmpty
? source.hosts[0]
: '',
required: true,
),
],
],
);
},
);
if (values != null) {
setState(() {
importInProgress = true;
});
if (source.hosts.isEmpty || values['url'] != source.hosts[0]) {
source = sourceProvider.getSource(
values['url'],
overrideSource: source.runtimeType.toString(),
);
}
var urlsWithDescriptions = await source.search(
values['searchQuery'] as String,
querySettings: values,
);
if (urlsWithDescriptions.isNotEmpty) {
var selectedUrls =
// ignore: use_build_context_synchronously
await showDialog<List<String>?>(
context: context,
builder: (BuildContext ctx) {
return SelectionModal(
entries: urlsWithDescriptions,
selectedByDefault: false,
);
},
);
if (selectedUrls != null && selectedUrls.isNotEmpty) {
var errors = await appsProvider.addAppsByURL(
selectedUrls,
sourceOverride: source,
);
if (errors.isEmpty) {
// ignore: use_build_context_synchronously
showMessage(
tr(
'importedX',
args: [
plural('apps', selectedUrls.length).toLowerCase(),
],
),
context,
);
} else {
// ignore: use_build_context_synchronously
showDialog(
context: context,
builder: (BuildContext ctx) {
return ImportErrorDialog(
urlsLength: selectedUrls.length,
errors: errors,
);
},
);
}
}
} else {
throw ObtainiumError(tr('noResults'));
}
}
}()
.catchError((e) {
showError(e, context);
})
.whenComplete(() {
setState(() {
importInProgress = false;
});
});
}
runMassSourceImport(MassAppUrlSource source) {
() async {
var values = await showDialog<Map<String, dynamic>?>(
context: context,
builder: (BuildContext ctx) {
return GeneratedFormModal(
title: tr('importX', args: [source.name]),
items: source.requiredArgs
.map((e) => [GeneratedFormTextField(e, label: e)])
.toList(),
);
},
);
if (values != null) {
setState(() {
importInProgress = true;
});
var urlsWithDescriptions = await source.getUrlsWithDescriptions(
values.values.map((e) => e.toString()).toList(),
);
var selectedUrls =
// ignore: use_build_context_synchronously
await showDialog<List<String>?>(
context: context,
builder: (BuildContext ctx) {
return SelectionModal(entries: urlsWithDescriptions);
},
);
if (selectedUrls != null) {
var errors = await appsProvider.addAppsByURL(selectedUrls);
if (errors.isEmpty) {
// ignore: use_build_context_synchronously
showMessage(
tr(
'importedX',
args: [plural('apps', selectedUrls.length).toLowerCase()],
),
context,
);
} else {
// ignore: use_build_context_synchronously
showDialog(
context: context,
builder: (BuildContext ctx) {
return ImportErrorDialog(
urlsLength: selectedUrls.length,
errors: errors,
);
},
);
}
}
}
}()
.catchError((e) {
showError(e, context);
})
.whenComplete(() {
setState(() {
importInProgress = false;
});
});
}
var sourceStrings = <String, List<String>>{};
sourceProvider.sources.where((e) => e.canSearch).forEach((s) {
sourceStrings[s.name] = [s.name];
});
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.surface,
body: CustomScrollView(
slivers: <Widget>[
CustomAppBar(title: tr('importExport')),
SliverFillRemaining(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
FutureBuilder(
future: settingsProvider.getExportDir(),
builder: (context, snapshot) {
return Column(
children: [
Row(
children: [
Expanded(
child: TextButton(
style: outlineButtonStyle,
onPressed: importInProgress
? null
: () {
runObtainiumExport(pickOnly: true);
},
child: Text(
tr('pickExportDir'),
textAlign: TextAlign.center,
),
),
),
const SizedBox(width: 16),
Expanded(
child: TextButton(
style: outlineButtonStyle,
onPressed:
importInProgress || snapshot.data == null
? null
: runObtainiumExport,
child: Text(
tr('obtainiumExport'),
textAlign: TextAlign.center,
),
),
),
],
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: TextButton(
style: outlineButtonStyle,
onPressed: importInProgress
? null
: runObtainiumImport,
child: Text(
tr('obtainiumImport'),
textAlign: TextAlign.center,
),
),
),
],
),
if (snapshot.data != null)
Column(
children: [
const SizedBox(height: 16),
GeneratedForm(
items: [
[
GeneratedFormSwitch(
'autoExportOnChanges',
label: tr('autoExportOnChanges'),
defaultValue: settingsProvider
.autoExportOnChanges,
),
],
[
GeneratedFormDropdown(
'exportSettings',
[
MapEntry('0', tr('none')),
MapEntry('1', tr('excludeSecrets')),
MapEntry('2', tr('all')),
],
label: tr('includeSettings'),
defaultValue: settingsProvider
.exportSettings
.toString(),
),
],
],
onValueChanges: (value, valid, isBuilding) {
if (valid && !isBuilding) {
if (value['autoExportOnChanges'] !=
null) {
settingsProvider.autoExportOnChanges =
value['autoExportOnChanges'] ==
true;
}
if (value['exportSettings'] != null) {
settingsProvider.exportSettings =
int.parse(value['exportSettings']);
}
}
},
),
],
),
],
);
},
),
if (importInProgress)
const Column(
children: [
SizedBox(height: 14),
LinearProgressIndicator(),
SizedBox(height: 14),
],
)
else
Column(
children: [
SizedBox(height: 32),
Row(
children: [
Expanded(
child: TextButton(
onPressed: importInProgress
? null
: () async {
var searchSourceName =
await showDialog<List<String>?>(
context: context,
builder: (BuildContext ctx) {
return SelectionModal(
title: tr(
'selectX',
args: [
tr(
'source',
).toLowerCase(),
],
),
entries: sourceStrings,
selectedByDefault: false,
onlyOneSelectionAllowed: true,
titlesAreLinks: false,
);
},
) ??
[];
var searchSource = sourceProvider
.sources
.where(
(e) => searchSourceName.contains(
e.name,
),
)
.toList();
if (searchSource.isNotEmpty) {
runSourceSearch(searchSource[0]);
}
},
child: Text(
tr(
'searchX',
args: [lowerCaseIfEnglish(tr('source'))],
),
),
),
),
],
),
const SizedBox(height: 8),
TextButton(
onPressed: importInProgress ? null : urlListImport,
child: Text(tr('importFromURLList')),
),
const SizedBox(height: 8),
TextButton(
onPressed: importInProgress ? null : runUrlImport,
child: Text(tr('importFromURLsInFile')),
),
],
),
...sourceProvider.massUrlSources.map(
(source) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 8),
TextButton(
onPressed: importInProgress
? null
: () {
runMassSourceImport(source);
},
child: Text(tr('importX', args: [source.name])),
),
],
),
),
const Spacer(),
const Divider(height: 32),
Text(
tr('importedAppsIdDisclaimer'),
textAlign: TextAlign.center,
style: const TextStyle(
fontStyle: FontStyle.italic,
fontSize: 12,
),
),
const SizedBox(height: 8),
],
),
),
),
],
),
);
}
}
class ImportErrorDialog extends StatefulWidget {
const ImportErrorDialog({
super.key,
required this.urlsLength,
required this.errors,
});
final int urlsLength;
final List<List<String>> errors;
@override
State<ImportErrorDialog> createState() => _ImportErrorDialogState();
}
class _ImportErrorDialogState extends State<ImportErrorDialog> {
@override
Widget build(BuildContext context) {
return AlertDialog(
scrollable: true,
title: Text(tr('importErrors')),
content: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
tr(
'importedXOfYApps',
args: [
(widget.urlsLength - widget.errors.length).toString(),
widget.urlsLength.toString(),
],
),
style: Theme.of(context).textTheme.bodyLarge,
),
const SizedBox(height: 16),
Text(
tr('followingURLsHadErrors'),
style: Theme.of(context).textTheme.bodyLarge,
),
...widget.errors.map((e) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 16),
Text(e[0]),
Text(e[1], style: const TextStyle(fontStyle: FontStyle.italic)),
],
);
}),
],
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(null);
},
child: Text(tr('ok')),
),
],
);
}
}
// ignore: must_be_immutable
class SelectionModal extends StatefulWidget {
SelectionModal({
super.key,
required this.entries,
this.selectedByDefault = true,
this.onlyOneSelectionAllowed = false,
this.titlesAreLinks = true,
this.title,
this.deselectThese = const [],
});
String? title;
Map<String, List<String>> entries;
bool selectedByDefault;
List<String> deselectThese;
bool onlyOneSelectionAllowed;
bool titlesAreLinks;
@override
State<SelectionModal> createState() => _SelectionModalState();
}
class _SelectionModalState extends State<SelectionModal> {
Map<MapEntry<String, List<String>>, bool> entrySelections = {};
String filterRegex = '';
@override
void initState() {
super.initState();
for (var entry in widget.entries.entries) {
entrySelections.putIfAbsent(
entry,
() =>
widget.selectedByDefault &&
!widget.onlyOneSelectionAllowed &&
!widget.deselectThese.contains(entry.key),
);
}
if (widget.selectedByDefault && widget.onlyOneSelectionAllowed) {
selectOnlyOne(widget.entries.entries.first.key);
}
}
void selectOnlyOne(String url) {
for (var e in entrySelections.keys) {
entrySelections[e] = e.key == url;
}
}
void selectAll({bool deselect = false}) {
for (var e in entrySelections.keys) {
entrySelections[e] = !deselect;
}
}
@override
Widget build(BuildContext context) {
Map<MapEntry<String, List<String>>, bool> filteredEntrySelections = {};
entrySelections.forEach((key, value) {
var searchableText = key.value.isEmpty ? key.key : key.value[0];
if (filterRegex.isEmpty || RegExp(filterRegex).hasMatch(searchableText)) {
filteredEntrySelections.putIfAbsent(key, () => value);
}
});
if (filterRegex.isNotEmpty && filteredEntrySelections.isEmpty) {
entrySelections.forEach((key, value) {
var searchableText = key.value.isEmpty ? key.key : key.value[0];
if (filterRegex.isEmpty ||
RegExp(
filterRegex,
caseSensitive: false,
).hasMatch(searchableText)) {
filteredEntrySelections.putIfAbsent(key, () => value);
}
});
}
getSelectAllButton() {
if (widget.onlyOneSelectionAllowed) {
return SizedBox.shrink();
}
var noneSelected = entrySelections.values.where((v) => v == true).isEmpty;
return noneSelected
? TextButton(
style: const ButtonStyle(visualDensity: VisualDensity.compact),
onPressed: () {
setState(() {
selectAll();
});
},
child: Text(tr('selectAll')),
)
: TextButton(
style: const ButtonStyle(visualDensity: VisualDensity.compact),
onPressed: () {
setState(() {
selectAll(deselect: true);
});
},
child: Text(tr('deselectX', args: [''])),
);
}
return AlertDialog(
scrollable: true,
title: Text(widget.title ?? tr('pick')),
content: Column(
children: [
GeneratedForm(
items: [
[
GeneratedFormTextField(
'filter',
label: tr('filter'),
required: false,
additionalValidators: [
(value) {
return regExValidator(value);
},
],
),
],
],
onValueChanges: (value, valid, isBuilding) {
if (valid && !isBuilding) {
if (value['filter'] != null) {
setState(() {
filterRegex = value['filter'];
});
}
}
},
),
...filteredEntrySelections.keys.map((entry) {
selectThis(bool? value) {
setState(() {
value ??= false;
if (value! && widget.onlyOneSelectionAllowed) {
selectOnlyOne(entry.key);
} else {
entrySelections[entry] = value!;
}
});
}
var urlLink = GestureDetector(
onTap: !widget.titlesAreLinks
? null
: () {
launchUrlString(
entry.key,
mode: LaunchMode.externalApplication,
);
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
entry.value.isEmpty ? entry.key : entry.value[0],
style: TextStyle(
decoration: widget.titlesAreLinks
? TextDecoration.underline
: null,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.start,
),
if (widget.titlesAreLinks)
Text(
Uri.parse(entry.key).host,
style: const TextStyle(
decoration: TextDecoration.underline,
fontSize: 12,
),
),
],
),
);
var descriptionText = entry.value.length <= 1
? const SizedBox.shrink()
: Text(
entry.value[1].length > 128
? '${entry.value[1].substring(0, 128)}...'
: entry.value[1],
style: const TextStyle(
fontStyle: FontStyle.italic,
fontSize: 12,
),
);
var selectedEntries = entrySelections.entries
.where((e) => e.value)
.toList();
var singleSelectTile = ListTile(
title: GestureDetector(
onTap: widget.titlesAreLinks
? null
: () {
selectThis(!(entrySelections[entry] ?? false));
},
child: urlLink,
),
subtitle: entry.value.length <= 1
? null
: GestureDetector(
onTap: () {
setState(() {
selectOnlyOne(entry.key);
});
},
child: descriptionText,
),
leading: Radio<String>(
value: entry.key,
groupValue: selectedEntries.isEmpty
? null
: selectedEntries.first.key.key,
onChanged: (value) {
setState(() {
selectOnlyOne(entry.key);
});
},
),
);
var multiSelectTile = Row(
children: [
Checkbox(
value: entrySelections[entry],
onChanged: (value) {
selectThis(value);
},
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 8),
GestureDetector(
onTap: widget.titlesAreLinks
? null
: () {
selectThis(!(entrySelections[entry] ?? false));
},
child: urlLink,
),
entry.value.length <= 1
? const SizedBox.shrink()
: GestureDetector(
onTap: () {
selectThis(!(entrySelections[entry] ?? false));
},
child: descriptionText,
),
const SizedBox(height: 8),
],
),
),
],
);
return widget.onlyOneSelectionAllowed
? singleSelectTile
: multiSelectTile;
}),
],
),
actions: [
getSelectAllButton(),
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(tr('cancel')),
),
TextButton(
onPressed: entrySelections.values.where((b) => b).isEmpty
? null
: () {
Navigator.of(context).pop(
entrySelections.entries
.where((entry) => entry.value)
.map((e) => e.key.key)
.toList(),
);
},
child: Text(
widget.onlyOneSelectionAllowed
? tr('pick')
: tr(
'selectX',
args: [
entrySelections.values.where((b) => b).length.toString(),
],
),
),
),
],
);
}
}

1173
lib/pages/settings.dart Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,127 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:sqflite/sqflite.dart';
const String logTable = 'logs';
const String idColumn = '_id';
const String levelColumn = 'level';
const String messageColumn = 'message';
const String timestampColumn = 'timestamp';
const String dbPath = 'logs.db';
enum LogLevels { debug, info, warning, error }
class Log {
int? id;
late LogLevels level;
late String message;
DateTime timestamp = DateTime.now();
Map<String, Object?> toMap() {
var map = <String, Object?>{
idColumn: id,
levelColumn: level.index,
messageColumn: message,
timestampColumn: timestamp.millisecondsSinceEpoch,
};
return map;
}
Log(this.message, this.level);
Log.fromMap(Map<String, Object?> map) {
id = map[idColumn] as int;
level = LogLevels.values.elementAt(map[levelColumn] as int);
message = map[messageColumn] as String;
timestamp = DateTime.fromMillisecondsSinceEpoch(
map[timestampColumn] as int,
);
}
@override
String toString() {
return '${timestamp.toString()}: ${level.name}: $message';
}
}
class LogsProvider {
LogsProvider({bool runDefaultClear = true}) {
clear(before: DateTime.now().subtract(const Duration(days: 7)));
}
Database? db;
Future<Database> getDB() async {
db ??= await openDatabase(
dbPath,
version: 1,
onCreate: (Database db, int version) async {
await db.execute('''
create table if not exists $logTable (
$idColumn integer primary key autoincrement,
$levelColumn integer not null,
$messageColumn text not null,
$timestampColumn integer not null)
''');
},
);
return db!;
}
Future<Log> add(String message, {LogLevels level = LogLevels.info}) async {
Log l = Log(message, level);
l.id = await (await getDB()).insert(logTable, l.toMap());
if (kDebugMode) {
print(l);
}
return l;
}
Future<List<Log>> get({DateTime? before, DateTime? after}) async {
var where = getWhereDates(before: before, after: after);
return (await (await getDB()).query(
logTable,
where: where.key,
whereArgs: where.value,
)).map((e) => Log.fromMap(e)).toList();
}
Future<int> clear({DateTime? before, DateTime? after}) async {
var where = getWhereDates(before: before, after: after);
var res = await (await getDB()).delete(
logTable,
where: where.key,
whereArgs: where.value,
);
if (res > 0) {
add(
plural(
'clearedNLogsBeforeXAfterY',
res,
namedArgs: {'before': before.toString(), 'after': after.toString()},
name: 'n',
),
);
}
return res;
}
}
MapEntry<String?, List<int>?> getWhereDates({
DateTime? before,
DateTime? after,
}) {
List<String> where = [];
List<int> whereArgs = [];
if (before != null) {
where.add('$timestampColumn < ?');
whereArgs.add(before.millisecondsSinceEpoch);
}
if (after != null) {
where.add('$timestampColumn > ?');
whereArgs.add(after.millisecondsSinceEpoch);
}
return whereArgs.isEmpty
? const MapEntry(null, null)
: MapEntry(where.join(' and '), whereArgs);
}

View file

@ -0,0 +1,22 @@
import 'dart:async';
import 'dart:io';
import 'package:android_system_font/android_system_font.dart';
import 'package:flutter/services.dart';
class NativeFeatures {
static bool _systemFontLoaded = false;
static Future<ByteData> _readFileBytes(String path) async {
var bytes = await File(path).readAsBytes();
return ByteData.view(bytes.buffer);
}
static Future loadSystemFont() async {
if (_systemFontLoaded) return;
var fontLoader = FontLoader('SystemFont');
var fontFilePath = await AndroidSystemFont().getFilePath();
fontLoader.addFont(_readFileBytes(fontFilePath!));
fontLoader.load();
_systemFontLoaded = true;
}
}

View file

@ -0,0 +1,323 @@
// Exposes functions that can be used to send notifications to the user
// Contains a set of pre-defined ObtainiumNotification objects that should be used throughout the app
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:obtainium/main.dart';
import 'package:obtainium/providers/settings_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
class ObtainiumNotification {
late int id;
late String title;
late String message;
late String channelCode;
late String channelName;
late String channelDescription;
Importance importance;
int? progPercent;
bool onlyAlertOnce;
String? payload;
ObtainiumNotification(
this.id,
this.title,
this.message,
this.channelCode,
this.channelName,
this.channelDescription,
this.importance, {
this.onlyAlertOnce = false,
this.progPercent,
this.payload,
});
}
class UpdateNotification extends ObtainiumNotification {
UpdateNotification(List<App> updates, {int? id})
: super(
id ?? 2,
tr('updatesAvailable'),
'',
'UPDATES_AVAILABLE',
tr('updatesAvailableNotifChannel'),
tr('updatesAvailableNotifDescription'),
Importance.max,
) {
message = updates.isEmpty
? tr('noNewUpdates')
: updates.length == 1
? tr('xHasAnUpdate', args: [updates[0].finalName])
: plural(
'xAndNMoreUpdatesAvailable',
updates.length - 1,
args: [updates[0].finalName, (updates.length - 1).toString()],
);
}
}
class SilentUpdateNotification extends ObtainiumNotification {
SilentUpdateNotification(List<App> updates, bool succeeded, {int? id})
: super(
id ?? 3,
succeeded ? tr('appsUpdated') : tr('appsNotUpdated'),
'',
'APPS_UPDATED',
tr('appsUpdatedNotifChannel'),
tr('appsUpdatedNotifDescription'),
Importance.defaultImportance,
) {
message = updates.length == 1
? tr(
succeeded ? 'xWasUpdatedToY' : 'xWasNotUpdatedToY',
args: [updates[0].finalName, updates[0].latestVersion],
)
: plural(
succeeded ? 'xAndNMoreUpdatesInstalled' : "xAndNMoreUpdatesFailed",
updates.length - 1,
args: [updates[0].finalName, (updates.length - 1).toString()],
);
}
}
class SilentUpdateAttemptNotification extends ObtainiumNotification {
SilentUpdateAttemptNotification(List<App> updates, {int? id})
: super(
id ?? 3,
tr('appsPossiblyUpdated'),
'',
'APPS_POSSIBLY_UPDATED',
tr('appsPossiblyUpdatedNotifChannel'),
tr('appsPossiblyUpdatedNotifDescription'),
Importance.defaultImportance,
) {
message = updates.length == 1
? tr(
'xWasPossiblyUpdatedToY',
args: [updates[0].finalName, updates[0].latestVersion],
)
: plural(
'xAndNMoreUpdatesPossiblyInstalled',
updates.length - 1,
args: [updates[0].finalName, (updates.length - 1).toString()],
);
}
}
class ErrorCheckingUpdatesNotification extends ObtainiumNotification {
ErrorCheckingUpdatesNotification(String error, {int? id})
: super(
id ?? 5,
tr('errorCheckingUpdates'),
error,
'BG_UPDATE_CHECK_ERROR',
tr('errorCheckingUpdatesNotifChannel'),
tr('errorCheckingUpdatesNotifDescription'),
Importance.high,
payload: "${tr('errorCheckingUpdates')}\n$error",
);
}
class AppsRemovedNotification extends ObtainiumNotification {
AppsRemovedNotification(List<List<String>> namedReasons)
: super(
6,
tr('appsRemoved'),
'',
'APPS_REMOVED',
tr('appsRemovedNotifChannel'),
tr('appsRemovedNotifDescription'),
Importance.max,
) {
message = '';
for (var r in namedReasons) {
message += '${tr('xWasRemovedDueToErrorY', args: [r[0], r[1]])} \n';
}
message = message.trim();
}
}
class DownloadNotification extends ObtainiumNotification {
DownloadNotification(String appName, int progPercent)
: super(
appName.hashCode,
tr('downloadingX', args: [appName]),
'',
'APP_DOWNLOADING',
tr('downloadingXNotifChannel', args: [tr('app')]),
tr('downloadNotifDescription'),
Importance.low,
onlyAlertOnce: true,
progPercent: progPercent,
);
}
class DownloadedNotification extends ObtainiumNotification {
DownloadedNotification(String fileName, String downloadUrl)
: super(
downloadUrl.hashCode,
tr('downloadedX', args: [fileName]),
'',
'FILE_DOWNLOADED',
tr('downloadedXNotifChannel', args: [tr('app')]),
tr('downloadedX', args: [tr('app')]),
Importance.defaultImportance,
);
}
final completeInstallationNotification = ObtainiumNotification(
1,
tr('completeAppInstallation'),
tr('obtainiumMustBeOpenToInstallApps'),
'COMPLETE_INSTALL',
tr('completeAppInstallationNotifChannel'),
tr('completeAppInstallationNotifDescription'),
Importance.max,
);
class CheckingUpdatesNotification extends ObtainiumNotification {
CheckingUpdatesNotification(String appName)
: super(
4,
tr('checkingForUpdates'),
appName,
'BG_UPDATE_CHECK',
tr('checkingForUpdatesNotifChannel'),
tr('checkingForUpdatesNotifDescription'),
Importance.min,
);
}
class NotificationsProvider {
FlutterLocalNotificationsPlugin notifications =
FlutterLocalNotificationsPlugin();
bool isInitialized = false;
Map<Importance, Priority> importanceToPriority = {
Importance.defaultImportance: Priority.defaultPriority,
Importance.high: Priority.high,
Importance.low: Priority.low,
Importance.max: Priority.max,
Importance.min: Priority.min,
Importance.none: Priority.min,
Importance.unspecified: Priority.defaultPriority,
};
Future<void> initialize() async {
isInitialized =
await notifications.initialize(
const InitializationSettings(
android: AndroidInitializationSettings('ic_notification'),
),
onDidReceiveNotificationResponse: (NotificationResponse response) {
_showNotificationPayload(response.payload);
},
) ??
false;
}
Future<void> checkLaunchByNotif() async {
final NotificationAppLaunchDetails? launchDetails = await notifications
.getNotificationAppLaunchDetails();
if (launchDetails?.didNotificationLaunchApp ?? false) {
_showNotificationPayload(
launchDetails!.notificationResponse?.payload,
doublePop: true,
);
}
}
void _showNotificationPayload(String? payload, {bool doublePop = false}) {
if (payload?.isNotEmpty == true) {
var title = (payload ?? '\n\n').split('\n').first;
var content = (payload ?? '\n\n').split('\n').sublist(1).join('\n');
globalNavigatorKey.currentState?.push(
PageRouteBuilder(
pageBuilder: (context, _, __) => AlertDialog(
title: Text(title),
content: Text(content),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(null);
if (doublePop) {
Navigator.of(context).pop(null);
}
},
child: Text(tr('ok')),
),
],
),
),
);
}
}
Future<void> cancel(int id) async {
if (!isInitialized) {
await initialize();
}
await notifications.cancel(id);
}
Future<void> notifyRaw(
int id,
String title,
String message,
String channelCode,
String channelName,
String channelDescription,
Importance importance, {
bool cancelExisting = false,
int? progPercent,
bool onlyAlertOnce = false,
String? payload,
}) async {
if (cancelExisting) {
await cancel(id);
}
if (!isInitialized) {
await initialize();
}
await notifications.show(
id,
title,
message,
NotificationDetails(
android: AndroidNotificationDetails(
channelCode,
channelName,
channelDescription: channelDescription,
importance: importance,
priority: importanceToPriority[importance]!,
groupKey: '$obtainiumId.$channelCode',
progress: progPercent ?? 0,
maxProgress: 100,
showProgress: progPercent != null,
onlyAlertOnce: onlyAlertOnce,
indeterminate: progPercent != null && progPercent < 0,
),
),
payload: payload,
);
}
Future<void> notify(
ObtainiumNotification notif, {
bool cancelExisting = false,
}) => notifyRaw(
notif.id,
notif.title,
notif.message,
notif.channelCode,
notif.channelName,
notif.channelDescription,
notif.importance,
cancelExisting: cancelExisting,
onlyAlertOnce: notif.onlyAlertOnce,
progPercent: notif.progPercent,
payload: notif.payload,
);
}

View file

@ -0,0 +1,525 @@
// Exposes functions used to save/load app settings
import 'dart:convert';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:obtainium/app_sources/github.dart';
import 'package:obtainium/main.dart';
import 'package:obtainium/providers/apps_provider.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_storage/shared_storage.dart' as saf;
String obtainiumTempId = 'imranr98_obtainium_${GitHub().hosts[0]}';
String obtainiumId = 'dev.imranr.obtainium';
String obtainiumUrl = 'https://github.com/ImranR98/Obtainium';
Color obtainiumThemeColor = const Color(0xFF6438B5);
enum ThemeSettings { system, light, dark }
enum SortColumnSettings { added, nameAuthor, authorName, releaseDate }
enum SortOrderSettings { ascending, descending }
class SettingsProvider with ChangeNotifier {
SharedPreferences? prefs;
String? defaultAppDir;
bool justStarted = true;
String sourceUrl = 'https://github.com/ImranR98/Obtainium';
// Not done in constructor as we want to be able to await it
Future<void> initializeSettings() async {
prefs = await SharedPreferences.getInstance();
defaultAppDir = (await getAppStorageDir()).path;
notifyListeners();
}
bool get useSystemFont {
return prefs?.getBool('useSystemFont') ?? false;
}
set useSystemFont(bool useSystemFont) {
prefs?.setBool('useSystemFont', useSystemFont);
notifyListeners();
}
bool get useShizuku {
return prefs?.getBool('useShizuku') ?? false;
}
set useShizuku(bool useShizuku) {
prefs?.setBool('useShizuku', useShizuku);
notifyListeners();
}
ThemeSettings get theme {
return ThemeSettings.values[prefs?.getInt('theme') ??
ThemeSettings.system.index];
}
set theme(ThemeSettings t) {
prefs?.setInt('theme', t.index);
notifyListeners();
}
Color get themeColor {
int? colorCode = prefs?.getInt('themeColor');
return (colorCode != null) ? Color(colorCode) : obtainiumThemeColor;
}
set themeColor(Color themeColor) {
prefs?.setInt('themeColor', themeColor.value);
notifyListeners();
}
bool get useMaterialYou {
return prefs?.getBool('useMaterialYou') ?? false;
}
set useMaterialYou(bool useMaterialYou) {
prefs?.setBool('useMaterialYou', useMaterialYou);
notifyListeners();
}
bool get useBlackTheme {
return prefs?.getBool('useBlackTheme') ?? false;
}
set useBlackTheme(bool useBlackTheme) {
prefs?.setBool('useBlackTheme', useBlackTheme);
notifyListeners();
}
int get updateInterval {
return prefs?.getInt('updateInterval') ?? 360;
}
set updateInterval(int min) {
prefs?.setInt('updateInterval', min);
notifyListeners();
}
double get updateIntervalSliderVal {
return prefs?.getDouble('updateIntervalSliderVal') ?? 6.0;
}
set updateIntervalSliderVal(double val) {
prefs?.setDouble('updateIntervalSliderVal', val);
notifyListeners();
}
bool get checkOnStart {
return prefs?.getBool('checkOnStart') ?? false;
}
set checkOnStart(bool checkOnStart) {
prefs?.setBool('checkOnStart', checkOnStart);
notifyListeners();
}
SortColumnSettings get sortColumn {
return SortColumnSettings.values[prefs?.getInt('sortColumn') ??
SortColumnSettings.nameAuthor.index];
}
set sortColumn(SortColumnSettings s) {
prefs?.setInt('sortColumn', s.index);
notifyListeners();
}
SortOrderSettings get sortOrder {
return SortOrderSettings.values[prefs?.getInt('sortOrder') ??
SortOrderSettings.ascending.index];
}
set sortOrder(SortOrderSettings s) {
prefs?.setInt('sortOrder', s.index);
notifyListeners();
}
bool checkAndFlipFirstRun() {
bool result = prefs?.getBool('firstRun') ?? true;
if (result) {
prefs?.setBool('firstRun', false);
}
return result;
}
bool get welcomeShown {
return prefs?.getBool('welcomeShown') ?? false;
}
set welcomeShown(bool welcomeShown) {
prefs?.setBool('welcomeShown', welcomeShown);
notifyListeners();
}
bool checkJustStarted() {
if (justStarted) {
justStarted = false;
return true;
}
return false;
}
Future<bool> getInstallPermission({bool enforce = false}) async {
while (!(await Permission.requestInstallPackages.isGranted)) {
// Explicit request as InstallPlugin request sometimes bugged
Fluttertoast.showToast(
msg: tr('pleaseAllowInstallPerm'),
toastLength: Toast.LENGTH_LONG,
);
if ((await Permission.requestInstallPackages.request()) ==
PermissionStatus.granted) {
return true;
}
if (!enforce) {
return false;
}
}
return true;
}
bool get showAppWebpage {
return prefs?.getBool('showAppWebpage') ?? false;
}
set showAppWebpage(bool show) {
prefs?.setBool('showAppWebpage', show);
notifyListeners();
}
bool get pinUpdates {
return prefs?.getBool('pinUpdates') ?? true;
}
set pinUpdates(bool show) {
prefs?.setBool('pinUpdates', show);
notifyListeners();
}
bool get buryNonInstalled {
return prefs?.getBool('buryNonInstalled') ?? false;
}
set buryNonInstalled(bool show) {
prefs?.setBool('buryNonInstalled', show);
notifyListeners();
}
bool get groupByCategory {
return prefs?.getBool('groupByCategory') ?? false;
}
set groupByCategory(bool show) {
prefs?.setBool('groupByCategory', show);
notifyListeners();
}
bool get hideTrackOnlyWarning {
return prefs?.getBool('hideTrackOnlyWarning') ?? false;
}
set hideTrackOnlyWarning(bool show) {
prefs?.setBool('hideTrackOnlyWarning', show);
notifyListeners();
}
bool get hideAPKOriginWarning {
return prefs?.getBool('hideAPKOriginWarning') ?? false;
}
set hideAPKOriginWarning(bool show) {
prefs?.setBool('hideAPKOriginWarning', show);
notifyListeners();
}
String? getSettingString(String settingId) {
String? str = prefs?.getString(settingId);
return str?.isNotEmpty == true ? str : null;
}
void setSettingString(String settingId, String value) {
prefs?.setString(settingId, value);
notifyListeners();
}
bool? getSettingBool(String settingId) {
return prefs?.getBool(settingId) ?? false;
}
void setSettingBool(String settingId, bool value) {
prefs?.setBool(settingId, value);
notifyListeners();
}
Map<String, int> get categories =>
Map<String, int>.from(jsonDecode(prefs?.getString('categories') ?? '{}'));
void setCategories(Map<String, int> cats, {AppsProvider? appsProvider}) {
if (appsProvider != null) {
List<App> changedApps = appsProvider
.getAppValues()
.map((a) {
var n1 = a.app.categories.length;
a.app.categories.removeWhere((c) => !cats.keys.contains(c));
return n1 > a.app.categories.length ? a.app : null;
})
.where((element) => element != null)
.map((e) => e as App)
.toList();
if (changedApps.isNotEmpty) {
appsProvider.saveApps(changedApps);
}
}
prefs?.setString('categories', jsonEncode(cats));
notifyListeners();
}
Locale? get forcedLocale {
var flSegs = prefs?.getString('forcedLocale')?.split('-');
var fl = flSegs != null && flSegs.isNotEmpty
? Locale(flSegs[0], flSegs.length > 1 ? flSegs[1] : null)
: null;
var set = supportedLocales.where((element) => element.key == fl).isNotEmpty
? fl
: null;
return set;
}
set forcedLocale(Locale? fl) {
if (fl == null) {
prefs?.remove('forcedLocale');
} else if (supportedLocales
.where((element) => element.key == fl)
.isNotEmpty) {
prefs?.setString('forcedLocale', fl.toLanguageTag());
}
notifyListeners();
}
bool setEqual(Set<String> a, Set<String> b) =>
a.length == b.length && a.union(b).length == a.length;
void resetLocaleSafe(BuildContext context) {
if (context.supportedLocales.contains(context.deviceLocale)) {
context.resetLocale();
} else {
context.setLocale(context.fallbackLocale!);
context.deleteSaveLocale();
}
}
bool get removeOnExternalUninstall {
return prefs?.getBool('removeOnExternalUninstall') ?? false;
}
set removeOnExternalUninstall(bool show) {
prefs?.setBool('removeOnExternalUninstall', show);
notifyListeners();
}
bool get checkUpdateOnDetailPage {
return prefs?.getBool('checkUpdateOnDetailPage') ?? true;
}
set checkUpdateOnDetailPage(bool show) {
prefs?.setBool('checkUpdateOnDetailPage', show);
notifyListeners();
}
bool get disablePageTransitions {
return prefs?.getBool('disablePageTransitions') ?? false;
}
set disablePageTransitions(bool show) {
prefs?.setBool('disablePageTransitions', show);
notifyListeners();
}
bool get reversePageTransitions {
return prefs?.getBool('reversePageTransitions') ?? false;
}
set reversePageTransitions(bool show) {
prefs?.setBool('reversePageTransitions', show);
notifyListeners();
}
bool get enableBackgroundUpdates {
return prefs?.getBool('enableBackgroundUpdates') ?? true;
}
set enableBackgroundUpdates(bool val) {
prefs?.setBool('enableBackgroundUpdates', val);
notifyListeners();
}
bool get bgUpdatesOnWiFiOnly {
return prefs?.getBool('bgUpdatesOnWiFiOnly') ?? false;
}
set bgUpdatesOnWiFiOnly(bool val) {
prefs?.setBool('bgUpdatesOnWiFiOnly', val);
notifyListeners();
}
bool get bgUpdatesWhileChargingOnly {
return prefs?.getBool('bgUpdatesWhileChargingOnly') ?? false;
}
set bgUpdatesWhileChargingOnly(bool val) {
prefs?.setBool('bgUpdatesWhileChargingOnly', val);
notifyListeners();
}
DateTime get lastCompletedBGCheckTime {
int? temp = prefs?.getInt('lastCompletedBGCheckTime');
return temp != null
? DateTime.fromMillisecondsSinceEpoch(temp)
: DateTime.fromMillisecondsSinceEpoch(0);
}
set lastCompletedBGCheckTime(DateTime val) {
prefs?.setInt('lastCompletedBGCheckTime', val.millisecondsSinceEpoch);
notifyListeners();
}
bool get showDebugOpts {
return prefs?.getBool('showDebugOpts') ?? false;
}
set showDebugOpts(bool val) {
prefs?.setBool('showDebugOpts', val);
notifyListeners();
}
bool get highlightTouchTargets {
return prefs?.getBool('highlightTouchTargets') ?? false;
}
set highlightTouchTargets(bool val) {
prefs?.setBool('highlightTouchTargets', val);
notifyListeners();
}
Future<Uri?> getExportDir() async {
var uriString = prefs?.getString('exportDir');
if (uriString != null) {
Uri? uri = Uri.parse(uriString);
if (!(await saf.canRead(uri) ?? false) ||
!(await saf.canWrite(uri) ?? false)) {
uri = null;
prefs?.remove('exportDir');
notifyListeners();
}
return uri;
} else {
return null;
}
}
Future<void> pickExportDir({bool remove = false}) async {
var existingSAFPerms = (await saf.persistedUriPermissions()) ?? [];
var currentOneWayDataSyncDir = await getExportDir();
Uri? newOneWayDataSyncDir;
if (!remove) {
newOneWayDataSyncDir = (await saf.openDocumentTree());
}
if (currentOneWayDataSyncDir?.path != newOneWayDataSyncDir?.path) {
if (newOneWayDataSyncDir == null) {
prefs?.remove('exportDir');
} else {
prefs?.setString('exportDir', newOneWayDataSyncDir.toString());
}
notifyListeners();
}
for (var e in existingSAFPerms) {
await saf.releasePersistableUriPermission(e.uri);
}
}
bool get autoExportOnChanges {
return prefs?.getBool('autoExportOnChanges') ?? false;
}
set autoExportOnChanges(bool val) {
prefs?.setBool('autoExportOnChanges', val);
notifyListeners();
}
bool get onlyCheckInstalledOrTrackOnlyApps {
return prefs?.getBool('onlyCheckInstalledOrTrackOnlyApps') ?? false;
}
set onlyCheckInstalledOrTrackOnlyApps(bool val) {
prefs?.setBool('onlyCheckInstalledOrTrackOnlyApps', val);
notifyListeners();
}
int get exportSettings {
try {
return prefs?.getInt('exportSettings') ??
1; // 0 for no, 1 for yes but no secrets, 2 for everything
} catch (e) {
var val = prefs?.getBool('exportSettings') == true ? 1 : 0;
prefs?.setInt('exportSettings', val);
return val;
}
}
set exportSettings(int val) {
prefs?.setInt('exportSettings', val > 2 || val < 0 ? 1 : val);
notifyListeners();
}
bool get parallelDownloads {
return prefs?.getBool('parallelDownloads') ?? false;
}
set parallelDownloads(bool val) {
prefs?.setBool('parallelDownloads', val);
notifyListeners();
}
List<String> get searchDeselected {
return prefs?.getStringList('searchDeselected') ??
SourceProvider().sources.map((s) => s.name).toList();
}
set searchDeselected(List<String> list) {
prefs?.setStringList('searchDeselected', list);
notifyListeners();
}
bool get beforeNewInstallsShareToAppVerifier {
return prefs?.getBool('beforeNewInstallsShareToAppVerifier') ?? true;
}
set beforeNewInstallsShareToAppVerifier(bool val) {
prefs?.setBool('beforeNewInstallsShareToAppVerifier', val);
notifyListeners();
}
bool get shizukuPretendToBeGooglePlay {
return prefs?.getBool('shizukuPretendToBeGooglePlay') ?? false;
}
set shizukuPretendToBeGooglePlay(bool val) {
prefs?.setBool('shizukuPretendToBeGooglePlay', val);
notifyListeners();
}
bool get useFGService {
return prefs?.getBool('useFGService') ?? false;
}
set useFGService(bool val) {
prefs?.setBool('useFGService', val);
notifyListeners();
}
}

File diff suppressed because it is too large Load diff