]> git.cworth.org Git - sup/blob - lib/sup/modes/edit-message-mode.rb
attachment tweaks
[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 EditMessageMode < LineCursorMode
9   FORCE_HEADERS = %w(From To Cc Bcc Subject)
10   MULTI_HEADERS = %w(To Cc Bcc)
11   NON_EDITABLE_HEADERS = %w(Message-Id Date)
12
13   attr_reader :status
14   attr_accessor :body, :header
15   bool_reader :edited
16
17   register_keymap do |k|
18     k.add :send_message, "Send message", 'y'
19     k.add :edit, "Edit message", 'e', :enter
20     k.add :save_as_draft, "Save as draft", 'P'
21     k.add :attach_file, "Attach a file", 'a'
22     k.add :delete_attachment, "Delete an attachment", 'd'
23   end
24
25   def initialize opts={}
26     @header = opts.delete(:header) || {} 
27     @body = opts.delete(:body) || []
28     @body += sig_lines if $config[:edit_signature]
29     @attachments = []
30     @attachment_lines = {}
31     @message_id = "<#{Time.now.to_i}-sup-#{rand 10000}@#{Socket.gethostname}>"
32
33     @edited = false
34     @message_id = "<#{Time.now.to_i}-sup-#{rand 10000}@#{Socket.gethostname}>"
35     super opts
36     regen_text
37   end
38
39   def lines; @text.length end
40   def [] i; @text[i] end
41
42   ## a hook
43   def handle_new_text header, body; end
44
45   def edit
46     @file = Tempfile.new "sup.#{self.class.name.gsub(/.*::/, '').camel_to_hyphy}"
47     @file.puts header_lines(@header - NON_EDITABLE_HEADERS)
48     @file.puts
49     @file.puts @body
50     @file.close
51
52     editor = $config[:editor] || ENV['EDITOR'] || "/usr/bin/vi"
53
54     mtime = File.mtime @file.path
55     BufferManager.shell_out "#{editor} #{@file.path}"
56     @edited = true if File.mtime(@file.path) > mtime
57
58     header, @body = parse_file @file.path
59     @header = header - NON_EDITABLE_HEADERS
60     handle_new_text @header, @body
61     update
62   end
63
64   def killable?
65     !edited? || BufferManager.ask_yes_or_no("Discard message?")
66   end
67
68   def attach_file
69     fn = BufferManager.ask_for_filenames :attachment, "File name (enter for browser): "
70     fn.each { |f| @attachments << Pathname.new(f) }
71     update
72   end
73
74   def delete_attachment
75     i = curpos - @attachment_lines_offset
76     if i >= 0 && i < @attachments.size && BufferManager.ask_yes_or_no("Delete attachment #{@attachments[i]}?")
77       @attachments.delete_at i
78       update
79     end
80   end
81
82 protected
83
84   def update
85     regen_text
86     buffer.mark_dirty if buffer
87   end
88
89   def regen_text
90     top = header_lines(@header - NON_EDITABLE_HEADERS) + [""]
91     @text = top + @body
92     @text += sig_lines unless $config[:edit_signature]
93
94     unless @attachments.empty?
95       @text += [""]
96       @attachment_lines_offset = @text.length
97       @text += @attachments.map { |f| [[:attachment_color, "+ Attachment: #{f} (#{f.human_size})"]] }
98     end
99   end
100
101   def parse_file fn
102     File.open(fn) do |f|
103       header = MBox::read_header f
104       body = f.readlines
105
106       header.delete_if { |k, v| NON_EDITABLE_HEADERS.member? k }
107       header.each do |k, v|
108         next unless MULTI_HEADERS.include?(k) && !v.empty?
109         header[k] = v.split_on_commas.map do |name|
110           (p = ContactManager.person_with(name)) && p.full_address || name
111         end
112       end
113
114       [header, body]
115     end
116   end
117
118   def header_lines header
119     force_headers = FORCE_HEADERS.map { |h| make_lines "#{h}:", header[h] }
120     other_headers = (header.keys - FORCE_HEADERS).map do |h|
121       make_lines "#{h}:", header[h]
122     end
123
124     (force_headers + other_headers).flatten.compact
125   end
126
127   def make_lines header, things
128     case things
129     when nil, []
130       [header + " "]
131     when String
132       [header + " " + things]
133     else
134       if things.empty?
135         [header]
136       else
137         things.map_with_index do |name, i|
138           raise "an array: #{name.inspect} (things #{things.inspect})" if Array === name
139           if i == 0
140             header + " " + name
141           else
142             (" " * (header.length + 1)) + name
143           end + (i == things.length - 1 ? "" : ",")
144         end
145       end
146     end
147   end
148
149   def send_message
150     return unless edited? || BufferManager.ask_yes_or_no("Message unedited. Really send?")
151
152     date = Time.now
153     from_email = 
154       if @header["From"] =~ /<?(\S+@(\S+?))>?$/
155         $1
156       else
157         AccountManager.default_account.email
158       end
159
160     acct = AccountManager.account_for(from_email) || AccountManager.default_account
161     BufferManager.flash "Sending..."
162
163     begin
164       IO.popen(acct.sendmail, "w") { |p| write_full_message_to p }
165     rescue SystemCallError
166     end
167     if $? == 0
168       SentManager.write_sent_message(date, from_email) { |f| write_message f, true, date }
169       BufferManager.kill_buffer buffer
170       BufferManager.flash "Message sent!"
171     else
172       Redwood::log "Non-zero return value in running sendmail command for #{acct.longname}: #{acct.sendmail.inspect}"
173       BufferManager.flash "Problem sending mail. See log for details."
174     end
175   end
176
177   def save_as_draft
178     DraftManager.write_draft { |f| write_message f, false }
179     BufferManager.kill_buffer buffer
180     BufferManager.flash "Saved for later editing."
181   end
182
183   def write_full_message_to f
184     m = RMail::Message.new
185     @header.each { |k, v| m.header[k] = v.to_s unless v.to_s.empty? }
186     m.header["Date"] = Time.now.rfc2822
187     m.header["Message-Id"] = @message_id
188     m.header["User-Agent"] = "Sup/#{Redwood::VERSION}"
189     if @attachments.empty?
190       m.header["Content-Disposition"] = "inline"
191       m.header["Content-Type"] = "text/plain; charset=#{$encoding}"
192       m.body = @body.join "\n"
193       m.body += sig_lines.join("\n") unless $config[:edit_signature]
194     else
195       body_m = RMail::Message.new
196       body_m.body = @body.join "\n"
197       body_m.body += sig_lines.join("\n") unless $config[:edit_signature]
198       
199       m.add_part body_m
200       @attachments.each { |fn| m.add_attachment fn.to_s }
201     end
202     f.puts m.to_s
203   end
204
205   ## this is going to change soon: draft messages (currently written
206   ## with full=false) will be output as yaml.
207   def write_message f, full=true, date=Time.now
208     raise ArgumentError, "no pre-defined date: header allowed" if @header["Date"]
209     f.puts header_lines(@header)
210     f.puts <<EOS
211 Date: #{date.rfc2822}
212 Message-Id: #{@message_id}
213 EOS
214     if full
215       f.puts <<EOS
216 Mime-Version: 1.0
217 Content-Type: text/plain; charset=us-ascii
218 Content-Disposition: inline
219 User-Agent: Redwood/#{Redwood::VERSION}
220 EOS
221     end
222
223     f.puts
224     f.puts @body.map { |l| l =~ /^From / ? ">#{l}" : l }
225     f.puts sig_lines if full unless $config[:edit_signature]
226   end  
227
228 private
229
230   def sig_lines
231     p = PersonManager.person_for @header["From"]
232     sigfn = (AccountManager.account_for(p.email) || 
233              AccountManager.default_account).signature
234
235     if sigfn && File.exists?(sigfn)
236       ["", "-- "] + File.readlines(sigfn).map { |l| l.chomp }
237     else
238       []
239     end
240   end
241 end
242
243 end