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