flutter app untuk unitstock
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

273 lines
8.7 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/Util/Prefs.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. StreamSubscription dlulStream;
  15. String _error = '';
  16. get path => _path;
  17. get error => _error;
  18. StreamController _progress = new StreamController<double>();
  19. Stream<double> get progress =>_progress.stream;
  20. bool useLocal = false;
  21. 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. void mainThrow(e){
  31. cancel();
  32. _progress.add(-1.0);
  33. if(util.htmlErrorTitle(e.message??e)!=""){
  34. _error = util.htmlErrorTitle(e.message??e);
  35. }
  36. else _error = e.message??e;
  37. // print("mainthrow $_error");
  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']);
  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. print(resString);
  60. // if(util.htmlErrorTitle(resString)!=""){
  61. // _error = util.htmlErrorTitle(resString);
  62. // }
  63. // else
  64. // _error = resString;
  65. mainThrow(Exception(resString));
  66. }
  67. },onDone:() async {
  68. if(_error==''){
  69. _progress.add(0.0);
  70. print('Finish Download');
  71. final file = File(
  72. "${(await getApplicationDocumentsDirectory()).path}/$fileName");
  73. await file.writeAsBytes(_bytes);
  74. _path = file.path;
  75. }
  76. else{
  77. mainThrow(_error);
  78. }
  79. } ,onError: (e) async {
  80. mainThrow(e);
  81. },cancelOnError: true);
  82. }
  83. on HandshakeException catch(e){
  84. cancel();
  85. if(useLocal){
  86. // print('Error Download 3, $e');
  87. _progress.add(-1.0);
  88. if(util.htmlErrorTitle(e.message ?? e)!=""){
  89. _error = util.htmlErrorTitle(e.message ?? e);
  90. }
  91. else _error = e.toString();
  92. }
  93. else{
  94. useLocal = true;
  95. http = IOClient(HttpClient(context: clientContext));
  96. await downloadFile(fileName,link);
  97. }
  98. }
  99. catch(e){
  100. cancel();
  101. _progress.add(-1.0);
  102. if(util.htmlErrorTitle(e.message??e)!=""){
  103. _error = util.htmlErrorTitle(e.message??e);
  104. }
  105. else _error = e.toString();
  106. }
  107. }
  108. uploadFile(String fileName,String link,String company,String cabang_id) async{
  109. httpClient = await util.getOauth2Client();
  110. oauth2.Credentials tokenRestData = oauth2.Credentials.fromJson(prefs.getString(keyClass.rest_data));
  111. final file = File(
  112. "${(await getApplicationDocumentsDirectory()).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: {"User":prefs.getString(keyClass.loginId),"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. var message;
  151. try{
  152. var Obj = JsonDecoder().convert(e);
  153. message = Obj["DATA"];
  154. }
  155. catch(e) {
  156. message = 'Request timeout. Make sure server is up and running';
  157. }
  158. return {"STATUS":0,"DATA":message};
  159. }
  160. }
  161. else{
  162. return {"STATUS":0,"DATA":'No such file'};
  163. }
  164. }
  165. unPackDb(String link,String company,String cabang_id,String dbPath) async{
  166. try{
  167. var _response = await http.post(
  168. Uri.parse(link), headers: {'Content-type': 'application/json'},
  169. body: json.encode({"cabangId":cabang_id,"company":company,"dbPath":dbPath}));
  170. final Map data = JsonDecoder().convert(_response.body);
  171. return data;
  172. }
  173. on HandshakeException catch(e){
  174. if(useLocal){
  175. return {"STATUS":0,"DATA":'Upload timeout. Make sure server is up and running'};
  176. }
  177. else{
  178. useLocal = true;
  179. http = IOClient(HttpClient(context: clientContext));
  180. return await unPackDb( link, company, cabang_id, dbPath);
  181. }
  182. }
  183. catch(e){
  184. print(e);
  185. return {"STATUS":0,"DATA":'Upload timeout. Make sure server is up and running'};
  186. }
  187. }
  188. submitDb(String link,String company,String stock_id) async{
  189. try{
  190. var _response = await http.post(
  191. Uri.parse(link), headers: {'Content-type': 'application/json'},
  192. body: json.encode({"stockTakingId":stock_id,"company":company}));
  193. final Map data = JsonDecoder().convert(_response.body);
  194. return data;
  195. }
  196. on HandshakeException catch(e){
  197. if(useLocal){
  198. return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'};
  199. }
  200. else{
  201. useLocal = true;
  202. http = IOClient(HttpClient(context: clientContext));
  203. return await submitDb(link,company,stock_id);
  204. }
  205. }
  206. catch(e){
  207. print(e);
  208. return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'};
  209. }
  210. }
  211. // apex rest blm support multipart
  212. uploadMultipart(String fileName,String link)async{
  213. httpClient = await util.getOauth2Client();
  214. StreamedResponse _response;
  215. List<int> _bytes = [];
  216. int _total = 0;
  217. try{
  218. var request = MultipartRequest('PUT', Uri.parse(link));
  219. request.files.add(
  220. await MultipartFile.fromPath(
  221. 'picture',
  222. "${(await getApplicationDocumentsDirectory()).path}/$fileName"
  223. )
  224. );
  225. _response = await httpClient.send(request);
  226. _total = File("${(await getApplicationDocumentsDirectory()).path}/$fileName").lengthSync();
  227. dlulStream = _response.stream.listen((value) {
  228. _bytes.addAll(value);
  229. print('upload ${_bytes.length/_total}');
  230. _progress.add(((_bytes.length / _total)));
  231. })
  232. ..onDone(() async {
  233. _progress.add(0.0);
  234. print('Finish Download');
  235. final file = File(
  236. "${(await getApplicationDocumentsDirectory()).path}/$fileName");
  237. await file.writeAsBytes(_bytes);
  238. _path = file.path;
  239. })
  240. ..onError((e) async {
  241. print('Error Download, $e');
  242. _progress.add(-1.0);
  243. _error = e.toString();
  244. });
  245. }
  246. on HandshakeException catch(e){
  247. if(useLocal){
  248. print('Error Download, $e');
  249. _progress.add(-1.0);
  250. _error = e.toString();
  251. }
  252. else{
  253. useLocal = true;
  254. http = IOClient(HttpClient(context: clientContext));
  255. await uploadMultipart(fileName,link);
  256. }
  257. }
  258. }
  259. cancel()async{
  260. // http?.close();
  261. await dlulStream?.cancel();
  262. _progress?.close();
  263. }
  264. }