86 lines
2 KiB
Ruby
Executable file
86 lines
2 KiB
Ruby
Executable file
#!/usr/bin/env ruby
|
|
|
|
require 'json'
|
|
require 'shellwords'
|
|
require 'time'
|
|
|
|
DEBUG = false
|
|
|
|
def log_file
|
|
@log_file ||= begin
|
|
at_exit { log_file.close }
|
|
File.open(File.expand_path('~/linky-notify.log'), 'a')
|
|
end
|
|
end
|
|
|
|
def log(line)
|
|
log_file.puts(line) if DEBUG
|
|
end
|
|
|
|
def munge_invalid_encoding(s)
|
|
s.chars.map { |c| c >= "\0" && c <= "\176" ? c : '?' }.join
|
|
end
|
|
|
|
def force_utf8(s)
|
|
if !s.valid_encoding?
|
|
log "forcing encoding of #{s[0..30].inspect}"
|
|
s = s.force_encoding('UTF-8')
|
|
if !s.valid_encoding?
|
|
log "munging #{s[0..30].inspect}"
|
|
s = munge_invalid_encoding(s)
|
|
end
|
|
log "s is now #{s[0..30].inspect}"
|
|
end
|
|
s
|
|
end
|
|
|
|
def e(s)
|
|
Shellwords.escape(force_utf8(s))
|
|
end
|
|
|
|
def notify_command(title, url)
|
|
notifier = File.expand_path '~/.rbenv/shims/terminal-notifier'
|
|
"#{notifier} -title #{e(title)} -message #{e(url)} -open #{e(url)} -actions 'Open' -closeLabel Ignore 2>&1"
|
|
end
|
|
|
|
def main
|
|
dir = ENV['WATCH_DIR']
|
|
created = JSON.parse(force_utf8(ENV['WATCH_CREATED']))
|
|
log "dir = #{dir}"
|
|
log "created = #{created.inspect}"
|
|
created.each do |filename|
|
|
path = File.join(dir, filename)
|
|
next if File.directory? path
|
|
lines = File.readlines(path).map { |l| force_utf8(l).strip }
|
|
title, url = nil, nil
|
|
until (title && url) || lines.empty?
|
|
line = lines.shift
|
|
next if line == ''
|
|
|
|
if line =~ /^http/
|
|
url ||= line
|
|
else
|
|
title ||= line
|
|
end
|
|
end
|
|
title ||= filename.sub(/^[0-9]+-/, '').sub(/\.[^.]+$/, '')
|
|
if url
|
|
command = notify_command(title, url)
|
|
log "[#{Time.now.iso8601}] #{command}"
|
|
output = `#{command}`
|
|
unless $?.success?
|
|
exit 1
|
|
end
|
|
archive_dir = File.join(dir, 'Archive')
|
|
Dir.mkdir(archive_dir) unless File.exists?(archive_dir)
|
|
File.rename(path, File.join(archive_dir, filename))
|
|
else
|
|
log "[#{Time.now.iso8601}] Failed to find URL in #{filename}: #{File.read(path)[0..200]}"
|
|
end
|
|
end
|
|
rescue Exception => e
|
|
log "#{e.class}: #{e.message}"
|
|
log e.backtrace.join("\n")
|
|
end
|
|
|
|
main if $0 == __FILE__
|