meandervalley.rb 7.4 KB

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