process_interac_email

 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
38pubsub = BlatherNotify::PubSub::Address.new(**CONFIG[:pubsub])
39
40m = Mail.new(ARGF.read)
41id_builder = ->(id) { "#{pubsub.to_uri};item=#{id}" }
42
43EM.run do
44	BlatherNotify.start(
45		CONFIG[:jid],
46		CONFIG[:password],
47		default_pubsub_addr: pubsub
48	).then {
49		InteracEmail.for(m, id_builder: id_builder).process
50	}.catch_only(InteracEmail::Error) { |e|
51		uuid = SecureRandom.uuid
52		BlatherNotify.publish "#{uuid}":
53			error_entry("💥 Exception #{e.class}", e, id_builder.call(uuid))
54	}.catch { |e|
55		if e.is_a?(::Exception)
56			Sentry.capture_exception(e)
57		else
58			Sentry.capture_message(e.to_s)
59		end
60		puts e
61	}.then { BlatherNotify.shutdown }
62end