poznan_ztm_alerts.lua 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. -- SPDX-FileCopyrightText: Adam Evyčędo
  2. --
  3. -- SPDX-License-Identifier: AGPL-3.0-or-later
  4. ---@diagnostic disable-next-line: unused-local, lowercase-global
  5. function getAlerts(stopID, stopCode, tripID, lineID)
  6. if stopCode == '' then
  7. return '[]', ''
  8. end
  9. local http = require("http")
  10. local json = require("json")
  11. local error_struct = {
  12. httpResponseCode=0,
  13. message="",
  14. willNextRequestFail=false
  15. }
  16. local headers = {}
  17. headers['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8"
  18. local response, error_message = http.post("https://www.peka.poznan.pl/vm/method.vm", {
  19. timeout="30s",
  20. headers=headers,
  21. body='method=findMessagesForBollard&p0={"symbol": "' .. stopCode .. '"}'
  22. })
  23. if response == nil then
  24. error_struct.message = "while getting alerts: " .. error_message
  25. local error_json, _ = json.encode(error_struct)
  26. return "", error_json
  27. end
  28. if response.status_code ~= 200 then
  29. error_struct.message = "api returned code " .. response.status_code .. "; " .. response.body
  30. error_struct.httpResponseCode = response.status_code
  31. error_struct.willNextRequestFail = true
  32. local error_json, _ = json.encode(error_struct)
  33. return "", error_json
  34. end
  35. ---@diagnostic disable-next-line: redefined-local
  36. local struct, error_message = json.decode(response.body)
  37. if struct == nil then
  38. error_struct.message = "while decoding alerts: " .. error_message
  39. local error_json, _ = json.encode(error_struct)
  40. return "", error_json
  41. end
  42. local alerts = {}
  43. for i,entry in ipairs(struct.success) do
  44. local content = entry.content:gsub('<a href="[^"]+">', '')
  45. content = content:gsub('</a>', '')
  46. local url = string.match(entry.content, '<a href="([^"]+)">')
  47. alerts[i] = {
  48. timeRanges={
  49. {
  50. startDate=entry.startDate,
  51. endDate=entry.endDate
  52. }
  53. },
  54. headers={pl_PL=content},
  55. descriptions={pl_PL=content},
  56. urls={pl_PL=url},
  57. cause=0,
  58. effect=0
  59. }
  60. end
  61. ---@diagnostic disable-next-line: redefined-local
  62. local result, error_message = json.encode(alerts)
  63. if result == nil then
  64. error_struct.message = "while encoding result: " .. error_message
  65. local error_json, _ = json.encode(error_struct)
  66. return "", error_json
  67. end
  68. return result, ""
  69. end