-
Notifications
You must be signed in to change notification settings - Fork 0
/
campingatmailbox.rb
1770 lines (1624 loc) · 45.4 KB
/
campingatmailbox.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/ruby
# encoding: utf-8
$0 = "campingatthemailbox"
Dir.chdir(File.dirname(__FILE__))
$LOAD_PATH.unshift 'lib'
require 'camping'
require 'camping/session'
require 'yaml'
require 'markaby'
require 'net/imap'
require 'net/imap2'
require 'net/smtp'
require 'net/smtp_tls'
require 'net/ldap'
require 'stringio'
require 'nokogiri'
require 'yaml'
require 'rack/sendfile'
require 'securerandom'
$config = YAML.load(File.read('mailbox.conf'))
$residentsession = {} if !$residentsession
$connections = Hash.new if !$connections
class Net::IMAP
def idle
cmd = "IDLE"
synchronize do
tag = generate_tag
put_string(tag + " " + cmd)
put_string(CRLF)
end
end
def done
cmd = "DONE"
synchronize do
put_string(cmd)
put_string(CRLF)
end
end
end
class String
def htmlsafe
gsub(/&/, '&').gsub(/>/, '>').gsub(/</, '<')
end
end
class ReconnectingIMAP
class ReconnectNeeded < Exception
end
def authenticated?
@authenticated
end
def secured?
@secured
end
def initialize(*args)
@initargs = args
@connection = Net::IMAP.new(*args)
end
def login(*args)
@loginargs = args
@loginmethod = :authenticate
r = method_missing(:login, *args)
@authenticated = true
r
end
def select(*args)
@selectargs = args
method_missing(:select, *args)
end
def authenticate(*args)
@loginargs = args
@loginmethod = :authenticate
r = method_missing(:authenticate, *args)
@authenticated = true
r
end
def starttls
@connection.starttls
@secured = true
end
def reconnect
$stderr.puts "Reconnecting"
begin
@connection.disconnect
rescue
end
initialize(*@initargs)
starttls
send(@loginmethod, *@loginargs) if @authenticated
select(*@selectargs) if @selectargs
end
def method_missing(*args, &block)
tries = 0
begin
if !@connection
raise ReconnectNeeded
end
@connection.send(*args, &block)
rescue IOError, ReconnectNeeded
if tries <= 2
tries += 1
reconnect
retry
else
$!.message << " (tried #{tries}) more times)"
raise
end
end
end
end
class Net::IMAP::Address
def to_s
if name
"#{name} <#{mailbox}@#{host}>"
else
"#{mailbox}@#{host}"
end
end
def self.parse address
return nil unless address
if /(.*) <(.*)@(.*)>/ === address
self.new $1, nil, $2, $3
elsif /(.*)@(.*) \((.*)\)/ === address
self.new $3, nil, $1, $2
else
parts = address.split('@')
self.new nil, nil, parts[0], parts[1]
end
end
def email
"#{mailbox}@#{host}"
end
end
Camping.goes :CampingAtMailbox
module CampingAtMailbox
use Rack::ShowExceptions
set :secret, $config['secret']
include Camping::Session
Flagnames = { Seen: 'read', Answered: 'replied to' }
Filetypes = { js: 'text/javascript', css: 'text/css' }
class UserError < Exception
end
module Helpers
def imap
if !residentsession[:imap]
if(@state['imaphost'])
residentsession[:imap] = ReconnectingIMAP.new(@state['imaphost'], ($config['imapport'] || 143).to_i, false)
residentsession[:imap].starttls
residentsession[:imap].authenticate('LOGIN', @state['username'], @state['password'])
else
return false
end
end
residentsession[:imap]
end
def from
Net::IMAP::Address.parse(@state['from'])
end
def ldap
residentsession[:ldap]
end
def ldap_base
$config['ldapbase'].gsub('%{domain}', @state['domain'].split('.').map { |e| "dc=#{e}" }.join(','))
end
def composing_messages(k)
if !residentsession[:composing_messages]
residentsession[:composing_messages] = Hash.new
end
if residentsession[:composing_messages][k]
residentsession[:composing_messages][k]
else
residentsession[:composing_messages][k] = Models::Message.new
end
end
def finish_message(k)
residentsession[:composing_messages][k] = nil
end
def setup_pager
if @input.page.to_i > 0
@page = @input.page.to_i
@start = (@page - 1) * 25
@fin = if @page * 25 > @total then @total else @page * 25 end
else
@page = 1
@start = 0
@fin = if @total > 25
25
else
@total
end
end
end
def decode_header(h)
value = h
h.gsub(/=\?([^[:space:]]*?)\?([^[:space:]]*?)\?([^[:space:]]*?)\?=/) do |m|
charset = $1
enc = $2
value = $3
if enc.downcase == 'q'
value = value.unpack('M').first
elsif enc.downcase == 'b'
value = value.unpack('m').first
else
value = h.force_encoding('ASCII')
end
begin
value = value.force_encoding(charset.downcase).encode('utf-8')
rescue ArgumentError
charset = 'utf-8'
retry
rescue Encoding::InvalidByteSequenceError, Encoding::UndefinedConversionError
if charset.downcase != 'iso8859-1'
charset = 'iso8859-1'
retry
else
return value = '?' * value.length
end
end
end
begin
value = value.encode('UTF-8')
rescue Encoding::CompatibilityError, Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError
begin
value = value.force_encoding('ISO-8859-1').encode('UTF-8')
rescue Encoding::CompatibilityError, Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError
value = '?' * value.length
end
end
value
end
def new_messageid
Time.now.to_i.to_s + '-' + Process.pid.to_s
end
def serve2(file)
extension = file.split('.').last
@headers['Content-Type'] = Filetypes[extension] || 'text/plain'
@headers['Last-Modified'] = File.stat(file).mtime.rfc2822
@body = File.read(file)
end
def fetch_body_quoted
part = if @structure.respond_to? :parts and @structure.parts
@structure.parts.sort_by { |part|
[
if part.media_type == 'TEXT' then 0 else 1 end,
case part.media_type
when 'PLAIN', 0
when 'HTML', 1
else 2
end
]
}.first
else
@structure
end
@cmessage.body = WordWrapper.wrap(decode(part)).gsub(/^/, '> ')
end
def fetch_addresses(pattern = nil)
@addresses = []
if pattern
st = ('SELECT name, address FROM addresses WHERE user_id = ? AND (name like ? OR address like ?) ORDER BY name, address')
rh = $db.execute(st, from.email)
rh = $db.execute(st, from.email, "#{pattern}%", "#{pattern}%")
else
st = ('SELECT name, address FROM addresses WHERE user_id = ? ORDER BY name, address')
rh = $db.execute(st, from.email)
end
rh.fetch do |name,address|
@addresses << [name,address]
end
if ldap and pattern and pattern.length > 2
name_attr = $config['ldapnameattr'] || 'cn'
mail_attr = $config['ldapmailattr'] || 'mail'
ldap_search = ($config['ldapsearch'] || [name_attr]).map do |a|
"(#{a}=#{@pattern}*)"
end.join('|')
ldap.search(:base => ldap_base, :filter => ldap_search).each do |ent|
@addresses << [ent[name_attr][0], ent[mail_attr][0]]
end
@addresses.sort! { |a,b| a[0] <=> b[0] }
end
end
def select_mailbox(mb)
imap.select(mb)
if residentsession[:selectedmbox] != mb
residentsession[:selectedmbox] = mb
residentsession.delete :uidlist
end
end
def envelope
@message.attr['ENVELOPE']
end
def residentsession
@state[:sid] ||= SecureRandom.alphanumeric
$residentsession[@state[:sid]] ||= {}
end
def imap_response_handler(resp)
case resp
when Net::IMAP::UntaggedResponse
case resp.name
# FIXME: update the uidlist, rather than invalidating it. Easier
# said than done, considering that the server knows the order
# and we don't based on resp.
when 'EXISTS'
residentsession.delete :uidlist
when 'EXPUNGE'
residentsession.delete :uidlist
end
end
end
def decode(structure)
# FIXME: handle multipart messages way better than this.
if !structure.respond_to? :encoding
return @parts[structure.part_id]
end
case structure.encoding
when 'BASE64'
@parts[structure.part_id].unpack('m*').first
when 'QUOTED-PRINTABLE'
@parts[structure.part_id].gsub(/\r\n/, "\n").unpack('M*').first
else @parts[structure.part_id]
end
end
def get_mailbox_list
@mailboxes = imap.lsub('', '*')
if !@mailboxes
@error = 'You have no mailboxes subscribed, showing everything'
@mailboxes = imap.list('', '*')
end
@mailboxes = @mailboxes.sort_by { |mb| [if mb.name.split(mb.delim).first == 'INBOX' then 1 else 2 end, *mb.name.downcase.split(mb.delim)] }
end
def fetch_structure
@message = imap.uid_fetch(@uid, ['ENVELOPE', 'BODYSTRUCTURE'])
if !@message
raise UserError, 'Message already deleted'
else
@message = @message.first
end
@structure = @message.attr['BODYSTRUCTURE']
@parts = Hash.new do |h,k|
h[k] = imap.uid_fetch(@uid, "BODY[#{k}]")[0].attr["BODY[#{k}]"]
end
@structureindex = {}
index_structure(@structure)
end
def index_structure(structure)
@structureindex[structure.part_id] = structure
case structure
when Net::IMAP::BodyTypeMultipart
structure.parts.each do |part|
index_structure part
end
when Net::IMAP::BodyTypeMessage
case structure.subtype
when 'DISPOSITION-NOTIFICATION'
when 'DELIVERY-STATUS'
else
index_structure structure.body
end
end
end
def output_message_to(out)
out.puts "From: #{from}"
out.puts "To: #{@cmessage.to}"
out.puts "CC: #{@cmessage.cc}"
out.puts "Subject: #{@cmessage.subject}"
out.puts "Date: #{Time.now.rfc822}"
if @cmessage.attachments.size == 0
out.puts "Content-Type: text/plain; charset=UTF-8"
out.puts ""
out.puts "#{@cmessage.body}"
else
boundary = "=_#{Time.now.to_i.to_s}"
out.puts 'Content-Type: multipart/mixed; boundary="'+boundary+'"'
out.puts ''
out.puts %{This is a MIME-formatted email message.}
out.puts ''
out.puts "--#{boundary}"
out.puts "Content-type: text/plain; charset=UTF-8"
out.puts "Content-transfer-encoding: quoted-printable"
out.puts ""
out.puts [@cmessage.body].pack('M')
out.puts ""
@cmessage.attachments.each do |att|
out.puts "--#{boundary}"
out.puts "Content-Type: #{att['type']}"
out.puts "Content-Disposition: attachment; filename=\"#{att['filename']}\""
att['tempfile'].seek(0)
if /^text/ === att['type']
out.puts "Content-transfer-encoding: quoted-printable"
out.puts ""
att['tempfile'].each_line do |l|
out.puts [l].pack("M")
end
out.puts ""
else
out.puts "Content-transfer-encoding: base64"
out.puts ""
until att['tempfile'].eof?
out << [att['tempfile'].read(4500)].pack("m").gsub("\n", "\r\n")
end
out.puts ""
end
end
out.puts "--#{boundary}--"
end
end
def Pager(controller, current, total, n, *args)
pages = (total) / n + ((total) % n == 0 ? 0 : 1)
prior = current - 1
nxt = current + 1
p "Page #{current} of #{pages}"
p.controls do
if prior > 0
a("Previous #{n}", :href => R(controller, *args) << "?page=#{prior}")
end
text ' '
if nxt <= pages
a("Next #{n}", :href => R(controller, *args) << "?page=#{nxt}")
end
end
return
p do
(1..pages).map do |page|
if page == current
text page
else
a(page, :href => R(controller, *args) << "?page=#{page}")
end
end
end if pages > 1
end
end
module Controllers
class Index < R '/'
def get
if imap
if imap.disconnected?
begin
imap.reconnect
redirect Mailboxes
rescue
redirect Login
end
else
redirect Mailboxes
end
else
redirect Login
end
end
end
# You see a locked door.
#
class Login < R '/login'
# The key opens the door. You slip inside.
#
# See Mailboxes
def post
if /@/ === input.username
@state['domain'] = input.username.split('@').last
@state['from'] = input.username
else
@state['domain'] = @env['HTTP_HOST'].split(':').first.gsub(/^(web)?mail\./, '')
@state['from'] = input.username + '@' + @state['domain']
end
begin
@state['imaphost'] = imaphost = ($config['imaphost'] || input.imaphost).gsub('%{domain}', @state['domain'])
if !imap_connection = $connections[[imaphost, input.username, input.password]]
imap_connection = $connections[[imaphost, input.username, input.password]] = ReconnectingIMAP.new(
imaphost,
($config['imapport'] || 143).to_i,
($config['imapssl'] || false)
)
end
rescue SocketError => e
if e.message =~ /getaddrinfo/
@error = "Mail server not found at #{imaphost}"
return render(:error)
else
raise
end
end
if !imap_connection.secured?
imap_connection.starttls
end
if !imap_connection.authenticated?
begin
if imap_connection.capability.include? 'AUTH=LOGIN'
imap_connection.authenticate('LOGIN', input.username, input.password)
elsif imap_connection.capability.include? 'AUTH=PLAIN'
imap_connection.authenticate('PLAIN', input.username, input.password)
else
imap_connection.login(input.username, input.password)
end
imap_connection.add_response_handler { |r| imap_response_handler(r) }
begin
imap_connection.subscribe('INBOX')
imap_connection.create("Drafts")
imap_connection.subscribe("Drafts")
imap_connection.create("Sent")
imap_connection.subscribe("Sent")
rescue Net::IMAP::NoResponseError => e
end
rescue Net::IMAP::NoResponseError => e
@error = 'wrong user name or password'
end
end
residentsession[:imap] = imap_connection
residentsession[:pinger] = Thread.new do
while residentsession[:imap] and !imap.disconnected?
imap.noop
sleep 60
end
end
residentsession[:usesort] = if imap.capability.include? "SORT" then true else false end
if $config['ldaphost']
residentsession[:ldap] = Net::LDAP.new(
:host => $config['ldaphost'].gsub('%{domain}', @state['domain']),
:port => $config['ldapport'] || 389
)
ldap_filter = "(#{$config['ldaprdnattr'] || 'dn'}=#{input.username})"
mail_attr = $config['ldapmailattr'] || 'mail'
name_attr = $config['ldapnameattr'] || 'cn'
ldap.search(:base => ldap_base, :filter => ldap_filter) do |ent|
@state['from'] = if ent[name_attr]
"#{ent[name_attr][0]} <#{ent[mail_attr][0]}>"
else
"#{ent[mail_attr][0]}"
end
end
end
@state['username'] = input.username
@state['password'] = input.password
t = imap_connection.dup
t.send(:instance_variable_set, :@connection, nil)
residentsession[:imap] = t
if @error
@error = "There was an error: " + @error
render :login
else
redirect Mailboxes
end
end
# You slip your key in the lock.
#
def get
render :login
end
end
# You see a room with row upon row of shiny brass doors.
# Which door do you open?
#
class Mailboxes < R '/mailboxes'
# You open a Mailbox
#
def get
return redirect R(Login) unless imap
get_mailbox_list
render :mailboxes
end
end
# Inside the box seems to be a room. You climb through the tiny brass
# door, surprised at how roomy the inside of the box is. There seems
# to be a pile of packages to the left, and a simple writing desk on the
# right.
#
# Off in the distance, a faint 'whoopwhoop' noise can be heard.
#
class Mailbox < R '/mailboxes/(.+)/'
# Suddenly, there's a whizthunk! and you see an arrow embed itself
# in the wall next to your head. There seems to be a Message attached.
#
def get(mb)
return redirect R(Login) unless imap
@mailbox = mb
@class = Mailbox
select_mailbox(mb)
if !residentsession[:uidlist]
if residentsession[:usesort]
residentsession[:uidlist] = imap.uid_sort(['REVERSE', 'ARRIVAL'], 'UNDELETED', 'UTF-8')
else
residentsession[:uidlist] = imap.uid_search('UNDELETED')
end
end
@total = residentsession[:uidlist].length
setup_pager
if @total > 0
# UGLY
@messageset = residentsession[:uidlist][@start..@fin]
@messages = imap.uid_fetch(@messageset, ['FLAGS', 'ENVELOPE', 'UID'])
@messages = @messages.sort_by { |e| @messageset.index(e.attr['UID']) }
end
render :mailbox
end
def post(mailbox)
return redirect R(Login) unless imap
if input.message
if input.action =~ /Delete/
if Array === input.message
@messages = input.message
else
@messages = [input.message]
end
end
select_mailbox(mailbox)
@input = imap.uid_store(@messages.map { |e| e.to_i }, '+FLAGS', [:Deleted])
if residentsession[:uidlist]
@messages.each do |e|
residentsession[:uidlist].delete(e.to_i)
end
end
end
redirect R(Mailbox, mailbox)
end
end
# A snappily dressed mailman stands over a postal scale in the front
# lobby.
#
class Style < R '/(.*).css'
def get(file)
serve2 'public/'+file+'.css'
end
end
class Scripts < R '/(.*).js'
def get(file)
serve2 'public/'+file+'.js'
end
end
class Logout < R '/logout'
def get
begin
imap.disconnect
rescue Exception => e
end
residentsession
@state.clear
residentsession.clear
redirect R(Login)
end
end
# There is a scroll tacked to the wall with an arrow. You take it
# down and read it.
#
class Message < R '/mailboxes/(.*)/m(\d+)'
def get(mailbox, uid)
return redirect R(Login) unless imap
@mailbox = mailbox
@uid = uid.to_i
select_mailbox(mailbox)
fetch_structure
render :message
end
end
# An inner piece of parchment flutters to the ground as you unroll
# the scroll. You pick it up and read it.
#
class MessagePart < R '/mailboxes/(.*)/m(\d+)/part(.*)'
def get(mailbox, uid, part)
return redirect R(Login) unless imap
@mailbox = mailbox
@uid = uid.to_i
select_mailbox(mailbox)
fetch_structure
@part = @structureindex[part]
case @part
when Net::IMAP::BodyTypeMultipart
render :messagepart
when Net::IMAP::BodyTypeMessage
render :messagepart
when nil
@status = 404
@pagetitle = 'Not Found'
render :messagepartnotfound
else
@headers['Content-Type'] = @part.media_type.downcase << '/' << @part.subtype.downcase
@body = decode(@part)
end
end
end
# There seems to be another object tied to the arrow.
#
class Attachment < R '/mailboxes/(.*)/m(\d+)/attachment/(.*)'
def get(mailbox, uid, part)
return redirect R(Login) unless imap
@mailbox = mailbox
@uid = uid.to_i
@part = part
select_mailbox(mailbox)
fetch_structure
@part = @structureindex[part]
@headers['Content-Type'] = @part.media_type.downcase << '/' << @part.subtype.downcase
@headers['Content-Disposition'] = "attachment; filename=\"#{@part.disposition.param['FILENAME']}\""
@body = decode(@part)
end
end
# You examine the scroll and arrow for signs of its origin.
#
class Header < R '/mailboxes/(.*)/m(\d+)/headers'
def get(mailbox, uid)
return redirect R(Login) unless imap
@mailbox = mailbox
@uid = uid.to_i
select_mailbox(mailbox)
@header = imap.uid_fetch(@uid, ['RFC822.HEADER'])[0].attr['RFC822.HEADER']
render :header
end
end
# There is a large, red button here.
#
class DeleteMessage < R '/mailboxes/(.*)/m(\d+)/delete'
# You press it to see what it does.
#
def get(mailbox, uid)
@mailbox = mailbox
@uid = uid.to_i
render :deleteq
end
# There is a loud klaxon and the scroll you were holding in your
# hand disappears
#
def post(mailbox, uid)
@mailbox = mailbox
@uid = uid.to_i
if input.deletemessage == uid
imap.uid_store(@uid, '+FLAGS', [:Deleted])
residentsession[:uidlist].delete(@uid) if residentsession[:uidlist]
redirect Mailbox, mailbox
else
render :deleteq
end
end
end
# You realize that there's a better place to keep the scroll than
# wrapped around an arrow on the outside of the building. You move
# it to a safer location.
#
class MoveMessage < R '/mailboxes/(.*)/m(\d+)/move'
def get(mailbox, uid)
@mailbox = mailbox
@uid = uid.to_i
get_mailbox_list
render :movemessage
end
def post(mailbox, uid)
@mailbox = mailbox
@uid = uid.to_i
imap.uid_copy(@uid, input.folder)
imap.uid_store(@uid, '+FLAGS', [:Deleted])
residentsession[:uidlist].delete(@uid) if residentsession[:uidlist]
redirect Mailbox, mailbox
end
end
# You'll have to write their mother a note.
#
class Compose < R('/compose/(.*)')
def get(messageid)
if messageid.empty?
messageid = new_messageid
end
@messageid = messageid
@cmessage = composing_messages(messageid)
if ([email protected] or @cmessage.to.empty?) and @input.to
@cmessage.to = @input.to
end
render :compose
end
def post(messageid)
return redirect R(Login) unless imap
select_mailbox("Drafts")
@messageid = new_messageid
@uid = input.uid.to_i
fetch_structure
@cmessage = composing_messages(@messageid)
part = if @structure.respond_to? :parts and @structure.parts
@structure.parts.sort_by { |part|
[
if part.media_type == 'TEXT' then 0 else 1 end,
case part.media_type
when 'PLAIN', 0
when 'HTML', 1
else 2
end
]
}.first
else
@structure
end
@cmessage.body = WordWrapper.wrap(imap.uid_fetch(@uid, "BODY[#{part.part_id}]").first.attr["BODY[#{part.part_id}]"])
@cmessage.subject = envelope.subject if envelope.subject
@cmessage.to = envelope.to.map { |e| e.to_s }.join(', ') if envelope.to
@cmessage.cc = envelope.cc.map { |e| e.to_s }.join(', ') if envelope.cc
@cmessage.bcc = envelope.bcc.map { |e| e.to_s }.join(', ') if envelope.bcc
# FIXME: handle attachments
redirect R(Compose, @messageid)
end
end
class Search < R '/search/([^/]*)'
def post(mailbox)
return redirect R(Login) unless imap
@mailbox = mailbox
select_mailbox(@mailbox)
uids = imap.uid_search(input.search.split(/\s+/).map { |e| ['OR', 'OR', 'BODY', e, 'SUBJECT', e, 'FROM', e] }.inject { |a, e| ['OR', a, e] }.flatten + ['UNDELETED'])
if !uids.empty?
@search_id = new_messageid
(residentsession[:searchresults] ||= Hash.new)[@search_id] = uids
(residentsession[:searchmailboxes] ||= Hash.new)[@search_id] = @mailbox
redirect R(SearchResults, @search_id)
else
render :no_results
end
end
end
class Purge < R '/purge/(.*)'
def get(mailbox)
@mailbox= mailbox
render :purgeconfirm
end
def post(mailbox)
return redirect R(Login) unless imap
select_mailbox(mailbox)
imap.expunge
redirect R(Mailbox, mailbox)
end
end
class SearchResults < R '/search/result/(.*)'
def get(search_id)
@class = SearchResults
@search_id = search_id
@results = residentsession[:searchresults][@search_id]
@mailbox = residentsession[:searchmailboxes][@search_id]
@total = @results.length
setup_pager
@messages = imap.uid_fetch(@results[@start..@fin], ['FLAGS', 'ENVELOPE', 'UID'])
render :mailbox
end
end
class Reply < R '/mailboxes/(.*)/m(\d+)/reply(.*)'
def get(mailbox, uid, mode)
return redirect R(Login) unless imap
@mailbox = mailbox
@uid = uid.to_i
@messageid = new_messageid
@cmessage = composing_messages(@messageid)
select_mailbox(mailbox)
fetch_structure
fetch_body_quoted
recips = if @message.attr['ENVELOPE'].reply_to.empty?
envelope.from
else
envelope.reply_to
end
if mode == 'all'
if envelope.to
recips += envelope.to
end
if envelope.cc
recips += envelope.cc
end
if envelope.bcc
recips += envelope.bcc
end
recips.uniq!
end
@cmessage.to = recips.select { |e| e.email != from.email }.join(', ')
@cmessage.subject = 'Re: ' << decode_header(@message.attr['ENVELOPE'].subject || '')
render :compose
end
end
class Forward < R '/mailboxes/(.*)/m(\d+)/forward'
def get(mailbox, uid)
return redirect R(Login) unless imap
@mailbox = mailbox
@uid = uid.to_i
@messageid = Time.now.to_i.to_s + '-' + Process.pid.to_s
@cmessage = composing_messages(@messageid)
select_mailbox(mailbox)
fetch_structure
fetch_body_quoted
@cmessage.subject = 'Fw: ' << decode_header(@message.attr['ENVELOPE'].subject || '')
render :compose
end
end
class CreateMailbox < R '/newmailbox'
def get
render :createmailbox
end
def post
@mailbox = input.mailbox
begin
imap.create(input.mailbox)
imap.subscribe(input.mailbox)
rescue Net::IMAP::NoResponseError => @error
render :createmailbox
else
redirect R(Mailboxes)
end
end
end
class AttachFile < R('/attach/(.*)')
def get(messageid)
@messageid = messageid
@cmessage = composing_messages(@messageid)
render :attach_files
end
end
class Send < R('/send/(.*)')
def post(messageid)
@messageid = messageid
@cmessage = composing_messages(@messageid)
if input.to
@cmessage.to = input.to
end
if input.cc
@cmessage.cc = input.cc
end