Module: Mournmail
- Defined in:
- lib/mournmail/summary.rb,
lib/mournmail/version.rb,
lib/mournmail/draft_mode.rb,
lib/mournmail/message_mode.rb,
lib/mournmail/summary_mode.rb,
lib/mournmail/header_folding.rb,
lib/mournmail/message_rendering.rb,
lib/mournmail/search_result_mode.rb,
lib/mournmail/mail_encoded_word_patch.rb,
lib/mournmail/utils.rb
Defined Under Namespace
Modules: MailEncodedWordPatch, MessageRendering
Classes: DraftMode, GoogleAuthCallbackServer, MessageMode, SearchResultMode, Summary, SummaryItem, SummaryMode, VirusDetected
Constant Summary
collapse
- VERSION =
"4"
78
Class Method Summary
collapse
-
.account_config ⇒ Object
-
.back_to_summary ⇒ Object
-
.background(skip_if_busy: false) ⇒ Object
-
.close_groonga_db ⇒ Object
-
.create_groonga_db(db_path) ⇒ Object
-
.current_account ⇒ Object
-
.current_account=(name) ⇒ Object
-
.decode_eword(s) ⇒ Object
-
.define_variable(name, initial_value: nil, attr: nil) ⇒ Object
-
.escape_binary(s) ⇒ Object
-
.fetch_summary(mailbox, all: false) ⇒ Object
-
.fold_header_field(name, value, max_line_length: HEADER_MAX_LINE_LENGTH) ⇒ Object
Return "#name: #value" folded so that each line is not longer than max_line_length characters whenever possible (RFC 5322 2.2.3).
-
.force_utf8(s) ⇒ Object
-
.google_access_token(account = current_account) ⇒ Object
-
.imap_connect ⇒ Object
-
.imap_disconnect ⇒ Object
-
.index_mail(cache_id, mail) ⇒ Object
-
.init_current_account ⇒ Object
-
.insert_signature ⇒ Object
-
.mail_cache_path(cache_id) ⇒ Object
-
.mailbox_cache_path(mailbox) ⇒ Object
-
.message_window ⇒ Object
-
.open_groonga_db ⇒ Object
-
.parse_mail(s) ⇒ Object
-
.read_account_name(prompt, **opts) ⇒ Object
-
.read_mail_cache(cache_id) ⇒ Object
-
.read_mailbox_name(prompt, **opts) ⇒ Object
-
.scan_virus(data) ⇒ Object
Returns the virus name if a virus is detected, nil otherwise.
-
.setup_tcp_keep_alive(imap) ⇒ Object
Detect dead connections at the kernel level (e.g. after a network switch, where reads block forever without an error).
-
.show_google_auth_uri(auth_uri) ⇒ Object
-
.show_summary(summary) ⇒ Object
-
.start_keep_alive_thread ⇒ Object
-
.stop_keep_alive_thread ⇒ Object
-
.to_utf8(s, charset) ⇒ Object
-
.unfold_header_value(value) ⇒ Object
Unfold a header field body (RFC 5322 2.2.3): remove each CRLF (or LF) that is immediately followed by whitespace, leaving the whitespace.
-
.write_mail_cache(s) ⇒ Object
Class Method Details
.account_config ⇒ Object
179
180
181
182
|
# File 'lib/mournmail/utils.rb', line 179
def self.account_config
init_current_account
@account_config
end
|
.back_to_summary ⇒ Object
152
153
154
155
156
157
158
159
|
# File 'lib/mournmail/utils.rb', line 152
def self.back_to_summary
summary_window = Window.list.find { |window|
window.buffer.name == "*summary*"
}
if summary_window
Window.current = summary_window
end
end
|
.background(skip_if_busy: false) ⇒ Object
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
# File 'lib/mournmail/utils.rb', line 89
def self.background(skip_if_busy: false)
@background_thread_mutex.synchronize do
if background_thread&.alive?
if skip_if_busy
return
else
raise EditorError, "Another background thread is running"
end
end
self.background_thread = Utils.background {
begin
yield
ensure
self.background_thread = nil
end
}
end
end
|
.close_groonga_db ⇒ Object
637
638
639
640
641
|
# File 'lib/mournmail/utils.rb', line 637
def self.close_groonga_db
if @groonga_db
@groonga_db.close
end
end
|
.create_groonga_db(db_path) ⇒ Object
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
|
# File 'lib/mournmail/utils.rb', line 606
def self.create_groonga_db(db_path)
FileUtils.mkdir_p(File.dirname(db_path), mode: 0700)
db = Groonga::Database.create(path: db_path)
Groonga::Schema.create_table("Messages", :type => :hash) do |table|
table.short_text("message_id")
table.short_text("thread_id")
table.time("date")
table.short_text("subject")
table.short_text("from")
table.short_text("to")
table.short_text("cc")
table.short_text("list_id")
table.text("body")
end
Groonga::Schema.create_table("Terms",
type: :patricia_trie,
normalizer: :NormalizerAuto,
default_tokenizer: "TokenBigram") do |table|
table.index("Messages.subject")
table.index("Messages.from")
table.index("Messages.to")
table.index("Messages.cc")
table.index("Messages.list_id")
table.index("Messages.body")
end
db
end
|
.current_account ⇒ Object
174
175
176
177
|
# File 'lib/mournmail/utils.rb', line 174
def self.current_account
init_current_account
@current_account
end
|
.current_account=(name) ⇒ Object
190
191
192
193
194
195
196
|
# File 'lib/mournmail/utils.rb', line 190
def self.current_account=(name)
unless CONFIG[:mournmail_accounts].key?(name)
raise ArgumentError, "No such account: #{name}"
end
@current_account = name
@account_config = CONFIG[:mournmail_accounts][name]
end
|
.decode_eword(s) ⇒ Object
167
168
169
170
171
172
|
# File 'lib/mournmail/utils.rb', line 167
def self.decode_eword(s)
Mail::Encodings.decode_encode(s, :decode).
encode(Encoding::UTF_8, replace: "?").gsub(/[\t\n]/, " ")
rescue Encoding::CompatibilityError, Encoding::UndefinedConversionError
escape_binary(s)
end
|
.define_variable(name, initial_value: nil, attr: nil) ⇒ Object
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
# File 'lib/mournmail/utils.rb', line 59
def self.define_variable(name, initial_value: nil, attr: nil)
var_name = "@" + name.to_s
if !instance_variable_defined?(var_name)
instance_variable_set(var_name, initial_value)
end
case attr
when :accessor
singleton_class.send(:attr_accessor, name)
when :reader
singleton_class.send(:attr_reader, name)
when :writer
singleton_class.send(:attr_writer, name)
end
end
|
.escape_binary(s) ⇒ Object
161
162
163
164
165
|
# File 'lib/mournmail/utils.rb', line 161
def self.escape_binary(s)
s.b.gsub(/[\x80-\xff]/n) { |c|
"<%02X>" % c.ord
}
end
|
.fetch_summary(mailbox, all: false) ⇒ Object
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
|
# File 'lib/mournmail/utils.rb', line 364
def self.fetch_summary(mailbox, all: false)
if all
summary = Mournmail::Summary.new(mailbox)
else
summary = Mournmail::Summary.load_or_new(mailbox)
end
imap_connect do |imap|
imap.select(mailbox)
uidvalidity = imap.responses["UIDVALIDITY"].last
if uidvalidity && summary.uidvalidity &&
uidvalidity != summary.uidvalidity
clear = foreground! {
yes_or_no?("UIDVALIDITY has been changed; Clear cache?")
}
if clear
summary = Mournmail::Summary.new(mailbox)
end
end
summary.uidvalidity = uidvalidity
uids = imap.uid_search("ALL")
new_uids = uids - summary.uids
return summary if new_uids.empty?
summary.synchronize do
new_uids.each_slice(1000) do |uid_chunk|
data = imap.uid_fetch(uid_chunk, ["UID", "ENVELOPE", "FLAGS"])
data&.each do |i|
uid = i.attr["UID"]
next if summary[uid]
env = i.attr["ENVELOPE"]
flags = i.attr["FLAGS"]
item = Mournmail::SummaryItem.new(uid, env.date, env.from,
env.subject, flags)
summary.add_item(item, env.message_id, env.in_reply_to)
end
end
end
summary
end
rescue SocketError, Timeout::Error => e
foreground do
message(e.message)
end
summary
end
|
Return "#name: #value" folded so that each line is not longer than
max_line_length characters whenever possible (RFC 5322 2.2.3).
Folding only happens at existing whitespace, and the whitespace is
preserved at the beginning of the continuation line, so unfolding the
result gives back the original value. A single token longer than
max_line_length is never split; it is put on a line of its own.
The first token always stays on the same line as the field name.
Lines are separated by "\n"; the mail library converts them into CRLF
when the message is sent.
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
# File 'lib/mournmail/header_folding.rb', line 22
def self.(name, value,
max_line_length: HEADER_MAX_LINE_LENGTH)
unfolded = (value).gsub(/\r?\n/, " ").strip
lines = []
line = nil
unfolded.scan(/([ \t]*)([^ \t]+)/) do |ws, token|
if line.nil?
line = "#{name}: #{token}"
elsif line.size + ws.size + token.size <= max_line_length
line << ws << token
else
lines.push(line)
line = ws + token
end
end
lines.push(line || "#{name}: ")
lines.join("\n")
end
|
.force_utf8(s) ⇒ Object
580
581
582
|
# File 'lib/mournmail/utils.rb', line 580
def self.force_utf8(s)
s.dup.force_encoding(Encoding::UTF_8).scrub("?")
end
|
.google_access_token(account = current_account) ⇒ Object
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
|
# File 'lib/mournmail/utils.rb', line 303
def self.google_access_token(account = current_account)
auth_path = File.expand_path("cache/#{account}/google_auth.json",
CONFIG[:mournmail_directory])
FileUtils.mkdir_p(File.dirname(auth_path))
store = Google::APIClient::FileStore.new(auth_path)
storage = Google::APIClient::Storage.new(store)
begin
storage.authorize
rescue Signet::AuthorizationError
File.unlink(auth_path)
raise
end
if storage.authorization.nil?
conf = CONFIG[:mournmail_accounts][account]
path = File.expand_path(conf[:client_secret_path])
client_secrets = Google::APIClient::ClientSecrets.load(path)
callback_server = GoogleAuthCallbackServer.new
auth_client = client_secrets.to_authorization
auth_client.update!(
:scope => 'https://mail.google.com/',
:redirect_uri => "http://127.0.0.1:#{callback_server.port}/"
)
auth_uri = auth_client.authorization_uri.to_s
foreground! do
begin
Launchy.open(auth_uri)
rescue Launchy::CommandNotFoundError
show_google_auth_uri(auth_uri)
end
end
auth_client.code = callback_server.receive_code
auth_client.fetch_access_token!
old_umask = File.umask(077)
begin
storage.write_credentials(auth_client)
ensure
File.umask(old_umask)
end
else
auth_client = storage.authorization
end
auth_client.access_token
end
|
.imap_connect ⇒ Object
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
|
# File 'lib/mournmail/utils.rb', line 198
def self.imap_connect
@imap_mutex.synchronize do
if keep_alive_thread.nil?
start_keep_alive_thread
end
if @imap.nil? || @imap.disconnected?
conf = account_config
auth_type = conf[:imap_options][:auth_type] || "PLAIN"
password = conf[:imap_options][:password]
if auth_type == "gmail"
auth_type = "XOAUTH2"
password = google_access_token
end
Timeout.timeout(CONFIG[:mournmail_imap_connect_timeout]) do
@imap = Net::IMAP.new(conf[:imap_host],
conf[:imap_options].except(:auth_type, :user_name, :password))
setup_tcp_keep_alive(@imap)
@imap.authenticate(auth_type, conf[:imap_options][:user_name],
password)
@mailboxes = @imap.list("", "*").map { |mbox|
Net::IMAP.decode_utf7(mbox.name)
}
if Mournmail.current_mailbox
@imap.select(Mournmail.current_mailbox)
end
end
end
yield(@imap)
end
rescue IOError, SystemCallError, SocketError, OpenSSL::SSL::SSLError,
Timeout::Error, Net::IMAP::ByeResponseError
imap_disconnect
raise
end
|
.imap_disconnect ⇒ Object
258
259
260
261
262
263
264
265
266
|
# File 'lib/mournmail/utils.rb', line 258
def self.imap_disconnect
@imap_mutex.synchronize do
stop_keep_alive_thread
if @imap
@imap.disconnect rescue nil
@imap = nil
end
end
end
|
.index_mail(cache_id, mail) ⇒ Object
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
|
# File 'lib/mournmail/utils.rb', line 488
def self.index_mail(cache_id, mail)
messages_db = Groonga["Messages"]
unless messages_db.has_key?(cache_id)
thread_id = find_thread_id(mail, messages_db)
list_id = (mail["List-Id"] || mail["X-ML-Name"])
messages_db.add(cache_id,
message_id: (mail.message_id),
thread_id: (thread_id),
date: mail.date&.to_time,
subject: (mail.subject),
from: (mail["From"]),
to: (mail["To"]),
cc: (mail["Cc"]),
list_id: (list_id),
body: body_text(mail))
end
end
|
.init_current_account ⇒ Object
184
185
186
187
188
|
# File 'lib/mournmail/utils.rb', line 184
def self.init_current_account
if @current_account.nil?
@current_account, @account_config = CONFIG[:mournmail_accounts].first
end
end
|
.insert_signature ⇒ Object
654
655
656
657
658
659
660
661
662
663
664
665
|
# File 'lib/mournmail/utils.rb', line 654
def self.insert_signature
account = Buffer.current[:mournmail_delivery_account] ||
Mournmail.current_account
signature = CONFIG[:mournmail_accounts][account][:signature]
if signature
Buffer.current.save_excursion do
end_of_buffer
insert("\n")
insert(signature)
end
end
end
|
.mail_cache_path(cache_id) ⇒ Object
437
438
439
440
441
|
# File 'lib/mournmail/utils.rb', line 437
def self.mail_cache_path(cache_id)
dir = cache_id[0, 2]
File.expand_path("cache/#{current_account}/mails/#{dir}/#{cache_id}",
CONFIG[:mournmail_directory])
end
|
.mailbox_cache_path(mailbox) ⇒ Object
432
433
434
435
|
# File 'lib/mournmail/utils.rb', line 432
def self.mailbox_cache_path(mailbox)
File.expand_path("cache/#{current_account}/mailboxes/#{mailbox}",
CONFIG[:mournmail_directory])
end
|
.message_window ⇒ Object
141
142
143
144
145
146
147
148
149
150
|
# File 'lib/mournmail/utils.rb', line 141
def self.message_window
if Window.list.size == 1
split_window
n = Window.current.lines - (CONFIG[:mournmail_summary_lines] + 1)
shrink_window(n)
end
windows = Window.list
i = (windows.index(Window.current) + 1) % windows.size
windows[i]
end
|
.open_groonga_db ⇒ Object
596
597
598
599
600
601
602
603
604
|
# File 'lib/mournmail/utils.rb', line 596
def self.open_groonga_db
db_path = File.expand_path("groonga/#{current_account}/messages.db",
CONFIG[:mournmail_directory])
if File.exist?(db_path)
@groonga_db = Groonga::Database.open(db_path)
else
@groonga_db = create_groonga_db(db_path)
end
end
|
.parse_mail(s) ⇒ Object
643
644
645
|
# File 'lib/mournmail/utils.rb', line 643
def self.parse_mail(s)
Mail.new(s.scrub("??"))
end
|
.read_account_name(prompt, **opts) ⇒ Object
647
648
649
650
651
652
|
# File 'lib/mournmail/utils.rb', line 647
def self.read_account_name(prompt, **opts)
f = ->(s) {
complete_for_minibuffer(s, CONFIG[:mournmail_accounts].keys)
}
read_from_minibuffer(prompt, completion_proc: f, **opts)
end
|
.read_mail_cache(cache_id) ⇒ Object
443
444
445
446
|
# File 'lib/mournmail/utils.rb', line 443
def self.read_mail_cache(cache_id)
path = Mournmail.mail_cache_path(cache_id)
File.read(path)
end
|
.read_mailbox_name(prompt, **opts) ⇒ Object
572
573
574
575
576
577
578
|
# File 'lib/mournmail/utils.rb', line 572
def self.read_mailbox_name(prompt, **opts)
f = ->(s) {
complete_for_minibuffer(s, @mailboxes)
}
mailbox = read_from_minibuffer(prompt, completion_proc: f, **opts)
Net::IMAP.encode_utf7(mailbox)
end
|
.scan_virus(data) ⇒ Object
Returns the virus name if a virus is detected, nil otherwise.
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
|
# File 'lib/mournmail/utils.rb', line 449
def self.scan_virus(data)
run_hooks(:mournmail_virus_scan_hook, data)
nil
rescue VirusDetected => e
foreground do
message("Virus detected: #{e.virus_name}")
end
e.virus_name
rescue => e
foreground do
message("Virus scan failed: #{e.class}: #{e.message}")
end
nil
end
|
.setup_tcp_keep_alive(imap) ⇒ Object
Detect dead connections at the kernel level (e.g. after a network
switch, where reads block forever without an error).
Net::IMAP does not expose its socket, so use its internal @sock.
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
|
# File 'lib/mournmail/utils.rb', line 236
def self.setup_tcp_keep_alive(imap)
sock = imap.instance_variable_get(:@sock)
return if sock.nil?
sock = sock.io if sock.respond_to?(:io) sock.setsockopt(:SOCKET, :KEEPALIVE, true)
if Socket.const_defined?(:TCP_KEEPIDLE)
sock.setsockopt(:TCP, :KEEPIDLE, 60)
end
if Socket.const_defined?(:TCP_KEEPINTVL)
sock.setsockopt(:TCP, :KEEPINTVL, 10)
end
if Socket.const_defined?(:TCP_KEEPCNT)
sock.setsockopt(:TCP, :KEEPCNT, 3)
end
if Socket.const_defined?(:TCP_USER_TIMEOUT)
sock.setsockopt(:TCP, :USER_TIMEOUT, 90_000) end
rescue StandardError
end
|
.show_google_auth_uri(auth_uri) ⇒ Object
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
|
# File 'lib/mournmail/utils.rb', line 347
def self.show_google_auth_uri(auth_uri)
buffer = Buffer.find_or_new("*message*",
undo_limit: 0, read_only: true)
buffer.apply_mode(Mournmail::MessageMode)
buffer.read_only_edit do
buffer.clear
buffer.insert(<<~EOF)
Open the following URI in your browser and type obtained code:
#{auth_uri}
EOF
end
window = Mournmail.message_window
window.buffer = buffer
buffer
end
|
.show_summary(summary) ⇒ Object
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
|
# File 'lib/mournmail/utils.rb', line 409
def self.show_summary(summary)
buffer = Buffer.find_or_new("*summary*", undo_limit: 0,
read_only: true)
buffer.apply_mode(Mournmail::SummaryMode)
buffer.read_only_edit do
buffer.clear
buffer.insert(summary.to_s)
end
switch_to_buffer(buffer)
Mournmail.current_mailbox = summary.mailbox
Mournmail.current_summary = summary
Mournmail.current_mail = nil
Mournmail.current_uid = nil
begin
buffer.beginning_of_buffer
buffer.re_search_forward(/^ *\d+ u/)
rescue SearchError
buffer.end_of_buffer
buffer.re_search_backward(/^ *\d+ /, raise_error: false)
end
summary_read_command
end
|
.start_keep_alive_thread ⇒ Object
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
|
# File 'lib/mournmail/utils.rb', line 108
def self.start_keep_alive_thread
@keep_alive_thread_mutex.synchronize do
if keep_alive_thread
raise EditorError, "Keep alive thread already running"
end
self.keep_alive_thread = Thread.start {
loop do
sleep(CONFIG[:mournmail_keep_alive_interval])
background(skip_if_busy: true) do
begin
imap_connect do |imap|
Timeout.timeout(CONFIG[:mournmail_imap_noop_timeout]) do
imap.noop
end
end
rescue => e
message("Error in IMAP NOOP: #{e.class}: #{e.message}")
end
end
end
}
end
end
|
.stop_keep_alive_thread ⇒ Object
132
133
134
135
136
137
138
139
|
# File 'lib/mournmail/utils.rb', line 132
def self.stop_keep_alive_thread
@keep_alive_thread_mutex.synchronize do
if keep_alive_thread
keep_alive_thread&.kill
self.keep_alive_thread = nil
end
end
end
|
.to_utf8(s, charset) ⇒ Object
584
585
586
587
588
589
590
591
592
593
594
|
# File 'lib/mournmail/utils.rb', line 584
def self.to_utf8(s, charset)
if /\Autf-8\z/i.match?(charset)
force_utf8(s)
else
begin
s.encode(Encoding::UTF_8, charset, replace: "?")
rescue
force_utf8(NKF.nkf("-w", s))
end
end.gsub(/\r\n/, "\n")
end
|
Unfold a header field body (RFC 5322 2.2.3): remove each CRLF (or LF)
that is immediately followed by whitespace, leaving the whitespace.
7
8
9
|
# File 'lib/mournmail/header_folding.rb', line 7
def self.(value)
value.to_s.gsub(/\r?\n(?=[ \t])/, "")
end
|
.write_mail_cache(s) ⇒ Object
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
|
# File 'lib/mournmail/utils.rb', line 466
def self.write_mail_cache(s)
= s.slice(/.*\r\n\r\n/m)
cache_id = Digest::SHA256.hexdigest()
path = mail_cache_path(cache_id)
dir = File.dirname(path)
base = File.basename(path)
begin
f = Tempfile.create(["#{base}-", ".tmp"], dir,
external_encoding: "ASCII-8BIT", binmode: true)
begin
f.write(s)
ensure
f.close
end
rescue Errno::ENOENT
FileUtils.mkdir_p(File.dirname(path))
retry
end
File.rename(f.path, path)
cache_id
end
|