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/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

Constant Summary collapse

VERSION =
"2"

Class Method Summary collapse

Class Method Details

.account_configObject



167
168
169
170
# File 'lib/mournmail/utils.rb', line 167

def self.
  
  @account_config
end

.back_to_summaryObject



140
141
142
143
144
145
146
147
# File 'lib/mournmail/utils.rb', line 140

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



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/mournmail/utils.rb', line 79

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_dbObject



575
576
577
578
579
# File 'lib/mournmail/utils.rb', line 575

def self.close_groonga_db
  if @groonga_db
    @groonga_db.close
  end
end

.create_groonga_db(db_path) ⇒ Object



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
# File 'lib/mournmail/utils.rb', line 544

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_accountObject



162
163
164
165
# File 'lib/mournmail/utils.rb', line 162

def self.
  
  @current_account
end

.current_account=(name) ⇒ Object



178
179
180
181
182
183
184
# File 'lib/mournmail/utils.rb', line 178

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



155
156
157
158
159
160
# File 'lib/mournmail/utils.rb', line 155

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



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/mournmail/utils.rb', line 49

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



149
150
151
152
153
# File 'lib/mournmail/utils.rb', line 149

def self.escape_binary(s)
  s.b.gsub(/[\x80-\xff]/n) { |c|
    "<%02X>" % c.ord
  }
end

.fetch_summary(mailbox, all: false) ⇒ Object



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
# File 'lib/mournmail/utils.rb', line 320

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

.force_utf8(s) ⇒ Object



518
519
520
# File 'lib/mournmail/utils.rb', line 518

def self.force_utf8(s)
  s.dup.force_encoding(Encoding::UTF_8).scrub("?")
end

.google_access_token(account = current_account) ⇒ Object



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
# File 'lib/mournmail/utils.rb', line 264

def self.google_access_token( = )
  auth_path = File.expand_path("cache/#{}/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)
  storage.authorize
  if storage.authorization.nil?
    conf = CONFIG[:mournmail_accounts][]
    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_connectObject



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
# File 'lib/mournmail/utils.rb', line 186

def self.imap_connect
  @imap_mutex.synchronize do
    if keep_alive_thread.nil?
      start_keep_alive_thread
    end
    if @imap.nil? || @imap.disconnected?
      conf = 
      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))
        @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, Errno::ECONNRESET
  imap_disconnect
  raise
end

.imap_disconnectObject



219
220
221
222
223
224
225
226
227
# File 'lib/mournmail/utils.rb', line 219

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



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/mournmail/utils.rb', line 426

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: header_text(mail.message_id),
                    thread_id: header_text(thread_id),
                    date: mail.date&.to_time,
                    subject: header_text(mail.subject),
                    from: header_text(mail["From"]),
                    to: header_text(mail["To"]),
                    cc: header_text(mail["Cc"]),
                    list_id: header_text(list_id),
                    body: body_text(mail))
  end
end

.init_current_accountObject



172
173
174
175
176
# File 'lib/mournmail/utils.rb', line 172

def self.
  if @current_account.nil?
    @current_account, @account_config = CONFIG[:mournmail_accounts].first
  end
end

.insert_signatureObject



592
593
594
595
596
597
598
599
600
601
602
603
# File 'lib/mournmail/utils.rb', line 592

def self.insert_signature
   = Buffer.current[:mournmail_delivery_account] ||
    Mournmail.
  signature = CONFIG[:mournmail_accounts][][:signature]
  if signature
    Buffer.current.save_excursion do
      end_of_buffer
      insert("\n")
      insert(signature)
    end
  end
end

.mail_cache_path(cache_id) ⇒ Object



393
394
395
396
397
# File 'lib/mournmail/utils.rb', line 393

def self.mail_cache_path(cache_id)
  dir = cache_id[0, 2]
  File.expand_path("cache/#{}/mails/#{dir}/#{cache_id}",
                   CONFIG[:mournmail_directory])
end

.mailbox_cache_path(mailbox) ⇒ Object



388
389
390
391
# File 'lib/mournmail/utils.rb', line 388

def self.mailbox_cache_path(mailbox)
  File.expand_path("cache/#{}/mailboxes/#{mailbox}",
                   CONFIG[:mournmail_directory])
end

.message_windowObject



129
130
131
132
133
134
135
136
137
138
# File 'lib/mournmail/utils.rb', line 129

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_dbObject



534
535
536
537
538
539
540
541
542
# File 'lib/mournmail/utils.rb', line 534

def self.open_groonga_db
  db_path = File.expand_path("groonga/#{}/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



581
582
583
# File 'lib/mournmail/utils.rb', line 581

def self.parse_mail(s)
  Mail.new(s.scrub("??"))
end

.read_account_name(prompt, **opts) ⇒ Object



585
586
587
588
589
590
# File 'lib/mournmail/utils.rb', line 585

def self.(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



399
400
401
402
# File 'lib/mournmail/utils.rb', line 399

def self.read_mail_cache(cache_id)
  path = Mournmail.mail_cache_path(cache_id)
  File.read(path)
end

.read_mailbox_name(prompt, **opts) ⇒ Object



510
511
512
513
514
515
516
# File 'lib/mournmail/utils.rb', line 510

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

.show_google_auth_uri(auth_uri) ⇒ Object



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/mournmail/utils.rb', line 303

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



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# File 'lib/mournmail/utils.rb', line 365

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_threadObject



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/mournmail/utils.rb', line 98

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|
              imap.noop
            end
          rescue => e
            message("Error in IMAP NOOP: #{e.class}: #{e.message}")
          end
        end
      end
    }
  end
end

.stop_keep_alive_threadObject



120
121
122
123
124
125
126
127
# File 'lib/mournmail/utils.rb', line 120

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



522
523
524
525
526
527
528
529
530
531
532
# File 'lib/mournmail/utils.rb', line 522

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

.write_mail_cache(s) ⇒ Object



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/mournmail/utils.rb', line 404

def self.write_mail_cache(s)
  header = s.slice(/.*\r\n\r\n/m)
  cache_id = Digest::SHA256.hexdigest(header)
  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