1#!/usr/bin/ruby
2# frozen_string_literal: true
3
4# This expects postfix to be piping an email into stdin
5
6require "dhall"
7require "mail"
8require "nokogiri"
9require "securerandom"
10require "sentry-ruby"
11require "time"
12
13require_relative "../lib/blather_notify"
14require_relative "../lib/interac_email"
15
16def error_entry(title, text, id)
17 Nokogiri::XML::Builder.new { |xml|
18 xml.entry(xmlns: "http://www.w3.org/2005/Atom") do
19 xml.updated DateTime.now.iso8601
20 xml.id id
21 xml.title title
22 xml.content text.to_s, type: "text"
23 xml.author { xml.name "interac_email" }
24 xml.generator "interac_email", version: "1.0"
25 end
26 }.doc.root
27end
28
29raise "Need a Dhall config" unless ARGV[0]
30
31# I shift here because ARGF will work with either stdin or a file in argv if
32# there are any
33CONFIG =
34 Dhall::Coder
35 .new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
36 .load(ARGV.shift, transform_keys: :to_sym)
37
38Sentry.init do |config|
39 config.background_worker_threads = 0
40end
41
42pubsub = BlatherNotify::PubSub::Address.new(**CONFIG[:pubsub])
43
44m = Mail.new(ARGF.read)
45id_builder = ->(id) { "#{pubsub.to_uri};item=#{id}" }
46
47EM.run do
48 BlatherNotify.start(
49 CONFIG[:jid],
50 CONFIG[:password],
51 default_pubsub_addr: pubsub
52 ).then {
53 InteracEmail.for(m, id_builder: id_builder).process
54 }.catch_only(InteracEmail::Error) { |e|
55 uuid = SecureRandom.uuid
56 BlatherNotify.publish "#{uuid}":
57 error_entry("💥 Exception #{e.class}", e, id_builder.call(uuid))
58 }.catch { |e|
59 if e.is_a?(Exception)
60 Sentry.capture_exception(e)
61 else
62 Sentry.capture_message(e.to_s)
63 end
64 puts e
65 }.then { BlatherNotify.shutdown }
66end