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