voyagehandbook/lib/api/wikimedia.dart

59 lines
2.1 KiB
Dart
Raw Permalink Normal View History

2023-03-18 16:55:08 +01:00
import 'dart:convert';
2023-03-16 14:57:15 +01:00
import 'package:dio/dio.dart';
2023-03-18 16:55:08 +01:00
import 'package:voyagehandbook/api/classes.dart';
2023-04-07 13:02:40 +02:00
import 'package:voyagehandbook/util/storage.dart';
2023-03-16 14:57:15 +01:00
2023-03-28 18:08:26 +02:00
/*
Voyage Handbook - The open-source WikiVoyage reader
Copyright (C) 2023 Matyáš Caras
This program is free software: you can redistribute it and/or modify
2023-03-28 20:10:46 +02:00
it under the terms of the GNU General Public License version 3 as published by
the Free Software Foundation.
2023-03-28 18:08:26 +02:00
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
2023-03-18 16:55:08 +01:00
class WikiApi {
static final _dio = Dio(
BaseOptions(baseUrl: "https://api.wikimedia.org/core/v1/wikivoyage/en/"));
2023-03-16 14:57:15 +01:00
2023-03-18 16:55:08 +01:00
static Future<Response> _getRequest(String endpoint) async {
2023-03-24 23:48:55 +01:00
return await _dio.get(
endpoint,
options: Options(
headers: {"User-Agent": "VoyageHandbook/1.0.0"},
validateStatus: (_) => true,
responseType: ResponseType.plain),
);
2023-03-18 16:55:08 +01:00
}
2023-03-16 14:57:15 +01:00
2023-03-18 16:55:08 +01:00
/// Searches for pages using the WikiMedia API
static Future<List<SearchResponse>> search(String q, {int limit = 5}) async {
var r = await _getRequest("search/page?q=$q&limit=$limit");
if (r.statusCode! > 399) return Future.error("API error ${r.statusCode}");
var json = jsonDecode(r.data)["pages"];
2023-04-07 13:02:40 +02:00
var list = List<SearchResponse>.generate(
2023-03-18 16:55:08 +01:00
json.length, (index) => SearchResponse.fromJson(json[index]));
2023-04-07 13:02:40 +02:00
for (var item in list) {
if (await StorageAccess.isDownloaded(item.key)) {
list[list.indexOf(item)].downloaded = true;
}
}
return list;
2023-03-18 16:55:08 +01:00
}
2023-03-24 23:48:55 +01:00
static Future<RawPage> getRawPage(String key) async {
var r = await _getRequest("page/$key/with_html");
if (r.statusCode! > 399) return Future.error("API error ${r.statusCode}");
return RawPage.fromJson(jsonDecode(r.data));
}
2023-03-16 14:57:15 +01:00
}