-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrigate.rb
88 lines (78 loc) · 2.89 KB
/
frigate.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
require 'mqtt'
require 'json'
require 'telegram/bot'
require 'httparty'
require 'tempfile'
token = ENV['TELEGRAM_TOKEN']
chat_id = ENV['TELEGRAM_CHAT_ID'].to_i
mqtt_host = ENV['MQTT_HOST']
mqtt_port = ENV['MQTT_PORT']
mqtt_user = ENV['MQTT_USER']
mqtt_pass = ENV['MQTT_PASS']
frigate_url = ENV['FRIGATE_URL']
telegram_clip_wait_time = ENV['TELEGRAM_CLIP_WAIT_TIME'] ||= "20"
id_list = []
def download_to_tmp(url)
count = 0
begin
resp = HTTParty.get(url)
rescue
puts "Failed to download #{url}. Retrying..."
sleep 1
count = count + 1
exit if count == 25
retry
end
file = Tempfile.new
file.binmode
file.write(resp.body)
file.rewind
puts file.path
puts file.size
file
end
Telegram::Bot::Client.run(token) do |bot|
MQTT::Client.connect(host: mqtt_host, port: mqtt_port, username: mqtt_user, password: mqtt_pass) do |c|
c.get('frigate/events') do |topic,message|
a = JSON.parse message
if a['before']['has_clip'] == true
formatted_message = "#{a['before']['camera'].capitalize} - #{a['before']['label'].capitalize} was detected."
if !id_list.include?("#{a['before']['id']}_snap")
id_list << "#{a['before']['id']}_snap"
snap_fork = fork do
snapshot = "#{frigate_url}/api/events/#{a['before']['id']}/thumbnail.jpg"
#bot.api.send_message(chat_id: chat_id, text: formatted_message)
file = download_to_tmp(snapshot)
if file.size > 100 && file.size < 10000000
bot.api.send_photo(chat_id: chat_id, photo: Faraday::UploadIO.new(file.path, 'image/jpeg'), caption: formatted_message, show_caption_above_media: true, disable_notification: false)
end
file.close
file.unlink # deletes the temp file
exit
end #fork
Process.detach(snap_fork)
end
if !id_list.include?("#{a['before']['id']}_clip")
formatted_message = "#{a['before']['camera'].capitalize} - #{a['before']['label'].capitalize} was detected."
id_list << "#{a['before']['id']}_clip"
clip = "#{frigate_url}/api/events/#{a['before']['id']}/clip.mp4"
clip_fork = fork do
sleep telegram_clip_wait_time.to_i
file = download_to_tmp(clip)
if file.size > 100 && file.size < 50000000
bot.api.send_video(chat_id: chat_id, video: Faraday::UploadIO.new(file.path, 'video/mp4'), caption: formatted_message, show_caption_above_media: true, supports_streaming: true, disable_notification: true)
elsif file.size > 50000000
bot.api.send_message(chat_id: chat_id, text: "#{formatted_message}: #{clip}")
end
file.close
file.unlink # deletes the temp file
exit
end#fork
Process.detach(clip_fork)
end
else
puts "skipped message, not new"
end
end
end
end