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