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