burnie.rb 12 KB

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