meandervalley.rb 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. # Meander Valley Council — Advertised & Approved Planning Applications
  2. # Source: https://www.meander.tas.gov.au/advertised-approved-planning-applications
  3. require "nokogiri"
  4. require "uri"
  5. require "cgi"
  6. require "date"
  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. require "json"
  13. DEBUG = ENV["DEBUG"] == "1"
  14. DRY_RUN = ENV["DRY_RUN"] == "1"
  15. TABLE = ENV.fetch("TABLE_NAME") # run_all.sh -> da_meandervalley
  16. URL = "https://www.meander.tas.gov.au/advertised-approved-planning-applications"
  17. DOWNLOAD_ATTACHMENTS = ENV["DOWNLOAD_ATTACHMENTS"] == "1"
  18. DOWNLOAD_DIR = ENV["DOWNLOAD_DIR"] || "/app/downloads"
  19. DB.ensure_table!(TABLE)
  20. # Pull nearest text around an anchor for parsing
  21. def host_block_for(a)
  22. n = a.ancestors("li, p, div, article").first || a.parent
  23. n ? n.text.to_s.gsub(/\s+/, " ").strip : ""
  24. end
  25. # Extract value after a label up to the next label token
  26. def field_value(text, key_rx, stops)
  27. s = text.to_s
  28. m = s.match(/#{key_rx.source}\s*:\s*(.+)/i)
  29. return "" unless m
  30. tail = m[1]
  31. cut = tail.length
  32. stops.each do |st|
  33. i = tail.index(st)
  34. cut = [cut, i].min if i
  35. end
  36. tail[0, cut].strip
  37. end
  38. # Normalize refs like "PA\26\0010", "PA.26.0010", "PA 26/0010" to "PA 26/0010"
  39. def normalize_pa_ref(text, pdf = "")
  40. s = [text.to_s, File.basename(pdf.to_s)].join(" ")
  41. s = s.tr("\\", "/")
  42. if (m = s.match(/\bPA\s*([0-9]{2})[\/\.\s]+([0-9]{3,4})\b/i))
  43. return "PA #{m[1]}/#{m[2]}"
  44. end
  45. nil
  46. end
  47. def extract_between(text, key)
  48. text[/#{key}\s*:\s*(.+?)\s*$/i, 1].to_s.strip
  49. end
  50. def find_pdf_in(nodes, base)
  51. if (a = nodes.css('a[href$=".pdf"], a[href*=".pdf?"]').first)
  52. u = a["href"].to_s
  53. return URI.join(base, u).to_s rescue u
  54. end
  55. ""
  56. end
  57. def block_from_anchor(start_node)
  58. out = [start_node]
  59. cur = start_node
  60. 20.times do
  61. cur = cur.next_element
  62. break if cur.nil?
  63. t = cur.text.to_s.strip
  64. break if t =~ /^\s*Application\s*:/i
  65. break if t =~ /^\s*(Approved|Refused)\b/i
  66. out << cur
  67. end
  68. out
  69. end
  70. def safe_name(s) = s.to_s.gsub(/[^\w\-.]+/, "_")
  71. # Download the PDF (if enabled) and return a web path:
  72. # /downloads/meandervalley/<council_reference>/<filename.pdf>
  73. def download_pdf(url, council_reference)
  74. return nil if DRY_RUN
  75. return nil unless DOWNLOAD_ATTACHMENTS && !url.to_s.strip.empty?
  76. folder = File.join(DOWNLOAD_DIR, "meandervalley", safe_name(council_reference))
  77. FileUtils.mkdir_p(folder)
  78. begin
  79. res = Http.get_response(url) rescue Http.get(url)
  80. body = res.respond_to?(:body) ? res.body : res.to_s
  81. fname = safe_name(File.basename(URI.parse(url).path))
  82. fname += ".pdf" unless fname.downcase.end_with?(".pdf")
  83. path = File.join(folder, fname)
  84. File.binwrite(path, body)
  85. puts "Saved PDF #{path}"
  86. "/downloads/meandervalley/#{safe_name(council_reference)}/#{fname}"
  87. rescue StandardError => e
  88. warn "PDF download failed for #{url}: #{e.class} #{e.message}"
  89. nil
  90. end
  91. end
  92. html = Http.get(URL, referer: URL)
  93. doc = Nokogiri::HTML(html)
  94. # Items are listed inline under the "Advertised" section with lines like:
  95. # Application: <link> Applicant: ... Property: ... Proposal: ... Closes: <date>
  96. items = []
  97. # Looser, case-insensitive match for the advertised PDFs
  98. all_anchors = doc.css('a[href]')
  99. if DEBUG
  100. puts "[DEBUG] anchors total=#{all_anchors.size}"
  101. end
  102. pdf_anchors = all_anchors.select do |a|
  103. href = a["href"].to_s
  104. hd = href.downcase
  105. hd.include?("/planning-applications/advertised/") && hd.include?(".pdf")
  106. end
  107. puts "[DEBUG] matched advertised pdf anchors=#{pdf_anchors.size}" if DEBUG
  108. pdf_anchors.each do |a|
  109. href = a["href"].to_s
  110. pdf = begin
  111. URI.join(URL, href).to_s
  112. rescue URI::InvalidURIError
  113. href
  114. end
  115. blk_text = host_block_for(a)
  116. # Try to normalize reference from nearby text or the file name
  117. ref = normalize_pa_ref(blk_text, pdf)
  118. ref ||= a.text.to_s.gsub(/\s+/, " ")[0, 100] # backstop so it never overflows
  119. address = field_value(blk_text, /Property/, [/Proposal/i, /Closes/i, /Application/i])
  120. desc = field_value(blk_text, /Proposal/, [/Closes/i, /Application/i])
  121. close_r = field_value(blk_text, /Closes/, [/Application/i])
  122. address = address[0, 255]
  123. desc = desc.empty? ? "Development Application" : desc[0, 1000]
  124. items << {
  125. council_reference: ref,
  126. address: address,
  127. description: desc,
  128. on_notice_raw: close_r,
  129. on_notice: Util.parse_aus_date(close_r),
  130. pdf: pdf,
  131. title_reference: a.text.to_s.strip
  132. }
  133. end
  134. items.uniq! { |r| [r[:council_reference], r[:address]] }
  135. puts "Found #{items.length} item(s) for #{TABLE}"
  136. items.each_with_index do |r, idx|
  137. if DEBUG
  138. puts "[DEBUG] ##{idx+1} "\
  139. "ref=#{r[:council_reference].inspect} (#{r[:council_reference].to_s.length}) | "\
  140. "addr=#{r[:address].inspect} (#{r[:address].to_s.length}) | "\
  141. "desc.len=#{r[:description].to_s.length} | "\
  142. "date_raw=#{r[:on_notice_raw].inspect} (#{r[:on_notice_raw].to_s.length}) | "\
  143. "pdf=#{r[:pdf].to_s[0,120]}"
  144. # If you want to see the full source text that was parsed:
  145. # puts JSON.pretty_generate(raw: r[:_raw].to_s[0,2000])
  146. end
  147. if DRY_RUN
  148. next
  149. end
  150. #items.each do |r|
  151. ref = r[:council_reference].to_s.tr("\\", "/")[0, 100]
  152. addr = r[:address].to_s[0, 255]
  153. desc = r[:description].to_s[0, 1000]
  154. date_received = Date.today
  155. DB.upsert(TABLE, {
  156. description: r[:description],
  157. date_received: date_received,
  158. on_notice_to: r[:on_notice], # store close date for consistency
  159. on_notice_to_raw: r[:on_notice_raw],
  160. address: r[:address],
  161. council_reference: r[:council_reference],
  162. applicant: "",
  163. owner: ""
  164. })
  165. enrich_after_upsert!(
  166. table: TABLE,
  167. council_reference: r[:council_reference],
  168. address: r[:address]
  169. )
  170. # Download & set local_document_url
  171. local_doc_url = download_pdf(r[:pdf], r[:council_reference])
  172. begin
  173. upd = DB.client.prepare(
  174. "UPDATE `#{DB.client.escape(TABLE)}` SET " \
  175. " document_url = ?, " \
  176. " local_document_url = COALESCE(?, local_document_url), " \
  177. " on_notice_to = ?, on_notice_to_raw = ?, title_reference = ? " \
  178. "WHERE council_reference = ? AND address = ?"
  179. )
  180. upd.execute(
  181. r[:pdf],
  182. local_doc_url,
  183. r[:on_notice],
  184. r[:on_notice_raw],
  185. r[:title_reference],
  186. r[:council_reference],
  187. r[:address]
  188. )
  189. rescue StandardError => e
  190. warn "Extras update skipped for #{r[:council_reference]}: #{e.class} #{e.message}"
  191. end
  192. puts "Upserted #{r[:council_reference]} -> #{r[:address]} saved: #{local_doc_url ? 1 : 0}"
  193. end
  194. puts "Done #{TABLE}."