kemono_client.dart 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. KemonoClient(String sourceUrl) :_dio = Dio(BaseOptions(baseUrl: sourceUrl, headers:
  7. {
  8. 'Accept': 'text/css',
  9. 'Accept-Encoding': 'gzip, deflate, br',
  10. 'Accept-Language': 'en-US,en;q=0.5',
  11. 'Cache-Control': 'no-cache',
  12. 'Connection': 'keep-alive',
  13. 'Pragma': 'no-cache',
  14. 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/116.0'
  15. }));
  16. final Dio _dio;
  17. String sourceUrl() => _dio.options.baseUrl;
  18. Future<List<Creator>> getCreators() async {
  19. try {
  20. final response = await _dio.get('/api/v1/creators');
  21. if (response.statusCode != 200) {
  22. throw DioException(
  23. requestOptions: response.requestOptions,
  24. response: response,
  25. error: 'Unexpected status code: ${response.statusCode}'
  26. );
  27. }
  28. final parsedData = switch(response.data) {
  29. String s => jsonDecode(s),
  30. List<dynamic> list => list,
  31. Map<String,dynamic> map => [map],
  32. _ => throw FormatException('Unprocessable data')
  33. };
  34. return (parsedData as List).map((x) => Creator.fromJson(x,_dio.options.baseUrl)).toList();
  35. } on DioException catch (e) {
  36. throw Exception('Network error: ${e.message} ${e.response?.data as String}');
  37. } on FormatException catch (e) {
  38. throw Exception('Data format error: ${e.message}');
  39. }
  40. }
  41. Future<List<Post>> getPosts(String creatorId, String service, int start, String query) async {
  42. try {
  43. final response = await _dio.get(
  44. '/api/v1/$service/user/$creatorId/posts',
  45. queryParameters: query.isEmpty ? {'o': start} : {'o':start, 'q': query},
  46. );
  47. final parsedData = switch(response.data) {
  48. String s => jsonDecode(s),
  49. List<dynamic> list => list,
  50. Map<String,dynamic> map => [map],
  51. _ => throw FormatException('Unprocessable data')
  52. };
  53. return (parsedData as List).map((x) => Post.fromJson(x,_dio.options.baseUrl)).toList();
  54. } on DioException catch (e) {
  55. throw Exception('Posts load failed: ${e.message} ${e.stackTrace}');
  56. } on Exception {
  57. throw Exception('Oops something go wrong}');
  58. }
  59. }
  60. }