lido_api.dart 23 KB

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