flutter app untuk unitstock
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 

273 行
8.6 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. // 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. "${(await getExternalStorageDirectory()).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 ?? e)!=""){
  88. _error = util.htmlErrorTitle(e.message ?? e);
  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.message??e)!=""){
  102. _error = util.htmlErrorTitle(e.message??e);
  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. oauth2.Credentials tokenRestData = oauth2.Credentials.fromJson(prefs.getString(keyClass.rest_data));
  110. final file = File(
  111. "${(await getExternalStorageDirectory()).path}/$fileName");
  112. String mimeType = 'application/vnd.sqlite3';
  113. if(file.existsSync()){
  114. Uint8List byte = file.readAsBytesSync();
  115. try{
  116. var _response = await httpClient.put(
  117. Uri.parse(link), headers: {"User":prefs.getString(keyClass.loginId),"cabangId":cabang_id,"company":company,'Content-type': mimeType,'Authorization':'Bearer ${tokenRestData.accessToken}'},
  118. body: byte).onError((error, stackTrace){
  119. return new Response("Internal Server Error", 400);
  120. });
  121. print('File send ${file.lengthSync()/1024} KB');
  122. if(_response.statusCode!=200){
  123. if(util.htmlErrorTitle(_response.body.toString())!=""){
  124. return {"STATUS":0,"DATA":util.htmlErrorTitle(_response.body.toString())};
  125. }
  126. throw _response.body.toString();
  127. }
  128. final Map data = JsonDecoder().convert(_response.body);
  129. // print(_response.body);
  130. // if(data['STATUS']==1){
  131. // return {"STATUS":1,"DATA":'File send ${file.lengthSync()/1024} KB'};
  132. // }
  133. // else {
  134. return data;
  135. // }
  136. }
  137. on HandshakeException catch(e){
  138. if(useLocal){
  139. return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'};
  140. }
  141. else{
  142. useLocal = true;
  143. http = IOClient(HttpClient(context: clientContext));
  144. return await uploadFile( fileName, link, company, cabang_id);
  145. }
  146. }
  147. catch(e){
  148. print(e);
  149. var message;
  150. try{
  151. var Obj = JsonDecoder().convert(e);
  152. message = Obj["DATA"];
  153. }
  154. catch(e) {
  155. message = 'Request timeout. Make sure server is up and running';
  156. }
  157. return {"STATUS":0,"DATA":message};
  158. }
  159. }
  160. else{
  161. return {"STATUS":0,"DATA":'No such file'};
  162. }
  163. }
  164. unPackDb(String link,String company,String cabang_id,String dbPath) async{
  165. try{
  166. var _response = await http.post(
  167. Uri.parse(link), headers: {'Content-type': 'application/json'},
  168. body: json.encode({"cabangId":cabang_id,"company":company,"dbPath":dbPath}));
  169. final Map data = JsonDecoder().convert(_response.body);
  170. return data;
  171. }
  172. on HandshakeException catch(e){
  173. if(useLocal){
  174. return {"STATUS":0,"DATA":'Upload timeout. Make sure server is up and running'};
  175. }
  176. else{
  177. useLocal = true;
  178. http = IOClient(HttpClient(context: clientContext));
  179. return await unPackDb( link, company, cabang_id, dbPath);
  180. }
  181. }
  182. catch(e){
  183. print(e);
  184. return {"STATUS":0,"DATA":'Upload timeout. Make sure server is up and running'};
  185. }
  186. }
  187. submitDb(String link,String company,String stock_id) async{
  188. try{
  189. var _response = await http.post(
  190. Uri.parse(link), headers: {'Content-type': 'application/json'},
  191. body: json.encode({"stockTakingId":stock_id,"company":company}));
  192. final Map data = JsonDecoder().convert(_response.body);
  193. return data;
  194. }
  195. on HandshakeException catch(e){
  196. if(useLocal){
  197. return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'};
  198. }
  199. else{
  200. useLocal = true;
  201. http = IOClient(HttpClient(context: clientContext));
  202. return await submitDb(link,company,stock_id);
  203. }
  204. }
  205. catch(e){
  206. print(e);
  207. return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'};
  208. }
  209. }
  210. // apex rest blm support multipart
  211. uploadMultipart(String fileName,String link)async{
  212. httpClient = await util.getOauth2Client();
  213. StreamedResponse _response;
  214. List<int> _bytes = [];
  215. int _total = 0;
  216. try{
  217. var request = MultipartRequest('PUT', Uri.parse(link));
  218. request.files.add(
  219. await MultipartFile.fromPath(
  220. 'picture',
  221. "${(await getExternalStorageDirectory()).path}/$fileName"
  222. )
  223. );
  224. _response = await httpClient.send(request);
  225. _total = File("${(await getExternalStorageDirectory()).path}/$fileName").lengthSync();
  226. dlulStream = _response.stream.listen((value) {
  227. _bytes.addAll(value);
  228. print('upload ${_bytes.length/_total}');
  229. _progress.add(((_bytes.length / _total)));
  230. })
  231. ..onDone(() async {
  232. _progress.add(0.0);
  233. print('Finish Download');
  234. final file = File(
  235. "${(await getExternalStorageDirectory()).path}/$fileName");
  236. await file.writeAsBytes(_bytes);
  237. _path = file.path;
  238. })
  239. ..onError((e) async {
  240. print('Error Download, $e');
  241. _progress.add(-1.0);
  242. _error = e.toString();
  243. });
  244. }
  245. on HandshakeException catch(e){
  246. if(useLocal){
  247. print('Error Download, $e');
  248. _progress.add(-1.0);
  249. _error = e.toString();
  250. }
  251. else{
  252. useLocal = true;
  253. http = IOClient(HttpClient(context: clientContext));
  254. await uploadMultipart(fileName,link);
  255. }
  256. }
  257. }
  258. cancel()async{
  259. // http?.close();
  260. await dlulStream?.cancel();
  261. _progress?.close();
  262. }
  263. }