glenorchy.rb 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. # Glenorchy City Council – Planning Applications (site page, not PlanBuild)
  2. require "nokogiri"
  3. require "date"
  4. require_relative "../lib/enrich"
  5. require_relative "../lib/log"
  6. TABLE = ENV.fetch("TABLE_NAME") # run_all.sh sets from filename: da_glenorchy
  7. URL = "https://www.gcc.tas.gov.au/services/planning-and-building/planning-and-development/planning-applications/"
  8. DOWNLOAD_ATTACHMENTS = ENV["DOWNLOAD_ATTACHMENTS"] == "1"
  9. DOWNLOAD_DIR = ENV["DOWNLOAD_DIR"] || "/app/downloads"
  10. DB.ensure_table!(TABLE)
  11. # Optional: keep the document link with each row (adds a column if missing)
  12. begin
  13. DB.client.query("ALTER TABLE `#{DB.client.escape(TABLE)}` ADD COLUMN IF NOT EXISTS document_url VARCHAR(1024) NULL")
  14. rescue StandardError => e
  15. Log.warn "scraper", "Could not add document_url column: #{e.class} #{e.message}"
  16. end
  17. def text_or(node, default = "")
  18. node ? node.text.strip : default
  19. end
  20. def abs_url(href)
  21. return "" if href.to_s.strip.empty?
  22. URI.join(URL, href).to_s
  23. rescue URI::InvalidURIError
  24. href.to_s
  25. end
  26. def safe_name(s) = s.to_s.gsub(/[^\w\-.]+/, "_")
  27. def filename_from_response(res, fallback_url)
  28. cd = res["content-disposition"].to_s
  29. name =
  30. if cd =~ /filename\*?=(?:UTF-8''|")?([^\";]+)/
  31. $1
  32. else
  33. File.basename(URI.parse(fallback_url).path)
  34. end
  35. name = "document.pdf" if name.to_s.strip.empty?
  36. name += ".pdf" unless name.downcase.end_with?(".pdf")
  37. safe_name(name)
  38. end
  39. def download_pdf(doc_url, council_reference)
  40. return "" unless DOWNLOAD_ATTACHMENTS && !doc_url.to_s.strip.empty?
  41. begin
  42. u = abs_url(doc_url)
  43. res = Http.request(URI.parse(u), headers: {}, jar: {}, referer: URL)
  44. raise "HTTP #{res.code}" unless res.is_a?(Net::HTTPSuccess)
  45. dir = File.join(DOWNLOAD_DIR, "glenorchy", safe_name(council_reference))
  46. FileUtils.mkdir_p(dir)
  47. fname = filename_from_response(res, u)
  48. path = File.join(dir, fname)
  49. File.binwrite(path, res.body.to_s)
  50. puts " saved #{path}"
  51. # web-facing relative path (match your nginx/apache mapping)
  52. "/downloads/glenorchy/#{safe_name(council_reference)}/#{fname}"
  53. rescue StandardError => e
  54. Log.warn "scraper", "Download failed for #{doc_url}: #{e.class} #{e.message}"
  55. ""
  56. end
  57. end
  58. html = Http.get(URL)
  59. doc = Nokogiri::HTML(html)
  60. # Cards on this page use “content-block” classes (WordPress pattern).
  61. cards = doc.css(".content-block, .content-block--featured")
  62. puts "Found #{cards.length} items for #{TABLE}"
  63. saved = 0
  64. cards.each do |card|
  65. # Title / address: try specific title element, then fall back to header text or first link text
  66. title_el = card.at_css(".content-block__title, .content-block__heading, h3, h2, a")
  67. address = text_or(title_el)
  68. # Closing date appears like: "Closes: 29 August 2025"
  69. date_el = card.at_css(".content-block__date")
  70. on_notice_to_raw = text_or(date_el).sub(/^Closes:\s*/i, "")
  71. on_notice_to = Util.parse_aus_date(on_notice_to_raw)
  72. date_received = Date.today
  73. # Short description paragraph
  74. desc_el = card.at_css(".content-block__description p, .content-block__description")
  75. description = text_or(desc_el)
  76. # Document link button (often a PDF)
  77. doc_link = card.at_css(".content-block__button a, a[href$='.pdf']")
  78. document_url = doc_link ? doc_link["href"].to_s.strip : ""
  79. # Council reference: prefer the document file name (e.g., ABC-123) if present
  80. council_reference =
  81. if document_url && !document_url.empty?
  82. File.basename(document_url).sub(/\.pdf\z/i, "").upcase
  83. else
  84. # fallback: compact title text
  85. address.gsub(/\s+/, " ")[0,120]
  86. end
  87. # Require key fields
  88. next if address.empty? || council_reference.empty?
  89. DB.upsert(TABLE, {
  90. description: description,
  91. date_received: date_received,
  92. on_notice_to: on_notice_to, # keep the closing date in the DATE column
  93. on_notice_to_raw: on_notice_to_raw, # raw text as seen on page
  94. address: address,
  95. council_reference: council_reference,
  96. applicant: "",
  97. owner: ""
  98. })
  99. # store remote doc URL
  100. begin
  101. DB.client.prepare("UPDATE `#{DB.client.escape(TABLE)}` SET document_url = ? WHERE council_reference = ? AND address = ?")
  102. .execute(document_url, council_reference, address)
  103. rescue StandardError => e
  104. Log.warn "scraper", "document_url update failed: #{e.class} #{e.message}"
  105. end
  106. # download + store local_document_url
  107. local_rel = download_pdf(document_url, council_reference)
  108. if !local_rel.empty?
  109. begin
  110. DB.client.prepare("UPDATE `#{DB.client.escape(TABLE)}` SET local_document_url = ? WHERE council_reference = ? AND address = ?")
  111. .execute(local_rel, council_reference, address)
  112. rescue StandardError => e
  113. Log.warn "scraper", "local_document_url update failed: #{e.class} #{e.message}"
  114. end
  115. end
  116. enrich_after_upsert!(
  117. table: TABLE,
  118. council_reference: council_reference,
  119. address: address
  120. )
  121. # If we added the optional column earlier, keep the link
  122. begin
  123. upd = DB.client.prepare("UPDATE `#{DB.client.escape(TABLE)}` SET document_url = ? WHERE council_reference = ? AND address = ?")
  124. upd.execute(document_url, council_reference, address)
  125. rescue StandardError => e
  126. # ignore if column not present
  127. end
  128. puts "Upserted #{council_reference} -> #{address} (doc: #{document_url.empty? ? 'none' : 'remote'}#{local_rel.empty? ? '' : ', saved'})"
  129. saved += 1
  130. end
  131. puts "Done #{TABLE}. Saved #{saved} item(s)."