lido_api.dart 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. //import 'package:html';
  2. import 'dart:convert';
  3. import 'dart:developer';
  4. import 'dart:io';
  5. import 'package:flutter_riverpod/flutter_riverpod.dart';
  6. import 'package:hive_flutter/hive_flutter.dart';
  7. import 'package:http/http.dart' as http;
  8. import 'package:flutter/foundation.dart';
  9. import 'package:jiffy/jiffy.dart';
  10. import 'package:tp5/core/utils.dart';
  11. final lidoapiProvider = Provider<LidoApi>((ref) {
  12. return LidoApi();
  13. });
  14. class LidoApi {
  15. //static const url = "https://tar.lido.aero";
  16. static const url =
  17. kIsWeb ? "https://proxy.fares.cyou" : "https://tar.lido.aero";
  18. //static const url = "https://proxy.fares.cyou";
  19. static const realurl = "https://tar.lido.aero";
  20. final timeout = Duration(seconds: 7);
  21. LidoApi({this.username = "", this.password = ""});
  22. bool logged = false;
  23. String username;
  24. String password;
  25. String get cookie =>
  26. "${cookieMap.keys.fold("", (t, e) => (t == "") ? "$e=${cookieMap[e]}" : "$t; $e=${cookieMap[e]}")};SameSite=None; Secure";
  27. Map cookieMap = {};
  28. Map<String, String> get headers => {
  29. "Accept": "application/vnd.lsy.lido.lcb.v1.hal+json",
  30. "Accept-Encoding": "gzip, deflate, br",
  31. "Accept-Language": "en",
  32. "Connection": "keep-alive",
  33. "Content-Type": "application/json;charset=UTF-8",
  34. //"Host": Uri.parse(realurl).host,
  35. "Origin": Uri.parse(realurl).host,
  36. //"sec-ch-ua":'" Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"',
  37. // "sec-ch-ua-mobile": "?0",
  38. // "sec-ch-ua-platform": "Windows",
  39. // "Sec-Fetch-Dest": "empty",
  40. // "Sec-Fetch-Mode": "cors",
  41. // "Sec-Fetch-Site": "same-origin",
  42. "User-Agent":
  43. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36',
  44. "X-lido-applicationId": "lido-lcb",
  45. "X-lido-clientId": "lido-lcb-web",
  46. "X-lido-customerId": "TAR",
  47. "X-lido-operatingAirline": "",
  48. "X-lido-timeStamp": DateTime.now().toUtc().toIso8601String(),
  49. "X-lido-traceId": "0c497133-2a92-45a0-8ffe-a03c77852201",
  50. "cookie": "SERVERID=docker2; $cookie",
  51. "X-lido-csrf": cookieMap["lido_csrf"] ?? "",
  52. };
  53. Future logout() async {
  54. var response = await http.post(Uri.parse('${url}USR/actionLogout.jsp'),
  55. body: {"Cookie": cookie});
  56. logged = false;
  57. }
  58. bool credSaved() {
  59. return (Hive.box("settings").get("lido_user", defaultValue: "") != "") &&
  60. (Hive.box("settings").get("lido_pass", defaultValue: "") != "");
  61. }
  62. Future login({String? user, String? pass, String? newpass}) async {
  63. username = user ?? Hive.box("settings").get("lido_user", defaultValue: "");
  64. password = pass ?? Hive.box("settings").get("lido_pass", defaultValue: "");
  65. try {
  66. var response = await http
  67. .get(
  68. Uri.parse(
  69. '$url/lido/las/login.jsp?DESMON_RESULT_PAGE=$realurl/briefing//'),
  70. )
  71. .timeout(timeout);
  72. cookieMap.addAll(_getcookies(response.headers["set-cookie"] ??
  73. response.headers["_set-cookie"] ??
  74. ""));
  75. //print(response.headers);
  76. response = await http.post(
  77. Uri.parse('$url/lido/las/dwr/call/plaincall/LoginBean.login.dwr'),
  78. body: {
  79. "callCount": "1",
  80. "nextReverseAjaxIndex": "0",
  81. "c0-scriptName": "LoginBean",
  82. "c0-methodName": "login",
  83. "c0-id": "0",
  84. "c0-param0": "string:$username",
  85. "c0-param1": "string:$password",
  86. "c0-param2": "string:${newpass ?? ""}",
  87. "c0-param3": "string:LIDO",
  88. "c0-param4": "string:en",
  89. "batchId": "0",
  90. "instanceId": "0",
  91. "page":
  92. "/lido/las/login.jsp?DESMON_RESULT_PAGE=$realurl/briefing&DESMON_CODE=LAS_002&DESMON_LANG=en",
  93. "scriptSessionId":
  94. "lSUqDnaTyhevHY6vpNvPdIR~IuUygzP8a2p/kYr1m2p-BgwpWJ4*a"
  95. },
  96. headers: {});
  97. cookieMap.addAll(_getcookies(response.headers["set-cookie"] ?? ""));
  98. //log("lidoapi: login : $username $password ${response.statusCode} ${response.body}");
  99. final message = RegExp(r'(?<=errorMessage2:")(.+)(?=",)')
  100. .firstMatch(response.body)
  101. ?.group(0) ??
  102. RegExp(r'(?<=errorMessage1:")(.+)(?=",)')
  103. .firstMatch(response.body)
  104. ?.group(0);
  105. final errorcode = RegExp(r'(?<=errorCode:)(.+?)(?=,)')
  106. .firstMatch(response.body)
  107. ?.group(0) ??
  108. "xx";
  109. final plschangepass =
  110. response.body.contains("please change your password");
  111. final changepass = RegExp(r'(?<=forcePasswdChange:)(.+)(?=,)')
  112. .firstMatch(response.body)
  113. ?.group(0) ==
  114. "true";
  115. // print("lidoapi: login: errorcode: $errorcode");
  116. // print("lidoapi: login: message: $message");
  117. // print("lidoapi: login: changepass: $changepass");
  118. // print("lidoapi: login: responsebody: ${response.body}");
  119. logged = errorcode == "null";
  120. cookieMap = (!logged) ? {} : cookieMap;
  121. // log("api lido 4d login \nuser:$username\npass:$password\nstatuscode${response.statusCode}\nlogged:$logged\nmsg:$message");
  122. log("api lido 4d login errorcode: $errorcode");
  123. //invalide username or password
  124. if (['"LAS_112"', '"LAS_113"'].contains(errorcode)) {
  125. print("lidoapi: login: invalidate user & pass");
  126. await Hive.box("settings").delete("lido_user");
  127. await Hive.box("settings").delete("lido_pass");
  128. if (username != "" && password != "") {
  129. await Hive.box("settings").put("lido_user_old", username);
  130. await Hive.box("settings").put("lido_pass_old", password);
  131. } //username = "";
  132. password = "";
  133. }
  134. final res = extractCallbackData(response.body);
  135. final passwordChanged =
  136. (newpass != null) && (res["errorMessage1"] != null);
  137. // log("lidoapi: login: return: ${extractCallbackData(response.body)}");
  138. if (newpass != null && passwordChanged) {
  139. await Hive.box("settings").put("lido_user", username);
  140. await Hive.box("settings").put("lido_pass", newpass);
  141. log("lidoapi: login: newpass: $newpass");
  142. }
  143. return {
  144. 'error': logged ? null : message,
  145. 'data': {
  146. "logged": logged,
  147. "message": message,
  148. "passwordChanged": passwordChanged
  149. },
  150. 'meta': {
  151. "changepass": changepass,
  152. "plschangepass": plschangepass,
  153. "user": username,
  154. "pass": password,
  155. "cookie": cookieMap,
  156. "errorcode": errorcode
  157. }
  158. };
  159. } catch (e) {
  160. return {
  161. 'error': e.toString(),
  162. 'data': {"logged": false},
  163. 'meta': {"user": username, "pass": password, "cookie": null}
  164. };
  165. }
  166. }
  167. Future forgotpass({String? user}) async {
  168. var response = await http.get(Uri.parse('$url/lido/las/login.jsp'));
  169. cookieMap.addAll(_getcookies(response.headers["set-cookie"] ?? ""));
  170. response = await http.post(
  171. Uri.parse(
  172. '$url/lido/las/dwr/call/plaincall/LoginBean.forgotPassword.dwr'),
  173. body: {
  174. "callCount": "1",
  175. "nextReverseAjaxIndex": "0",
  176. "c0-scriptName": "LoginBean",
  177. "c0-methodName": "forgotPasswordLink",
  178. "c0-id": "0",
  179. "c0-param0": "string:$user",
  180. "c0-param1":
  181. "string:$realurl/lido/lsc/application-center-ui/startCenter",
  182. "c0-param2": "string:LIDO",
  183. "c0-param3": "string:en",
  184. "batchId": "0",
  185. "instanceId": "0",
  186. "page":
  187. "/lido/las/forgotPassword.jsp?DESMON_RESULT_PAGE=$realurl/briefing&DESMON_CODE=LAS_002&DESMON_LANG=en",
  188. "scriptSessionId":
  189. "lSUqDnaTyhevHY6vpNvPdIR~IuUygzP8a2p/kYr1m2p-BgwpWJ4*a"
  190. });
  191. cookieMap.addAll(_getcookies(response.headers["set-cookie"] ?? ""));
  192. //print("lidoapi: forgotpass: header: ${response.headers}");
  193. //print("lidoapi: forgotpass: ${response.body}");
  194. return {
  195. 'error':
  196. response.statusCode < 300 ? null : response.statusCode.toString(),
  197. 'data': {},
  198. 'meta': {
  199. "user": username,
  200. "pass": password,
  201. "cookie": cookieMap,
  202. }
  203. };
  204. }
  205. Future changePass(
  206. {required String user,
  207. required String pass,
  208. required String token}) async {
  209. var response = await http.get(Uri.parse('$url/lido/las/login.jsp'));
  210. cookieMap.addAll(_getcookies(response.headers["set-cookie"] ?? ""));
  211. response = await http.post(
  212. Uri.parse(
  213. '$url/lido/las/dwr/call/plaincall/LoginBean.forgotPassword.dwr'),
  214. body: {
  215. "callCount": "1",
  216. "nextReverseAjaxIndex": "0",
  217. "c0-scriptName": "LoginBean",
  218. "c0-methodName": "changePassword",
  219. "c0-id": "0",
  220. "c0-param0": "string:$user",
  221. "c0-param1": "string:$pass",
  222. "c0-param2": "string:$token",
  223. "batchId": "0",
  224. "instanceId": "0",
  225. "page": "/lido/las/changePassword.jsp?token=$token",
  226. "scriptSessionId":
  227. "lBgkwVDs5bVASGOoKyVfCkOJjxBwXBJERcp/4WXGUcp-7few1oOHw"
  228. });
  229. cookieMap.addAll(_getcookies(response.headers["set-cookie"] ?? ""));
  230. final decodedMsg = extractCallbackData(response.body);
  231. for (var e in decodedMsg.entries) {
  232. decodedMsg[e.key] = e.value == "null" ? null : e.value;
  233. }
  234. return {
  235. 'error':
  236. response.statusCode < 300 ? null : response.statusCode.toString(),
  237. 'data': {
  238. "error": decodedMsg["erroeMessage1"] ?? decodedMsg["erroeMessage2"]
  239. },
  240. 'meta': {
  241. "user": username,
  242. "pass": password,
  243. "cookie": cookieMap,
  244. }
  245. };
  246. }
  247. Future getDoc(String link,
  248. {String? mediaType, bool loginfirst = false}) async {
  249. try {
  250. if (loginfirst) {
  251. final out = await login();
  252. if (!logged) return out;
  253. }
  254. final murl = link.replaceFirst(realurl, url);
  255. var response = await http.get(
  256. Uri.parse(murl)
  257. // .replace(queryParameters: {}),
  258. ,
  259. headers: {"X-lido-businessId": "ViewBP", ...headers});
  260. // log(response.headers.toString());
  261. Map decodedresponse;
  262. print("lidoapi: getdoc: ${response.statusCode} ");
  263. // try {
  264. // decodedresponse = json.decode(response.body) ?? {};
  265. // } catch (e) {
  266. // decodedresponse = {
  267. // "body": response.body,
  268. // "response": response.statusCode
  269. // };
  270. // }
  271. //log("lidoapi: getDoc: responsestatus: ${response.body}");
  272. if (!loginfirst && response.statusCode != 200) {
  273. return await getDoc(link, mediaType: mediaType, loginfirst: true);
  274. }
  275. // String? message = decodedresponse["errorsAndWarnings"]?["warnings"]?[0]
  276. // ?["message"] ??
  277. // decodedresponse["errorsAndWarnings"]?["errors"]?[0]?["message"] ??
  278. // ((response.statusCode == 200) ? null : "ERR");
  279. // log("lidoapi: getDoc: success: ${decodedresponse["content"]}");
  280. return {
  281. 'error': response.statusCode >= 300 ? response.statusCode : null,
  282. 'data': response.body,
  283. 'meta': {"user": username, "pass": password, "cookie": cookieMap}
  284. };
  285. } catch (e) {
  286. return {'error': e.toString(), 'data': {}, 'meta': {}};
  287. }
  288. }
  289. Future list(
  290. {Jiffy? start,
  291. Jiffy? end,
  292. String dep = "",
  293. String des = "",
  294. String al = "",
  295. String fnum = "",
  296. bool loginfirst = false}) async {
  297. final key =
  298. "${start?.format(pattern: "yyyyMMdd_HH_mm") ?? ""} $dep $des $al $fnum";
  299. try {
  300. if (loginfirst) {
  301. final out = await login();
  302. if (!logged) return out;
  303. }
  304. final startdate = (start ?? (Jiffy.now().toUtc().subtract(hours: 12)))
  305. .millisecondsSinceEpoch;
  306. final enddate = (end ??
  307. Jiffy.parseFromMillisecondsSinceEpoch(startdate).add(hours: 48))
  308. .millisecondsSinceEpoch;
  309. var response = await http.get(
  310. Uri.parse(
  311. "$url/lido/lcb/ui/flights?page=0&size=100&startDateTime=1653148128544&endDateTime=1653191328544")
  312. .replace(queryParameters: {
  313. "page": "0",
  314. "size": "1000",
  315. "startDateTime": startdate.toString(),
  316. "endDateTime": enddate.toString(),
  317. ...(al != "" ? {"commAirLine": al} : {}),
  318. ...(fnum != "" ? {"flightNumber": fnum} : {}),
  319. ...(dep != "" ? {"departure": dep} : {}),
  320. ...(des != "" ? {"destination": des} : {}),
  321. }),
  322. headers: {"X-lido-businessId": "SearchFlights", ...headers});
  323. //log(response.headers.toString());
  324. Map decodedresponse;
  325. // print("${response.body}");
  326. try {
  327. decodedresponse = json.decode(response.body) ?? {};
  328. } catch (e) {
  329. decodedresponse = {
  330. "body": response.body,
  331. "response": response.statusCode
  332. };
  333. }
  334. //log("lidoapi: list: responsestatus: ${response.statusCode}");
  335. if (!loginfirst && response.statusCode != 200) {
  336. return await list(
  337. al: al,
  338. fnum: fnum,
  339. dep: dep,
  340. des: des,
  341. start: start,
  342. end: end,
  343. loginfirst: true);
  344. }
  345. String? message = decodedresponse["errorsAndWarnings"]?["warnings"]?[0]
  346. ?["message"] ??
  347. decodedresponse["errorsAndWarnings"]?["errors"]?[0]?["message"] ??
  348. ((response.statusCode == 200) ? null : "ERR");
  349. // log("lidoapi: list: success: ${decodedresponse["content"]}");
  350. Map res = {
  351. 'error': message,
  352. 'data': (message == null) ? decodedresponse["content"] : null,
  353. 'meta': {
  354. "legs": (decodedresponse["totalElements"] ?? 0) > 0
  355. ? decodedresponse["content"].fold([], (t, e) {
  356. t.add(e["leg"]["legidentifier"]);
  357. return t;
  358. })
  359. : [],
  360. "user": username,
  361. "pass": password,
  362. "nb": decodedresponse["totalElements"] ?? 0,
  363. "cookie": cookieMap
  364. }
  365. };
  366. // cache response if success
  367. Hive.box("lido").put(key, json.encode(res));
  368. return res;
  369. } catch (e) {
  370. print("lidoapi: list:");
  371. final res = {
  372. 'error': e.toString(),
  373. 'data': {},
  374. 'meta': {},
  375. 'cache': json.decode(Hive.box("lido").get(key, defaultValue: "{}"))
  376. };
  377. return res;
  378. }
  379. }
  380. Future ofp(
  381. {required String legid,
  382. String? brieflink,
  383. bool loginfirst = false}) async {
  384. try {
  385. if (loginfirst) {
  386. final out = await login();
  387. if (!logged) return out;
  388. }
  389. // brieflink = res["data"]?[0]?["_links"]?["self"]?["href"];
  390. // legid = res["data"]?[0]?["leg"]?["legidentifier"];
  391. brieflink = brieflink ?? "$url/lido/lcb/ui/$legid/briefing";
  392. var response = await http.put(Uri.parse(brieflink),
  393. headers: {
  394. "X-lido-businessId": 'SearchBP',
  395. ...headers,
  396. },
  397. //body: json.encode(({"commercialAirline": al,"flightNumber": fnum,"operationalSuffix": "","date": dateoforigin.toString()
  398. body: json.encode(({
  399. "categories": [
  400. "OFP",
  401. "IWFR",
  402. "ATS",
  403. "DISP",
  404. "NOTAM",
  405. "SIGWXROUTE",
  406. "VERTPROF",
  407. "CREWINFO",
  408. "UAD",
  409. "RAIM",
  410. "VAATCA",
  411. "CDA",
  412. "DISMAP",
  413. "DMS",
  414. "ABD",
  415. "OFPDLK",
  416. "TLR",
  417. // "OFP",
  418. // "NOTAM",
  419. // // "APTDXML",
  420. // "SOFP",
  421. // "CDA",
  422. // "RADAR",
  423. // "OFPDLK",
  424. // // "ATSXML",
  425. // // "REGWXXML",
  426. // "WXSIGWX",
  427. // "SIGWXROUTE",
  428. // "VAATCA",
  429. // // "ASPDXML",
  430. // // "NOTAMXML",
  431. // "OTS",
  432. // "SFC",
  433. // "WINDDATA",
  434. // // "RAIMXML",
  435. // "TLR",
  436. // // "ARPTWXXML",
  437. // "SOFPINFO",
  438. // // "HAZARDADVISORYXML",
  439. // "IWFRXML",
  440. // "OFPNLXML",
  441. // "VERTPROF",
  442. // "SOFPSUM",
  443. // "APLI",
  444. // "RAIM",
  445. // "UAD",
  446. // "DISMAP",
  447. // "WXSATWX"
  448. // "APLI",
  449. // "APTDXML",
  450. // "SOFP",
  451. // "CDA",
  452. // "RADAR",
  453. // "OFPDLK",
  454. // "ATSXML",
  455. // "REGWXXML",
  456. // "WXSIGWX",
  457. // "SIGWXROUTE",
  458. // "VAATCA",
  459. // "ASPDXML",
  460. // "NOTAMXML",
  461. // "OTS",
  462. // "SFC",
  463. // "WINDDATA",
  464. // "RAIMXML",
  465. // "ARPTWXXML",
  466. // "SOFPINFO",
  467. // "IWFRXML",
  468. // "OFPNLXML",
  469. // "VERTPROF",
  470. // "SOFPSUM",
  471. // "RAIM",
  472. // "UAD",
  473. // "DISMAP",
  474. // "WXSATWX"
  475. ],
  476. })));
  477. //log(response.body);
  478. Map decodedresponse;
  479. try {
  480. decodedresponse = (json.decode(response.body) ?? {});
  481. } catch (e) {
  482. decodedresponse = {};
  483. }
  484. String? message = decodedresponse["errorsAndWarnings"]?["warnings"]?[0]
  485. ?["message"] ??
  486. decodedresponse["errorsAndWarnings"]?["errors"]?[0]?["message"] ??
  487. ((response.statusCode == 201) ? null : "ERR");
  488. log("lidoapi: ofp: statuscode: ${response.statusCode} msg: $message");
  489. return {
  490. 'error': (message == null) ? null : message,
  491. 'data': decodedresponse,
  492. 'meta': {
  493. "user": username,
  494. "pass": password,
  495. "cookie": cookieMap,
  496. "legid": legid
  497. }
  498. };
  499. } catch (e) {
  500. return {'error': e.toString(), 'data': {}, 'meta': {}};
  501. }
  502. }
  503. Future ofppdf(
  504. {required String legid, String? fileid, bool loginfirst = false}) async {
  505. try {
  506. if (loginfirst) {
  507. final out = await login();
  508. if (!logged) return out;
  509. }
  510. var response = await http.put(
  511. Uri.parse("$url/lido/lcb/ui/briefing/multi/print?force=true"),
  512. headers: {
  513. "Accept":
  514. "application/vnd.lsy.lido.lcb.v1.hal+json,application/pdf",
  515. //"Accept-Encoding": "gzip, deflate, br",
  516. "Accept-Language": "en",
  517. "Connection": "keep-alive",
  518. "Content-Type": "application/json;charset=UTF-8",
  519. "Cookie": cookie,
  520. //"host": Uri.parse(realurl).host,
  521. "Origin": Uri.parse(realurl).host,
  522. // "sec-ch-ua":'" Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"',
  523. "User-Agent":
  524. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36",
  525. "X-lido-applicationId": "lido-lcb",
  526. "X-lido-businessId": "printBP",
  527. "X-lido-clientId": "lido-lcb-web",
  528. "X-lido-csrf": cookieMap["lido_csrf"] ?? "",
  529. "X-lido-customerId": "TAR",
  530. "X-lido-operatingAirline": "TU",
  531. "X-lido-timeStamp": "2022-05-25T06:29:56.659Z",
  532. "X-lido-traceId": "3cbab7e0-56ca-49ec-b158-8899c0d3bbbb",
  533. },
  534. body: json.encode({
  535. "legIdentifiers": [legid],
  536. "categories": [
  537. "OFP",
  538. "ATS",
  539. "CREWINFO",
  540. "DISP",
  541. "IWFR",
  542. "NOTAM",
  543. "UAD",
  544. "WXSIGWX",
  545. "VERTPROF",
  546. "RAIM",
  547. "DMS",
  548. "WXNOTAM",
  549. "ABD",
  550. "SIGWXROUTE",
  551. //"WXSATWX"
  552. ],
  553. "merge": false,
  554. "quickprint": false,
  555. "weatherDataRequired": false,
  556. }));
  557. if (!loginfirst && response.statusCode > 201) {
  558. return ofppdf(legid: legid, fileid: fileid, loginfirst: true);
  559. }
  560. // log("lidoapi: pdfofp2: status: ${response.statusCode} fileid: $fileid ");
  561. //final id ="${DateFormat("yyyyMMdd").format(DateTime.fromMillisecondsSinceEpoch(dateoforigin))}_${dep}_${des}_$al$fnum";
  562. final ok = response.headers.containsKey("content-disposition");
  563. // log("lidoapi: pdfofp2: status: ${response.headers} ");
  564. final xfileid = fileid ?? PathTo().lidoFile("$legid.pdf");
  565. if (ok) {
  566. await downloadPdf(response, xfileid);
  567. }
  568. final res = {
  569. 'error': (ok) ? null : "no PDF downloaded",
  570. 'data': (ok)
  571. ? {
  572. "downloaded": true,
  573. "fileid": xfileid,
  574. }
  575. : {
  576. "downloaded": false,
  577. "fileid": null,
  578. },
  579. 'meta': {"user": username, "pass": password, "cookie": cookieMap}
  580. };
  581. return res;
  582. } catch (e) {
  583. final res = {
  584. 'error': e.toString(),
  585. 'data': {
  586. {
  587. "downloaded": false,
  588. "fileid": null,
  589. }
  590. },
  591. 'meta': {}
  592. };
  593. final xfileid = fileid ?? PathTo().lidoFile("$legid.pdf");
  594. if (File(xfileid).existsSync()) {
  595. res["cache"] = xfileid;
  596. }
  597. return res;
  598. }
  599. }
  600. Map<String, String> _getcookies(String cookiesData,
  601. {List<String> vars = const [
  602. "lido_auth",
  603. "lido_csrf",
  604. "JSESSIONID",
  605. "SERVERID"
  606. ]}) {
  607. Map<String, String> cookies = {};
  608. for (var title in vars) {
  609. if (cookiesData.contains(title)) {
  610. List at =
  611. (RegExp(r'(' + title + ')(.*?)[^;]+').stringMatch(cookiesData) ??
  612. "")
  613. .split('=');
  614. cookies[title] = at[1];
  615. }
  616. }
  617. return cookies;
  618. }
  619. Future<void> downloadPdf(http.Response response, String fileid) async {
  620. try {
  621. if (response.statusCode == 201) {
  622. final pdfBytes = response.bodyBytes;
  623. final file = File(fileid);
  624. await file.writeAsBytes(pdfBytes);
  625. print('PDF downloaded and saved to $fileid');
  626. } else {
  627. print('Error downloading PDF: ${response.statusCode}');
  628. }
  629. } catch (e) {
  630. print('Error downloading file: $e');
  631. }
  632. }
  633. Map<String, String?> extractCallbackData(String inputString) {
  634. // log("lidoapi: extractCallbackData: $inputString");
  635. final RegExp regex =
  636. RegExp(r'dwr\.engine\.remote\.handleCallback\(\"0\",\"0\",([^)]+)\)');
  637. final Match? match = regex.firstMatch(inputString);
  638. //log("lidoapi: extractCallbackData: match: ${match?[1]}");
  639. if (match != null && match[1] != null) {
  640. final String callbackData = match[1]!;
  641. final Map<String, String?> jsonData = convertStringToMap(callbackData);
  642. //log("lidoapi: extractCallbackData: jsonData: $jsonData");
  643. return jsonData;
  644. }
  645. return {};
  646. }
  647. Map<String, String?> convertStringToMap(String inputString) {
  648. final Map<String, String?> result = {};
  649. final RegExp regex = RegExp(r'(\w+):("?.*"?)(,|})');
  650. final Iterable<RegExpMatch> matches = regex.allMatches(inputString);
  651. for (var match in matches) {
  652. final String key = match[1]!;
  653. final String value = match[2]!;
  654. result[key] = value;
  655. }
  656. return result;
  657. }
  658. }