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