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
54 k.add :move_cursor_left, "Move selector to the left", :left
57 def initialize opts={}
58 @header = opts.delete(:header) || {}
61 @body = opts.delete(:body) || []
62 @body += sig_lines if $config[:edit_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
97 "-" * buffer.content_width
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
108 if (curpos - lines) >= @header_lines.length
111 edit_field @header_lines[curpos - lines]
115 def edit_to; edit_field "To" end
116 def edit_cc; edit_field "Cc" end
117 def edit_subject; edit_field "Subject" end
120 @file = Tempfile.new "sup.#{self.class.name.gsub(/.*::/, '').camel_to_hyphy}"
121 @file.puts format_headers(@header - NON_EDITABLE_HEADERS).first
126 editor = $config[:editor] || ENV['EDITOR'] || "/usr/bin/vi"
128 mtime = File.mtime @file.path
129 BufferManager.shell_out "#{editor} #{@file.path}"
130 @edited = true if File.mtime(@file.path) > mtime
132 return @edited unless @edited
134 header, @body = parse_file @file.path
135 @header = header - NON_EDITABLE_HEADERS
136 handle_new_text @header, @body
143 !edited? || BufferManager.ask_yes_or_no("Discard message?")
147 fn = BufferManager.ask_for_filename :attachment, "File name (enter for browser): "
149 @attachments << RMail::Message.make_file_attachment(fn)
150 @attachment_names << fn
154 def delete_attachment
155 i = curpos - @attachment_lines_offset - DECORATION_LINES - 1
156 if i >= 0 && i < @attachments.size && BufferManager.ask_yes_or_no("Delete attachment #{@attachment_names[i]}?")
157 @attachments.delete_at i
158 @attachment_names.delete_at i
166 return unless curpos < @selectors.length
167 @selectors[curpos].roll_left
171 def move_cursor_right
172 return unless curpos < @selectors.length
173 @selectors[curpos].roll_right
179 @selector_label_width = [@selector_label_width, s.label.length].max
184 buffer.mark_dirty if buffer
188 header, @header_lines = format_headers(@header - NON_EDITABLE_HEADERS) + [""]
189 @text = header + [""] + @body
190 @text += sig_lines unless $config[:edit_signature]
192 @attachment_lines_offset = 0
194 unless @attachments.empty?
196 @attachment_lines_offset = @text.length
197 @text += (0 ... @attachments.size).map { |i| [[:attachment_color, "+ Attachment: #{@attachment_names[i]} (#{@attachments[i].body.size.to_human_size})"]] }
203 header = MBox::read_header f
206 header.delete_if { |k, v| NON_EDITABLE_HEADERS.member? k }
207 header.each { |k, v| header[k] = parse_header k, v }
213 def parse_header k, v
214 if MULTI_HEADERS.include?(k)
215 v.split_on_commas.map do |name|
216 (p = ContactManager.contact_for(name)) && p.full_address || name
223 def format_headers header
225 headers = (FORCE_HEADERS + (header.keys - FORCE_HEADERS)).map do |h|
226 lines = make_lines "#{h}:", header[h]
227 lines.length.times { header_lines << h }
230 [headers, header_lines]
233 def make_lines header, things
238 [header + " " + things]
243 things.map_with_index do |name, i|
244 raise "an array: #{name.inspect} (things #{things.inspect})" if Array === name
248 (" " * (header.length + 1)) + name
249 end + (i == things.length - 1 ? "" : ",")
256 return false if !edited? && !BufferManager.ask_yes_or_no("Message unedited. Really send?")
257 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
258 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
262 if @header["From"] =~ /<?(\S+@(\S+?))>?$/
265 AccountManager.default_account.email
268 acct = AccountManager.account_for(from_email) || AccountManager.default_account
269 BufferManager.flash "Sending..."
272 IO.popen(acct.sendmail, "w") { |p| write_full_message_to p, date, false }
273 raise SendmailCommandFailed, "Couldn't execute #{acct.sendmail}" unless $? == 0
274 SentManager.write_sent_message(date, from_email) { |f| write_full_message_to f, date, true }
275 BufferManager.kill_buffer buffer
276 BufferManager.flash "Message sent!"
278 rescue SystemCallError, SendmailCommandFailed => e
279 Redwood::log "Problem sending mail: #{e.message}"
280 BufferManager.flash "Problem sending mail: #{e.message}"
286 DraftManager.write_draft { |f| write_message f, false }
287 BufferManager.kill_buffer buffer
288 BufferManager.flash "Saved for later editing."
291 def write_full_message_to f, date=Time.now, escape=false
292 m = RMail::Message.new
293 @header.each do |k, v|
294 next if v.nil? || v.empty?
304 m.header["Date"] = date.rfc2822
305 m.header["Message-Id"] = @message_id
306 m.header["User-Agent"] = "Sup/#{Redwood::VERSION}"
308 if @attachments.empty?
309 m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
311 m.body = sanitize_body m.body if escape
312 m.body += sig_lines.join("\n") unless $config[:edit_signature]
314 body_m = RMail::Message.new
315 body_m.body = @body.join
316 body_m.body = sanitize_body body_m.body if escape
317 body_m.body += sig_lines.join("\n") unless $config[:edit_signature]
318 body_m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
319 body_m.header["Content-Disposition"] = "inline"
322 @attachments.each { |a| m.add_part a }
327 ## TODO: remove this. redundant with write_full_message_to.
329 ## this is going to change soon: draft messages (currently written
330 ## with full=false) will be output as yaml.
331 def write_message f, full=true, date=Time.now
332 raise ArgumentError, "no pre-defined date: header allowed" if @header["Date"]
333 f.puts format_headers(@header).first
335 Date: #{date.rfc2822}
336 Message-Id: #{@message_id}
341 Content-Type: text/plain; charset=us-ascii
342 Content-Disposition: inline
343 User-Agent: Redwood/#{Redwood::VERSION}
348 f.puts sanitize_body(@body.join)
349 f.puts sig_lines if full unless $config[:edit_signature]
357 text = BufferManager.ask :subject, "Subject: ", @header[field]
359 @header[field] = parse_header field, text
367 @header[field].join(", ")
372 contacts = BufferManager.ask_for_contacts :people, "#{field}: ", default
374 text = contacts.map { |s| s.longname }.join(", ")
375 @header[field] = parse_header field, text
384 def sanitize_body body
385 body.gsub(/^From /, ">From ")
388 def mentions_attachments?
389 @body.any? { |l| l =~ /^[^>]/ && l =~ /\battach(ment|ed|ing|)\b/i }
393 @body.join =~ /(\S+)\s*Excerpts from.*\n(>.*\n)+\s*\Z/
397 p = PersonManager.person_for(@header["From"])
398 from_email = p && p.email
400 ## first run the hook
401 hook_sig = HookManager.run "signature", :header => @header, :from_email => from_email
402 return ["", "-- "] + hook_sig.split("\n") if hook_sig
404 ## no hook, do default signature generation based on config.yaml
405 return [] unless from_email
406 sigfn = (AccountManager.account_for(from_email) ||
407 AccountManager.default_account).signature
409 if sigfn && File.exists?(sigfn)
410 ["", "-- "] + File.readlines(sigfn).map { |l| l.chomp }