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