burnie.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. # Burnie City Council — permit applications on exhibition (robust / WAF-aware + PDF download)
  2. require "date"
  3. require "nokogiri"
  4. require "cgi"
  5. require "fileutils"
  6. require "net/http"
  7. require "uri"
  8. require "zlib"
  9. require "stringio"
  10. require "base64"
  11. require "securerandom"
  12. require_relative "../lib/http"
  13. require_relative "../lib/db"
  14. require_relative "../lib/util"
  15. require_relative "../lib/geocode"
  16. require_relative "../lib/enrich"
  17. TABLE = ENV.fetch("TABLE_NAME") # run_all.sh sets from filename: da_burnie
  18. BASE_URL = "https://www.burnie.tas.gov.au"
  19. URL = "#{BASE_URL}/Development/Planning/Permit-applications-on-exhibition"
  20. URL_EN = "#{URL}?oc_lang=en-AU"
  21. DOWNLOAD_ATTACHMENTS = ENV["DOWNLOAD_ATTACHMENTS"] == "1"
  22. DOWNLOAD_DIR = ENV["DOWNLOAD_DIR"] || "/app/downloads"
  23. DB.ensure_table!(TABLE)
  24. ensure_extra_columns!(TABLE)
  25. # ----- HTTP helpers (browser-y headers + cookie jar + gzip/deflate) -----
  26. UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "\
  27. "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
  28. SEC_CH_UA = %q{"Chromium";v="124", "Not.A/Brand";v="24", "Google Chrome";v="124"}
  29. SEC_CH_UA_PLATFORM = %q{"Windows"}
  30. SEC_CH_UA_MOBILE = "?0"
  31. BASE_HEADERS = {
  32. "User-Agent" => UA,
  33. "Accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  34. "Accept-Language" => "en-AU,en;q=0.8",
  35. # Avoid Brotli (Ruby stdlib won’t auto-decode it)
  36. "Accept-Encoding" => "gzip,deflate",
  37. "Upgrade-Insecure-Requests" => "1",
  38. "Sec-Fetch-Dest" => "document",
  39. "Sec-Fetch-Mode" => "navigate",
  40. "Sec-Fetch-Site" => "none",
  41. "Sec-Fetch-User" => "?1",
  42. "sec-ch-ua" => SEC_CH_UA,
  43. "sec-ch-ua-platform" => SEC_CH_UA_PLATFORM,
  44. "sec-ch-ua-mobile" => SEC_CH_UA_MOBILE,
  45. "Pragma" => "no-cache",
  46. "Cache-Control" => "no-cache",
  47. "Connection" => "close",
  48. }.freeze
  49. # Very small cookie jar (domain -> cookie string)
  50. class Jar
  51. def initialize; @h = {}; end
  52. def for(host)
  53. @h[host] || ""
  54. end
  55. def merge_from(resp, host)
  56. cookies = resp.get_fields("Set-Cookie") || []
  57. return if cookies.empty?
  58. existing = parse_cookie_header(@h[host])
  59. cookies.each do |sc|
  60. kv = sc.split(";", 2).first
  61. k, v = kv.split("=", 2)
  62. next if k.to_s.empty?
  63. existing[k] = v.to_s
  64. end
  65. @h[host] = existing.map { |k, v| "#{k}=#{v}" }.join("; ")
  66. end
  67. def parse_cookie_header(s)
  68. s.to_s.split(";").map(&:strip).map { |kv|
  69. k, v = kv.split("=", 2); [k, v]
  70. }.select { |k, _| !k.to_s.empty? }.to_h
  71. end
  72. end
  73. def decompress(body, enc)
  74. return body if body.nil? || body.empty?
  75. if enc.to_s =~ /gzip/i
  76. Zlib::GzipReader.new(StringIO.new(body)).read
  77. elsif enc.to_s =~ /deflate/i
  78. begin
  79. Zlib::Inflate.inflate(body)
  80. rescue Zlib::Error
  81. body
  82. end
  83. else
  84. body
  85. end
  86. rescue Zlib::Error
  87. body
  88. end
  89. def http_get_with_cookies(url, jar:, headers: {}, referer: nil, site_fetch: "none")
  90. uri = URI(url)
  91. hdrs = BASE_HEADERS.merge(headers)
  92. hdrs["Referer"] = referer if referer
  93. hdrs["Sec-Fetch-Site"] = site_fetch
  94. cookie = jar.for(uri.host)
  95. hdrs["Cookie"] = cookie unless cookie.empty?
  96. limit = 5
  97. enc = ""
  98. msg = ""
  99. code = 0
  100. body = ""
  101. while limit > 0
  102. req = Net::HTTP::Get.new(uri, hdrs)
  103. Net::HTTP.start(uri.host, uri.port, use_ssl: (uri.scheme == "https")) do |http|
  104. resp = http.request(req)
  105. jar.merge_from(resp, uri.host)
  106. enc = resp["content-encoding"].to_s
  107. msg = resp.message
  108. code = resp.code.to_i
  109. if [301, 302, 303, 307, 308].include?(code) && resp["location"]
  110. uri = URI.join(uri, resp["location"])
  111. limit -= 1
  112. next
  113. end
  114. # For HTML we decompress; for PDF we only requested gzip/deflate off,
  115. # so this remains identity unless server forces it (we still handle).
  116. body = decompress(resp.body.to_s, enc)
  117. end
  118. break
  119. end
  120. [code, body, enc, msg]
  121. end
  122. def short_sleep
  123. sleep(0.4 + rand * 0.6)
  124. end
  125. # ----- Burnie-specific parsing helpers -----
  126. REF_RX = %r{\bDA\s*(20\d{2})\s*/\s*([A-Za-z0-9\-_.]+)}i
  127. def extract_ref(text)
  128. if (m = text.to_s.match(REF_RX))
  129. "DA #{m[1]} / #{m[2]}"
  130. end
  131. end
  132. def normalize_ref(text)
  133. extract_ref(text) ||
  134. text.to_s[/\bDA\s*[12]\d{3}\s*\/\s*[A-Za-z0-9\-_.]+\b/i].to_s.gsub(/\s*\/\s*/, " / ").strip
  135. end
  136. def extract_on_notice_date(text)
  137. s = text.to_s.gsub(/\s+/, " ")
  138. if (m = s.match(/\b\d{1,2}\s+[A-Za-z]{3,}\s+\d{4}\b/))
  139. m[0]
  140. elsif (m = s.match(/\b\d{1,2}\/\d{1,2}\/\d{2,4}\b/))
  141. m[0]
  142. else
  143. ""
  144. end
  145. end
  146. def first_pdf_on_detail(detail_url, jar)
  147. code, html, _enc, _msg = http_get_with_cookies(
  148. detail_url,
  149. jar: jar,
  150. site_fetch: "same-origin",
  151. referer: URL_EN
  152. )
  153. return "" unless code == 200
  154. doc = Nokogiri::HTML(html)
  155. # Prefer explicit doc buttons if present
  156. a = doc.at_css(".hyperlink-button-container a.ext-pdf") ||
  157. doc.at_css("a[href$='.pdf'], a[href*='.pdf?']")
  158. return "" unless a
  159. URI.join(detail_url, a["href"].to_s).to_s
  160. rescue => e
  161. warn "Detail fetch failed for #{detail_url}: #{e.class} #{e.message}"
  162. ""
  163. end
  164. def decode_seamless_viewstate(doc)
  165. b64 = doc.at_css("#__SEAMLESSVIEWSTATE")&.[]("value").to_s
  166. return nil if b64.empty?
  167. raw = Base64.decode64(b64)
  168. html = begin
  169. Zlib::GzipReader.new(StringIO.new(raw)).read
  170. rescue Zlib::Error
  171. raw
  172. end
  173. Nokogiri::HTML(html)
  174. rescue => e
  175. warn "Failed to decode __SEAMLESSVIEWSTATE: #{e.class} #{e.message}"
  176. nil
  177. end
  178. def sanitize_filename(s)
  179. s.to_s.gsub(/[^\w.\-]+/, "_")[0, 180]
  180. end
  181. def save_pdf(document_url, council_reference, jar, referer:)
  182. return if document_url.to_s.strip.empty?
  183. return unless DOWNLOAD_ATTACHMENTS
  184. # Decide filename
  185. url_path = URI.parse(document_url).path rescue "/document.pdf"
  186. base_name = File.basename(url_path)
  187. safe_base = sanitize_filename(base_name)
  188. # Prefix with reference for uniqueness & traceability
  189. prefix = sanitize_filename(council_reference.to_s.gsub(" / ", "-"))
  190. file_name = "#{prefix}__#{safe_base}"
  191. out_dir = File.join(DOWNLOAD_DIR, TABLE)
  192. out_path = File.join(out_dir, file_name)
  193. FileUtils.mkdir_p(out_dir)
  194. code, data, _enc, msg = http_get_with_cookies(
  195. document_url,
  196. jar: jar,
  197. headers: {
  198. # Ask for PDF explicitly
  199. "Accept" => "application/pdf,*/*;q=0.8",
  200. "Accept-Encoding" => "identity" # avoid gzip'd binary when possible
  201. },
  202. referer: referer,
  203. site_fetch: "same-origin"
  204. )
  205. if code == 200 && data && data.bytesize > 0
  206. File.open(out_path, "wb") { |f| f.write(data) }
  207. puts "Saved PDF to #{out_path} (#{data.bytesize} bytes)"
  208. else
  209. warn "PDF fetch failed (#{code} #{msg}) for #{document_url}"
  210. end
  211. rescue => e
  212. warn "PDF save error for #{document_url}: #{e.class} #{e.message}"
  213. end
  214. # ----- Warm-up sequence to appease WAF -----
  215. jar = Jar.new
  216. # 1) Direct try
  217. code1, body1, enc1, msg1 = http_get_with_cookies(URL, jar: jar)
  218. puts "List fetch #1: status=#{code1} #{msg1}, enc=#{enc1}, bytes=#{body1.to_s.bytesize}"
  219. html = nil
  220. if code1 == 200 && body1.bytesize > 5_000
  221. html = body1
  222. else
  223. short_sleep
  224. # 2) Language variant (often works)
  225. code2, body2, enc2, msg2 = http_get_with_cookies(
  226. URL_EN, jar: jar, site_fetch: "same-origin", referer: "#{BASE_URL}/"
  227. )
  228. puts "List fetch #2: status=#{code2} #{msg2}, enc=#{enc2}, bytes=#{body2.to_s.bytesize} (#{URL_EN})"
  229. if code2 == 200 && body2.bytesize > 5_000
  230. html = body2
  231. else
  232. # 3) Warm up by hitting Home (sets benign cookies), then websitesettings.js, then retry
  233. short_sleep
  234. h_code, _h_body, _h_enc, h_msg = http_get_with_cookies("#{BASE_URL}/Home", jar: jar, site_fetch: "none")
  235. puts "Warmup Home: status=#{h_code} #{h_msg}"
  236. short_sleep
  237. oc_api = "#{BASE_URL}/ocapi/0ff2db3d-0235-40e2-b373-42294eee3a55/en-AU/websitesettings.js"
  238. w_code, _w_body, _w_enc, w_msg = http_get_with_cookies(oc_api, jar: jar, site_fetch: "same-origin", referer: "#{BASE_URL}/Home")
  239. puts "Warmup websitesettings.js: status=#{w_code} #{w_msg}"
  240. short_sleep
  241. code3, body3, enc3, msg3 = http_get_with_cookies(URL_EN, jar: jar, site_fetch: "same-origin", referer: "#{BASE_URL}/Home")
  242. puts "List fetch #3: status=#{code3} #{msg3}, enc=#{enc3}, bytes=#{body3.to_s.bytesize} (retry with referer)"
  243. html = body3 if code3 == 200 && body3.bytesize > 5_000
  244. end
  245. end
  246. # Fall back to whatever we got first if nothing passed threshold
  247. html ||= body1
  248. puts "Fetched list page (#{html.to_s.bytesize} bytes)"
  249. list_doc = Nokogiri::HTML(html)
  250. # Try visible DOM first
  251. nodes = list_doc.css(".list-container.da-list-container .list-item-container a[href]")
  252. puts "Primary selector found #{nodes.length} anchors"
  253. # If nothing, decode Seamless payload and try again
  254. if nodes.empty?
  255. sv_doc = decode_seamless_viewstate(list_doc)
  256. if sv_doc
  257. nodes = sv_doc.css(".list-container.da-list-container .list-item-container a[href]")
  258. puts "Seamless ViewState selector found #{nodes.length} anchors"
  259. if nodes.empty?
  260. nodes = sv_doc.css(".list-item-container").map { |c| c.at_css("a[href]") }.compact
  261. puts "Seamless final fallback found #{nodes.length} anchors"
  262. end
  263. else
  264. puts "__SEAMLESSVIEWSTATE not found or could not be decoded"
  265. end
  266. end
  267. puts "Found #{nodes.length} application(s) for #{TABLE}"
  268. saved = 0
  269. nodes.each do |a|
  270. detail_url = URI.join(URL, a["href"].to_s).to_s
  271. ref_text = a.at_css(".da-application-number")&.text.to_s
  272. council_reference = normalize_ref(ref_text)
  273. address = a.at_css(".list-item-address")&.text.to_s.strip
  274. closing_text = a.at_css(".display-until-date")&.text.to_s
  275. on_notice_to_raw = if closing_text.empty?
  276. extract_on_notice_date(a.text)
  277. else
  278. extract_on_notice_date(closing_text.sub(/^On display until\s*/i, ""))
  279. end
  280. on_notice_to = Util.parse_aus_date(on_notice_to_raw)
  281. date_received = on_notice_to ? (on_notice_to - 14) : nil
  282. # First <p> that isn't a helper class = description
  283. desc_p = a.css("p").find { |p|
  284. cls = p["class"].to_s
  285. cls.empty? || !(cls =~ /(da-application-number|list-item-address|display-until)/)
  286. }
  287. description = desc_p&.text.to_s.strip
  288. description = "Development Application" if description.empty?
  289. next if address.empty? || council_reference.empty?
  290. document_url = first_pdf_on_detail(detail_url, jar)
  291. # Download the PDF if requested
  292. save_pdf(document_url, council_reference, jar, referer: detail_url) if DOWNLOAD_ATTACHMENTS
  293. DB.upsert(TABLE, {
  294. description: description,
  295. date_received: date_received,
  296. date_received_raw: on_notice_to_raw, # keep the raw on-notice text
  297. on_notice_to: on_notice_to, # store close/on-notice date here
  298. on_notice_to_raw: on_notice_to_raw,
  299. address: address,
  300. council_reference: council_reference,
  301. applicant: "",
  302. owner: ""
  303. })
  304. enrich_after_upsert!(
  305. table: TABLE,
  306. council_reference: council_reference,
  307. address: address
  308. )
  309. begin
  310. upd = DB.client.prepare(
  311. "UPDATE `#{DB.client.escape(TABLE)}` " \
  312. "SET document_url = ?, on_notice_to = ?, on_notice_to_raw = ?, title_reference = ? " \
  313. "WHERE council_reference = ? AND address = ?"
  314. )
  315. title_reference = a.at_css(".list-item-title")&.text&.strip.to_s
  316. upd.execute(document_url, on_notice_to, on_notice_to_raw, title_reference, council_reference, address)
  317. rescue => e
  318. warn "Extra fields update skipped for #{council_reference}: #{e.class} #{e.message}"
  319. end
  320. puts "Upserted #{council_reference} -> #{address}"
  321. saved += 1
  322. end
  323. puts "Done #{TABLE}. Saved #{saved} item(s)."