This repository was archived by the owner on Jan 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathimaprowl.rb
More file actions
executable file
·592 lines (532 loc) · 15.9 KB
/
Copy pathimaprowl.rb
File metadata and controls
executable file
·592 lines (532 loc) · 15.9 KB
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
#!/usr/bin/ruby
#
# IMAProwl - Prowl notification for IMAP new mail
# Version: 1.2
#
# Copyright (c) 2009 Takuo Kitame.
#
# You can redistribute it and/or modify it under the same term as Ruby.
#
STDOUT.sync = STDERR.sync = true
$:.unshift File.dirname(__FILE__)
IMAPROWL_VERSION = "1.2.1.2"
if RUBY_VERSION < "1.9.0"
STDERR.puts "IMAProwl #{IMAPROWL_VERSION} requires Ruby >= 1.9.0"
exit
end
$0 = "IMAProwl/#{IMAPROWL_VERSION}"
require 'optparse'
require 'uri'
require 'net/https'
require 'net/imap'
require 'yaml'
require 'logger'
require 'imapidle' unless Net::IMAP.respond_to?("idle")
class IMAProwl
PROWL_API_ADD = "https://prowl.weks.net/publicapi/add"
@@conf = Hash.new
@@logger = nil
@@prowl_conf = nil
attr_reader :enable
attr_reader :loop_thread
def initialize( global, conf )
@@conf = global
_prowl_conf_validate( global['Prowl'] )
@application = conf['Application'] ? conf['Application'] : "IMAProwl"
@user = conf['User']
@pass = conf['Pass']
@host = conf['Host']
@port = conf['Port'] ? conf['Port'] : 993
@mailbox = conf['MailBox'] ? conf['MailBox'] : "INBOX"
# backward compat
@timeout = conf['Timeout'] ? conf['Timeout'] : ( conf['Interval'] ? conf['Interval'] : 20 )
if conf['Interval']
warn = "Warning: 'Interval' is deprecated. You should use 'Timeout' instead."
STDERR.print "#{warn}\n"
warn warn
end
@noop = conf['NOOPInterval'] ? conf['NOOPInterval'] : 30
@subject_length = conf['SubjectLength'] ? conf['SubjectLength'] - 1 : 19
@body_length = conf['BodyLength'] ? conf['BodyLength'] - 1 : 99
@body_length = 1 if @body_length < 0
@subject_length = 1 if @subject_length < 0
@priority = conf['Priority'] ? conf['Priority'] : 0
@notified = []
@enable = conf.has_key?('Enable') ? conf['Enable'] : true
@no_idle = conf.has_key?('NoIDLE') ? conf['NoIDLE'] : false
@format = conf.has_key?('Format') ? conf['Format'] : "%{subject} (%{from})"
end
# start() should run only once
def start
begin
info "Starting."
connect()
if !@no_idle and !@imap.capability.include?( 'IDLE' )
warn "Error: #{@host} does not support IDLE."
warn "Falling back to no IDLE support mode."
@no_idle = true
end
login()
check_unseen( false )
if @no_idle
checker()
else
idler()
end
rescue
error "Error while starting thread. disabling #{@application}"
debug $!.to_s
return false
end
true
end
def restart
info "Restarting..."
connect()
login()
if @no_idle
checker()
else
check_unseen( true )
idler()
end
debug "Restarted"
end
def stop
unless @no_idle
@idle_time = nil
@imap.idle_done
debug "DONE IDLE."
end
end
def status
return if @no_idle
retried = false
debug "Check process status..."
begin
if @imap.disconnected?
@loop_thread.exit if @loop_thread.alive?
error "socket is disconnected. trying to reconnect..."
restart
elsif ! @loop_thread.alive?
error "IDLE thread is dead."
restart
end
if @timeout > 0 && @idle_time && Time.now - @idle_time > 60 * @timeout
info "Timeout exceed. "
stop
end
rescue
@loop_thread.exit if @loop_thread.alive?
error $!.to_s
unless retried
retried = true
retry
end
end
end
private
def post_escape( string )
string.gsub(/([^ a-zA-Z0-9_.-]+)/) do
'%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
end.tr(' ', '+')
end
def mime_decode( input, out_charset = 'utf-8' )
while input.sub!(/(=\?[A-Za-z0-9_-]+\?[BQbq]\?[^\?]+\?=)(?:(?:\r\n)?[\s\t])+(=\?[A-Za-z0-9_-]+\?[BQbq]\?[^\?]+\?=)/, '\1\2')
end
begin
ret = input.sub!( /=\?([A-Za-z0-9_-]+)\?([BQbq])\?([^\?]+)\?=/ ) {
charset = $1
enc = $2.upcase
word = $3
debug "Decode MIME header: Charset: #{charset}, Encode: #{enc}, Word: #{word}"
word = word.unpack( { "B"=>"m*", "Q"=>"M*" }[enc] ).first
# Iconv.conv( out_charset + "//IGNORE", charset, word )
word.encode( out_charset, charset, :undef=>:replace, :invalid=>:replace )
}
return ret ? mime_decode( input ) : input
rescue
# "Error while convert MIME string."
error "Error while converting MIME header: #{input}"
debug "E: #{$!}"
return input
end
end
def _prowl_conf_validate( val )
return if @@prowl_conf
@@prowl_conf = val
unless @@prowl_conf.kind_of?( Hash )
STDERR.print "Configuration Error: Prowl section must be Hash.\n"
exit 1
end
unless @@prowl_conf.has_key?( 'APIKey' )
STDERR.print "Configuration Error: APIKey must be given.\n"
exit 1
end
_init_logger()
end
def _init_logger
if @@conf['LogDir']
logdir = @@conf['LogDir']
Dir.mkdir( logdir ) unless File.exist?( logdir )
filename = File.join( logdir, "imaprowl.log" )
STDOUT.puts "All logs will be written into #{filename}."
@@logger = Logger.new( filename, 'daily' )
@@logger.level = @@conf['Debug'] ? Logger::DEBUG : Logger::INFO
@@logger.datetime_format = "%Y-%m-%dT%H:%M:%S"
else
@@logger = nil
end
end
def _log( severity, str )
if @@logger
@@logger.add( severity, str, @application )
else
format = "[%Y-%m-%dT%H:%M:%S##{Process.pid}] #{@application} - #{str}\n"
if severity == Logger::ERROR
STDERR.print Time.now.strftime( format )
else
print Time.now.strftime( format )
end
end
end
def debug( str )
_log( Logger::DEBUG, "#{Thread.current}:#{str}" )
end
def error( str )
_log( Logger::ERROR, "#{Thread.current}:#{str}" )
end
def warn( str )
_log( Logger::WARN, str)
end
def info( str )
_log( Logger::INFO, str )
end
def login
return true if @logged_in
ret = @imap.login( @user, @pass )
if ret.name != "OK"
error "Failed to login: user: #{@user}@#{@host}."
return false
end
@imap.select( Net::IMAP.encode_utf7( @mailbox ) )
@logged_in = true
return true
end
def connect
@logged_in = false
begin
@imap = Net::IMAP.new( @host, @port, true, nil, false ) # don't verify cert
rescue
error "Error on connect()"
end
end
def disconnected?
return @imap.disconnected?
end
def prowl( params = {} )
uri = URI::parse( PROWL_API_ADD )
if @@prowl_conf['ProxyHost']
http = Net::HTTP::Proxy( @@prowl_conf['ProxyHost'],
@@prowl_conf['ProxyPort'],
@@prowl_conf['ProxyUser'],
@@prowl_conf['ProxyPass']).new( uri.host,
uri.port )
else
http = Net::HTTP.new( uri.host, uri.port )
end
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new( uri.request_uri )
request.content_type = "application/x-www-form-urlencoded"
query = params.map do |key, val| "#{key}=#{post_escape( val.to_s )}" end
return http.request(request, query.join('&'))
end
def get_text_part( struct, pos )
if struct.kind_of?( Net::IMAP::BodyTypeMultipart )
struct.parts.each_index do |i|
pos.push( i+1 )
part, pos = get_text_part( struct.parts[i], pos )
return part, pos if part && part.media_type == "TEXT"
pos.pop
end
end
if struct.media_type == "TEXT"
return struct, pos
end
return nil, pos
end
def check_unseen( will_prowl = false )
debug "Checking UNSEEN mail."
unseen = @imap.search( ['UNSEEN'] )
if unseen.size == 0
@notified = []
debug("No UNSEEN mail.")
return
end
debug("#{unseen.size} UNSEEN mails.")
unseen_set = Array.new
data_set = @imap.fetch( unseen, "(ENVELOPE BODYSTRUCTURE UID)" )
data_set.each do |data|
begin
attr = data.attr
if @notified.include?( attr["UID"] )
debug "SKIP Already notified: UID=#{attr["UID"]}"
unseen_set.push attr["UID"]
next
end
# header process
envelope = attr["ENVELOPE"]
addr = "#{envelope.from.first.mailbox}@#{envelope.from.first.host}"
name = envelope.from.first.name
begin
name = name ? mime_decode( name ) : ""
from = name != "" ? name : addr
rescue
error "Error: Invalid From."
debug $!.to_s
from = "[Invalid From]"
end
begin
subject = envelope.subject ? mime_decode( envelope.subject ) : "Untitled"
if subject.size > @subject_length
subject = subject[0..@subject_length] + "..."
end
rescue
error "Error: Invalid Subject."
debug $!.to_s
subject = "[Invalid Subject]"
end
begin
event = @format % { :subject => subject, :from => from,
:name=>name, :addr=>addr }
rescue KeyError
error "Invalid format string: #{@format}"
@format = "%{subject} from: %{from}"
warn "Failing back to default format: #{@format}"
retry
rescue ArgumentError
warn "This ruby does not support format string with Hash argument. falling back to default format."
event = "#{subject} (#{from})"
end
# body process
begin
part, pos = get_text_part( attr['BODYSTRUCTURE'], [] )
if part
section = pos.size > 0 ? pos.join('.') : "1"
debug "Detected text part: [#{section}]"
tmp = @imap.uid_fetch( attr['UID'], "BODY.PEEK[#{section}]" ).first
body = tmp.attr["BODY[#{section}]"]
else
body = "[Body does not contain TEXT part]"
part = attr['BODYSTRUCTURE']
debug "No text part found."
end
if part.media_type != "TEXT"
# do nothing
elsif part.respond_to?('encoding') && part.encoding == "QUOTED-PRINTABLE"
body = body.unpack("M*").first
elsif part.respond_to?('encoding') && part.encoding == "BASE64"
body = body.unpack("m*").first
end
charset = nil
if part.param && part.param['CHARSET']
charset = part.param['CHARSET']
end
body.force_encoding( "ISO-2022-JP" ) if body.encoding == Encoding::US_ASCII
debug "Convert body charset from #{charset ? charset : body.encoding.to_s}"
begin
body.encode!( "UTF-8", charset, :undef=>:replace, :invalid=>:replace )
rescue
error "Error while converting body from #{charset}"
debug $!.to_s
body = "[Body contains invalid charactor]"
end
body = body.gsub(/^[\s\t]*/, '').gsub(/^$/, '')
if body.size > @body_length
body = body[0..@body_length] + "..."
end
rescue
error "Error: Could not parse body text"
debug $!.to_s
body = "[Could not parse body]"
end
# prowling
if will_prowl
info "Prowling... UID=#{attr["UID"]}"
debug "Prowling: " + event + " " + body
begin
presp = prowl( :apikey=> @@prowl_conf['APIKey'],
:application => @application,
:event => event,
:description => body,
:priority => @priority
)
unseen_set.push attr["UID"] if presp && presp.code == "200"
debug "Response: #{presp.code}"
rescue
error "Error while HTTP/POST process."
debug $!
end
else
unseen_set.push attr["UID"]
debug "Caching: " + event + " " + body
debug "Not Prowled (Caching): UID=#{attr["UID"]}"
end
rescue
error "Error while parsing mail: UID=#{attr["UID"]}. Skipped."
unseen_set.push attr["UID"]
debug $!
end
end
# caching
@notified = unseen_set
end
def checker
debug "Won't use IDLE to check unseen mail."
@loop_thread = Thread.start do
loop do
begin
event = false
@imap.synchronize do
@imap.noop
debug("Execute NOOP")
event = true if @imap.responses["EXISTS"][-1]
@imap.responses.delete("EXISTS")
end
info "Received EXISTS." if event
check_unseen( true ) if event
sleep( @noop )
rescue
error "Error in checker(): #{$!}"
debug "Exiting thread"
Thread.current.exit
end
end # loop
end # Thread
end
def idler
@loop_thread = Thread.start do
loop do
begin
event = false
debug "Entering IDLE."
@idle_time = Time.now
@imap.idle do |resp|
if resp.kind_of?( Net::IMAP::UntaggedResponse )
case resp.name
when "EXISTS"
event = true
info "Received EXISTS."
@idle_time = nil
@imap.idle_done
debug "DONE IDLE."
when "OK"
info "Received OK" +
resp.data.respond_to('text') ? resp.data.text : ""
else
debug "FIXME: Unhandled response: #{resp.name}: #{resp}"
end
elsif resp.kind_of?( Net::IMAP::ContinuationRequest )
debug "Received idling"
else
debug "FIXME: Unhandled response: #{resp.name}, #{resp}"
end
end
check_unseen( true ) if event
rescue
error "Error in idler(): #{$!}"
debug "Exiting thread"
Thread.current.exit
end
debug "idler(): Still in loop"
end # loop
end # Thread
end
end # class
## __MAIN__
## command line options
ProgramConfig = Hash.new
opts = OptionParser.new
opts.on( "-c", "--config FILENAME", String, "Specify the config file." ) { |v| ProgramConfig[:config] = v }
opts.on( "-q", "--daemon",nil, "Enable daemon mode.") { |v| ProgramConfig[:daemon] = true }
opts.on( "-d", "--debug", nil, "Enable debug output." ) { |v| ProgramConfig[:debug] = true }
opts.version = IMAPROWL_VERSION
opts.program_name = "imaprowl"
opts.parse!( ARGV )
## config file
config_order = [
File.join( ENV['HOME'], '.imaprowl.conf' ),
File.join( Dir.pwd, 'imaprowl.conf' ),
File.join( Dir.pwd, 'config.yml' ),
File.join( File.dirname( __FILE__ ), 'imaprowl.conf' )
]
filename = nil
if ProgramConfig[:config]
if File.exist?( ProgramConfig[:config] )
filename = ProgramConfig[:config]
else
STDERR.print "Configuration file does not exist: #{ProgramConfig[:config]}\n"
exit 1
end
else
config_order.each do |conf|
next unless File.exist?( conf )
filename = conf
break
end
end
if filename.nil?
STDERR.print "No configuration file exist.\n"
STDERR.print "File candidates are:\n"
STDERR.print config_order.join("\n")
STDERR.print "\n"
exit 1
end
STDOUT.print "LoadConf: #{filename}\n"
config = YAML.load_file( filename )
config["Debug"] = true if ProgramConfig[:debug]
## Daemon mode
if ProgramConfig[:daemon] || config['Daemon']
begin
Process.daemon( true, true )
rescue
STDERR.print $!
exit 1
end
STDOUT.print "Daemonized. PID=#{Process.pid}\n"
end
## Create Account Thread
application = Array.new
config['Accounts'].each do |account|
app = IMAProwl.new( config, account )
next unless app.enable
if app.start()
application.push( app )
end
end
## Signal trap
Signal.trap(:INT) {
application.each do |app|
app.loop_thread.exit if app.loop_thread.alive?
app.stop
end
sleep 1
exit
}
Signal.trap(:TERM) {
application.each do |app|
app.loop_thread.exit if app.loop_thread.alive?
app.stop
end
sleep 1
exit
}
## main loop
loop do
sleep 60
application.each do |app|
app.status
end
end
## __END__