Line data Source code
1 : import 'dart:convert';
2 : import 'dart:io';
3 :
4 : import 'package:app_pym/core/error/exceptions.dart';
5 : import 'package:flutter/foundation.dart';
6 : import 'package:http/http.dart' as http;
7 : import 'package:injectable/injectable.dart';
8 :
9 : abstract class SNCFRemoteDataSource {
10 : Stream<List<int>> download();
11 :
12 : Future<DateTime> get timestamp;
13 : }
14 :
15 : @prod
16 : @LazySingleton(as: SNCFRemoteDataSource)
17 : class SNCFRemoteDataSourceImpl implements SNCFRemoteDataSource {
18 : final http.Client client;
19 :
20 1 : SNCFRemoteDataSourceImpl({@required this.client});
21 :
22 : @override
23 1 : Stream<List<int>> download() async* {
24 : // Get zip url
25 3 : final response = await client.get(
26 : 'https://ressources.data.sncf.com/api/records/1.0/search/?dataset=sncf-ter-gtfs');
27 2 : if (response.statusCode != HttpStatus.ok) {
28 1 : throw ServerException(
29 2 : 'https://ressources.data.sncf.com/api/: ${response.statusCode}');
30 : }
31 2 : final body = json.decode(response.body) as Map<String, dynamic>;
32 5 : final id = body['records'].first["fields"]['download']['id'] as String;
33 :
34 : // Download file
35 1 : final http.Request request = http.Request(
36 : 'GET',
37 1 : Uri.parse(
38 1 : "https://ressources.data.sncf.com/explore/dataset/sncf-ter-gtfs/files/$id/download/"),
39 : );
40 3 : final http.StreamedResponse streamedResponse = await client.send(request);
41 :
42 2 : if (streamedResponse.statusCode != HttpStatus.ok) {
43 1 : throw ServerException(
44 2 : 'https://ressources.data.sncf.com/explore/: ${response.statusCode}');
45 : }
46 :
47 2 : yield* streamedResponse.stream;
48 : }
49 :
50 : @override
51 1 : Future<DateTime> get timestamp async {
52 : // Get zip url
53 3 : final response = await client.get(
54 : 'https://ressources.data.sncf.com/api/records/1.0/search/?dataset=sncf-ter-gtfs');
55 2 : if (response.statusCode != HttpStatus.ok) {
56 1 : throw ServerException(
57 2 : 'https://ressources.data.sncf.com/api/: ${response.statusCode}');
58 : }
59 2 : final body = json.decode(response.body) as Map<String, dynamic>;
60 4 : return DateTime.parse(body['records'].first["record_timestamp"] as String);
61 : }
62 : }
|