2 require 'socket' # just for gethostname!
8 class SendmailCommandFailed < StandardError; end
10 class EditMessageMode < LineCursorMode
13 FORCE_HEADERS = %w(From To Cc Bcc Subject)
14 MULTI_HEADERS = %w(To Cc Bcc)
15 NON_EDITABLE_HEADERS = %w(Message-Id Date)
17 HookManager.register "signature", <<EOS
18 Generates a message signature.
20 header: an object that supports string-to-string hashtable-style access
21 to the raw headers for the message. E.g., header["From"],
23 from_email: the email part of the From: line, or nil if empty
25 A string (multi-line ok) containing the text of the signature, or nil to
26 use the default signature.
29 HookManager.register "before-edit", <<EOS
30 Modifies message body and headers before editing a new message. Variables
31 should be modified in place.
33 header: a hash of headers. See 'signature' hook for documentation.
34 body: an array of lines of body text.
40 attr_accessor :body, :header
43 register_keymap do |k|
44 k.add :send_message, "Send message", 'y'
45 k.add :edit_message_or_field, "Edit selected field", 'e'
46 k.add :edit_to, "Edit To:", 't'
47 k.add :edit_cc, "Edit Cc:", 'c'
48 k.add :edit_subject, "Edit Subject", 's'
49 k.add :edit_message, "Edit message", :enter
50 k.add :save_as_draft, "Save as draft", 'P'
51 k.add :attach_file, "Attach a file", 'a'
52 k.add :delete_attachment, "Delete an attachment", 'd'
53 k.add :move_cursor_right, "Move selector to the right", :right, 'l'
54 k.add :move_cursor_left, "Move selector to the left", :left, 'h'
57 def initialize opts={}
58 @header = opts.delete(:header) || {}
61 @body = opts.delete(:body) || []
62 @body += sig_lines if $config[:edit_signature] && !opts.delete(:have_signature)
65 @attachments = opts[:attachments].values
66 @attachment_names = opts[:attachments].keys
69 @attachment_names = []
72 @message_id = "<#{Time.now.to_i}-sup-#{rand 10000}@#{Socket.gethostname}>"
75 @selector_label_width = 0
78 if CryptoManager.have_crypto?
79 HorizontalSelector.new "Crypto:", [:none] + CryptoManager::OUTGOING_MESSAGE_OPERATIONS.keys, ["None"] + CryptoManager::OUTGOING_MESSAGE_OPERATIONS.values
81 add_selector @crypto_selector if @crypto_selector
83 HookManager.run "before-edit", :header => @header, :body => @body
89 def lines; @text.length + (@selectors.empty? ? 0 : (@selectors.length + DECORATION_LINES)) end
94 elsif i < @selectors.length
95 @selectors[i].line @selector_label_width
96 elsif i == @selectors.length
99 @text[i - @selectors.length - DECORATION_LINES]
103 ## hook for subclasses. i hate this style of programming.
104 def handle_new_text header, body; end
106 def edit_message_or_field
107 lines = DECORATION_LINES + @selectors.size
110 elsif (curpos - lines) >= @header_lines.length
113 edit_field @header_lines[curpos - lines]
117 def edit_to; edit_field "To" end
118 def edit_cc; edit_field "Cc" end
119 def edit_subject; edit_field "Subject" end
122 @file = Tempfile.new "sup.#{self.class.name.gsub(/.*::/, '').camel_to_hyphy}"
123 @file.puts format_headers(@header - NON_EDITABLE_HEADERS).first
128 editor = $config[:editor] || ENV['EDITOR'] || "/usr/bin/vi"
130 mtime = File.mtime @file.path
131 BufferManager.shell_out "#{editor} #{@file.path}"
132 @edited = true if File.mtime(@file.path) > mtime
134 return @edited unless @edited
136 header, @body = parse_file @file.path
137 @header = header - NON_EDITABLE_HEADERS
138 handle_new_text @header, @body
145 !edited? || BufferManager.ask_yes_or_no("Discard message?")
149 fn = BufferManager.ask_for_filename :attachment, "File name (enter for browser): "
152 @attachments << RMail::Message.make_file_attachment(fn)
153 @attachment_names << fn
155 rescue SystemCallError => e
156 BufferManager.flash "Can't read #{fn}: #{e.message}"
160 def delete_attachment
161 i = curpos - @attachment_lines_offset - DECORATION_LINES - 1
162 if i >= 0 && i < @attachments.size && BufferManager.ask_yes_or_no("Delete attachment #{@attachment_names[i]}?")
163 @attachments.delete_at i
164 @attachment_names.delete_at i
172 if curpos < @selectors.length
173 @selectors[curpos].roll_left
180 def move_cursor_right
181 if curpos < @selectors.length
182 @selectors[curpos].roll_right
191 @selector_label_width = [@selector_label_width, s.label.length].max
196 buffer.mark_dirty if buffer
200 header, @header_lines = format_headers(@header - NON_EDITABLE_HEADERS) + [""]
201 @text = header + [""] + @body
202 @text += sig_lines unless $config[:edit_signature]
204 @attachment_lines_offset = 0
206 unless @attachments.empty?
208 @attachment_lines_offset = @text.length
209 @text += (0 ... @attachments.size).map { |i| [[:attachment_color, "+ Attachment: #{@attachment_names[i]} (#{@attachments[i].body.size.to_human_size})"]] }
215 header = MBox::read_header f
218 header.delete_if { |k, v| NON_EDITABLE_HEADERS.member? k }
219 header.each { |k, v| header[k] = parse_header k, v }
225 def parse_header k, v
226 if MULTI_HEADERS.include?(k)
227 v.split_on_commas.map do |name|
228 (p = ContactManager.contact_for(name)) && p.full_address || name
235 def format_headers header
237 headers = (FORCE_HEADERS + (header.keys - FORCE_HEADERS)).map do |h|
238 lines = make_lines "#{h}:", header[h]
239 lines.length.times { header_lines << h }
242 [headers, header_lines]
245 def make_lines header, things
250 [header + " " + things]
255 things.map_with_index do |name, i|
256 raise "an array: #{name.inspect} (things #{things.inspect})" if Array === name
260 (" " * (header.length + 1)) + name
261 end + (i == things.length - 1 ? "" : ",")
268 return false if !edited? && !BufferManager.ask_yes_or_no("Message unedited. Really send?")
269 return false if $config[:confirm_no_attachments] && mentions_attachments? && @attachments.size == 0 && !BufferManager.ask_yes_or_no("You haven't added any attachments. Really send?")#" stupid ruby-mode
270 return false if $config[:confirm_top_posting] && top_posting? && !BufferManager.ask_yes_or_no("You're top-posting. That makes you a bad person. Really send?") #" stupid ruby-mode
273 if @header["From"] =~ /<?(\S+@(\S+?))>?$/
276 AccountManager.default_account.email
279 acct = AccountManager.account_for(from_email) || AccountManager.default_account
280 BufferManager.flash "Sending..."
284 m = build_message date
285 IO.popen(acct.sendmail, "w") { |p| p.puts m }
286 raise SendmailCommandFailed, "Couldn't execute #{acct.sendmail}" unless $? == 0
287 SentManager.write_sent_message(date, from_email) { |f| f.puts sanitize_body(m.to_s) }
288 BufferManager.kill_buffer buffer
289 BufferManager.flash "Message sent!"
291 rescue SystemCallError, SendmailCommandFailed, CryptoManager::Error => e
292 Redwood::log "Problem sending mail: #{e.message}"
293 BufferManager.flash "Problem sending mail: #{e.message}"
299 DraftManager.write_draft { |f| write_message f, false }
300 BufferManager.kill_buffer buffer
301 BufferManager.flash "Saved for later editing."
304 def build_message date
305 m = RMail::Message.new
306 m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
309 m.body += sig_lines.join("\n") unless $config[:edit_signature]
311 ## there are attachments, so wrap body in an attachment of its own
312 unless @attachments.empty?
314 body_m.header["Content-Disposition"] = "inline"
315 m = RMail::Message.new
318 @attachments.each { |a| m.add_part a }
321 ## do whatever crypto transformation is necessary
322 if @crypto_selector && @crypto_selector.val != :none
323 from_email = PersonManager.person_for(@header["From"]).email
324 to_email = [@header["To"], @header["Cc"], @header["Bcc"]].flatten.compact.map { |p| PersonManager.person_for(p).email }
326 m = CryptoManager.send @crypto_selector.val, from_email, to_email, m
329 ## finally, set the top-level headers
330 @header.each do |k, v|
331 next if v.nil? || v.empty?
340 m.header["Date"] = date.rfc2822
341 m.header["Message-Id"] = @message_id
342 m.header["User-Agent"] = "Sup/#{Redwood::VERSION}"
346 ## TODO: remove this. redundant with write_full_message_to.
348 ## this is going to change soon: draft messages (currently written
349 ## with full=false) will be output as yaml.
350 def write_message f, full=true, date=Time.now
351 raise ArgumentError, "no pre-defined date: header allowed" if @header["Date"]
352 f.puts format_headers(@header).first
354 Date: #{date.rfc2822}
355 Message-Id: #{@message_id}
360 Content-Type: text/plain; charset=us-ascii
361 Content-Disposition: inline
362 User-Agent: Redwood/#{Redwood::VERSION}
367 f.puts sanitize_body(@body.join)
368 f.puts sig_lines if full unless $config[:edit_signature]
376 text = BufferManager.ask :subject, "Subject: ", @header[field]
378 @header[field] = parse_header field, text
386 @header[field] ||= []
387 @header[field].join(", ")
392 contacts = BufferManager.ask_for_contacts :people, "#{field}: ", default
394 text = contacts.map { |s| s.longname }.join(", ")
395 @header[field] = parse_header field, text
404 def sanitize_body body
405 body.gsub(/^From /, ">From ")
408 def mentions_attachments?
409 @body.any? { |l| l =~ /^[^>]/ && l =~ /\battach(ment|ed|ing|)\b/i }
413 @body.join =~ /(\S+)\s*Excerpts from.*\n(>.*\n)+\s*\Z/
417 p = PersonManager.person_for(@header["From"])
418 from_email = p && p.email
420 ## first run the hook
421 hook_sig = HookManager.run "signature", :header => @header, :from_email => from_email
422 return ["", "-- "] + hook_sig.split("\n") if hook_sig
424 ## no hook, do default signature generation based on config.yaml
425 return [] unless from_email
426 sigfn = (AccountManager.account_for(from_email) ||
427 AccountManager.default_account).signature
429 if sigfn && File.exists?(sigfn)
430 ["", "-- "] + File.readlines(sigfn).map { |l| l.chomp }