brighton.rb 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # Brighton Council — Advertised Development Applications (site page, not PlanBuild)
  2. require "date"
  3. require "nokogiri"
  4. require "cgi"
  5. require "fileutils"
  6. require_relative "../lib/enrich"
  7. require_relative "../lib/log"
  8. TABLE = ENV.fetch("TABLE_NAME") # run_all.sh sets this from filename: da_brighton
  9. URL = "https://www.brighton.tas.gov.au/planning/advertised-development-applications/"
  10. DOWNLOAD_ATTACHMENTS = ENV["DOWNLOAD_ATTACHMENTS"] == "1"
  11. DOWNLOAD_DIR = ENV["DOWNLOAD_DIR"] || "/app/downloads"
  12. DB.ensure_table!(TABLE)
  13. # --- helpers ---------------------------------------------------------------
  14. # DA/APP refs like “DA2025-130”, “DA 2024/174”, etc → “DA YYYY / NNN…”
  15. REF_RX = %r{
  16. \b(?:DA|APP|APPLICATION)\s*
  17. (20\d{2})\s*[/\-]?\s*
  18. ([A-Za-z0-9\-_.]{2,})\b
  19. }ix
  20. def extract_ref_from(str)
  21. s = CGI.unescape(str.to_s)
  22. if (m = s.match(REF_RX))
  23. return "DA #{m[1]} / #{m[2]}"
  24. end
  25. # Compact like DA20250123
  26. if (m = s.match(/\bDA(20\d{2})(\d{3,})\b/i))
  27. return "DA #{m[1]} / #{m[2]}"
  28. end
  29. nil
  30. end
  31. def abs_url(base, href)
  32. return "" if href.to_s.strip.empty?
  33. URI.join(base, href).to_s
  34. rescue URI::InvalidURIError
  35. href.to_s
  36. end
  37. def safe_name(s) = s.to_s.gsub(/[^\w\-.]+/, "_")
  38. def strip_ordinals(s)
  39. s.to_s.gsub(/\b(\d{1,2})(st|nd|rd|th)\b/i, '\1')
  40. end
  41. def parse_close_date(s)
  42. Util.parse_aus_date(strip_ordinals(s.to_s))
  43. end
  44. def download_pdf(url, council_reference)
  45. return nil unless DOWNLOAD_ATTACHMENTS && !url.to_s.strip.empty?
  46. folder = File.join(DOWNLOAD_DIR, "brighton", safe_name(council_reference))
  47. FileUtils.mkdir_p(folder)
  48. begin
  49. res = Http.get_response(url) rescue Http.get(url)
  50. body = res.respond_to?(:body) ? res.body : res.to_s
  51. fname = safe_name(File.basename(URI.parse(url).path))
  52. fname += ".pdf" unless fname.downcase.end_with?(".pdf")
  53. path = File.join(folder, fname)
  54. File.binwrite(path, body)
  55. puts "Saved PDF #{path}"
  56. "/downloads/brighton/#{safe_name(council_reference)}/#{fname}"
  57. rescue StandardError => e
  58. Log.warn "scraper", "PDF download failed for #{url}: #{e.class} #{e.message}"
  59. nil
  60. end
  61. end
  62. # --- scrape ---------------------------------------------------------------
  63. html = Http.get(URL)
  64. doc = Nokogiri::HTML(html)
  65. # Find the advertised table by headers
  66. table = doc.css("table").find do |t|
  67. heads = t.css("thead th").map { |th| th.text.strip.downcase }
  68. heads.any? &&
  69. heads.any? { |h| h.include?("description") } &&
  70. heads.any? { |h| h.include?("address") } &&
  71. heads.any? { |h| h.include?("closing") || h.include?("closing date") } &&
  72. heads.any? { |h| h.include?("pdf") }
  73. end
  74. unless table
  75. puts "No advertised table found on #{URL}"
  76. exit 0
  77. end
  78. # Column indexes by header text (fallback to 0..3 if needed)
  79. heads = table.css("thead th").map { |th| th.text.strip.downcase }
  80. i_desc = heads.index { |h| h.include?("description") } || 0
  81. i_addr = heads.index { |h| h.include?("address") } || 1
  82. i_close= heads.index { |h| h.include?("closing") } || 2
  83. i_pdf = heads.index { |h| h.include?("pdf") } || 3
  84. rows = table.css("tbody tr")
  85. puts "Found #{rows.length} row(s) for #{TABLE}"
  86. saved = 0
  87. today = Date.today
  88. rows.each do |tr|
  89. tds = tr.css("td")
  90. next if tds.empty?
  91. description = tds[i_desc]&.text&.strip.to_s
  92. address = tds[i_addr]&.text&.strip.to_s
  93. close_raw = tds[i_close]&.text&.strip.to_s
  94. on_notice_to = parse_close_date(close_raw)
  95. date_received = on_notice_to && (on_notice_to - 14)
  96. # one or more PDF links
  97. pdf_links = tds[i_pdf]&.css('a[href]')&.map { |a| abs_url(URL, a["href"].to_s) } || []
  98. document_url = pdf_links.first.to_s
  99. # reference from link text or file name
  100. ref_texts = tds[i_pdf]&.css('a')&.map { |a| a.text.to_s } || []
  101. council_reference =
  102. ref_texts.map { |tx| extract_ref_from(tx) }.compact.first ||
  103. pdf_links.map { |u| extract_ref_from(File.basename(u)) }.compact.first
  104. # minimal keys
  105. next if address.empty? || council_reference.nil?
  106. DB.upsert(TABLE, {
  107. description: description.empty? ? "Development Application" : description,
  108. date_received: date_received,
  109. date_received_raw: today.strftime("%Y-%m-%d"),
  110. on_notice_to: on_notice_to, # store close date in DATE column
  111. on_notice_to_raw: strip_ordinals(close_raw),
  112. address: address,
  113. council_reference: council_reference,
  114. applicant: "",
  115. owner: ""
  116. })
  117. enrich_after_upsert!(
  118. table: TABLE,
  119. council_reference: council_reference,
  120. address: address
  121. )
  122. # remote URL
  123. begin
  124. upd = DB.client.prepare("UPDATE `#{DB.client.escape(TABLE)}` SET document_url = ? WHERE council_reference = ? AND address = ?")
  125. upd.execute(document_url, council_reference, address)
  126. rescue StandardError => e
  127. Log.warn "scraper", "document_url update skipped for #{council_reference}: #{e.class} #{e.message}"
  128. end
  129. # local copy
  130. local_doc_url = download_pdf(document_url, council_reference)
  131. if local_doc_url
  132. begin
  133. upd2 = DB.client.prepare("UPDATE `#{DB.client.escape(TABLE)}` SET local_document_url = ? WHERE council_reference = ? AND address = ?")
  134. upd2.execute(local_doc_url, council_reference, address)
  135. rescue StandardError => e
  136. Log.warn "scraper", "local_document_url update skipped for #{council_reference}: #{e.class} #{e.message}"
  137. end
  138. end
  139. puts "Upserted #{council_reference} -> #{address} (doc: #{document_url.empty? ? 0 : 1}, saved: #{local_doc_url ? 1 : 0})"
  140. saved += 1
  141. end
  142. puts "Done #{TABLE}. Saved #{saved} item(s)."