]> git.cworth.org Git - sup/blob - lib/sup/modes/edit-message-mode.rb
78e88965c8a03e210f4fec4347c1eba73c135e67
[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
54     k.add :move_cursor_left, "Move selector to the left", :left
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       "-" * buffer.content_width
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     return unless curpos < @selectors.length
167     @selectors[curpos].roll_left
168     buffer.mark_dirty
169   end
170
171   def move_cursor_right
172     return unless curpos < @selectors.length
173     @selectors[curpos].roll_right
174     buffer.mark_dirty
175   end
176
177   def add_selector s
178     @selectors << s
179     @selector_label_width = [@selector_label_width, s.label.length].max
180   end
181
182   def update
183     regen_text
184     buffer.mark_dirty if buffer
185   end
186
187   def regen_text
188     header, @header_lines = format_headers(@header - NON_EDITABLE_HEADERS) + [""]
189     @text = header + [""] + @body
190     @text += sig_lines unless $config[:edit_signature]
191     
192     @attachment_lines_offset = 0
193
194     unless @attachments.empty?
195       @text += [""]
196       @attachment_lines_offset = @text.length
197       @text += (0 ... @attachments.size).map { |i| [[:attachment_color, "+ Attachment: #{@attachment_names[i]} (#{@attachments[i].body.size.to_human_size})"]] }
198     end
199   end
200
201   def parse_file fn
202     File.open(fn) do |f|
203       header = MBox::read_header f
204       body = f.readlines
205
206       header.delete_if { |k, v| NON_EDITABLE_HEADERS.member? k }
207       header.each { |k, v| header[k] = parse_header k, v }
208
209       [header, body]
210     end
211   end
212
213   def parse_header k, v
214     if MULTI_HEADERS.include?(k)
215       v.split_on_commas.map do |name|
216         (p = ContactManager.contact_for(name)) && p.full_address || name
217       end
218     else
219       v
220     end
221   end
222
223   def format_headers header
224     header_lines = []
225     headers = (FORCE_HEADERS + (header.keys - FORCE_HEADERS)).map do |h|
226       lines = make_lines "#{h}:", header[h]
227       lines.length.times { header_lines << h }
228       lines
229     end.flatten.compact
230     [headers, header_lines]
231   end
232
233   def make_lines header, things
234     case things
235     when nil, []
236       [header + " "]
237     when String
238       [header + " " + things]
239     else
240       if things.empty?
241         [header]
242       else
243         things.map_with_index do |name, i|
244           raise "an array: #{name.inspect} (things #{things.inspect})" if Array === name
245           if i == 0
246             header + " " + name
247           else
248             (" " * (header.length + 1)) + name
249           end + (i == things.length - 1 ? "" : ",")
250         end
251       end
252     end
253   end
254
255   def send_message
256     return false if !edited? && !BufferManager.ask_yes_or_no("Message unedited. Really send?")
257     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
258     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
259
260     date = Time.now
261     from_email = 
262       if @header["From"] =~ /<?(\S+@(\S+?))>?$/
263         $1
264       else
265         AccountManager.default_account.email
266       end
267
268     acct = AccountManager.account_for(from_email) || AccountManager.default_account
269     BufferManager.flash "Sending..."
270
271     begin
272       IO.popen(acct.sendmail, "w") { |p| write_full_message_to p, date, false }
273       raise SendmailCommandFailed, "Couldn't execute #{acct.sendmail}" unless $? == 0
274       SentManager.write_sent_message(date, from_email) { |f| write_full_message_to f, date, true }
275       BufferManager.kill_buffer buffer
276       BufferManager.flash "Message sent!"
277       true
278     rescue SystemCallError, SendmailCommandFailed => e
279       Redwood::log "Problem sending mail: #{e.message}"
280       BufferManager.flash "Problem sending mail: #{e.message}"
281       false
282     end
283   end
284
285   def save_as_draft
286     DraftManager.write_draft { |f| write_message f, false }
287     BufferManager.kill_buffer buffer
288     BufferManager.flash "Saved for later editing."
289   end
290
291   def write_full_message_to f, date=Time.now, escape=false
292     m = RMail::Message.new
293     @header.each do |k, v|
294       next if v.nil? || v.empty?
295       m.header[k] = 
296         case v
297         when String
298           v
299         when Array
300           v.join ", "
301         end
302     end
303
304     m.header["Date"] = date.rfc2822
305     m.header["Message-Id"] = @message_id
306     m.header["User-Agent"] = "Sup/#{Redwood::VERSION}"
307
308     if @attachments.empty?
309       m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
310       m.body = @body.join
311       m.body = sanitize_body m.body if escape
312       m.body += sig_lines.join("\n") unless $config[:edit_signature]
313     else
314       body_m = RMail::Message.new
315       body_m.body = @body.join
316       body_m.body = sanitize_body body_m.body if escape
317       body_m.body += sig_lines.join("\n") unless $config[:edit_signature]
318       body_m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
319       body_m.header["Content-Disposition"] = "inline"
320       
321       m.add_part body_m
322       @attachments.each { |a| m.add_part a }
323     end
324     f.puts m.to_s
325   end
326
327   ## TODO: remove this. redundant with write_full_message_to.
328   ##
329   ## this is going to change soon: draft messages (currently written
330   ## with full=false) will be output as yaml.
331   def write_message f, full=true, date=Time.now
332     raise ArgumentError, "no pre-defined date: header allowed" if @header["Date"]
333     f.puts format_headers(@header).first
334     f.puts <<EOS
335 Date: #{date.rfc2822}
336 Message-Id: #{@message_id}
337 EOS
338     if full
339       f.puts <<EOS
340 Mime-Version: 1.0
341 Content-Type: text/plain; charset=us-ascii
342 Content-Disposition: inline
343 User-Agent: Redwood/#{Redwood::VERSION}
344 EOS
345     end
346
347     f.puts
348     f.puts sanitize_body(@body.join)
349     f.puts sig_lines if full unless $config[:edit_signature]
350   end  
351
352 protected
353
354   def edit_field field
355     case field
356     when "Subject"
357       text = BufferManager.ask :subject, "Subject: ", @header[field]
358        if text
359          @header[field] = parse_header field, text
360          update
361          field
362        end
363     else
364       default =
365         case field
366         when *MULTI_HEADERS
367           @header[field].join(", ")
368         else
369           @header[field]
370         end
371
372       contacts = BufferManager.ask_for_contacts :people, "#{field}: ", default
373       if contacts
374         text = contacts.map { |s| s.longname }.join(", ")
375         @header[field] = parse_header field, text
376         update
377         field
378       end
379     end
380   end
381
382 private
383
384   def sanitize_body body
385     body.gsub(/^From /, ">From ")
386   end
387
388   def mentions_attachments?
389     @body.any? { |l| l =~ /^[^>]/ && l =~ /\battach(ment|ed|ing|)\b/i }
390   end
391
392   def top_posting?
393     @body.join =~ /(\S+)\s*Excerpts from.*\n(>.*\n)+\s*\Z/
394   end
395
396   def sig_lines
397     p = PersonManager.person_for(@header["From"])
398     from_email = p && p.email
399
400     ## first run the hook
401     hook_sig = HookManager.run "signature", :header => @header, :from_email => from_email
402     return ["", "-- "] + hook_sig.split("\n") if hook_sig
403
404     ## no hook, do default signature generation based on config.yaml
405     return [] unless from_email
406     sigfn = (AccountManager.account_for(from_email) || 
407              AccountManager.default_account).signature
408
409     if sigfn && File.exists?(sigfn)
410       ["", "-- "] + File.readlines(sigfn).map { |l| l.chomp }
411     else
412       []
413     end
414   end
415 end
416
417 end