]> git.cworth.org Git - sup/blob - lib/sup/modes/edit-message-mode.rb
3ae0eeb8284f2ac8098f664ac6e4a1662e188f3a
[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     unless @attachments.empty?
132       @text += [""]
133       @attachment_lines_offset = @text.length
134       @text += @attachments.map { |f| [[:attachment_color, "+ Attachment: #{f} (#{f.human_size})"]] }
135     end
136   end
137
138   def parse_file fn
139     File.open(fn) do |f|
140       header = MBox::read_header f
141       body = f.readlines
142
143       header.delete_if { |k, v| NON_EDITABLE_HEADERS.member? k }
144       header.each { |k, v| header[k] = parse_header k, v }
145
146       [header, body]
147     end
148   end
149
150   def parse_header k, v
151     if MULTI_HEADERS.include?(k)
152       v.split_on_commas.map do |name|
153         (p = ContactManager.contact_for(name)) && p.full_address || name
154       end
155     else
156       v
157     end
158   end
159
160   def format_headers header
161     header_lines = []
162     headers = (FORCE_HEADERS + (header.keys - FORCE_HEADERS)).map do |h|
163       lines = make_lines "#{h}:", header[h]
164       lines.length.times { header_lines << h }
165       lines
166     end.flatten.compact
167     [headers, header_lines]
168   end
169
170   def make_lines header, things
171     case things
172     when nil, []
173       [header + " "]
174     when String
175       [header + " " + things]
176     else
177       if things.empty?
178         [header]
179       else
180         things.map_with_index do |name, i|
181           raise "an array: #{name.inspect} (things #{things.inspect})" if Array === name
182           if i == 0
183             header + " " + name
184           else
185             (" " * (header.length + 1)) + name
186           end + (i == things.length - 1 ? "" : ",")
187         end
188       end
189     end
190   end
191
192   def send_message
193     return false if !edited? && !BufferManager.ask_yes_or_no("Message unedited. Really send?")
194     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
195     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
196
197     date = Time.now
198     from_email = 
199       if @header["From"] =~ /<?(\S+@(\S+?))>?$/
200         $1
201       else
202         AccountManager.default_account.email
203       end
204
205     acct = AccountManager.account_for(from_email) || AccountManager.default_account
206     BufferManager.flash "Sending..."
207
208     begin
209       IO.popen(acct.sendmail, "w") { |p| write_full_message_to p, date, false }
210       raise SendmailCommandFailed, "Couldn't execute #{acct.sendmail}" unless $? == 0
211       SentManager.write_sent_message(date, from_email) { |f| write_full_message_to f, date, true }
212       BufferManager.kill_buffer buffer
213       BufferManager.flash "Message sent!"
214       true
215     rescue SystemCallError, SendmailCommandFailed => e
216       Redwood::log "Problem sending mail: #{e.message}"
217       BufferManager.flash "Problem sending mail: #{e.message}"
218       false
219     end
220   end
221
222   def save_as_draft
223     DraftManager.write_draft { |f| write_message f, false }
224     BufferManager.kill_buffer buffer
225     BufferManager.flash "Saved for later editing."
226   end
227
228   def write_full_message_to f, date=Time.now, escape=false
229     m = RMail::Message.new
230     @header.each do |k, v|
231       next if v.nil? || v.empty?
232       m.header[k] = 
233         case v
234         when String
235           v
236         when Array
237           v.join ", "
238         end
239     end
240
241     m.header["Date"] = date.rfc2822
242     m.header["Message-Id"] = @message_id
243     m.header["User-Agent"] = "Sup/#{Redwood::VERSION}"
244
245     if @attachments.empty?
246       m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
247       m.body = @body.join
248       m.body = sanitize_body m.body if escape
249       m.body += sig_lines.join("\n") unless $config[:edit_signature]
250     else
251       body_m = RMail::Message.new
252       body_m.body = @body.join
253       body_m.body = sanitize_body body_m.body if escape
254       body_m.body += sig_lines.join("\n") unless $config[:edit_signature]
255       body_m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
256       body_m.header["Content-Disposition"] = "inline"
257       
258       m.add_part body_m
259       @attachments.each { |fn| m.add_file_attachment fn.to_s }
260     end
261     f.puts m.to_s
262   end
263
264   ## TODO: remove this. redundant with write_full_message_to.
265   ##
266   ## this is going to change soon: draft messages (currently written
267   ## with full=false) will be output as yaml.
268   def write_message f, full=true, date=Time.now
269     raise ArgumentError, "no pre-defined date: header allowed" if @header["Date"]
270     f.puts format_headers(@header).first
271     f.puts <<EOS
272 Date: #{date.rfc2822}
273 Message-Id: #{@message_id}
274 EOS
275     if full
276       f.puts <<EOS
277 Mime-Version: 1.0
278 Content-Type: text/plain; charset=us-ascii
279 Content-Disposition: inline
280 User-Agent: Redwood/#{Redwood::VERSION}
281 EOS
282     end
283
284     f.puts
285     f.puts sanitize_body(@body.join)
286     f.puts sig_lines if full unless $config[:edit_signature]
287   end  
288
289 protected
290
291   def edit_field field
292     case field
293     when "Subject"
294       text = BufferManager.ask :subject, "Subject: ", @header[field]
295        if text
296          @header[field] = parse_header field, text
297          update
298          field
299        end
300     else
301       default =
302         case field
303         when *MULTI_HEADERS
304           @header[field].join(", ")
305         else
306           @header[field]
307         end
308
309       contacts = BufferManager.ask_for_contacts :people, "#{field}: ", default
310       if contacts
311         text = contacts.map { |s| s.longname }.join(", ")
312         @header[field] = parse_header field, text
313         update
314         field
315       end
316     end
317   end
318
319 private
320
321   def sanitize_body body
322     body.gsub(/^From /, ">From ")
323   end
324
325   def mentions_attachments?
326     @body.any? { |l| l =~ /^[^>]/ && l =~ /\battach(ment|ed|ing|)\b/i }
327   end
328
329   def top_posting?
330     @body.join =~ /(\S+)\s*Excerpts from.*\n(>.*\n)+\s*\Z/
331   end
332
333   def sig_lines
334     p = PersonManager.person_for(@header["From"])
335     from_email = p && p.email
336
337     ## first run the hook
338     hook_sig = HookManager.run "signature", :header => @header, :from_email => from_email
339     return ["", "-- "] + hook_sig.split("\n") if hook_sig
340
341     ## no hook, do default signature generation based on config.yaml
342     return [] unless from_email
343     sigfn = (AccountManager.account_for(from_email) || 
344              AccountManager.default_account).signature
345
346     if sigfn && File.exists?(sigfn)
347       ["", "-- "] + File.readlines(sigfn).map { |l| l.chomp }
348     else
349       []
350     end
351   end
352 end
353
354 end