centralcoast.rb 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # Central Coast Council — Current Planning Applications (site page)
  2. # Source: https://www.centralcoast.tas.gov.au/current-planning-applications/
  3. require "date"
  4. require "nokogiri"
  5. require "cgi"
  6. require "fileutils"
  7. require_relative "../lib/http"
  8. require_relative "../lib/db"
  9. require_relative "../lib/util"
  10. require_relative "../lib/geocode"
  11. require_relative "../lib/enrich"
  12. TABLE = ENV.fetch("TABLE_NAME") # run_all.sh sets from filename: da_centralcoast
  13. URL = "https://www.centralcoast.tas.gov.au/current-planning-applications/"
  14. DOWNLOAD_ATTACHMENTS = ENV["DOWNLOAD_ATTACHMENTS"] == "1"
  15. DOWNLOAD_DIR = ENV["DOWNLOAD_DIR"] || "/app/downloads"
  16. DB.ensure_table!(TABLE)
  17. def abs_url(base, href)
  18. return "" if href.to_s.strip.empty?
  19. URI.join(base, href).to_s
  20. rescue URI::InvalidURIError
  21. href.to_s
  22. end
  23. def safe_name(s) = s.to_s.gsub(/[^\w\-.]+/, "_")
  24. def filename_from_response(res, fallback)
  25. cd = res.respond_to?(:[]) ? res["content-disposition"].to_s : ""
  26. if cd =~ /filename\*?=(?:UTF-8''|")?([^\";]+)/
  27. return safe_name($1)
  28. end
  29. base = safe_name(fallback || "document")
  30. ct = res.respond_to?(:[]) ? res["content-type"].to_s.downcase : ""
  31. ext = if base =~ /\.[A-Za-z0-9]{2,4}\z/
  32. ""
  33. elsif ct.include?("pdf")
  34. ".pdf"
  35. else
  36. ".bin"
  37. end
  38. "#{base}#{ext}"
  39. end
  40. def download_pdf(url, council_reference)
  41. return nil if url.to_s.strip.empty?
  42. dir = File.join(DOWNLOAD_DIR, "centralcoast", safe_name(council_reference))
  43. FileUtils.mkdir_p(dir)
  44. res = (Http.get_response(url) rescue nil)
  45. body = if res && res.respond_to?(:body)
  46. res.body
  47. else
  48. Http.get(url)
  49. end
  50. fname = filename_from_response(res, File.basename(URI.parse(url).path))
  51. path = File.join(dir, fname)
  52. File.binwrite(path, body.to_s)
  53. puts " saved #{File.basename(path)} (#{body.to_s.bytesize} bytes)"
  54. # adjust if your web container mounts differently
  55. "/downloads/centralcoast/#{safe_name(council_reference)}/#{fname}"
  56. rescue StandardError => e
  57. warn "Download failed for #{url}: #{e.class} #{e.message}"
  58. nil
  59. end
  60. # Normalize refs like "DA2025123" or "DA 2025/123" -> "DA 2025 / 123"
  61. def normalize_ref(s)
  62. t = s.to_s
  63. if (m = t.match(/\bDA\s*([12]\d{3})\s*[-\/]?\s*0*([A-Za-z0-9]{2,})\b/i))
  64. return "DA #{m[1]} / #{m[2]}"
  65. elsif (m = t.match(/\bDA(20\d{2})\s*0*([A-Za-z0-9]{2,})\b/i))
  66. return "DA #{m[1]} / #{m[2]}"
  67. end
  68. t.split(/\s*-\s*/, 2).first # fallback
  69. end
  70. # Parse dd-mm-yyyy shown in "Date modified"
  71. def parse_dd_mm_yyyy(s)
  72. s = s.to_s.strip
  73. if s =~ /\A\d{2}-\d{2}-\d{4}\z/
  74. Date.strptime(s, "%d-%m-%Y") rescue nil
  75. else
  76. # fall back to your common AUS parser
  77. Util.parse_aus_date(s)
  78. end
  79. end
  80. html = Http.get(URL)
  81. doc = Nokogiri::HTML(html)
  82. rows = doc.css("table.wpfd-search-result tbody tr.file")
  83. puts "Found #{rows.length} items for #{TABLE}"
  84. saved = 0
  85. rows.each do |tr|
  86. # Primary link + title from the first column
  87. a = tr.at_css("td.file_title a.wpfd_downloadlink")
  88. next unless a
  89. document_url = abs_url(URL, a["href"].to_s)
  90. title_reference = a["title"].to_s.strip
  91. title_text = tr.at_css("input.wpfd_file_preview_link_download")&.[]("data-filetitle").to_s.strip
  92. title_reference = title_reference.empty? ? title_text : title_reference
  93. # Title looks like: "DA2025123 - 148 Main Street, Ulverstone"
  94. council_reference_raw = title_reference.split(" - ").first.to_s.strip
  95. council_reference = normalize_ref(council_reference_raw)
  96. address = if title_reference.include?(" - ")
  97. title_reference.split(" - ", 2)[1].to_s.strip
  98. else
  99. # crude fallback to a street-like token
  100. title_reference[/\b\d+[A-Za-z]*\s[\w\s,]+/, 0].to_s.strip
  101. end
  102. address = title_reference[0, 140] if address.empty?
  103. # Optional description column (often blank)
  104. description = tr.at_css("td.file_desc")&.text.to_s.strip
  105. description = "Development Application" if description.empty?
  106. # Date modified -> date_received
  107. date_received_raw = tr.at_css("td.file_modified")&.text.to_s.strip
  108. date_received = parse_dd_mm_yyyy(date_received_raw)
  109. # Minimal required fields
  110. next if council_reference.to_s.strip.empty? || address.to_s.strip.empty?
  111. DB.upsert(TABLE, {
  112. description: description,
  113. date_received: date_received,
  114. date_received_raw: date_received_raw,
  115. address: address,
  116. council_reference: council_reference,
  117. applicant: "",
  118. owner: ""
  119. })
  120. enrich_after_upsert!(
  121. table: TABLE,
  122. council_reference: council_reference,
  123. address: address
  124. )
  125. local_doc_url = nil
  126. if DOWNLOAD_ATTACHMENTS && !document_url.empty?
  127. local_doc_url = download_pdf(document_url, council_reference)
  128. end
  129. begin
  130. upd = DB.client.prepare(
  131. "UPDATE `#{DB.client.escape(TABLE)}` " \
  132. "SET document_url = ?, local_document_url = ?, title_reference = ? " \
  133. "WHERE council_reference = ? AND address = ?"
  134. )
  135. upd.execute(document_url, local_doc_url, title_reference, council_reference, address)
  136. rescue StandardError => e
  137. warn "Extras update skipped for #{council_reference}: #{e.class} #{e.message}"
  138. end
  139. puts "Upserted #{council_reference} -> #{address} #{local_doc_url ? '(downloaded)' : ''}"
  140. saved += 1
  141. end
  142. puts "Done #{TABLE}. Saved #{saved} item(s)."