brighton.rb 6.0 KB

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