]> git.cworth.org Git - sup/blob - lib/sup/modes/edit-message-mode.rb
Add new :crypto_default configuration option.
[sup] / lib / sup / modes / edit-message-mode.rb
1 require 'tempfile'
2 require 'socket' # just for gethostname!
3 require 'pathname'
4 require 'rmail'
5
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')
9
10 module Redwood
11
12 class SendmailCommandFailed < StandardError; end
13
14 class EditMessageMode < LineCursorMode
15   DECORATION_LINES = 1
16
17   FORCE_HEADERS = %w(From To Cc Bcc Subject)
18   MULTI_HEADERS = %w(To Cc Bcc)
19   NON_EDITABLE_HEADERS = %w(Message-id Date)
20
21   HookManager.register "signature", <<EOS
22 Generates a message signature.
23 Variables:
24       header: an object that supports string-to-string hashtable-style access
25               to the raw headers for the message. E.g., header["From"],
26               header["To"], etc.
27   from_email: the email part of the From: line, or nil if empty
28 Return value:
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.
31 EOS
32
33   HookManager.register "before-edit", <<EOS
34 Modifies message body and headers before editing a new message. Variables
35 should be modified in place.
36 Variables:
37         header: a hash of headers. See 'signature' hook for documentation.
38         body: an array of lines of body text.
39 Return value:
40         none
41 EOS
42
43   attr_reader :status
44   attr_accessor :body, :header
45   bool_reader :edited
46
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'
59   end
60
61   def initialize opts={}
62     @header = opts.delete(:header) || {} 
63     @header_lines = []
64
65     @body = opts.delete(:body) || []
66     @body += sig_lines if $config[:edit_signature] && !opts.delete(:have_signature)
67
68     if opts[:attachments]
69       @attachments = opts[:attachments].values
70       @attachment_names = opts[:attachments].keys
71     else
72       @attachments = []
73       @attachment_names = []
74     end
75
76     begin
77       hostname = File.open("/etc/mailname", "r").gets.chomp
78     rescue
79         nil
80     end
81     hostname = Socket.gethostname if hostname.nil? or hostname.empty?
82
83     @message_id = "<#{Time.now.to_i}-sup-#{rand 10000}@#{hostname}>"
84     @edited = false
85     @selectors = []
86     @selector_label_width = 0
87
88     @crypto_selector =
89       if CryptoManager.have_crypto?
90         HorizontalSelector.new "Crypto:", [:none] + CryptoManager::OUTGOING_MESSAGE_OPERATIONS.keys, ["None"] + CryptoManager::OUTGOING_MESSAGE_OPERATIONS.values
91       end
92     if @crypto_selector
93       if !$config[:crypto_default].nil?
94         @crypto_selector.set_to $config[:crypto_default]
95       end
96       add_selector @crypto_selector
97     end
98     
99     HookManager.run "before-edit", :header => @header, :body => @body
100
101     super opts
102     regen_text
103   end
104
105   def lines; @text.length + (@selectors.empty? ? 0 : (@selectors.length + DECORATION_LINES)) end
106   
107   def [] i
108     if @selectors.empty?
109       @text[i]
110     elsif i < @selectors.length
111       @selectors[i].line @selector_label_width
112     elsif i == @selectors.length
113       ""
114     else
115       @text[i - @selectors.length - DECORATION_LINES]
116     end
117   end
118
119   ## hook for subclasses. i hate this style of programming.
120   def handle_new_text header, body; end
121
122   def edit_message_or_field
123     lines = DECORATION_LINES + @selectors.size
124     if lines > curpos
125       return
126     elsif (curpos - lines) >= @header_lines.length
127       edit_message
128     else
129       edit_field @header_lines[curpos - lines]
130     end
131   end
132
133   def edit_to; edit_field "To" end
134   def edit_cc; edit_field "Cc" end
135   def edit_subject; edit_field "Subject" end
136
137   def edit_message
138     @file = Tempfile.new "sup.#{self.class.name.gsub(/.*::/, '').camel_to_hyphy}"
139     @file.puts format_headers(@header - NON_EDITABLE_HEADERS).first
140     @file.puts
141     @file.puts @body.join("\n")
142     @file.close
143
144     editor = $config[:editor] || ENV['EDITOR'] || "/usr/bin/vi"
145
146     mtime = File.mtime @file.path
147     BufferManager.shell_out "#{editor} #{@file.path}"
148     @edited = true if File.mtime(@file.path) > mtime
149
150     return @edited unless @edited
151
152     header, @body = parse_file @file.path
153     @header = header - NON_EDITABLE_HEADERS
154     handle_new_text @header, @body
155     update
156
157     @edited
158   end
159
160   def killable?
161     !edited? || BufferManager.ask_yes_or_no("Discard message?")
162   end
163
164   def unsaved?; edited? end
165
166   def attach_file
167     fn = BufferManager.ask_for_filename :attachment, "File name (enter for browser): "
168     return unless fn
169     begin
170       @attachments << RMail::Message.make_file_attachment(fn)
171       @attachment_names << fn
172       update
173     rescue SystemCallError => e
174       BufferManager.flash "Can't read #{fn}: #{e.message}"
175     end
176   end
177
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
183       update
184     end
185   end
186
187 protected
188
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}?="
196   end
197
198   def mime_encode_subject string
199     return string unless string.match(RE_UTF8)
200     mime_encode string
201   end
202
203   RE_ADDRESS = /(.+)( <.*@.*>)/
204
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 }
210   end
211
212   def move_cursor_left
213     if curpos < @selectors.length
214       @selectors[curpos].roll_left
215       buffer.mark_dirty
216     else
217       col_left
218     end
219   end
220
221   def move_cursor_right
222     if curpos < @selectors.length
223       @selectors[curpos].roll_right
224       buffer.mark_dirty
225     else
226       col_right
227     end
228   end
229
230   def add_selector s
231     @selectors << s
232     @selector_label_width = [@selector_label_width, s.label.length].max
233   end
234
235   def update
236     regen_text
237     buffer.mark_dirty if buffer
238   end
239
240   def regen_text
241     header, @header_lines = format_headers(@header - NON_EDITABLE_HEADERS) + [""]
242     @text = header + [""] + @body
243     @text += sig_lines unless $config[:edit_signature]
244     
245     @attachment_lines_offset = 0
246
247     unless @attachments.empty?
248       @text += [""]
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})"]] }
251     end
252   end
253
254   def parse_file fn
255     File.open(fn) do |f|
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 }
258
259       header.delete_if { |k, v| NON_EDITABLE_HEADERS.member? k }
260       header.each { |k, v| header[k] = parse_header k, v }
261
262       [header, body]
263     end
264   end
265
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
270       end
271     else
272       v
273     end
274   end
275
276   def format_headers header
277     header_lines = []
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 }
281       lines
282     end.flatten.compact
283     [headers, header_lines]
284   end
285
286   def make_lines header, things
287     case things
288     when nil, []
289       [header + " "]
290     when String
291       [header + " " + things]
292     else
293       if things.empty?
294         [header]
295       else
296         things.map_with_index do |name, i|
297           raise "an array: #{name.inspect} (things #{things.inspect})" if Array === name
298           if i == 0
299             header + " " + name
300           else
301             (" " * (header.display_length + 1)) + name
302           end + (i == things.length - 1 ? "" : ",")
303         end
304       end
305     end
306   end
307
308   def send_message
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
312
313     from_email = 
314       if @header["From"] =~ /<?(\S+@(\S+?))>?$/
315         $1
316       else
317         AccountManager.default_account.email
318       end
319
320     acct = AccountManager.account_for(from_email) || AccountManager.default_account
321     BufferManager.flash "Sending..."
322
323     begin
324       date = Time.now
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!"
331       true
332     rescue SystemCallError, SendmailCommandFailed, CryptoManager::Error => e
333       warn "Problem sending mail: #{e.message}"
334       BufferManager.flash "Problem sending mail: #{e.message}"
335       false
336     end
337   end
338
339   def save_as_draft
340     DraftManager.write_draft { |f| write_message f, false }
341     BufferManager.kill_buffer buffer
342     BufferManager.flash "Saved for later editing."
343   end
344
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/
352
353     ## there are attachments, so wrap body in an attachment of its own
354     unless @attachments.empty?
355       body_m = m
356       body_m.header["Content-Disposition"] = "inline"
357       m = RMail::Message.new
358       
359       m.add_part body_m
360       @attachments.each { |a| m.add_part a }
361     end
362
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 }
367
368       m = CryptoManager.send @crypto_selector.val, from_email, to_email, m
369     end
370
371     ## finally, set the top-level headers
372     @header.each do |k, v|
373       next if v.nil? || v.empty?
374       m.header[k] = 
375         case v
376         when String
377           k.match(/subject/i) ? mime_encode_subject(v) : mime_encode_address(v)
378         when Array
379           v.map { |v| mime_encode_address v }.join ", "
380         end
381     end
382
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'
387     m
388   end
389
390   ## TODO: remove this. redundant with write_full_message_to.
391   ##
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
397     f.puts <<EOS
398 Date: #{date.rfc2822}
399 Message-Id: #{@message_id}
400 EOS
401     if full
402       f.puts <<EOS
403 Mime-Version: 1.0
404 Content-Type: text/plain; charset=us-ascii
405 Content-Disposition: inline
406 User-Agent: Redwood/#{Redwood::VERSION}
407 EOS
408     end
409
410     f.puts
411     f.puts sanitize_body(@body.join("\n"))
412     f.puts sig_lines if full unless $config[:edit_signature]
413   end  
414
415 protected
416
417   def edit_field field
418     case field
419     when "Subject"
420       text = BufferManager.ask :subject, "Subject: ", @header[field]
421        if text
422          @header[field] = parse_header field, text
423          update
424        end
425     else
426       default = case field
427         when *MULTI_HEADERS
428           @header[field] ||= []
429           @header[field].join(", ")
430         else
431           @header[field]
432         end
433
434       contacts = BufferManager.ask_for_contacts :people, "#{field}: ", default
435       if contacts
436         text = contacts.map { |s| s.full_address }.join(", ")
437         @header[field] = parse_header field, text
438         update
439       end
440     end
441   end
442
443 private
444
445   def sanitize_body body
446     body.gsub(/^From /, ">From ")
447   end
448
449   def mentions_attachments?
450     @body.any? { |l| l =~ /^[^>]/ && l =~ /\battach(ment|ed|ing|)\b/i }
451   end
452
453   def top_posting?
454     @body.join("\n") =~ /(\S+)\s*Excerpts from.*\n(>.*\n)+\s*\Z/
455   end
456
457   def sig_lines
458     p = Person.from_address(@header["From"])
459     from_email = p && p.email
460
461     ## first run the hook
462     hook_sig = HookManager.run "signature", :header => @header, :from_email => from_email
463
464     return [] if hook_sig == :none
465     return ["", "-- "] + hook_sig.split("\n") if hook_sig
466
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
471
472     if sigfn && File.exists?(sigfn)
473       ["", "-- "] + File.readlines(sigfn).map { |l| l.chomp }
474     else
475       []
476     end
477   end
478 end
479
480 end