]> git.cworth.org Git - sup/blob - lib/sup/modes/edit-message-mode.rb
Merge branch 'utf8-fixes' into next
[sup] / lib / sup / modes / edit-message-mode.rb
1 require 'tempfile'
2 require 'socket' # just for gethostname!
3 require 'pathname'
4 require 'rmail'
5 require 'jcode' # for RE_UTF8
6
7 module Redwood
8
9 class SendmailCommandFailed < StandardError; end
10
11 class EditMessageMode < LineCursorMode
12   DECORATION_LINES = 1
13
14   FORCE_HEADERS = %w(From To Cc Bcc Subject)
15   MULTI_HEADERS = %w(To Cc Bcc)
16   NON_EDITABLE_HEADERS = %w(Message-id Date)
17
18   HookManager.register "signature", <<EOS
19 Generates a message signature.
20 Variables:
21       header: an object that supports string-to-string hashtable-style access
22               to the raw headers for the message. E.g., header["From"],
23               header["To"], etc.
24   from_email: the email part of the From: line, or nil if empty
25 Return value:
26   A string (multi-line ok) containing the text of the signature, or nil to
27   use the default signature, or :none for no signature.
28 EOS
29
30   HookManager.register "before-edit", <<EOS
31 Modifies message body and headers before editing a new message. Variables
32 should be modified in place.
33 Variables:
34         header: a hash of headers. See 'signature' hook for documentation.
35         body: an array of lines of body text.
36 Return value:
37         none
38 EOS
39
40   attr_reader :status
41   attr_accessor :body, :header
42   bool_reader :edited
43
44   register_keymap do |k|
45     k.add :send_message, "Send message", 'y'
46     k.add :edit_message_or_field, "Edit selected field", 'e'
47     k.add :edit_to, "Edit To:", 't'
48     k.add :edit_cc, "Edit Cc:", 'c'
49     k.add :edit_subject, "Edit Subject", 's'
50     k.add :edit_message, "Edit message", :enter
51     k.add :save_as_draft, "Save as draft", 'P'
52     k.add :attach_file, "Attach a file", 'a'
53     k.add :delete_attachment, "Delete an attachment", 'd'
54     k.add :move_cursor_right, "Move selector to the right", :right, 'l'
55     k.add :move_cursor_left, "Move selector to the left", :left, 'h'
56   end
57
58   def initialize opts={}
59     @header = opts.delete(:header) || {} 
60     @header_lines = []
61
62     @body = opts.delete(:body) || []
63     @body += sig_lines if $config[:edit_signature] && !opts.delete(:have_signature)
64
65     if opts[:attachments]
66       @attachments = opts[:attachments].values
67       @attachment_names = opts[:attachments].keys
68     else
69       @attachments = []
70       @attachment_names = []
71     end
72
73     @message_id = "<#{Time.now.to_i}-sup-#{rand 10000}@#{Socket.gethostname}>"
74     @edited = false
75     @selectors = []
76     @selector_label_width = 0
77
78     @crypto_selector =
79       if CryptoManager.have_crypto?
80         HorizontalSelector.new "Crypto:", [:none] + CryptoManager::OUTGOING_MESSAGE_OPERATIONS.keys, ["None"] + CryptoManager::OUTGOING_MESSAGE_OPERATIONS.values
81       end
82     add_selector @crypto_selector if @crypto_selector
83     
84     HookManager.run "before-edit", :header => @header, :body => @body
85
86     super opts
87     regen_text
88   end
89
90   def lines; @text.length + (@selectors.empty? ? 0 : (@selectors.length + DECORATION_LINES)) end
91   
92   def [] i
93     if @selectors.empty?
94       @text[i]
95     elsif i < @selectors.length
96       @selectors[i].line @selector_label_width
97     elsif i == @selectors.length
98       ""
99     else
100       @text[i - @selectors.length - DECORATION_LINES]
101     end
102   end
103
104   ## hook for subclasses. i hate this style of programming.
105   def handle_new_text header, body; end
106
107   def edit_message_or_field
108     lines = DECORATION_LINES + @selectors.size
109     if lines > curpos
110       return
111     elsif (curpos - lines) >= @header_lines.length
112       edit_message
113     else
114       edit_field @header_lines[curpos - lines]
115     end
116   end
117
118   def edit_to; edit_field "To" end
119   def edit_cc; edit_field "Cc" end
120   def edit_subject; edit_field "Subject" end
121
122   def edit_message
123     @file = Tempfile.new "sup.#{self.class.name.gsub(/.*::/, '').camel_to_hyphy}"
124     @file.puts format_headers(@header - NON_EDITABLE_HEADERS).first
125     @file.puts
126     @file.puts @body.join("\n")
127     @file.close
128
129     editor = $config[:editor] || ENV['EDITOR'] || "/usr/bin/vi"
130
131     mtime = File.mtime @file.path
132     BufferManager.shell_out "#{editor} #{@file.path}"
133     @edited = true if File.mtime(@file.path) > mtime
134
135     return @edited unless @edited
136
137     header, @body = parse_file @file.path
138     @header = header - NON_EDITABLE_HEADERS
139     handle_new_text @header, @body
140     update
141
142     @edited
143   end
144
145   def killable?
146     !edited? || BufferManager.ask_yes_or_no("Discard message?")
147   end
148
149   def unsaved?; edited? end
150
151   def attach_file
152     fn = BufferManager.ask_for_filename :attachment, "File name (enter for browser): "
153     return unless fn
154     begin
155       @attachments << RMail::Message.make_file_attachment(fn)
156       @attachment_names << fn
157       update
158     rescue SystemCallError => e
159       BufferManager.flash "Can't read #{fn}: #{e.message}"
160     end
161   end
162
163   def delete_attachment
164     i = curpos - @attachment_lines_offset - DECORATION_LINES - 1
165     if i >= 0 && i < @attachments.size && BufferManager.ask_yes_or_no("Delete attachment #{@attachment_names[i]}?")
166       @attachments.delete_at i
167       @attachment_names.delete_at i
168       update
169     end
170   end
171
172 protected
173
174   def mime_encode string
175     string = [string].pack('M') # basic quoted-printable
176     string.gsub!(/=\n/,'')      # .. remove trailing newline
177     string.gsub!(/_/,'=96')     # .. encode underscores
178     string.gsub!(/\?/,'=3F')    # .. encode question marks
179     string.gsub!(/ /,'_')       # .. translate space to underscores
180     "=?utf-8?q?#{string}?="
181   end
182
183   def mime_encode_subject string
184     return string unless string.match(String::RE_UTF8)
185     mime_encode string
186   end
187
188   RE_ADDRESS = /(.+)( <.*@.*>)/
189
190   # Encode "bælammet mitt <user@example.com>" into
191   # "=?utf-8?q?b=C3=A6lammet_mitt?= <user@example.com>
192   def mime_encode_address string
193     return string unless string.match(String::RE_UTF8)
194     string.sub(RE_ADDRESS) { |match| mime_encode($1) + $2 }
195   end
196
197   def move_cursor_left
198     if curpos < @selectors.length
199       @selectors[curpos].roll_left
200       buffer.mark_dirty
201     else
202       col_left
203     end
204   end
205
206   def move_cursor_right
207     if curpos < @selectors.length
208       @selectors[curpos].roll_right
209       buffer.mark_dirty
210     else
211       col_right
212     end
213   end
214
215   def add_selector s
216     @selectors << s
217     @selector_label_width = [@selector_label_width, s.label.length].max
218   end
219
220   def update
221     regen_text
222     buffer.mark_dirty if buffer
223   end
224
225   def regen_text
226     header, @header_lines = format_headers(@header - NON_EDITABLE_HEADERS) + [""]
227     @text = header + [""] + @body
228     @text += sig_lines unless $config[:edit_signature]
229     
230     @attachment_lines_offset = 0
231
232     unless @attachments.empty?
233       @text += [""]
234       @attachment_lines_offset = @text.length
235       @text += (0 ... @attachments.size).map { |i| [[:attachment_color, "+ Attachment: #{@attachment_names[i]} (#{@attachments[i].body.size.to_human_size})"]] }
236     end
237   end
238
239   def parse_file fn
240     File.open(fn) do |f|
241       header = Source.parse_raw_email_header(f).inject({}) { |h, (k, v)| h[k.capitalize] = v; h } # lousy HACK
242       body = f.readlines.map { |l| l.chomp }
243
244       header.delete_if { |k, v| NON_EDITABLE_HEADERS.member? k }
245       header.each { |k, v| header[k] = parse_header k, v }
246
247       [header, body]
248     end
249   end
250
251   def parse_header k, v
252     if MULTI_HEADERS.include?(k)
253       v.split_on_commas.map do |name|
254         (p = ContactManager.contact_for(name)) && p.full_address || name
255       end
256     else
257       v
258     end
259   end
260
261   def format_headers header
262     header_lines = []
263     headers = (FORCE_HEADERS + (header.keys - FORCE_HEADERS)).map do |h|
264       lines = make_lines "#{h}:", header[h]
265       lines.length.times { header_lines << h }
266       lines
267     end.flatten.compact
268     [headers, header_lines]
269   end
270
271   def make_lines header, things
272     case things
273     when nil, []
274       [header + " "]
275     when String
276       [header + " " + things]
277     else
278       if things.empty?
279         [header]
280       else
281         things.map_with_index do |name, i|
282           raise "an array: #{name.inspect} (things #{things.inspect})" if Array === name
283           if i == 0
284             header + " " + name
285           else
286             (" " * (header.display_length + 1)) + name
287           end + (i == things.length - 1 ? "" : ",")
288         end
289       end
290     end
291   end
292
293   def send_message
294     return false if !edited? && !BufferManager.ask_yes_or_no("Message unedited. Really send?")
295     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
296     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
297
298     from_email = 
299       if @header["From"] =~ /<?(\S+@(\S+?))>?$/
300         $1
301       else
302         AccountManager.default_account.email
303       end
304
305     acct = AccountManager.account_for(from_email) || AccountManager.default_account
306     BufferManager.flash "Sending..."
307
308     begin
309       date = Time.now
310       m = build_message date
311       IO.popen(acct.sendmail, "w") { |p| p.puts m }
312       raise SendmailCommandFailed, "Couldn't execute #{acct.sendmail}" unless $? == 0
313       SentManager.write_sent_message(date, from_email) { |f| f.puts sanitize_body(m.to_s) }
314       BufferManager.kill_buffer buffer
315       BufferManager.flash "Message sent!"
316       true
317     rescue SystemCallError, SendmailCommandFailed, CryptoManager::Error => e
318       Redwood::log "Problem sending mail: #{e.message}"
319       BufferManager.flash "Problem sending mail: #{e.message}"
320       false
321     end
322   end
323
324   def save_as_draft
325     DraftManager.write_draft { |f| write_message f, false }
326     BufferManager.kill_buffer buffer
327     BufferManager.flash "Saved for later editing."
328   end
329
330   def build_message date
331     m = RMail::Message.new
332     m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
333     m.body = @body.join("\n")
334     m.body += sig_lines.join("\n") unless $config[:edit_signature]
335     ## body must end in a newline or GPG signatures will be WRONG!
336     m.body += "\n" unless m.body =~ /\n\Z/
337
338     ## there are attachments, so wrap body in an attachment of its own
339     unless @attachments.empty?
340       body_m = m
341       body_m.header["Content-Disposition"] = "inline"
342       m = RMail::Message.new
343       
344       m.add_part body_m
345       @attachments.each { |a| m.add_part a }
346     end
347
348     ## do whatever crypto transformation is necessary
349     if @crypto_selector && @crypto_selector.val != :none
350       from_email = Person.from_address(@header["From"]).email
351       to_email = [@header["To"], @header["Cc"], @header["Bcc"]].flatten.compact.map { |p| Person.from_address(p).email }
352
353       m = CryptoManager.send @crypto_selector.val, from_email, to_email, m
354     end
355
356     ## finally, set the top-level headers
357     @header.each do |k, v|
358       next if v.nil? || v.empty?
359       m.header[k] = 
360         case v
361         when String
362           k.match(/subject/i) ? mime_encode_subject(v) : mime_encode_address(v)
363         when Array
364           v.map { |v| mime_encode_address v }.join ", "
365         end
366     end
367
368     m.header["Date"] = date.rfc2822
369     m.header["Message-Id"] = @message_id
370     m.header["User-Agent"] = "Sup/#{Redwood::VERSION}"
371     m.header["Content-Transfer-Encoding"] = '8bit'
372     m
373   end
374
375   ## TODO: remove this. redundant with write_full_message_to.
376   ##
377   ## this is going to change soon: draft messages (currently written
378   ## with full=false) will be output as yaml.
379   def write_message f, full=true, date=Time.now
380     raise ArgumentError, "no pre-defined date: header allowed" if @header["Date"]
381     f.puts format_headers(@header).first
382     f.puts <<EOS
383 Date: #{date.rfc2822}
384 Message-Id: #{@message_id}
385 EOS
386     if full
387       f.puts <<EOS
388 Mime-Version: 1.0
389 Content-Type: text/plain; charset=us-ascii
390 Content-Disposition: inline
391 User-Agent: Redwood/#{Redwood::VERSION}
392 EOS
393     end
394
395     f.puts
396     f.puts sanitize_body(@body.join("\n"))
397     f.puts sig_lines if full unless $config[:edit_signature]
398   end  
399
400 protected
401
402   def edit_field field
403     case field
404     when "Subject"
405       text = BufferManager.ask :subject, "Subject: ", @header[field]
406        if text
407          @header[field] = parse_header field, text
408          update
409        end
410     else
411       default = case field
412         when *MULTI_HEADERS
413           @header[field] ||= []
414           @header[field].join(", ")
415         else
416           @header[field]
417         end
418
419       contacts = BufferManager.ask_for_contacts :people, "#{field}: ", default
420       if contacts
421         text = contacts.map { |s| s.full_address }.join(", ")
422         @header[field] = parse_header field, text
423         update
424       end
425     end
426   end
427
428 private
429
430   def sanitize_body body
431     body.gsub(/^From /, ">From ")
432   end
433
434   def mentions_attachments?
435     @body.any? { |l| l =~ /^[^>]/ && l =~ /\battach(ment|ed|ing|)\b/i }
436   end
437
438   def top_posting?
439     @body.join("\n") =~ /(\S+)\s*Excerpts from.*\n(>.*\n)+\s*\Z/
440   end
441
442   def sig_lines
443     p = Person.from_address(@header["From"])
444     from_email = p && p.email
445
446     ## first run the hook
447     hook_sig = HookManager.run "signature", :header => @header, :from_email => from_email
448
449     return [] if hook_sig == :none
450     return ["", "-- "] + hook_sig.split("\n") if hook_sig
451
452     ## no hook, do default signature generation based on config.yaml
453     return [] unless from_email
454     sigfn = (AccountManager.account_for(from_email) || 
455              AccountManager.default_account).signature
456
457     if sigfn && File.exists?(sigfn)
458       ["", "-- "] + File.readlines(sigfn).map { |l| l.chomp }
459     else
460       []
461     end
462   end
463 end
464
465 end