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