2 require 'socket' # just for gethostname!
6 # from jcode.rb, not included in ruby 1.9
7 PATTERN_UTF8 = '[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]'
8 RE_UTF8 = Regexp.new(PATTERN_UTF8, 0, 'n')
12 class SendmailCommandFailed < StandardError; end
14 class EditMessageMode < LineCursorMode
17 FORCE_HEADERS = %w(From To Cc Bcc Subject)
18 MULTI_HEADERS = %w(To Cc Bcc)
19 NON_EDITABLE_HEADERS = %w(Message-id Date)
21 HookManager.register "signature", <<EOS
22 Generates a message signature.
24 header: an object that supports string-to-string hashtable-style access
25 to the raw headers for the message. E.g., header["From"],
27 from_email: the email part of the From: line, or nil if empty
29 A string (multi-line ok) containing the text of the signature, or nil to
30 use the default signature, or :none for no signature.
33 HookManager.register "before-edit", <<EOS
34 Modifies message body and headers before editing a new message. Variables
35 should be modified in place.
37 header: a hash of headers. See 'signature' hook for documentation.
38 body: an array of lines of body text.
44 attr_accessor :body, :header
47 register_keymap do |k|
48 k.add :send_message, "Send message", 'y'
49 k.add :edit_message_or_field, "Edit selected field", 'e'
50 k.add :edit_to, "Edit To:", 't'
51 k.add :edit_cc, "Edit Cc:", 'c'
52 k.add :edit_subject, "Edit Subject", 's'
53 k.add :edit_message, "Edit message", :enter
54 k.add :save_as_draft, "Save as draft", 'P'
55 k.add :attach_file, "Attach a file", 'a'
56 k.add :delete_attachment, "Delete an attachment", 'd'
57 k.add :move_cursor_right, "Move selector to the right", :right, 'l'
58 k.add :move_cursor_left, "Move selector to the left", :left, 'h'
61 def initialize opts={}
62 @header = opts.delete(:header) || {}
65 @body = opts.delete(:body) || []
66 @body += sig_lines if $config[:edit_signature] && !opts.delete(:have_signature)
69 @attachments = opts[:attachments].values
70 @attachment_names = opts[:attachments].keys
73 @attachment_names = []
77 hostname = File.open("/etc/mailname", "r").gets.chomp
81 hostname = Socket.gethostname if hostname.nil? or hostname.empty?
83 @message_id = "<#{Time.now.to_i}-sup-#{rand 10000}@#{hostname}>"
86 @selector_label_width = 0
89 if CryptoManager.have_crypto?
90 HorizontalSelector.new "Crypto:", [:none] + CryptoManager::OUTGOING_MESSAGE_OPERATIONS.keys, ["None"] + CryptoManager::OUTGOING_MESSAGE_OPERATIONS.values
93 if !$config[:crypto_default].nil?
94 @crypto_selector.set_to $config[:crypto_default]
96 add_selector @crypto_selector
99 HookManager.run "before-edit", :header => @header, :body => @body
105 def lines; @text.length + (@selectors.empty? ? 0 : (@selectors.length + DECORATION_LINES)) end
110 elsif i < @selectors.length
111 @selectors[i].line @selector_label_width
112 elsif i == @selectors.length
115 @text[i - @selectors.length - DECORATION_LINES]
119 ## hook for subclasses. i hate this style of programming.
120 def handle_new_text header, body; end
122 def edit_message_or_field
123 lines = DECORATION_LINES + @selectors.size
126 elsif (curpos - lines) >= @header_lines.length
129 edit_field @header_lines[curpos - lines]
133 def edit_to; edit_field "To" end
134 def edit_cc; edit_field "Cc" end
135 def edit_subject; edit_field "Subject" end
138 @file = Tempfile.new "sup.#{self.class.name.gsub(/.*::/, '').camel_to_hyphy}"
139 @file.puts format_headers(@header - NON_EDITABLE_HEADERS).first
141 @file.puts @body.join("\n")
144 editor = $config[:editor] || ENV['EDITOR'] || "/usr/bin/vi"
146 mtime = File.mtime @file.path
147 BufferManager.shell_out "#{editor} #{@file.path}"
148 @edited = true if File.mtime(@file.path) > mtime
150 return @edited unless @edited
152 header, @body = parse_file @file.path
153 @header = header - NON_EDITABLE_HEADERS
154 handle_new_text @header, @body
161 !edited? || BufferManager.ask_yes_or_no("Discard message?")
164 def unsaved?; edited? end
167 fn = BufferManager.ask_for_filename :attachment, "File name (enter for browser): "
170 @attachments << RMail::Message.make_file_attachment(fn)
171 @attachment_names << fn
173 rescue SystemCallError => e
174 BufferManager.flash "Can't read #{fn}: #{e.message}"
178 def delete_attachment
179 i = curpos - @attachment_lines_offset - DECORATION_LINES - 1
180 if i >= 0 && i < @attachments.size && BufferManager.ask_yes_or_no("Delete attachment #{@attachment_names[i]}?")
181 @attachments.delete_at i
182 @attachment_names.delete_at i
189 def mime_encode string
190 string = [string].pack('M') # basic quoted-printable
191 string.gsub!(/=\n/,'') # .. remove trailing newline
192 string.gsub!(/_/,'=96') # .. encode underscores
193 string.gsub!(/\?/,'=3F') # .. encode question marks
194 string.gsub!(/ /,'_') # .. translate space to underscores
195 "=?utf-8?q?#{string}?="
198 def mime_encode_subject string
199 return string unless string.match(RE_UTF8)
203 RE_ADDRESS = /(.+)( <.*@.*>)/
205 # Encode "bælammet mitt <user@example.com>" into
206 # "=?utf-8?q?b=C3=A6lammet_mitt?= <user@example.com>
207 def mime_encode_address string
208 return string unless string.match(RE_UTF8)
209 string.sub(RE_ADDRESS) { |match| mime_encode($1) + $2 }
213 if curpos < @selectors.length
214 @selectors[curpos].roll_left
221 def move_cursor_right
222 if curpos < @selectors.length
223 @selectors[curpos].roll_right
232 @selector_label_width = [@selector_label_width, s.label.length].max
237 buffer.mark_dirty if buffer
241 header, @header_lines = format_headers(@header - NON_EDITABLE_HEADERS) + [""]
242 @text = header + [""] + @body
243 @text += sig_lines unless $config[:edit_signature]
245 @attachment_lines_offset = 0
247 unless @attachments.empty?
249 @attachment_lines_offset = @text.length
250 @text += (0 ... @attachments.size).map { |i| [[:attachment_color, "+ Attachment: #{@attachment_names[i]} (#{@attachments[i].body.size.to_human_size})"]] }
256 header = Source.parse_raw_email_header(f).inject({}) { |h, (k, v)| h[k.capitalize] = v; h } # lousy HACK
257 body = f.readlines.map { |l| l.chomp }
259 header.delete_if { |k, v| NON_EDITABLE_HEADERS.member? k }
260 header.each { |k, v| header[k] = parse_header k, v }
266 def parse_header k, v
267 if MULTI_HEADERS.include?(k)
268 v.split_on_commas.map do |name|
269 (p = ContactManager.contact_for(name)) && p.full_address || name
276 def format_headers header
278 headers = (FORCE_HEADERS + (header.keys - FORCE_HEADERS)).map do |h|
279 lines = make_lines "#{h}:", header[h]
280 lines.length.times { header_lines << h }
283 [headers, header_lines]
286 def make_lines header, things
291 [header + " " + things]
296 things.map_with_index do |name, i|
297 raise "an array: #{name.inspect} (things #{things.inspect})" if Array === name
301 (" " * (header.display_length + 1)) + name
302 end + (i == things.length - 1 ? "" : ",")
309 return false if !edited? && !BufferManager.ask_yes_or_no("Message unedited. Really send?")
310 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
311 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
314 if @header["From"] =~ /<?(\S+@(\S+?))>?$/
317 AccountManager.default_account.email
320 acct = AccountManager.account_for(from_email) || AccountManager.default_account
321 BufferManager.flash "Sending..."
325 m = build_message date
326 IO.popen(acct.sendmail, "w") { |p| p.puts m }
327 raise SendmailCommandFailed, "Couldn't execute #{acct.sendmail}" unless $? == 0
328 SentManager.write_sent_message(date, from_email) { |f| f.puts sanitize_body(m.to_s) }
329 BufferManager.kill_buffer buffer
330 BufferManager.flash "Message sent!"
332 rescue SystemCallError, SendmailCommandFailed, CryptoManager::Error => e
333 warn "Problem sending mail: #{e.message}"
334 BufferManager.flash "Problem sending mail: #{e.message}"
340 DraftManager.write_draft { |f| write_message f, false }
341 BufferManager.kill_buffer buffer
342 BufferManager.flash "Saved for later editing."
345 def build_message date
346 m = RMail::Message.new
347 m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
348 m.body = @body.join("\n")
349 m.body += sig_lines.join("\n") unless $config[:edit_signature]
350 ## body must end in a newline or GPG signatures will be WRONG!
351 m.body += "\n" unless m.body =~ /\n\Z/
353 ## there are attachments, so wrap body in an attachment of its own
354 unless @attachments.empty?
356 body_m.header["Content-Disposition"] = "inline"
357 m = RMail::Message.new
360 @attachments.each { |a| m.add_part a }
363 ## do whatever crypto transformation is necessary
364 if @crypto_selector && @crypto_selector.val != :none
365 from_email = Person.from_address(@header["From"]).email
366 to_email = [@header["To"], @header["Cc"], @header["Bcc"]].flatten.compact.map { |p| Person.from_address(p).email }
368 m = CryptoManager.send @crypto_selector.val, from_email, to_email, m
371 ## finally, set the top-level headers
372 @header.each do |k, v|
373 next if v.nil? || v.empty?
377 k.match(/subject/i) ? mime_encode_subject(v) : mime_encode_address(v)
379 v.map { |v| mime_encode_address v }.join ", "
383 m.header["Date"] = date.rfc2822
384 m.header["Message-Id"] = @message_id
385 m.header["User-Agent"] = "Sup/#{Redwood::VERSION}"
386 m.header["Content-Transfer-Encoding"] = '8bit'
390 ## TODO: remove this. redundant with write_full_message_to.
392 ## this is going to change soon: draft messages (currently written
393 ## with full=false) will be output as yaml.
394 def write_message f, full=true, date=Time.now
395 raise ArgumentError, "no pre-defined date: header allowed" if @header["Date"]
396 f.puts format_headers(@header).first
398 Date: #{date.rfc2822}
399 Message-Id: #{@message_id}
404 Content-Type: text/plain; charset=us-ascii
405 Content-Disposition: inline
406 User-Agent: Redwood/#{Redwood::VERSION}
411 f.puts sanitize_body(@body.join("\n"))
412 f.puts sig_lines if full unless $config[:edit_signature]
420 text = BufferManager.ask :subject, "Subject: ", @header[field]
422 @header[field] = parse_header field, text
428 @header[field] ||= []
429 @header[field].join(", ")
434 contacts = BufferManager.ask_for_contacts :people, "#{field}: ", default
436 text = contacts.map { |s| s.full_address }.join(", ")
437 @header[field] = parse_header field, text
445 def sanitize_body body
446 body.gsub(/^From /, ">From ")
449 def mentions_attachments?
450 @body.any? { |l| l =~ /^[^>]/ && l =~ /\battach(ment|ed|ing|)\b/i }
454 @body.join("\n") =~ /(\S+)\s*Excerpts from.*\n(>.*\n)+\s*\Z/
458 p = Person.from_address(@header["From"])
459 from_email = p && p.email
461 ## first run the hook
462 hook_sig = HookManager.run "signature", :header => @header, :from_email => from_email
464 return [] if hook_sig == :none
465 return ["", "-- "] + hook_sig.split("\n") if hook_sig
467 ## no hook, do default signature generation based on config.yaml
468 return [] unless from_email
469 sigfn = (AccountManager.account_for(from_email) ||
470 AccountManager.default_account).signature
472 if sigfn && File.exists?(sigfn)
473 ["", "-- "] + File.readlines(sigfn).map { |l| l.chomp }