Business Login Flutter Apps
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

267 line
8.4 KiB

  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'dart:typed_data';
  5. import 'package:http/io_client.dart';
  6. import 'package:path_provider/path_provider.dart';
  7. import 'package:http/http.dart';
  8. import 'package:unitstocks/Utils/keys.dart';
  9. import '../main.dart';
  10. import 'package:oauth2/oauth2.dart' as oauth2;
  11. class file_Trans_Handler {
  12. // double _progress = 0;
  13. String _path = '';
  14. late StreamSubscription dlulStream;
  15. String _error = '';
  16. get path => _path;
  17. get error => _error;
  18. StreamController _progress = new StreamController<double?>();
  19. Stream<dynamic> get progress =>_progress.stream;
  20. bool useLocal = false;
  21. late Client httpClient;
  22. downloadFile(String fileName,String link) async {
  23. StreamedResponse _response;
  24. List<int> _bytes = [];
  25. int _total = 0;
  26. httpClient = await util.getOauth2Client();
  27. print('Start Download $link');
  28. _progress.add(null);
  29. try {
  30. Directory? dir = await getExternalStorageDirectory();
  31. void mainThrow(e){
  32. cancel();
  33. _progress.add(-1.0);
  34. if(util.htmlErrorTitle(e.message??e)!=""){
  35. _error = util.htmlErrorTitle(e.message??e);
  36. }
  37. else _error = e.message??e;
  38. }
  39. Request req = new Request('GET', Uri.parse(link));
  40. // req.headers = '';
  41. _response = await httpClient.send(req).timeout(
  42. Duration(seconds: 20));
  43. // _response = await client.get('$link',headers: 'application/json')
  44. if(_response.statusCode==200){
  45. _total = _response.contentLength?? int.parse(_response.headers['file-size']??'0');
  46. }
  47. // print('${_total / 1024} KB');
  48. _error = '';
  49. dlulStream = _response.stream.listen((value) {
  50. if(_response.statusCode==200){
  51. _bytes.addAll(value);
  52. _progress.add(((_bytes.length / _total)));
  53. }
  54. else{
  55. // print("masuk error");
  56. // this.cancel();
  57. // cancel(); //stop stream
  58. String resString = utf8.decode(value);
  59. // if(util.htmlErrorTitle(resString)!=""){
  60. // _error = util.htmlErrorTitle(resString);
  61. // }
  62. // else
  63. // _error = resString;
  64. mainThrow(Exception(resString));
  65. }
  66. },onDone:() async {
  67. if(_error==''){
  68. // _progress.add(0.0);
  69. print('Finish Download');
  70. final file = File(
  71. "${dir!.path}/$fileName");
  72. await file.writeAsBytes(_bytes);
  73. _path = file.path;
  74. }
  75. else{
  76. mainThrow(_error);
  77. }
  78. } ,onError: (e) async {
  79. mainThrow(e);
  80. },cancelOnError: true);
  81. }
  82. on HandshakeException catch(e){
  83. cancel();
  84. if(useLocal){
  85. // print('Error Download 3, $e');
  86. _progress.add(-1.0);
  87. if(util.htmlErrorTitle(e.message)!=""){
  88. _error = util.htmlErrorTitle(e.message);
  89. }
  90. else _error = e.toString();
  91. }
  92. else{
  93. useLocal = true;
  94. http = IOClient(HttpClient(context: clientContext));
  95. await downloadFile(fileName,link);
  96. }
  97. }
  98. catch(e){
  99. cancel();
  100. _progress.add(-1.0);
  101. if(util.htmlErrorTitle(e.toString())!=""){
  102. _error = util.htmlErrorTitle(e.toString());
  103. }
  104. else _error = e.toString();
  105. }
  106. }
  107. uploadFile(String fileName,String link,String company,String cabang_id) async{
  108. httpClient = await util.getOauth2Client();
  109. Directory? dir = await getExternalStorageDirectory();
  110. oauth2.Credentials tokenRestData = oauth2.Credentials.fromJson(prefs.getString(Keys.restData));
  111. final file = File(
  112. "${dir!.path}/$fileName");
  113. String mimeType = 'application/vnd.sqlite3';
  114. if(file.existsSync()){
  115. Uint8List byte = file.readAsBytesSync();
  116. try{
  117. var _response = await httpClient.put(
  118. Uri.parse(link), headers: {"cabangId":cabang_id,"company":company,'Content-type': mimeType,'Authorization':'Bearer ${tokenRestData.accessToken}'},
  119. body: byte).onError((error, stackTrace){
  120. return new Response("Internal Server Error", 400);
  121. });
  122. print('File send ${file.lengthSync()/1024} KB');
  123. if(_response.statusCode!=200){
  124. if(util.htmlErrorTitle(_response.body.toString())!=""){
  125. return {"STATUS":0,"DATA":util.htmlErrorTitle(_response.body.toString())};
  126. }
  127. throw _response.body.toString();
  128. }
  129. final Map data = JsonDecoder().convert(_response.body);
  130. // print(_response.body);
  131. // if(data['STATUS']==1){
  132. // return {"STATUS":1,"DATA":'File send ${file.lengthSync()/1024} KB'};
  133. // }
  134. // else {
  135. return data;
  136. // }
  137. }
  138. on HandshakeException catch(e){
  139. if(useLocal){
  140. return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'};
  141. }
  142. else{
  143. useLocal = true;
  144. http = IOClient(HttpClient(context: clientContext));
  145. return await uploadFile( fileName, link, company, cabang_id);
  146. }
  147. }
  148. catch(e){
  149. print(e);
  150. return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'};
  151. }
  152. }
  153. else{
  154. return {"STATUS":0,"DATA":'No such file'};
  155. }
  156. }
  157. unPackDb(String link,String company,String cabang_id,String dbPath) async{
  158. try{
  159. var _response = await http.post(
  160. Uri.parse(link), headers: {'Content-type': 'application/json'},
  161. body: json.encode({"cabangId":cabang_id,"company":company,"dbPath":dbPath}));
  162. final Map data = JsonDecoder().convert(_response.body);
  163. return data;
  164. }
  165. on HandshakeException catch(e){
  166. if(useLocal){
  167. return {"STATUS":0,"DATA":'Upload timeout. Make sure server is up and running'};
  168. }
  169. else{
  170. useLocal = true;
  171. http = IOClient(HttpClient(context: clientContext));
  172. return await unPackDb( link, company, cabang_id, dbPath);
  173. }
  174. }
  175. catch(e){
  176. print(e);
  177. return {"STATUS":0,"DATA":'Upload timeout. Make sure server is up and running'};
  178. }
  179. }
  180. submitDb(String link,String company,String stock_id) async{
  181. try{
  182. var _response = await http.post(
  183. Uri.parse(link), headers: {'Content-type': 'application/json'},
  184. body: json.encode({"stockTakingId":stock_id,"company":company}));
  185. final Map data = JsonDecoder().convert(_response.body);
  186. return data;
  187. }
  188. on HandshakeException catch(e){
  189. if(useLocal){
  190. return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'};
  191. }
  192. else{
  193. useLocal = true;
  194. http = IOClient(HttpClient(context: clientContext));
  195. return await submitDb(link,company,stock_id);
  196. }
  197. }
  198. catch(e){
  199. print(e);
  200. return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'};
  201. }
  202. }
  203. // apex rest blm support multipart
  204. uploadMultipart(String fileName,String link)async{
  205. httpClient = await util.getOauth2Client();
  206. StreamedResponse _response;
  207. List<int> _bytes = [];
  208. int _total = 0;
  209. try{
  210. Directory? dir = await getExternalStorageDirectory();
  211. var request = MultipartRequest('PUT', Uri.parse(link));
  212. request.files.add(
  213. await MultipartFile.fromPath(
  214. 'picture',
  215. "${dir!.path}/$fileName"
  216. )
  217. );
  218. _response = await httpClient.send(request);
  219. _total = File("${dir.path}/$fileName").lengthSync();
  220. dlulStream = _response.stream.listen((value) {
  221. _bytes.addAll(value);
  222. print('upload ${_bytes.length/_total}');
  223. _progress.add(((_bytes.length / _total)));
  224. })
  225. ..onDone(() async {
  226. _progress.add(0.0);
  227. print('Finish Download');
  228. final file = File(
  229. "${dir.path}/$fileName");
  230. await file.writeAsBytes(_bytes);
  231. _path = file.path;
  232. })
  233. ..onError((e) async {
  234. print('Error Download, $e');
  235. _progress.add(-1.0);
  236. _error = e.toString();
  237. });
  238. }
  239. on HandshakeException catch(e){
  240. if(useLocal){
  241. print('Error Download, $e');
  242. _progress.add(-1.0);
  243. _error = e.toString();
  244. }
  245. else{
  246. useLocal = true;
  247. http = IOClient(HttpClient(context: clientContext));
  248. await uploadMultipart(fileName,link);
  249. }
  250. }
  251. }
  252. cancel()async{
  253. // http?.close();
  254. await dlulStream.cancel();
  255. _progress.close();
  256. }
  257. }