burnie.rb 12 KB

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