meandervalley.rb 7.4 KB

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