Repo created
This commit is contained in:
parent
2fd78f5dc9
commit
489cf0b2ea
148 changed files with 30898 additions and 2 deletions
136
lib/app_sources/apkcombo.dart
Normal file
136
lib/app_sources/apkcombo.dart
Normal 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
138
lib/app_sources/apkmirror.dart
Normal file
138
lib/app_sources/apkmirror.dart
Normal 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]);
|
||||
}
|
||||
}
|
||||
219
lib/app_sources/apkpure.dart
Normal file
219
lib/app_sources/apkpure.dart
Normal 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();
|
||||
}
|
||||
}
|
||||
94
lib/app_sources/aptoide.dart
Normal file
94
lib/app_sources/aptoide.dart
Normal 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
65
lib/app_sources/codeberg.dart
Normal file
65
lib/app_sources/codeberg.dart
Normal 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
193
lib/app_sources/coolapk.dart
Normal file
193
lib/app_sources/coolapk.dart
Normal 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/FuckCoolapkTokenV2、https://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};
|
||||
}
|
||||
}
|
||||
83
lib/app_sources/directAPKLink.dart
Normal file
83
lib/app_sources/directAPKLink.dart
Normal 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);
|
||||
}
|
||||
}
|
||||
95
lib/app_sources/farsroid.dart
Normal file
95
lib/app_sources/farsroid.dart
Normal 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
291
lib/app_sources/fdroid.dart
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
275
lib/app_sources/fdroidrepo.dart
Normal file
275
lib/app_sources/fdroidrepo.dart
Normal 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
769
lib/app_sources/github.dart
Normal 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
260
lib/app_sources/gitlab.dart
Normal 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
471
lib/app_sources/html.dart
Normal 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')),
|
||||
);
|
||||
}
|
||||
}
|
||||
113
lib/app_sources/huaweiappgallery.dart
Normal file
113
lib/app_sources/huaweiappgallery.dart
Normal 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
61
lib/app_sources/izzyondroid.dart
Normal file
61
lib/app_sources/izzyondroid.dart
Normal 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
76
lib/app_sources/jenkins.dart
Normal file
76
lib/app_sources/jenkins.dart
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
87
lib/app_sources/liteapks.dart
Normal file
87
lib/app_sources/liteapks.dart
Normal 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,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
75
lib/app_sources/mullvad.dart
Normal file
75
lib/app_sources/mullvad.dart
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
122
lib/app_sources/neutroncode.dart
Normal file
122
lib/app_sources/neutroncode.dart
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
110
lib/app_sources/rustore.dart
Normal file
110
lib/app_sources/rustore.dart
Normal 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
129
lib/app_sources/sourceforge.dart
Normal file
129
lib/app_sources/sourceforge.dart
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
142
lib/app_sources/sourcehut.dart
Normal file
142
lib/app_sources/sourcehut.dart
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
46
lib/app_sources/telegramapp.dart
Normal file
46
lib/app_sources/telegramapp.dart
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
84
lib/app_sources/tencent.dart
Normal file
84
lib/app_sources/tencent.dart
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
145
lib/app_sources/uptodown.dart
Normal file
145
lib/app_sources/uptodown.dart
Normal 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';
|
||||
}
|
||||
}
|
||||
111
lib/app_sources/vivoappstore.dart
Normal file
111
lib/app_sources/vivoappstore.dart
Normal 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;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue