kemono_client.dart 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import 'dart:convert';
  2. import 'package:dio/dio.dart';
  3. import 'package:veloe_kemono_party_flutter/models/creator.dart';
  4. import 'package:veloe_kemono_party_flutter/models/post.dart';
  5. class KemonoClient {
  6. final Dio _dio = Dio(BaseOptions(baseUrl: 'https://kemono.su/'));
  7. Future<List<Creator>> getCreators() async {
  8. try {
  9. final response = await _dio.get('/api/v1/creators.txt');
  10. if (response.statusCode != 200) {
  11. throw DioException(
  12. requestOptions: response.requestOptions,
  13. response: response,
  14. error: 'Unexpected status code: ${response.statusCode}'
  15. );
  16. }
  17. final parsedData = switch(response.data) {
  18. String s => jsonDecode(s),
  19. List<dynamic> list => list,
  20. Map<String,dynamic> map => [map],
  21. _ => throw FormatException('Unprocessable data')
  22. };
  23. return (parsedData as List).map((x) => Creator.fromJson(x)).toList();
  24. } on DioException catch (e) {
  25. throw Exception('Network error: ${e.message}');
  26. } on FormatException catch (e) {
  27. throw Exception('Data format error: ${e.message}');
  28. }
  29. }
  30. Future<List<Post>> getPosts(String creatorId, String service, int start, String query) async {
  31. try {
  32. final response = await _dio.get(
  33. '/api/v1/$service/user/$creatorId',
  34. queryParameters: query.isEmpty ? {'o': start} : {'o':start, 'q': query},
  35. );
  36. final parsedData = switch(response.data) {
  37. String s => jsonDecode(s),
  38. List<dynamic> list => list,
  39. Map<String,dynamic> map => [map],
  40. _ => throw FormatException('Unprocessable data')
  41. };
  42. return (parsedData as List).map((x) => Post.fromJson(x)).toList();
  43. } on DioException catch (e) {
  44. throw Exception('Posts load failed: ${e.message}');
  45. } on Exception {
  46. throw Exception('Oops something go wrong}');
  47. }
  48. }
  49. }