burnie.rb 12 KB

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