import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:http/io_client.dart'; import 'package:path_provider/path_provider.dart'; import 'package:http/http.dart'; import 'package:unitstocks/Util/Prefs.dart'; import '../main.dart'; import 'package:oauth2/oauth2.dart' as oauth2; class file_Trans_Handler { // double _progress = 0; String _path = ''; StreamSubscription dlulStream; String _error = ''; get path => _path; get error => _error; StreamController _progress = new StreamController(); Stream get progress =>_progress.stream; bool useLocal = false; Client httpClient; downloadFile(String fileName,String link) async { StreamedResponse _response; List _bytes = []; int _total = 0; httpClient = await util.getOauth2Client(); print('Start Download $link'); _progress.add(null); try { void mainThrow(e){ cancel(); _progress.add(-1.0); if(util.htmlErrorTitle(e.message??e)!=""){ _error = util.htmlErrorTitle(e.message??e); } else _error = e.message??e; // print("mainthrow $_error"); } Request req = new Request('GET', Uri.parse(link)); // req.headers = ''; _response = await httpClient.send(req).timeout( Duration(seconds: 20)); // _response = await client.get('$link',headers: 'application/json') if(_response.statusCode==200){ _total = _response.contentLength?? int.parse(_response.headers['file-size']); } // print('${_total / 1024} KB'); _error = ''; dlulStream = _response.stream.listen((value) { if(_response.statusCode==200){ _bytes.addAll(value); _progress.add(((_bytes.length / _total))); } else{ // print("masuk error"); // this.cancel(); // cancel(); //stop stream String resString = utf8.decode(value); // if(util.htmlErrorTitle(resString)!=""){ // _error = util.htmlErrorTitle(resString); // } // else // _error = resString; mainThrow(Exception(resString)); } },onDone:() async { if(_error==''){ _progress.add(0.0); print('Finish Download'); final file = File( "${(await getApplicationDocumentsDirectory()).path}/$fileName"); await file.writeAsBytes(_bytes); _path = file.path; } else{ mainThrow(_error); } } ,onError: (e) async { mainThrow(e); },cancelOnError: true); } on HandshakeException catch(e){ cancel(); if(useLocal){ // print('Error Download 3, $e'); _progress.add(-1.0); if(util.htmlErrorTitle(e.message ?? e)!=""){ _error = util.htmlErrorTitle(e.message ?? e); } else _error = e.toString(); } else{ useLocal = true; http = IOClient(HttpClient(context: clientContext)); await downloadFile(fileName,link); } } catch(e){ cancel(); _progress.add(-1.0); if(util.htmlErrorTitle(e.message??e)!=""){ _error = util.htmlErrorTitle(e.message??e); } else _error = e.toString(); } } uploadFile(String fileName,String link,String company,String cabang_id) async{ httpClient = await util.getOauth2Client(); oauth2.Credentials tokenRestData = oauth2.Credentials.fromJson(prefs.getString(keyClass.rest_data)); final file = File( "${(await getApplicationDocumentsDirectory()).path}/$fileName"); String mimeType = 'application/vnd.sqlite3'; if(file.existsSync()){ Uint8List byte = file.readAsBytesSync(); try{ var _response = await httpClient.put( Uri.parse(link), headers: {"cabangId":cabang_id,"company":company,'Content-type': mimeType,'Authorization':'Bearer ${tokenRestData.accessToken}'}, body: byte).onError((error, stackTrace){ return new Response("Internal Server Error", 400); }); print('File send ${file.lengthSync()/1024} KB'); if(_response.statusCode!=200){ if(util.htmlErrorTitle(_response.body.toString())!=""){ return {"STATUS":0,"DATA":util.htmlErrorTitle(_response.body.toString())}; } throw _response.body.toString(); } final Map data = JsonDecoder().convert(_response.body); // print(_response.body); // if(data['STATUS']==1){ // return {"STATUS":1,"DATA":'File send ${file.lengthSync()/1024} KB'}; // } // else { return data; // } } on HandshakeException catch(e){ if(useLocal){ return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'}; } else{ useLocal = true; http = IOClient(HttpClient(context: clientContext)); return await uploadFile( fileName, link, company, cabang_id); } } catch(e){ print(e); return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'}; } } else{ return {"STATUS":0,"DATA":'No such file'}; } } unPackDb(String link,String company,String cabang_id,String dbPath) async{ try{ var _response = await http.post( Uri.parse(link), headers: {'Content-type': 'application/json'}, body: json.encode({"cabangId":cabang_id,"company":company,"dbPath":dbPath})); final Map data = JsonDecoder().convert(_response.body); return data; } on HandshakeException catch(e){ if(useLocal){ return {"STATUS":0,"DATA":'Upload timeout. Make sure server is up and running'}; } else{ useLocal = true; http = IOClient(HttpClient(context: clientContext)); return await unPackDb( link, company, cabang_id, dbPath); } } catch(e){ print(e); return {"STATUS":0,"DATA":'Upload timeout. Make sure server is up and running'}; } } submitDb(String link,String company,String stock_id) async{ try{ var _response = await http.post( Uri.parse(link), headers: {'Content-type': 'application/json'}, body: json.encode({"stockTakingId":stock_id,"company":company})); final Map data = JsonDecoder().convert(_response.body); return data; } on HandshakeException catch(e){ if(useLocal){ return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'}; } else{ useLocal = true; http = IOClient(HttpClient(context: clientContext)); return await submitDb(link,company,stock_id); } } catch(e){ print(e); return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'}; } } // apex rest blm support multipart uploadMultipart(String fileName,String link)async{ httpClient = await util.getOauth2Client(); StreamedResponse _response; List _bytes = []; int _total = 0; try{ var request = MultipartRequest('PUT', Uri.parse(link)); request.files.add( await MultipartFile.fromPath( 'picture', "${(await getApplicationDocumentsDirectory()).path}/$fileName" ) ); _response = await httpClient.send(request); _total = File("${(await getApplicationDocumentsDirectory()).path}/$fileName").lengthSync(); dlulStream = _response.stream.listen((value) { _bytes.addAll(value); print('upload ${_bytes.length/_total}'); _progress.add(((_bytes.length / _total))); }) ..onDone(() async { _progress.add(0.0); print('Finish Download'); final file = File( "${(await getApplicationDocumentsDirectory()).path}/$fileName"); await file.writeAsBytes(_bytes); _path = file.path; }) ..onError((e) async { print('Error Download, $e'); _progress.add(-1.0); _error = e.toString(); }); } on HandshakeException catch(e){ if(useLocal){ print('Error Download, $e'); _progress.add(-1.0); _error = e.toString(); } else{ useLocal = true; http = IOClient(HttpClient(context: clientContext)); await uploadMultipart(fileName,link); } } } cancel()async{ // http?.close(); await dlulStream?.cancel(); _progress?.close(); } }