summaryrefslogtreecommitdiff
path: root/lib/gitlab/mail_room.rb
blob: f7699ef1718ce65d2f84ad19b4719314c27ae00e (plain)
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
# frozen_string_literal: true

require 'yaml'
require 'json'
require_relative 'redis/queues' unless defined?(Gitlab::Redis::Queues)

# This service is run independently of the main Rails process,
# therefore the `Rails` class and its methods are unavailable.

module Gitlab
  module MailRoom
    RAILS_ROOT_DIR = Pathname.new('../..').expand_path(__dir__).freeze

    DEFAULT_CONFIG = {
      enabled: false,
      port: 143,
      ssl: false,
      start_tls: false,
      mailbox: 'inbox',
      idle_timeout: 60,
      log_path: RAILS_ROOT_DIR.join('log', 'mail_room_json.log')
    }.freeze

    class << self
      def enabled?
        config[:enabled] && config[:address]
      end

      def config
        @config ||= fetch_config
      end

      def reset_config!
        @config = nil
      end

      private

      def fetch_config
        return {} unless File.exist?(config_file)

        config = load_from_yaml || {}
        config = DEFAULT_CONFIG.merge(config) do |_key, oldval, newval|
          newval.nil? ? oldval : newval
        end

        if config[:enabled] && config[:address]
          gitlab_redis_queues = Gitlab::Redis::Queues.new(rails_env)
          config[:redis_url] = gitlab_redis_queues.url

          if gitlab_redis_queues.sentinels?
            config[:sentinels] = gitlab_redis_queues.sentinels
          end
        end

        config[:log_path] = File.expand_path(config[:log_path], RAILS_ROOT_DIR)
        config
      end

      def rails_env
        @rails_env ||= ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
      end

      def config_file
        ENV['MAIL_ROOM_GITLAB_CONFIG_FILE'] || File.expand_path('../../config/gitlab.yml', __dir__)
      end

      def load_from_yaml
        YAML.load_file(config_file)[rails_env].deep_symbolize_keys[:incoming_email]
      end
    end
  end
end