Skip to content

A platform for community discussion. Free, open, simple.

DEV: Remove IMAP support in Discourse (#37002)

Martin Brennand2252b5cd338
diff --git a/Gemfile b/Gemfile
index 79e114ebe87..7b3a7e93317 100644
--- a/Gemfile
+++ b/Gemfile
@@ -114,7 +114,6 @@ gem "addressable"
gem "json_schemer"
gem "net-smtp", require: false
-gem "net-imap", require: false
gem "net-pop", require: false
gem "digest", require: false
diff --git a/Gemfile.lock b/Gemfile.lock
index f41390159ba..4e4735e550f 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -824,7 +824,6 @@ DEPENDENCIES
multipart-post
mustache
net-http
- net-imap
net-pop
net-smtp
nokogiri
diff --git a/app/assets/stylesheets/common/base/group.scss b/app/assets/stylesheets/common/base/group.scss
index c53c857a089..ef750fe2527 100644
--- a/app/assets/stylesheets/common/base/group.scss
+++ b/app/assets/stylesheets/common/base/group.scss
@@ -317,8 +317,7 @@ table.group-category-permissions {
}
}
-.group-smtp-email-settings,
-.group-imap-email-settings {
+.group-smtp-email-settings {
background-color: var(--primary-very-low);
padding: 1em;
margin: 1em 0;
diff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rb
index 27e04e8d365..a776cf98576 100644
--- a/app/controllers/groups_controller.rb
+++ b/app/controllers/groups_controller.rb
@@ -175,7 +175,6 @@ class GroupsController < ApplicationController
if group.update(group_attributes)
GroupActionLogger.new(current_user, group).log_change_group_settings
group.record_email_setting_changes!(current_user)
- group.expire_imap_mailbox_cache
if params[:update_existing_users] == "true"
update_existing_users(group.group_users, notification_level, categories, tags)
end
@@ -725,52 +724,31 @@ class GroupsController < ApplicationController
settings = params.except(:name, :protocol)
email_host = params[:host]
- if !%w[smtp imap].include?(params[:protocol])
- raise Discourse::InvalidParameters.new("Valid protocols to test are smtp and imap")
+ if params[:protocol] != "smtp"
+ raise Discourse::InvalidParameters.new("Valid protocol to test is smtp")
end
hijack do
begin
- case params[:protocol]
- when "smtp"
- raise Discourse::InvalidParameters if params[:ssl_mode].blank?
+ raise Discourse::InvalidParameters if params[:ssl_mode].blank?
- settings.delete(:ssl_mode)
+ settings.delete(:ssl_mode)
- if params[:ssl_mode].blank? ||
- !Group.smtp_ssl_modes.values.include?(params[:ssl_mode].to_i)
- raise Discourse::InvalidParameters.new("SSL mode must be present and valid")
- end
-
- final_settings =
- settings.merge(
- enable_tls: params[:ssl_mode].to_i == Group.smtp_ssl_modes[:ssl_tls],
- enable_starttls_auto: params[:ssl_mode].to_i == Group.smtp_ssl_modes[:starttls],
- ).permit(:host, :port, :username, :password, :enable_tls, :enable_starttls_auto, :debug)
- EmailSettingsValidator.validate_as_user(
- current_user,
- "smtp",
- **final_settings.to_h.symbolize_keys,
- )
- when "imap"
- raise Discourse::InvalidParameters if params[:ssl].blank?
-
- final_settings =
- settings.merge(ssl: settings[:ssl] == "true").permit(
- :host,
- :port,
- :username,
- :password,
- :ssl,
- :debug,
- )
- EmailSettingsValidator.validate_as_user(
- current_user,
- "imap",
- **final_settings.to_h.symbolize_keys,
- )
+ if params[:ssl_mode].blank? || !Group.smtp_ssl_modes.values.include?(params[:ssl_mode].to_i)
+ raise Discourse::InvalidParameters.new("SSL mode must be present and valid")
end
+ final_settings =
+ settings.merge(
+ enable_tls: params[:ssl_mode].to_i == Group.smtp_ssl_modes[:ssl_tls],
+ enable_starttls_auto: params[:ssl_mode].to_i == Group.smtp_ssl_modes[:starttls],
+ ).permit(:host, :port, :username, :password, :enable_tls, :enable_starttls_auto, :debug)
+ EmailSettingsValidator.validate_as_user(
+ current_user,
+ "smtp",
+ **final_settings.to_h.symbolize_keys,
+ )
+
render json: success_json
rescue *EmailSettingsExceptionHandler::EXPECTED_EXCEPTIONS, StandardError => err
render_json_error(EmailSettingsExceptionHandler.friendly_exception_message(err, email_host))
@@ -830,13 +808,6 @@ class GroupsController < ApplicationController
:smtp_enabled,
:smtp_updated_by,
:smtp_updated_at,
- :imap_server,
- :imap_port,
- :imap_ssl,
- :imap_mailbox_name,
- :imap_enabled,
- :imap_updated_by,
- :imap_updated_at,
:email_username,
:email_password,
:email_from_alias,
@@ -906,16 +877,8 @@ class GroupsController < ApplicationController
end
def reset_group_email_settings_if_disabled!(group, attributes)
- should_clear_imap = group.imap_enabled && attributes[:imap_enabled] == "false"
should_clear_smtp = group.smtp_enabled && attributes[:smtp_enabled] == "false"
- if should_clear_imap || should_clear_smtp
- attributes[:imap_server] = nil
- attributes[:imap_ssl] = false
- attributes[:imap_port] = nil
- attributes[:imap_mailbox_name] = ""
- end
-
if should_clear_smtp
attributes[:smtp_server] = nil
attributes[:smtp_ssl_mode] = false
diff --git a/app/jobs/regular/group_smtp_email.rb b/app/jobs/regular/group_smtp_email.rb
index c70b49a1709..6d05f4e884e 100644
--- a/app/jobs/regular/group_smtp_email.rb
+++ b/app/jobs/regular/group_smtp_email.rb
@@ -47,31 +47,6 @@ module Jobs
bcc_addresses = User.not_staged.with_email(cc_addresses).pluck(:email)
cc_addresses = cc_addresses - bcc_addresses
- # There is a rare race condition causing the Imap::Sync class to create
- # an incoming email and associated post/topic, which then kicks off
- # the PostAlerter to notify others in the PM about a reply in the topic,
- # but for the OP which is not necessary (because the person emailing the
- # IMAP inbox already knows about the OP)
- #
- # Basically, we should never be sending this notification for the first
- # post in a topic.
- #
- # If the group does not have IMAP enabled then this could be legitimate,
- # for example in cases where we are creating a new topic to reply to another
- # group PM and we need to send the participants the group OP email.
- if post.is_first_post? && group.imap_enabled
- ImapSyncLog.warn(
- "Aborting SMTP email for post #{post.id} in topic #{post.topic_id} to #{email}, the post is the OP and should not send an email.",
- group,
- )
- return
- end
-
- ImapSyncLog.debug(
- "Sending SMTP email for post #{post.id} in topic #{post.topic_id} to #{email}.",
- group,
- )
-
# The EmailLog record created by the sender will have the raw email
# stored, the group smtp ID, and any cc addresses recorded for later
# cross referencing.
@@ -101,10 +76,7 @@ module Jobs
raise err # Re-raise the error so Sidekiq's retry mechanism kicks in.
end
- # Create an incoming email record to avoid importing again from IMAP
- # server. While this may not be technically required if IMAP is not
- # currently enabled for the group, it will help a lot with the initial
- # sync if it is turned on at a later date.
+ # Create an incoming email record for tracking purposes.
begin
IncomingEmail.create!(
user_id: post.user_id,
diff --git a/app/jobs/scheduled/cleanup_imap_sync_log.rb b/app/jobs/scheduled/cleanup_imap_sync_log.rb
deleted file mode 100644
index ac17cdd325f..00000000000
--- a/app/jobs/scheduled/cleanup_imap_sync_log.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-# frozen_string_literal: true
-
-module Jobs
- class CleanupImapSyncLog < ::Jobs::Scheduled
- every 1.day
-
- def execute(args)
- ImapSyncLog.where("created_at < ?", ImapSyncLog::RETAIN_LOGS_DAYS.days.ago).delete_all
- end
- end
-end
diff --git a/app/models/group.rb b/app/models/group.rb
index 5f7478b25cb..4bdcaba7030 100644
--- a/app/models/group.rb
+++ b/app/models/group.rb
@@ -1,8 +1,22 @@
# frozen_string_literal: true
-require "net/imap"
-
class Group < ActiveRecord::Base
+ # NOTE (martin): Remove after 2026.02.0
+ # and drop columns.
+ self.ignored_columns += %w[
+ imap_server
+ imap_port
+ imap_ssl
+ imap_mailbox_name
+ imap_uid_validity
+ imap_last_uid
+ imap_last_error
+ imap_old_emails
+ imap_new_emails
+ imap_enabled
+ imap_updated_at
+ imap_updated_by_id
+ ]
# Maximum 255 characters including terminator.
# https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.4
MAX_EMAIL_DOMAIN_LENGTH = 253
@@ -39,7 +53,6 @@ class Group < ActiveRecord::Base
has_many :upload_references, as: :target, dependent: :destroy
belongs_to :smtp_updated_by, class_name: "User"
- belongs_to :imap_updated_by, class_name: "User"
has_and_belongs_to_many :web_hooks
@@ -72,11 +85,6 @@ class Group < ActiveRecord::Base
def expire_cache
ApplicationSerializer.expire_cache_fragment!("group_names")
SvgSprite.expire_cache
- expire_imap_mailbox_cache
- end
-
- def expire_imap_mailbox_cache
- Discourse.cache.delete("group_imap_mailboxes_#{self.id}")
end
validate :name_format_validator
@@ -108,19 +116,10 @@ class Group < ActiveRecord::Base
AUTO_GROUPS_ADD = "add"
AUTO_GROUPS_REMOVE = "remove"
- IMAP_SETTING_ATTRIBUTES = %w[
- imap_server
- imap_port
- imap_ssl
- imap_mailbox_name
- email_username
- email_password
- ]
-
SMTP_SETTING_ATTRIBUTES = %w[
- imap_server
- imap_port
- imap_ssl
+ smtp_server
+ smtp_port
+ smtp_ssl_mode
email_username
email_password
email_from_alias
@@ -157,7 +156,6 @@ class Group < ActiveRecord::Base
validates :mentionable_level, inclusion: { in: ALIAS_LEVELS.values }
validates :messageable_level, inclusion: { in: ALIAS_LEVELS.values }
- scope :with_imap_configured, -> { where(imap_enabled: true).where.not(imap_mailbox_name: "") }
scope :with_smtp_configured, -> { where(smtp_enabled: true) }
scope :visible_groups,
@@ -360,11 +358,6 @@ class Group < ActiveRecord::Base
end
def record_email_setting_changes!(user)
- if (self.previous_changes.keys & IMAP_SETTING_ATTRIBUTES).any?
- self.imap_updated_at = Time.zone.now
- self.imap_updated_by_id = user.id
- end
-
if (self.previous_changes.keys & SMTP_SETTING_ATTRIBUTES).any?
self.smtp_updated_at = Time.zone.now
self.smtp_updated_by_id = user.id
@@ -376,12 +369,6 @@ class Group < ActiveRecord::Base
self.email_password,
self.email_username,
].all?(&:present?)
- self.imap_enabled = [
- self.imap_port,
- self.imap_server,
- self.email_password,
- self.email_username,
- ].all?(&:present?)
self.save
end
@@ -1048,43 +1035,6 @@ class Group < ActiveRecord::Base
end
end
- def imap_mailboxes
- return [] if !self.imap_enabled || !SiteSetting.enable_imap
-
- Discourse
- .cache
- .fetch("group_imap_mailboxes_#{self.id}", expires_in: 30.minutes) do
- Rails.logger.info("[IMAP] Refreshing mailboxes list for group #{self.name}")
- mailboxes = []
-
- begin
- imap_provider = Imap::Providers::Detector.init_with_detected_provider(self.imap_config)
- imap_provider.connect!
- mailboxes = imap_provider.filter_mailboxes(imap_provider.list_mailboxes_with_attributes)
- imap_provider.disconnect!
-
- update_columns(imap_last_error: nil)
- rescue => ex
- Rails.logger.warn(
- "[IMAP] Mailbox refresh failed for group #{self.name} with error: #{ex}",
- )
- update_columns(imap_last_error: ex.message)
- end
-
- mailboxes
- end
- end
-
- def imap_config
- {
- server: self.imap_server,
- port: self.imap_port,
- ssl: self.imap_ssl,
- username: self.email_username,
- password: self.email_password,
- }
- end
-
def email_username_domain
email_username.split("@").last
end
@@ -1349,56 +1299,44 @@ end
# Table name: groups
#
# id :integer not null, primary key
-# name :string not null
-# created_at :datetime not null
-# updated_at :datetime not null
+# allow_membership_requests :boolean default(FALSE), not null
+# allow_unknown_sender_topic_replies :boolean default(FALSE), not null
# automatic :boolean default(FALSE), not null
-# user_count :integer default(0), not null
# automatic_membership_email_domains :text
-# primary_group :boolean default(FALSE), not null
-# title :string
-# grant_trust_level :integer
-# incoming_email :string
-# has_messages :boolean default(FALSE), not null
+# bio_cooked :text
+# bio_raw :text
+# default_notification_level :integer default(3), not null
+# email_from_alias :string
+# email_password :string
+# email_username :string
# flair_bg_color :string
# flair_color :string
-# bio_raw :text
-# bio_cooked :text
-# allow_membership_requests :boolean default(FALSE), not null
+# flair_icon :string
# full_name :string
-# default_notification_level :integer default(3), not null
-# visibility_level :integer default(0), not null
-# public_exit :boolean default(FALSE), not null
-# public_admission :boolean default(FALSE), not null
+# grant_trust_level :integer
+# has_messages :boolean default(FALSE), not null
+# incoming_email :string
+# members_visibility_level :integer default(0), not null
# membership_request_template :text
-# messageable_level :integer default(0)
# mentionable_level :integer default(0)
-# smtp_server :string
-# smtp_port :integer
-# imap_server :string
-# imap_port :integer
-# imap_ssl :boolean
-# imap_mailbox_name :string default(""), not null
-# imap_uid_validity :integer default(0), not null
-# imap_last_uid :integer default(0), not null
-# email_username :string
-# email_password :string
+# messageable_level :integer default(0)
+# name :string not null
+# primary_group :boolean default(FALSE), not null
+# public_admission :boolean default(FALSE), not null
+# public_exit :boolean default(FALSE), not null
# publish_read_state :boolean default(FALSE), not null
-# members_visibility_level :integer default(0), not null
-# imap_last_error :text
-# imap_old_emails :integer
-# imap_new_emails :integer
-# flair_icon :string
-# flair_upload_id :integer
-# allow_unknown_sender_topic_replies :boolean default(FALSE), not null
# smtp_enabled :boolean default(FALSE)
+# smtp_port :integer
+# smtp_server :string
+# smtp_ssl_mode :integer default(0), not null
# smtp_updated_at :datetime
+# title :string
+# user_count :integer default(0), not null
+# visibility_level :integer default(0), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# flair_upload_id :integer
# smtp_updated_by_id :integer
-# imap_enabled :boolean default(FALSE)
-# imap_updated_at :datetime
-# imap_updated_by_id :integer
-# email_from_alias :string
-# smtp_ssl_mode :integer default(0), not null
#
# Indexes
#
diff --git a/app/models/group_archived_message.rb b/app/models/group_archived_message.rb
index 30d9feb5ce7..14de99ba753 100644
--- a/app/models/group_archived_message.rb
+++ b/app/models/group_archived_message.rb
@@ -10,7 +10,6 @@ class GroupArchivedMessage < ActiveRecord::Base
trigger(:move_to_inbox, group_id, topic_id)
MessageBus.publish("/topic/#{topic_id}", { type: "move_to_inbox" }, group_ids: [group_id])
publish_topic_tracking_state(topic, group_id, opts[:acting_user_id])
- set_imap_sync(topic_id) if !opts[:skip_imap_sync] && destroyed.present?
Jobs.enqueue(
:group_pm_update_summary,
group_id: group_id,
@@ -26,7 +25,6 @@ class GroupArchivedMessage < ActiveRecord::Base
trigger(:archive_message, group_id, topic_id)
MessageBus.publish("/topic/#{topic_id}", { type: "archived" }, group_ids: [group_id])
publish_topic_tracking_state(topic, group_id, opts[:acting_user_id])
- set_imap_sync(topic_id) if !opts[:skip_imap_sync] && destroyed.blank?
Jobs.enqueue(
:group_pm_update_summary,
group_id: group_id,
@@ -41,15 +39,6 @@ class GroupArchivedMessage < ActiveRecord::Base
DiscourseEvent.trigger(event, group: group, topic: topic) if group && topic
end
- def self.set_imap_sync(topic_id)
- IncomingEmail
- .joins(:post)
- .where.not(imap_uid: nil)
- .where(topic_id: topic_id, posts: { post_number: 1 })
- .update_all(imap_sync: true)
- end
- private_class_method :set_imap_sync
-
def self.publish_topic_tracking_state(topic, group_id, acting_user_id = nil)
PrivateMessageTopicTrackingState.publish_group_archived(
topic: topic,
diff --git a/app/models/imap_sync_log.rb b/app/models/imap_sync_log.rb
deleted file mode 100644
index f5fc0ded5da..00000000000
--- a/app/models/imap_sync_log.rb
+++ /dev/null
@@ -1,68 +0,0 @@
-# frozen_string_literal: true
-
-class ImapSyncLog < ActiveRecord::Base
- RETAIN_LOGS_DAYS = 5
-
- belongs_to :group
-
- def self.levels
- @levels ||= Enum.new(:debug, :info, :warn, :error)
- end
-
- def self.log(message, level, group_id = nil, db = true)
- now = Time.now.strftime("%Y-%m-%d %H:%M:%S.%L")
-
- new_log = (create(message: message, level: ImapSyncLog.levels[level], group_id: group_id) if db)
-
- if ENV["DEBUG_IMAP"]
- Rails.logger.send(
- :warn,
- "#{level[0].upcase}, [#{now}] [IMAP] (group_id #{group_id}) #{message}",
- )
- else
- Rails.logger.send(
- level,
- "#{level[0].upcase}, [#{now}] [IMAP] (group_id #{group_id}) #{message}",
- )
- end
-
- new_log
- end
-
- def self.debug(message, group_or_id, db: true)
- group_id = group_or_id.is_a?(Integer) ? group_or_id : group_or_id.id
- log(message, :debug, group_id, db)
- end
-
- def self.info(message, group_or_id)
- group_id = group_or_id.is_a?(Integer) ? group_or_id : group_or_id.id
- log(message, :info, group_id)
- end
-
- def self.warn(message, group_or_id)
- group_id = group_or_id.is_a?(Integer) ? group_or_id : group_or_id.id
- log(message, :warn, group_id)
- end
-
- def self.error(message, group_or_id)
- group_id = group_or_id.is_a?(Integer) ? group_or_id : group_or_id.id
- log(message, :error, group_id)
- end
-end
-
-# == Schema Information
-#
-# Table name: imap_sync_logs
-#
-# id :bigint not null, primary key
-# level :integer not null
-# message :string not null
-# group_id :bigint
-# created_at :datetime not null
-# updated_at :datetime not null
-#
-# Indexes
-#
-# index_imap_sync_logs_on_group_id (group_id)
-# index_imap_sync_logs_on_level (level)
-#
diff --git a/app/models/incoming_email.rb b/app/models/incoming_email.rb
index 12bf4abf547..8e266437ac1 100644
--- a/app/models/incoming_email.rb
+++ b/app/models/incoming_email.rb
@@ -1,10 +1,11 @@
# frozen_string_literal: true
class IncomingEmail < ActiveRecord::Base
+ self.ignored_columns += %w[imap_missing imap_sync imap_uid imap_uid_validity imap_group_id]
+
belongs_to :user
belongs_to :topic
belongs_to :post
- belongs_to :group, foreign_key: :imap_group_id, class_name: "Group"
validates :created_via, presence: true
@@ -30,7 +31,8 @@ class IncomingEmail < ActiveRecord::Base
scope :without_raw, -> { select(self.column_names - ["raw"]) }
def self.created_via_types
- @types ||= Enum.new(unknown: 0, handle_mail: 1, pop3_poll: 2, imap: 3, group_smtp: 4)
+ @types ||=
+ Enum.new(unknown: 0, handle_mail: 1, pop3_poll: 2, _deprecated_imap: 3, group_smtp: 4)
end
def as_mail_message
@@ -78,10 +80,6 @@ end
# created_via :integer default(0), not null
# error :text
# from_address :text
-# imap_missing :boolean default(FALSE), not null
-# imap_sync :boolean
-# imap_uid :integer
-# imap_uid_validity :integer
# is_auto_generated :boolean default(FALSE)
# is_bounce :boolean default(FALSE), not null
# raw :text
@@ -90,7 +88,6 @@ end
# to_addresses :text
# created_at :datetime not null
# updated_at :datetime not null
-# imap_group_id :bigint
# message_id :text
# post_id :integer
# topic_id :integer
diff --git a/app/serializers/group_show_serializer.rb b/app/serializers/group_show_serializer.rb
index 9b5015678ec..278722e7f61 100644
--- a/app/serializers/group_show_serializer.rb
+++ b/app/serializers/group_show_serializer.rb
@@ -19,7 +19,6 @@ class GroupShowSerializer < BasicGroupSerializer
end
has_one :smtp_updated_by, embed: :object, serializer: BasicUserSerializer
- has_one :imap_updated_by, embed: :object, serializer: BasicUserSerializer
admin_attributes :automatic_membership_email_domains,
:smtp_server,
@@ -28,20 +27,9 @@ class GroupShowSerializer < BasicGroupSerializer
:smtp_enabled,
:smtp_updated_at,
:smtp_updated_by,
- :imap_server,
- :imap_port,
- :imap_ssl,
- :imap_mailbox_name,
- :imap_mailboxes,
- :imap_enabled,
- :imap_updated_at,
- :imap_updated_by,
:email_username,
:email_password,
:email_from_alias,
- :imap_last_error,
- :imap_old_emails,
- :imap_new_emails,
:message_count,
:allow_unknown_sender_topic_replies,
:associated_group_ids
diff --git a/app/services/email_settings_exception_handler.rb b/app/services/email_settings_exception_handler.rb
index 24f7f8fbc5e..f0f691b6e20 100644
--- a/app/services/email_settings_exception_handler.rb
+++ b/app/services/email_settings_exception_handler.rb
@@ -1,14 +1,11 @@
# frozen_string_literal: true
-require "net/imap"
require "net/smtp"
require "net/pop"
class EmailSettingsExceptionHandler
EXPECTED_EXCEPTIONS = [
Net::POPAuthenticationError,
- Net::IMAP::NoResponseError,
- Net::IMAP::Error,
Net::SMTPAuthenticationError,
Net::SMTPServerBusy,
Net::SMTPSyntaxError,
@@ -29,10 +26,6 @@ class EmailSettingsExceptionHandler
case @exception
when Net::POPAuthenticationError
net_pop_authentication_error
- when Net::IMAP::NoResponseError
- net_imap_no_response_error
- when Net::IMAP::Error
- net_imap_unhandled_error
when Net::SMTPAuthenticationError
net_smtp_authentication_error
when Net::SMTPServerBusy
@@ -54,26 +47,6 @@ class EmailSettingsExceptionHandler
I18n.t("email_settings.pop3_authentication_error")
end
- def net_imap_no_response_error
- # Most of IMAP's errors are lumped under the NoResponseError, including invalid
- # credentials errors, because it is raised when a "NO" response is
- # raised from the IMAP server https://datatracker.ietf.org/doc/html/rfc3501#section-7.1.2
- #
- # Generally, it should be fairly safe to just return the error message as is.
- if @exception.message.match(/Invalid credentials/)
- I18n.t("email_settings.imap_authentication_error")
- else
- I18n.t(
- "email_settings.imap_no_response_error",
- message: @exception.message.gsub(" (Failure)", ""),
- )
- end
- end
-
- def net_imap_unhandled_error
- I18n.t("email_settings.imap_unhandled_error", message: @exception.message)
- end
-
def net_smtp_authentication_error
# Generally SMTP authentication errors are due to invalid credentials,
# and most common mail servers provide more detailed error messages,
diff --git a/app/services/email_settings_validator.rb b/app/services/email_settings_validator.rb
index 38ec33c5daa..451adf0e92c 100644
--- a/app/services/email_settings_validator.rb
+++ b/app/services/email_settings_validator.rb
@@ -1,20 +1,8 @@
# frozen_string_literal: true
-require "net/imap"
require "net/smtp"
require "net/pop"
-# Usage:
-#
-# begin
-# EmailSettingsValidator.validate_imap(host: "imap.test.com", port: 999, username: "[email protected]", password: "password")
-#
-# # or for specific host preset
-# EmailSettingsValidator.validate_imap(**{ username: "[email protected]", password: "test" }.merge(Email.gmail_imap_settings))
-#
-# rescue *EmailSettingsExceptionHandler::EXPECTED_EXCEPTIONS => err
-# EmailSettingsExceptionHandler.friendly_exception_message(err, host)
-# end
class EmailSettingsValidator
def self.validate_as_user(user, protocol, **kwargs)
DistributedMutex.synchronize("validate_#{protocol}_#{user.id}", validity: 10) do
@@ -51,7 +39,7 @@ class EmailSettingsValidator
end
end
- # This disconnects itself, unlike SMTP and IMAP.
+ # This disconnects itself, unlike SMTP.
pop3.auth_only(username, password)
rescue => err
log_and_raise(err, debug)
@@ -138,35 +126,6 @@ class EmailSettingsValidator
end
end
- ##
- # Attempts to login, logout, and disconnect an IMAP session and if that raises
- # an error then it is assumed the credentials or some other settings are wrong.
- #
- # @param debug [Boolean] - When set to true, any errors will be logged at a warning
- # level before being re-raised.
- def self.validate_imap(
- host:,
- port:,
- username:,
- password:,
- open_timeout: 5,
- ssl: true,
- debug: false
- )
- begin
- imap = Net::IMAP.new(host, port: port, ssl: ssl, open_timeout: open_timeout)
- imap.login(username, password)
- begin
- imap.logout
- rescue StandardError
- nil
- end
- imap.disconnect
- rescue => err
- log_and_raise(err, debug)
- end
- end
-
def self.log_and_raise(err, debug)
if debug
Rails.logger.warn(
diff --git a/app/services/post_alerter.rb b/app/services/post_alerter.rb
index 6bd50c7caab..d68c2373442 100644
--- a/app/services/post_alerter.rb
+++ b/app/services/post_alerter.rb
@@ -817,9 +817,8 @@ class PostAlerter
warn_if_not_sidekiq
- # To simplify things and to avoid IMAP double sync issues, and to cut down
- # on emails sent via SMTP, any topic_allowed_users (except those who are
- # not_allowed?) for a group that has SMTP enabled will have their notification
+ # To simplify things and to cut down on emails sent via SMTP, any topic_allowed_users
+ # (except those who are not_allowed?) for a group that has SMTP enabled will have their notification
# email combined into one and sent via a single group SMTP email with CC addresses.
emails_to_skip_send = email_using_group_smtp_if_configured(post)
diff --git a/app/services/problem_check/group_email_credentials.rb b/app/services/problem_check/group_email_credentials.rb
index d54c9e65804..cb794e0ac3d 100644
--- a/app/services/problem_check/group_email_credentials.rb
+++ b/app/services/problem_check/group_email_credentials.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
##
-# If group SMTP or IMAP has been configured, we want to make sure the
+# If group SMTP has been configured, we want to make sure the
# credentials are always valid otherwise emails will not be sending out
# from group inboxes. This check is run as part of scheduled admin
# problem checks, and if any credentials have issues they will show up on
@@ -9,9 +9,7 @@
class ProblemCheck::GroupEmailCredentials < ProblemCheck
self.priority = "high"
self.perform_every = 30.minutes
- self.targets = -> do
- [*Group.with_smtp_configured.pluck(:name), *Group.with_imap_configured.pluck(:name)]
- end
+ self.targets = -> { Group.with_smtp_configured.pluck(:name) }
def call
if group = Group.with_smtp_configured.find_by(name: target)
@@ -29,21 +27,6 @@ class ProblemCheck::GroupEmailCredentials < ProblemCheck
)
end
- if group = Group.with_imap_configured.find_by(name: target)
- return no_problem if !SiteSetting.enable_imap
-
- return(
- try_validate(group) do
- EmailSettingsValidator.validate_imap(
- host: group.imap_server,
- port: group.imap_port,
- username: group.email_username,
- password: group.email_password,
- )
- end
- )
- end
-
no_problem
end
diff --git a/config/discourse_defaults.conf b/config/discourse_defaults.conf
index f14f4b08d37..a98add589b1 100644
--- a/config/discourse_defaults.conf
+++ b/config/discourse_defaults.conf
@@ -359,13 +359,8 @@ anon_cache_store_threshold = 2
# https://github.com/discourse/discourse-custom-header-links.git,https://github.com/discourse/discourse-simple-theme.git
allowed_theme_repos =
-# Demon::EmailSync is used in conjunction with the enable_imap site setting
-# to sync N IMAP mailboxes with specific groups. It is a process started in
-# unicorn.conf, and it spawns N threads (one for each multisite connection) and
-# for each database spans another N threads (one for each configured group).
-#
-# We want this off by default so the process is not started when it does not
-# need to be (e.g. development, test, certain hosting tiers)
+# DEPRECATED: This setting is no longer used as IMAP support has been removed.
+# Keeping the setting for backwards compatibility with existing configurations.
enable_email_sync_demon = false
# we never want to queue more than 10000 digests per 30 minute block
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 189cf551d65..5c7f41d6a21 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -1159,9 +1159,7 @@ en:
self_lockout: "You are about to change group visibility in a way that will remove your own access. Are you sure you want to proceed?"
email:
title: "Email"
- status: "Synchronized %{old_emails} / %{total_emails} emails via IMAP."
enable_smtp: "Enable SMTP"
- enable_imap: "Enable IMAP"
test_settings: "Test Settings"
save_settings: "Save Settings"
last_updated: "Last updated:"
@@ -1170,14 +1168,8 @@ en:
smtp_settings_valid: "SMTP settings valid."
smtp_title: "SMTP"
smtp_instructions: "When you enable SMTP for the group, all outbound emails sent from the group's inbox will be sent via the SMTP settings specified here instead of the mail server configured for other emails sent by your forum."
- imap_title: "IMAP"
- imap_additional_settings: "Additional Settings"
- imap_instructions: 'When you enable IMAP for the group, emails are synced between the group inbox and the provided IMAP server and mailbox. SMTP must be enabled with valid and tested credentials before IMAP can be enabled. The email username and password used for SMTP will be used for IMAP. For more information see <a target="_blank" href="https://meta.discourse.org/t/imap-support-for-group-inboxes/160588">feature announcement on Discourse Meta</a>.'
- imap_alpha_warning: "Warning: This is an alpha-stage feature. Only Gmail is officially supported. Use at your own risk!"
- imap_settings_valid: "IMAP settings valid."
- smtp_disable_confirm: "If you disable SMTP, all SMTP and IMAP settings will be reset and the associated functionality will be disabled. Are you sure you want to continue?"
- imap_disable_confirm: "If you disable IMAP, all IMAP settings will be reset and the associated functionality will be disabled. Are you sure you want to continue?"
- imap_mailbox_not_selected: "You must select a Mailbox for this IMAP configuration or no mailboxes will be synced!"
+ additional_settings: "Additional Settings"
+ smtp_disable_confirm: "If you disable SMTP, all SMTP settings will be reset and the associated functionality will be disabled. Are you sure you want to continue?"
prefill:
title: "Prefill with settings for:"
gmail: "Gmail"
@@ -1192,9 +1184,6 @@ en:
smtp_server: "SMTP Server"
smtp_port: "SMTP Port"
smtp_ssl_mode: "SSL Mode"
- imap_server: "IMAP Server"
- imap_port: "IMAP Port"
- imap_ssl: "Use SSL for IMAP"
username: "Username"
password: "Password"
settings:
@@ -1203,10 +1192,6 @@ en:
allow_unknown_sender_topic_replies_hint: "Allows unknown senders to reply to group topics. If this is not enabled, replies from email addresses not already invited to the topic will create a new topic."
from_alias: "From Alias"
from_alias_hint: "Alias to use as the from address when sending group SMTP emails. Note this may not be supported by all mail providers, please consult your mail provider's documentation."
- mailboxes:
- synchronized: "Synchronized Mailbox"
- none_found: "No mailboxes were found in this email account."
- disabled: "Disabled"
membership:
title: Membership
access: Access
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 82934f9dd19..95478f923b3 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -1136,12 +1136,9 @@ en:
email_settings:
pop3_authentication_error: "There was an issue with the POP3 credentials provided, check the username and password and try again."
- imap_authentication_error: "There was an issue with the IMAP credentials provided, check the username and password and try again."
- imap_no_response_error: "An error occurred when communicating with the IMAP server. %{message}"
smtp_authentication_error: "There was an issue with the SMTP credentials provided, check the username and password and try again. %{message}"
smtp_server_busy_error: "The SMTP server is currently busy, try again later."
smtp_unhandled_error: "There was an unhandled error when communicating with the SMTP server. %{message}"
- imap_unhandled_error: "There was an unhandled error when communicating with the IMAP server. %{message}"
connection_error: "There was an issue connecting with the server, check the server name and port and try again."
timeout_error: "Connection to the server timed out, check the server name and port and try again."
unhandled_error: "Unhandled error when testing email settings. %{message}"
@@ -2379,16 +2376,8 @@ en:
email_in_authserv_id: "The identifier of the service doing authentication checks on incoming emails. See <a href='https://meta.discourse.org/t/134358'>https://meta.discourse.org/t/134358</a> for instructions on how to configure this."
email_in_spam_header: "Selects the specific email header to use for identifying spam. This option can be X-Spam-Flag, X-Spam-Status, or X-SES-Spam-Verdict, and the email is tagged as spam based on the header's value. For instance, if the chosen setting is X-Spam-Flag, an email with this header value set to YES would be classified as spam."
- enable_imap: "Enable IMAP for synchronizing group messages."
- enable_imap_write: "Enable two-way IMAP synchronization. If disabled, all write-operations on IMAP accounts are disabled."
- enable_imap_idle: "Use IMAP IDLE mechanism to wait for new emails."
enable_smtp: "Enable SMTP for sending notifications for group messages."
- imap_polling_period_mins: "The period in minutes between checking the IMAP accounts for emails."
- imap_polling_old_emails: "The maximum number of old emails (processed) to be updated every time an IMAP box is polled (0 for all)."
- imap_polling_new_emails: "The maximum number of new emails (unprocessed) to be updated every time an IMAP box is polled ."
- imap_batch_import_email: "The minimum number of new emails that trigger import mode (disables notifications for imported posts)."
-
email_prefix: "The [label] used in the subject of emails. It will default to 'title' if not set."
email_site_title: "The title of the site used as the sender of emails from the site. Default to 'title' if not set. If your 'title' contains characters that are not allowed in email sender strings, use this setting."
@@ -5663,8 +5652,6 @@ en:
api_post_delete: "Deleted via API"
reminder_deleted: "Replaced by new reminder"
user_associated_posts_deleted: "User was destroyed"
- imap_email_deleted: "Email has been deleted on the IMAP server"
- imap_email_marked_as_spam: "Email has been moved to spam on the IMAP server"
auto_deleted_hidden_posts: "Automatically destroyed hidden posts"
seed_data_topic_updated: "Seed data topic updated"
seed_data_topic_deleted: "Seed data topic deleted"
diff --git a/config/site_settings.yml b/config/site_settings.yml
index 4a99ce15102..45d99df2766 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -1900,27 +1900,9 @@ email:
- X-Spam-Status
- X-SES-Spam-Verdict
area: "email"
- enable_imap:
- default: false
- client: true
- hidden: true
- enable_imap_write:
- default: false
- hidden: true
- enable_imap_idle:
- default: false
- hidden: true
enable_smtp:
default: false
client: true
- imap_polling_period_mins:
- default: 5
- imap_polling_old_emails:
- default: 1000
- imap_polling_new_emails:
- default: 250
- imap_batch_import_email:
- default: 100
email_prefix:
default: ""
area: "email"
diff --git a/db/post_migrate/20260108044513_drop_imap_sync_logs.rb b/db/post_migrate/20260108044513_drop_imap_sync_logs.rb
new file mode 100644
index 00000000000..b82259b61b5
--- /dev/null
+++ b/db/post_migrate/20260108044513_drop_imap_sync_logs.rb
@@ -0,0 +1,10 @@
+# frozen_string_literal: true
+class DropImapSyncLogs < ActiveRecord::Migration[8.0]
+ def change
+ drop_table :imap_sync_logs, if_exists: true
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/frontend/discourse/app/components/group-imap-email-settings.gjs b/frontend/discourse/app/components/group-imap-email-settings.gjs
deleted file mode 100644
index b2fd534ed05..00000000000
--- a/frontend/discourse/app/components/group-imap-email-settings.gjs
+++ /dev/null
@@ -1,228 +0,0 @@
-/* eslint-disable ember/no-classic-components */
-import Component, { Input } from "@ember/component";
-import { fn, hash } from "@ember/helper";
-import { on } from "@ember/modifier";
-import EmberObject, { action } from "@ember/object";
-import { LinkTo } from "@ember/routing";
-import { isEmpty } from "@ember/utils";
-import { tagName } from "@ember-decorators/component";
-import { on as onEvent } from "@ember-decorators/object";
-import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
-import DButton from "discourse/components/d-button";
-import icon from "discourse/helpers/d-icon";
-import formatDate from "discourse/helpers/format-date";
-import { ajax } from "discourse/lib/ajax";
-import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
-import emailProviderDefaultSettings from "discourse/lib/email-provider-default-settings";
-import ComboBox from "discourse/select-kit/components/combo-box";
-import { or } from "discourse/truth-helpers";
-import { i18n } from "discourse-i18n";
-
-@tagName("")
-export default class GroupImapEmailSettings extends Component {
- form = null;
-
- @discourseComputed(
- "group.email_username",
- "group.email_password",
- "form.imap_server",
- "form.imap_port"
- )
- missingSettings(email_username, email_password, imap_server, imap_port) {
- return [email_username, email_password, imap_server, imap_port].some(
- (value) => isEmpty(value)
- );
- }
-
- @discourseComputed("group.imap_mailboxes")
- mailboxes(imapMailboxes) {
- if (!imapMailboxes) {
- return [];
- }
- return imapMailboxes.map((mailbox) => ({ name: mailbox, value: mailbox }));
- }
-
- @discourseComputed("group.imap_mailbox_name", "mailboxes.length")
- mailboxSelected(mailboxName, mailboxesSize) {
- return mailboxesSize === 0 || !isEmpty(mailboxName);
- }
-
- @action
- resetSettingsValid() {
- this.set("imapSettingsValid", false);
- }
-
- @onEvent("init")
- _fillForm() {
- this.set(
- "form",
- EmberObject.create({
- imap_server: this.group.imap_server,
- imap_port: (this.group.imap_port || "").toString(),
- imap_ssl: this.group.imap_ssl,
- })
- );
- }
-
- @action
- prefillSettings(provider, event) {
- event?.preventDefault();
- this.form.setProperties(emailProviderDefaultSettings(provider, "imap"));
- }
-
- @action
- testImapSettings() {
- const settings = {
- host: this.form.imap_server,
- port: this.form.imap_port,
- ssl: this.form.imap_ssl,
- username: this.group.email_username,
- password: this.group.email_password,
- };
-
- this.set("testingSettings", true);
- this.set("imapSettingsValid", false);
-
- return ajax(`/groups/${this.group.id}/test_email_settings`, {
- type: "POST",
- data: Object.assign(settings, { protocol: "imap" }),
- })
- .then(() => {
- this.set("imapSettingsValid", true);
- this.group.setProperties({
- imap_server: this.form.imap_server,
- imap_port: this.form.imap_port,
- imap_ssl: this.form.imap_ssl,
- });
- })
- .catch(popupAjaxError)
- .finally(() => this.set("testingSettings", false));
- }
-
- <template>
- <div class="group-imap-email-settings">
- <form class="groups-form form-horizontal groups-form-imap">
- <div>
- <div class="control-group">
- <label for="imap_server">{{i18n
- "groups.manage.email.credentials.imap_server"
- }}</label>
- <Input
- @type="text"
- name="imap_server"
- @value={{this.form.imap_server}}
- tabindex="8"
- {{on "change" this.resetSettingsValid}}
- />
- </div>
-
- <label for="enable_ssl_imap" class="groups-form__enable-ssl">
- <Input
- @type="checkbox"
- @checked={{this.form.imap_ssl}}
- id="enable_ssl_imap"
- tabindex="11"
- {{on "change" this.resetSettingsValid}}
- />
- {{i18n "groups.manage.email.credentials.imap_ssl"}}
- </label>
- </div>
-
- <div>
- <div class="control-group">
- <label for="imap_port">{{i18n
- "groups.manage.email.credentials.imap_port"
- }}</label>
- <Input
- @type="text"
- name="imap_port"
- @value={{this.form.imap_port}}
- tabindex="9"
- {{on "change" (fn this.resetSettingsValid this.form.imap_port)}}
- />
- </div>
- </div>
-
- <div>
- <div class="control-group group-imap-mailboxes">
- {{#if this.mailboxes}}
- <label for="imap_mailbox_name">{{i18n
- "groups.manage.email.mailboxes.synchronized"
- }}</label>
- <ComboBox
- @name="imap_mailbox_name"
- @id="imap_mailbox"
- @value={{this.group.imap_mailbox_name}}
- @valueProperty="value"
- @content={{this.mailboxes}}
- @tabindex="10"
- @onChange={{fn (mut this.group.imap_mailbox_name)}}
- @options={{hash none="groups.manage.email.mailboxes.disabled"}}
- />
- {{/if}}
- </div>
-
- </div>
- </form>
-
- <div class="control-group">
- <div class="group-imap-prefill-options">
- {{i18n "groups.manage.email.prefill.title"}}
- <a
- id="prefill_imap_gmail"
- href
- {{on "click" (fn this.prefillSettings "gmail")}}
- >{{i18n "groups.manage.email.prefill.gmail"}}</a>
- </div>
- </div>
-
- {{#unless this.mailboxSelected}}
- <div class="alert alert-error imap-no-mailbox-selected">
- {{i18n "groups.manage.email.imap_mailbox_not_selected"}}
- </div>
- {{/unless}}
-
- <div class="control-group buttons">
- <DButton
- @disabled={{or this.missingSettings this.testingSettings}}
- @action={{this.testImapSettings}}
- @icon="gear"
- @label="groups.manage.email.test_settings"
- @title="groups.manage.email.settings_required"
- tabindex="12"
- class="btn-primary test-imap-settings"
- />
-
- <ConditionalLoadingSpinner
- @size="small"
- @condition={{this.testingSettings}}
- />
-
- {{#if this.imapSettingsValid}}
- <span class="imap-settings-ok">
- {{icon "circle-check"}}
- {{i18n "groups.manage.email.imap_settings_valid"}}
- </span>
- {{/if}}
- </div>
-
- {{#if this.group.imap_updated_at}}
- <div class="group-email-last-updated-details for-imap">
- <small>
- {{i18n "groups.manage.email.last_updated"}}
- <strong>{{formatDate
- this.group.imap_updated_at
- leaveAgo="true"
- }}</strong>
- {{i18n "groups.manage.email.last_updated_by"}}
- <LinkTo
- @route="user"
- @model={{this.group.imap_updated_by.username}}
- >{{this.group.imap_updated_by.username}}</LinkTo>
- </small>
- </div>
- {{/if}}
- </div>
- </template>
-}
diff --git a/frontend/discourse/app/components/group-manage-email-settings.gjs b/frontend/discourse/app/components/group-manage-email-settings.gjs
index b56f1f09e94..5d065814fcb 100644
--- a/frontend/discourse/app/components/group-manage-email-settings.gjs
+++ b/frontend/discourse/app/components/group-manage-email-settings.gjs
@@ -3,11 +3,9 @@ import Component, { Input } from "@ember/component";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { service } from "@ember/service";
-import { htmlSafe } from "@ember/template";
import { isEmpty } from "@ember/utils";
import { tagName } from "@ember-decorators/component";
import { on as onEvent } from "@ember-decorators/object";
-import GroupImapEmailSettings from "discourse/components/group-imap-email-settings";
import GroupManageSaveButton from "discourse/components/group-manage-save-button";
import GroupSmtpEmailSettings from "discourse/components/group-smtp-email-settings";
import discourseComputed from "discourse/lib/decorators";
@@ -18,45 +16,19 @@ import { i18n } from "discourse-i18n";
export default class GroupManageEmailSettings extends Component {
@service dialog;
- imapSettingsValid = false;
smtpSettingsValid = false;
@onEvent("init")
_determineSettingsValid() {
- this.set(
- "imapSettingsValid",
- this.group.imap_enabled && this.group.imap_server
- );
this.set(
"smtpSettingsValid",
this.group.smtp_enabled && this.group.smtp_server
);
}
- @discourseComputed(
- "emailSettingsValid",
- "group.smtp_enabled",
- "group.imap_enabled"
- )
- enableImapSettings(emailSettingsValid, smtpEnabled, imapEnabled) {
- return smtpEnabled && (emailSettingsValid || imapEnabled);
- }
-
- @discourseComputed(
- "smtpSettingsValid",
- "imapSettingsValid",
- "group.smtp_enabled",
- "group.imap_enabled"
- )
- emailSettingsValid(
- smtpSettingsValid,
- imapSettingsValid,
- smtpEnabled,
- imapEnabled
- ) {
- return (
- (!smtpEnabled || smtpSettingsValid) && (!imapEnabled || imapSettingsValid)
- );
+ @discourseComputed("smtpSettingsValid", "group.smtp_enabled")
+ emailSettingsValid(smtpSettingsValid, smtpEnabled) {
+ return !smtpEnabled || smtpSettingsValid;
}
_anySmtpFieldsFilled() {
@@ -68,12 +40,6 @@ export default class GroupManageEmailSettings extends Component {
].some((value) => !isEmpty(value));
}
- _anyImapFieldsFilled() {
- return [this.group.imap_server, this.group.imap_port].some(
- (value) => !isEmpty(value)
- );
- }
-
@action
onChangeSmtpSettingsValid(valid) {
this.set("smtpSettingsValid", valid);
@@ -89,32 +55,14 @@ export default class GroupManageEmailSettings extends Component {
this.dialog.confirm({
message: i18n("groups.manage.email.smtp_disable_confirm"),
didConfirm: () => this.group.set("smtp_enabled", true),
- didCancel: () => this.group.set("imap_enabled", false),
});
}
this.group.set("smtp_enabled", event.target.checked);
}
- @action
- imapEnabledChange(event) {
- if (
- !event.target.checked &&
- this.group.imap_enabled &&
- this._anyImapFieldsFilled()
- ) {
- this.dialog.confirm({
- message: i18n("groups.manage.email.imap_disable_confirm"),
- didConfirm: () => this.group.set("imap_enabled", true),
- });
- }
-
- this.group.set("imap_enabled", event.target.checked);
- }
-
@action
afterSave() {
- // reload the group to get the updated imap_mailboxes
this.store.find("group", this.group.name).then(() => {
this._determineSettingsValid();
});
@@ -144,43 +92,9 @@ export default class GroupManageEmailSettings extends Component {
/>
{{/if}}
- {{#if this.siteSettings.enable_imap}}
- <div class="group-manage-email-imap-wrapper">
- <br />
-
- <h3>{{i18n "groups.manage.email.imap_title"}}</h3>
- <p>
- {{htmlSafe (i18n "groups.manage.email.imap_instructions")}}
- </p>
-
- <div class="alert alert-warning">{{i18n
- "groups.manage.email.imap_alpha_warning"
- }}</div>
-
- <label for="enable_imap">
- <Input
- @type="checkbox"
- disabled={{not this.enableImapSettings}}
- @checked={{this.group.imap_enabled}}
- id="enable_imap"
- tabindex="8"
- {{on "input" this.imapEnabledChange}}
- />
- {{i18n "groups.manage.email.enable_imap"}}
- </label>
-
- {{#if this.group.imap_enabled}}
- <GroupImapEmailSettings
- @group={{this.group}}
- @imapSettingsValid={{this.imapSettingsValid}}
- />
- {{/if}}
- </div>
- {{/if}}
-
<div class="group-manage-email-additional-settings-wrapper">
<div class="control-group">
- <h3>{{i18n "groups.manage.email.imap_additional_settings"}}</h3>
+ <h3>{{i18n "groups.manage.email.additional_settings"}}</h3>
<label
class="control-group-inline"
for="allow_unknown_sender_topic_replies"
diff --git a/frontend/discourse/app/lib/email-provider-default-settings.js b/frontend/discourse/app/lib/email-provider-default-settings.js
index 1176623042b..e43dabf89fd 100644
--- a/frontend/discourse/app/lib/email-provider-default-settings.js
+++ b/frontend/discourse/app/lib/email-provider-default-settings.js
@@ -1,11 +1,6 @@
import { GROUP_SMTP_SSL_MODES } from "discourse/lib/constants";
const GMAIL = {
- imap: {
- imap_server: "imap.gmail.com",
- imap_port: "993",
- imap_ssl: true,
- },
smtp: {
smtp_server: "smtp.gmail.com",
smtp_port: "587",
diff --git a/frontend/discourse/app/models/group.js b/frontend/discourse/app/models/group.js
index 385f145a22d..b4423d28859 100644
--- a/frontend/discourse/app/models/group.js
+++ b/frontend/discourse/app/models/group.js
@@ -340,11 +340,6 @@ export default class Group extends RestModel {
smtp_port: this.smtp_port,
smtp_ssl_mode: this.smtp_ssl_mode,
smtp_enabled: this.smtp_enabled,
- imap_server: this.imap_server,
- imap_port: this.imap_port,
- imap_ssl: this.imap_ssl,
- imap_mailbox_name: this.imap_mailbox_name,
- imap_enabled: this.imap_enabled,
email_username: this.email_username,
email_from_alias: this.email_from_alias,
email_password: this.email_password,
diff --git a/frontend/discourse/app/routes/group/manage/email.js b/frontend/discourse/app/routes/group/manage/email.js
index 6090f73f755..d3b53171f8d 100644
--- a/frontend/discourse/app/routes/group/manage/email.js
+++ b/frontend/discourse/app/routes/group/manage/email.js
@@ -6,7 +6,6 @@ export default class GroupManageEmail extends DiscourseRoute {
@service router;
beforeModel() {
- // cannot configure IMAP without SMTP being enabled
if (!this.siteSettings.enable_smtp) {
return this.router.transitionTo("group.manage.profile");
}
diff --git a/frontend/discourse/tests/acceptance/group-manage-email-settings-test.js b/frontend/discourse/tests/acceptance/group-manage-email-settings-test.js
index dd85e661192..6d5b71c5600 100644
--- a/frontend/discourse/tests/acceptance/group-manage-email-settings-test.js
+++ b/frontend/discourse/tests/acceptance/group-manage-email-settings-test.js
@@ -3,7 +3,6 @@ import { test } from "qunit";
import { GROUP_SMTP_SSL_MODES } from "discourse/lib/constants";
import formKit from "discourse/tests/helpers/form-kit-helper";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-import selectKit from "discourse/tests/helpers/select-kit-helper";
import { i18n } from "discourse-i18n";
acceptance("Managing Group Email Settings - SMTP Disabled", function (needs) {
@@ -22,190 +21,103 @@ acceptance("Managing Group Email Settings - SMTP Disabled", function (needs) {
});
});
-acceptance(
- "Managing Group Email Settings - SMTP Enabled, IMAP Disabled",
- function (needs) {
- needs.user();
- needs.settings({ enable_smtp: true });
-
- test("When SiteSetting.enable_smtp is true but SiteSetting.enable_imap is false", async function (assert) {
- await visit("/g/discourse/manage/email");
- assert
- .dom(".user-secondary-navigation")
- .includesText("Email", "email link is shown in the sidebar");
- assert.strictEqual(
- currentRouteName(),
- "group.manage.email",
- "it redirects to the group email page"
- );
- assert
- .dom(".group-manage-email-imap-wrapper")
- .doesNotExist("does not show IMAP settings");
- });
- }
-);
-
-acceptance(
- "Managing Group Email Settings - SMTP and IMAP Enabled",
- function (needs) {
- needs.user();
- needs.settings({ enable_smtp: true, enable_imap: true });
+acceptance("Managing Group Email Settings - SMTP Enabled", function (needs) {
+ needs.user();
+ needs.settings({ enable_smtp: true });
- needs.pretender((server, helper) => {
- server.post("/groups/47/test_email_settings", () => {
- return helper.response({
- success: "OK",
- });
+ needs.pretender((server, helper) => {
+ server.post("/groups/47/test_email_settings", () => {
+ return helper.response({
+ success: "OK",
});
- server.put("/groups/47", () => {
- return helper.response({
- success: "OK",
- });
+ });
+ server.put("/groups/47", () => {
+ return helper.response({
+ success: "OK",
});
- server.put("/admin/groups/automatic_membership_count.json", () => {
- return helper.response({
- user_count: 0,
- });
+ });
+ server.put("/admin/groups/automatic_membership_count.json", () => {
+ return helper.response({
+ user_count: 0,
});
});
+ });
- test("enabling SMTP, testing, and saving", async function (assert) {
- await visit("/g/discourse/manage/email");
- assert
- .dom(".user-secondary-navigation")
- .includesText("Email", "email link is shown in the sidebar");
- assert
- .dom("#enable_imap")
- .isDisabled("IMAP is disabled until SMTP settings are valid");
+ test("When SiteSetting.enable_smtp is true", async function (assert) {
+ await visit("/g/discourse/manage/email");
+ assert
+ .dom(".user-secondary-navigation")
+ .includesText("Email", "email link is shown in the sidebar");
+ assert.strictEqual(
+ currentRouteName(),
+ "group.manage.email",
+ "it redirects to the group email page"
+ );
+ });
- await click("#enable_smtp");
- assert.dom(".group-smtp-email-settings").exists();
+ test("enabling SMTP, testing, and saving", async function (assert) {
+ await visit("/g/discourse/manage/email");
+ assert
+ .dom(".user-secondary-navigation")
+ .includesText("Email", "email link is shown in the sidebar");
- await click("#prefill_smtp_gmail");
- assert
- .form()
- .field("smtp_server")
- .hasValue("smtp.gmail.com", "prefills SMTP server settings for gmail");
- assert
- .form()
- .field("smtp_port")
- .hasValue("587", "prefills SMTP port settings for gmail");
- assert
- .form()
- .field("smtp_ssl_mode")
- .hasValue(
- GROUP_SMTP_SSL_MODES.starttls.toString(),
- "prefills SSL mode to STARTTLS for gmail"
- );
+ await click("#enable_smtp");
+ assert.dom(".group-smtp-email-settings").exists();
- await formKit().submit();
- assert.form().hasErrors(
- {
- [i18n("groups.manage.email.credentials.username")]: "Required",
- [i18n("groups.manage.email.credentials.password")]: "Required",
- },
- "does not allow testing settings if not all fields are filled"
+ await click("#prefill_smtp_gmail");
+ assert
+ .form()
+ .field("smtp_server")
+ .hasValue("smtp.gmail.com", "prefills SMTP server settings for gmail");
+ assert
+ .form()
+ .field("smtp_port")
+ .hasValue("587", "prefills SMTP port settings for gmail");
+ assert
+ .form()
+ .field("smtp_ssl_mode")
+ .hasValue(
+ GROUP_SMTP_SSL_MODES.starttls.toString(),
+ "prefills SSL mode to STARTTLS for gmail"
);
- await formKit().field("email_username").fillIn("[email protected]");
- await formKit().field("email_password").fillIn("password");
- await formKit()
- .field("email_from_alias")
- .fillIn("[email protected]");
-
- await formKit().submit();
- await click(".group-manage-save");
-
- assert.dom(".group-manage-save-button > span").hasText("Saved!");
-
- assert
- .dom("#enable_imap")
- .isEnabled("IMAP is able to be enabled now that SMTP is saved");
-
- await click("#enable_smtp");
- assert
- .dom(".dialog-body")
- .hasText(
- i18n("groups.manage.email.smtp_disable_confirm"),
- "shows a confirm dialogue warning SMTP settings will be wiped"
- );
-
- await click(".dialog-footer .btn-primary");
- });
-
- test("enabling IMAP, testing, and saving", async function (assert) {
- await visit("/g/discourse/manage/email");
-
- await click("#enable_smtp");
- await click("#prefill_smtp_gmail");
- await formKit().field("email_username").fillIn("[email protected]");
- await formKit().field("email_password").fillIn("password");
- await formKit().submit();
- await click(".group-manage-save");
-
- assert
- .dom("#enable_imap")
- .isEnabled("IMAP is able to be enabled now that IMAP is saved");
-
- await click("#enable_imap");
-
- assert
- .dom(".test-imap-settings")
- .isDisabled(
- "does not allow testing settings if not all fields are filled"
- );
-
- await click("#prefill_imap_gmail");
- assert
- .dom("input[name='imap_server']")
- .hasValue("imap.gmail.com", "prefills IMAP server settings for gmail");
- assert
- .dom("input[name='imap_port']")
- .hasValue("993", "prefills IMAP port settings for gmail");
- assert
- .dom("#enable_ssl_imap")
- .isChecked("prefills IMAP ssl settings for gmail");
- await click(".test-imap-settings");
-
- assert.dom(".imap-settings-ok").exists("tested settings are ok");
-
- await click(".group-manage-save");
+ await formKit().submit();
+ assert.form().hasErrors(
+ {
+ [i18n("groups.manage.email.credentials.username")]: "Required",
+ [i18n("groups.manage.email.credentials.password")]: "Required",
+ },
+ "does not allow testing settings if not all fields are filled"
+ );
- assert.dom(".group-manage-save-button > span").hasText("Saved!");
+ await formKit().field("email_username").fillIn("[email protected]");
+ await formKit().field("email_password").fillIn("password");
+ await formKit()
+ .field("email_from_alias")
+ .fillIn("[email protected]");
- assert
- .dom(".imap-no-mailbox-selected")
- .exists("shows a message saying no IMAP mailbox is selected");
+ await formKit().submit();
+ await click(".group-manage-save");
- await selectKit(
- ".control-group.group-imap-mailboxes .combo-box"
- ).expand();
- await selectKit(
- ".control-group.group-imap-mailboxes .combo-box"
- ).selectRowByValue("All Mail");
- await click(".group-manage-save");
+ assert.dom(".group-manage-save-button > span").hasText("Saved!");
- assert
- .dom(".imap-no-mailbox-selected")
- .doesNotExist("no longer shows a no mailbox selected message");
+ await click("#enable_smtp");
+ assert
+ .dom(".dialog-body")
+ .hasText(
+ i18n("groups.manage.email.smtp_disable_confirm"),
+ "shows a confirm dialogue warning SMTP settings will be wiped"
+ );
- await click("#enable_imap");
- assert
- .dom(".dialog-body")
- .hasText(
- i18n("groups.manage.email.imap_disable_confirm"),
- "shows a confirm dialogue warning IMAP settings will be wiped"
- );
- await click(".dialog-footer .btn-primary");
- });
- }
-);
+ await click(".dialog-footer .btn-primary");
+ });
+});
acceptance(
- "Managing Group Email Settings - SMTP and IMAP Enabled - Settings Prefilled",
+ "Managing Group Email Settings - SMTP Enabled - Settings Prefilled",
function (needs) {
needs.user();
- needs.settings({ enable_smtp: true, enable_imap: true });
+ needs.settings({ enable_smtp: true });
needs.pretender((server, helper) => {
server.get("/groups/discourse.json", () => {
@@ -239,20 +151,6 @@ acceptance(
avatar_template:
"/letter_avatar/eviltrout/{size}/3_f9720745f5ce6dfc2b5641fca999d934.png",
},
- imap_server: "imap.gmail.com",
- imap_port: 993,
- imap_ssl: true,
- imap_mailbox_name: "INBOX",
- imap_mailboxes: ["INBOX", "[Gmail]/All Mail", "[Gmail]/Important"],
- imap_enabled: true,
- imap_updated_at: "2021-06-16T02:58:12.738Z",
- imap_updated_by: {
- id: 19,
- username: "eviltrout",
- name: "Robin Ward",
- avatar_template:
- "/letter_avatar/eviltrout/{size}/3_f9720745f5ce6dfc2b5641fca999d934.png",
- },
email_username: "[email protected]",
email_password: "password",
},
@@ -263,11 +161,10 @@ acceptance(
});
});
- test("prefills smtp and imap saved settings and shows last updated details", async function (assert) {
+ test("prefills smtp saved settings and shows last updated details", async function (assert) {
await visit("/g/discourse/manage/email");
assert.dom("#enable_smtp").isNotDisabled("SMTP is not disabled");
- assert.dom("#enable_imap").isNotDisabled("IMAP is not disabled");
assert
.form()
@@ -292,35 +189,15 @@ acceptance(
GROUP_SMTP_SSL_MODES.starttls.toString(),
"SMTP ssl mode is prefilled"
);
-
- assert
- .dom("[name='imap_server']")
- .hasValue("imap.gmail.com", "imap server is prefilled");
- assert
- .dom("[name='imap_port']")
- .hasValue("993", "imap port is prefilled");
- assert.strictEqual(
- selectKit("#imap_mailbox").header().value(),
- "INBOX",
- "imap mailbox is prefilled"
- );
-
- assert.dom(".group-email-last-updated-details.for-imap").exists();
- assert
- .dom(".group-email-last-updated-details.for-imap")
- .hasText(
- "Last updated: Jun 16, 2021 by eviltrout",
- "shows last updated imap details"
- );
});
}
);
acceptance(
- "Managing Group Email Settings - SMTP and IMAP Enabled - Email Test Invalid",
+ "Managing Group Email Settings - SMTP Enabled - Email Test Invalid",
function (needs) {
needs.user();
- needs.settings({ enable_smtp: true, enable_imap: true });
+ needs.settings({ enable_smtp: true });
needs.pretender((server, helper) => {
server.post("/groups/47/test_email_settings", () => {
@@ -333,7 +210,7 @@ acceptance(
});
});
- test("enabling IMAP, testing, and saving", async function (assert) {
+ test("shows error when SMTP test fails", async function (assert) {
await visit("/g/discourse/manage/email");
await click("#enable_smtp");
diff --git a/frontend/discourse/tests/fixtures/group-fixtures.js b/frontend/discourse/tests/fixtures/group-fixtures.js
index 2270ae7830a..7802aa63cea 100644
--- a/frontend/discourse/tests/fixtures/group-fixtures.js
+++ b/frontend/discourse/tests/fixtures/group-fixtures.js
@@ -50,7 +50,6 @@ export default {
can_see_members: true,
has_messages: true,
message_count: 2,
- imap_mailboxes: ["All Mail", "Important"],
},
extras: {
visible_group_names: ["discourse"],
@@ -80,7 +79,6 @@ export default {
has_messages: true,
message_count: 2,
default_notification_level: 2,
- imap_mailboxes: ["All Mail", "Important"],
},
extras: {
visible_group_names: ["support"],
diff --git a/lib/demon/email_sync.rb b/lib/demon/email_sync.rb
deleted file mode 100644
index 8d07145f3c5..00000000000
--- a/lib/demon/email_sync.rb
+++ /dev/null
@@ -1,245 +0,0 @@
-# frozen_string_literal: true
-
-require "demon/base"
-
-class Demon::EmailSync < ::Demon::Base
- HEARTBEAT_KEY = "email_sync_heartbeat"
- HEARTBEAT_INTERVAL = 60.seconds
-
- def self.prefix
- "email_sync"
- end
-
- def self.max_email_sync_rss
- return 0 if demons.empty?
-
- email_sync_pids = demons.map { |uid, demon| demon.pid }
-
- return 0 if email_sync_pids.empty?
-
- rss =
- `ps -eo pid,rss,args | grep '#{email_sync_pids.join("|")}' | grep -v grep | awk '{print $2}'`.split(
- "\n",
- )
- .map(&:to_i)
- .max
-
- (rss || 0) * 1024
- end
- private_class_method :max_email_sync_rss
-
- DEFAULT_MAX_ALLOWED_EMAIL_SYNC_RSS_MEGABYTES = 500
-
- def self.max_allowed_email_sync_rss
- [
- ENV["UNICORN_EMAIL_SYNC_MAX_RSS"].to_i,
- DEFAULT_MAX_ALLOWED_EMAIL_SYNC_RSS_MEGABYTES,
- ].max.megabytes
- end
- private_class_method :max_allowed_email_sync_rss
-
- if Rails.env.test?
- def self.test_cleanup
- @@email_sync_next_heartbeat_check = nil
- end
- end
-
- def self.check_email_sync_heartbeat
- if defined?(@@email_sync_next_heartbeat_check) && @@email_sync_next_heartbeat_check &&
- @@email_sync_next_heartbeat_check > Time.now.to_i
- return
- end
-
- @@email_sync_next_heartbeat_check = (Time.now + HEARTBEAT_INTERVAL).to_i
-
- should_restart = false
-
- # Restart process if it does not respond anymore
- last_heartbeat_ago = Time.now.to_i - Discourse.redis.get(HEARTBEAT_KEY).to_i
-
- if last_heartbeat_ago > HEARTBEAT_INTERVAL.to_i
- Rails.logger.warn(
- "EmailSync heartbeat test failed (last heartbeat was #{last_heartbeat_ago}s ago), restarting",
- )
-
- should_restart = true
- end
-
- # Restart process if memory usage is too high
- if !should_restart && (email_sync_rss = max_email_sync_rss) > max_allowed_email_sync_rss
- Rails.logger.warn(
- "EmailSync is consuming too much memory (using: %0.2fM) for '%s', restarting" %
- [(email_sync_rss.to_f / 1.megabyte), HOSTNAME],
- )
-
- should_restart = true
- end
-
- restart if should_restart
- end
-
- private
-
- def suppress_stdout
- false
- end
-
- def suppress_stderr
- false
- end
-
- def start_thread(db, group)
- Thread.new do
- RailsMultisite::ConnectionManagement.with_connection(db) do
- ImapSyncLog.debug("Thread started for group #{group.name} in db #{db}", group, db: false)
- begin
- syncer = Imap::Sync.new(group)
- rescue Net::IMAP::NoResponseError => e
- group.update(imap_last_error: e.message)
- Thread.exit
- end
-
- @sync_lock.synchronize { @sync_data[db][group.id][:syncer] = syncer }
-
- status = nil
- idle = false
-
- while @running && group.reload.imap_mailbox_name.present?
- ImapSyncLog.debug("Processing mailbox for group #{group.name} in db #{db}", group)
- status =
- syncer.process(
- idle: syncer.can_idle? && status && status[:remaining] == 0,
- old_emails_limit: status && status[:remaining] > 0 ? 0 : nil,
- )
-
- if !syncer.can_idle? && status[:remaining] == 0
- ImapSyncLog.debug(
- "Going to sleep for group #{group.name} in db #{db} to wait for new emails",
- group,
- db: false,
- )
-
- # Thread goes into sleep for a bit so it is better to return any
- # connection back to the pool.
- ActiveRecord::Base.connection_handler.clear_active_connections!
-
- sleep SiteSetting.imap_polling_period_mins.minutes
- end
- end
-
- syncer.disconnect!
- end
- end
- end
-
- def kill_threads
- # This is not really safe so the caller should ensure it happens in a
- # thread-safe context.
- # It should be safe when called from within a `trap` (there are no
- # synchronization primitives available anyway).
- @running = false
-
- @sync_data.each { |db, sync_data| sync_data.each { |_, data| kill_and_disconnect!(data) } }
-
- exit 0
- end
-
- def after_fork
- log("[EmailSync] Loading EmailSync in process id #{Process.pid}")
-
- loop do
- break if Discourse.redis.set(HEARTBEAT_KEY, Time.now.to_i, ex: HEARTBEAT_INTERVAL, nx: true)
- sleep HEARTBEAT_INTERVAL
- end
-
- log("[EmailSync] Starting EmailSync main thread")
-
- @running = true
- @sync_data = {}
- @sync_lock = Mutex.new
-
- trap("INT") { kill_threads }
- trap("TERM") { kill_threads }
- trap("HUP") { kill_threads }
-
- while @running
- Discourse.redis.set(HEARTBEAT_KEY, Time.now.to_i, ex: HEARTBEAT_INTERVAL)
-
- # Kill all threads for databases that no longer exist
- all_dbs = Set.new(RailsMultisite::ConnectionManagement.all_dbs)
- @sync_data.filter! do |db, sync_data|
- next true if all_dbs.include?(db)
-
- sync_data.each { |_, data| kill_and_disconnect!(data) }
-
- false
- end
-
- RailsMultisite::ConnectionManagement.each_connection do |db|
- next if !SiteSetting.enable_imap
-
- groups = Group.with_imap_configured.index_by(&:id)
-
- @sync_lock.synchronize do
- @sync_data[db] ||= {}
-
- # Kill threads for group's mailbox that are no longer synchronized.
- @sync_data[db].filter! do |group_id, data|
- next true if groups[group_id] && data[:thread]&.alive? && !data[:syncer]&.disconnected?
-
- if !groups[group_id]
- ImapSyncLog.warn(
- "Killing thread for group because mailbox is no longer synced",
- group_id,
- )
- else
- ImapSyncLog.warn("Thread for group is dead", group_id)
- end
-
- kill_and_disconnect!(data)
- false
- end
-
- # Spawn new threads for groups that are now synchronized.
- groups.each do |group_id, group|
- if !@sync_data[db][group_id]
- ImapSyncLog.debug(
- "Starting thread for group #{group.name} mailbox #{group.imap_mailbox_name}",
- group,
- db: false,
- )
-
- @sync_data[db][group_id] = { thread: start_thread(db, group), syncer: nil }
- end
- end
- end
- end
-
- # Thread goes into sleep for a bit so it is better to return any
- # connection back to the pool.
- ActiveRecord::Base.connection_handler.clear_active_connections!
-
- sleep 5
- end
-
- @sync_lock.synchronize { kill_threads }
- Discourse.redis.del(HEARTBEAT_KEY)
- exit 0
- rescue => e
- log("#{e.message}: #{e.backtrace.join("\n")}")
- exit 1
- end
-
- def kill_and_disconnect!(data)
- data[:thread].kill
- data[:thread].join
-
- begin
- data[:syncer]&.disconnect!
- rescue Net::IMAP::ResponseError => err
- log(
- "[EmailSync] Encountered a response error when disconnecting: #{err}\n#{err.backtrace.join("\n")}",
- )
- end
- end
-end
diff --git a/lib/email/receiver.rb b/lib/email/receiver.rb
index ede0f3bd944..80f124e9dfe 100644
--- a/lib/email/receiver.rb
+++ b/lib/email/receiver.rb
@@ -127,7 +127,7 @@ module Email
begin
# If we find an existing incoming email record with the exact same `message_id`
# do not create a new `IncomingEmail` record to avoid double ups.
- return if @incoming_email = find_existing_and_update_imap
+ return if @incoming_email = IncomingEmail.find_by(message_id: @message_id)
Email::Validator.ensure_valid!(@mail)
@@ -148,33 +148,6 @@ module Email
end
end
- def find_existing_and_update_imap
- return unless incoming_email = IncomingEmail.find_by(message_id: @message_id)
-
- # If we are not doing this for IMAP purposes just return the record.
- return incoming_email if @opts[:imap_uid].blank?
-
- # If the message_id matches the post id regexp then we
- # generated the message_id not the imap server, e.g. in GroupSmtpEmail,
- # so we want to update the incoming email because it will
- # be missing IMAP details.
- #
- # Otherwise the incoming email is a completely new one from the IMAP
- # server (e.g. a message_id generated by Gmail) and does not need to
- # be updated, because message_ids from the IMAP server are not guaranteed
- # to be unique.
- return unless Email::MessageIdService.discourse_generated_message_id?(@message_id)
-
- incoming_email.update(
- imap_uid_validity: @opts[:imap_uid_validity],
- imap_uid: @opts[:imap_uid],
- imap_group_id: @opts[:imap_group_id],
- imap_sync: false,
- )
-
- incoming_email
- end
-
def is_blocked?
return false if SiteSetting.ignore_by_title.blank?
Regexp.new(SiteSetting.ignore_by_title, Regexp::IGNORECASE) =~ @mail.subject
@@ -190,10 +163,6 @@ module Email
from_address: @from_email,
to_addresses: @mail.to,
cc_addresses: cc_addresses,
- imap_uid_validity: @opts[:imap_uid_validity],
- imap_uid: @opts[:imap_uid],
- imap_group_id: @opts[:imap_group_id],
- imap_sync: false,
created_via: IncomingEmail.created_via_types[@opts[:source] || :unknown],
)
end
diff --git a/lib/imap/providers/detector.rb b/lib/imap/providers/detector.rb
deleted file mode 100644
index 7ad50c4ea28..00000000000
--- a/lib/imap/providers/detector.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-# frozen_string_literal: true
-
-module Imap
- module Providers
- class Detector
- def self.init_with_detected_provider(config)
- if config[:server] == "imap.gmail.com"
- return Imap::Providers::Gmail.new(config[:server], config)
- end
- Imap::Providers::Generic.new(config[:server], config)
- end
- end
- end
-end
diff --git a/lib/imap/providers/generic.rb b/lib/imap/providers/generic.rb
deleted file mode 100644
index 59f43d35f2d..00000000000
--- a/lib/imap/providers/generic.rb
+++ /dev/null
@@ -1,320 +0,0 @@
-# frozen_string_literal: true
-
-require "net/imap"
-
-module Imap
- module Providers
- class WriteDisabledError < StandardError
- end
-
- class TrashedMailResponse
- attr_accessor :trashed_emails, :trash_uid_validity
- end
-
- class SpamMailResponse
- attr_accessor :spam_emails, :spam_uid_validity
- end
-
- class BasicMail
- attr_accessor :uid, :message_id
-
- def initialize(uid: nil, message_id: nil)
- @uid = uid
- @message_id = message_id
- end
- end
-
- class Generic
- def initialize(server, options = {})
- @server = server
- @port = options[:port] || 993
- @ssl = options[:ssl] || true
- @username = options[:username]
- @password = options[:password]
- @timeout = options[:timeout] || 10
- end
-
- def account_digest
- @account_digest ||= Digest::MD5.hexdigest("#{@username}:#{@server}")
- end
-
- def imap
- @imap ||= Net::IMAP.new(@server, port: @port, ssl: @ssl, open_timeout: @timeout)
- end
-
- def disconnected?
- @imap && @imap.disconnected?
- end
-
- def connect!
- imap.login(@username, @password)
- end
-
- def disconnect!
- begin
- imap.logout
- rescue StandardError
- nil
- end
- imap.disconnect
- end
-
- def can?(capability)
- @capabilities ||= imap.responses["CAPABILITY"][-1] || imap.capability
- @capabilities.include?(capability)
- end
-
- def uids(opts = {})
- if opts[:from] && opts[:to]
- imap.uid_search("UID #{opts[:from]}:#{opts[:to]}")
- elsif opts[:from]
- imap.uid_search("UID #{opts[:from]}:*")
- elsif opts[:to]
- imap.uid_search("UID 1:#{opts[:to]}")
- else
- imap.uid_search("ALL")
- end
- end
-
- def labels
- @labels ||=
- begin
- labels = {}
-
- list_mailboxes.each do |name|
- if tag = to_tag(name)
- labels[tag] = name
- end
- end
-
- labels
- end
- end
-
- def open_mailbox(mailbox_name, write: false)
- if write
- if !SiteSetting.enable_imap_write
- raise WriteDisabledError.new("Two-way IMAP sync is disabled! Cannot write to inbox.")
- end
- imap.select(mailbox_name)
- else
- imap.examine(mailbox_name)
- end
-
- @open_mailbox_name = mailbox_name
- @open_mailbox_write = write
-
- { uid_validity: imap.responses["UIDVALIDITY"][-1] }
- end
-
- def emails(uids, fields, opts = {})
- fetched = imap.uid_fetch(uids, fields)
-
- # This will happen if the email does not exist in the provided mailbox.
- # It may have been deleted or otherwise moved, e.g. if deleted in Gmail
- # it will end up in "[Gmail]/Bin"
- return [] if fetched.nil?
-
- fetched.map do |email|
- attributes = {}
-
- fields.each { |field| attributes[field] = email.attr[field] }
-
- attributes
- end
- end
-
- def store(uid, attribute, old_set, new_set)
- additions = new_set.reject { |val| old_set.include?(val) }
- imap.uid_store(uid, "+#{attribute}", additions) if additions.length > 0
- removals = old_set.reject { |val| new_set.include?(val) }
- imap.uid_store(uid, "-#{attribute}", removals) if removals.length > 0
- end
-
- def to_tag(label)
- label = DiscourseTagging.clean_tag(label.to_s)
- label if label != "inbox" && label != "sent"
- end
-
- def tag_to_flag(tag)
- :Seen if tag == "seen"
- end
-
- def tag_to_label(tag)
- tag
- end
-
- def list_mailboxes(attr_filter = nil)
- # Lists all the mailboxes but just returns the names.
- list_mailboxes_with_attributes(attr_filter).map(&:name)
- end
-
- def list_mailboxes_with_attributes(attr_filter = nil)
- # Basically, list all mailboxes in the root of the server.
- # ref: https://tools.ietf.org/html/rfc3501#section-6.3.8
- imap
- .list("", "*")
- .reject do |m|
- # Noselect cannot be selected with the SELECT command.
- # technically we could use this for readonly mode when
- # SiteSetting.imap_write is disabled...maybe a later TODO
- # ref: https://tools.ietf.org/html/rfc3501#section-7.2.2
- m.attr.include?(:Noselect)
- end
- .select do |m|
- # There are Special-Use mailboxes denoted by an attribute. For
- # example, some common ones are \Trash or \Sent.
- # ref: https://tools.ietf.org/html/rfc6154
- if attr_filter
- m.attr.include? attr_filter
- else
- true
- end
- end
- end
-
- def filter_mailboxes(mailboxes)
- # we do not want to filter out any mailboxes for generic providers,
- # because we do not know what they are ahead of time
- mailboxes
- end
-
- def archive(uid)
- # do nothing by default, just removing the Inbox label should be enough
- end
-
- def unarchive(uid)
- # same as above
- end
-
- # Look for the special Trash XLIST attribute.
- def trash_mailbox
- Discourse
- .cache
- .fetch("imap_trash_mailbox_#{account_digest}", expires_in: 30.minutes) do
- list_mailboxes(:Trash).first
- end
- end
-
- # Look for the special Junk XLIST attribute.
- def spam_mailbox
- Discourse
- .cache
- .fetch("imap_spam_mailbox_#{account_digest}", expires_in: 30.minutes) do
- list_mailboxes(:Junk).first
- end
- end
-
- # open the trash mailbox for inspection or writing. after the yield we
- # close the trash and reopen the original mailbox to continue operations.
- # the normal open_mailbox call can be made if more extensive trash ops
- # need to be done.
- def open_trash_mailbox(write: false)
- open_mailbox_before_trash = @open_mailbox_name
- open_mailbox_before_trash_write = @open_mailbox_write
-
- trash_uid_validity = open_mailbox(trash_mailbox, write: write)[:uid_validity]
-
- yield(trash_uid_validity) if block_given?
-
- open_mailbox(open_mailbox_before_trash, write: open_mailbox_before_trash_write)
- trash_uid_validity
- end
-
- # open the spam mailbox for inspection or writing. after the yield we
- # close the spam and reopen the original mailbox to continue operations.
- # the normal open_mailbox call can be made if more extensive spam ops
- # need to be done.
- def open_spam_mailbox(write: false)
- open_mailbox_before_spam = @open_mailbox_name
- open_mailbox_before_spam_write = @open_mailbox_write
-
- spam_uid_validity = open_mailbox(spam_mailbox, write: write)[:uid_validity]
-
- yield(spam_uid_validity) if block_given?
-
- open_mailbox(open_mailbox_before_spam, write: open_mailbox_before_spam_write)
- spam_uid_validity
- end
-
- def find_trashed_by_message_ids(message_ids)
- trashed_emails = []
- trash_uid_validity =
- open_trash_mailbox do
- trashed_email_uids = find_uids_by_message_ids(message_ids)
- if trashed_email_uids.any?
- trashed_emails =
- emails(trashed_email_uids, %w[UID ENVELOPE]).map do |e|
- BasicMail.new(
- message_id: Email::MessageIdService.message_id_clean(e["ENVELOPE"].message_id),
- uid: e["UID"],
- )
- end
- end
- end
-
- TrashedMailResponse.new.tap do |resp|
- resp.trashed_emails = trashed_emails
- resp.trash_uid_validity = trash_uid_validity
- end
- end
-
- def find_spam_by_message_ids(message_ids)
- spam_emails = []
- spam_uid_validity =
- open_spam_mailbox do
- spam_email_uids = find_uids_by_message_ids(message_ids)
- if spam_email_uids.any?
- spam_emails =
- emails(spam_email_uids, %w[UID ENVELOPE]).map do |e|
- BasicMail.new(
- message_id: Email::MessageIdService.message_id_clean(e["ENVELOPE"].message_id),
- uid: e["UID"],
- )
- end
- end
- end
-
- SpamMailResponse.new.tap do |resp|
- resp.spam_emails = spam_emails
- resp.spam_uid_validity = spam_uid_validity
- end
- end
-
- def find_uids_by_message_ids(message_ids)
- header_message_id_terms =
- message_ids.map do |msgid|
- "HEADER Message-ID '#{Email::MessageIdService.message_id_rfc_format(msgid)}'"
- end
-
- # OR clauses are written in Polish notation...so the query looks like this:
- # OR OR HEADER Message-ID XXXX HEADER Message-ID XXXX HEADER Message-ID XXXX
- or_clauses = "OR " * (header_message_id_terms.length - 1)
- query = "#{or_clauses}#{header_message_id_terms.join(" ")}"
-
- imap.uid_search(query)
- end
-
- def trash(uid)
- # MOVE is way easier than doing the COPY \Deleted EXPUNGE dance ourselves.
- # It is supported by Gmail and Outlook.
- if can?("MOVE")
- trash_move(uid)
- else
- # default behaviour for IMAP servers is to add the \Deleted flag
- # then EXPUNGE the mailbox which permanently deletes these messages
- # https://tools.ietf.org/html/rfc3501#section-6.4.3
- #
- # TODO: We may want to add the option at some point to copy to some
- # other mailbox first before doing this (e.g. Trash)
- store(uid, "FLAGS", [], ["\\Deleted"])
- imap.expunge
- end
- end
-
- def trash_move(uid)
- # up to the provider
- end
- end
- end
-end
diff --git a/lib/imap/providers/gmail.rb b/lib/imap/providers/gmail.rb
deleted file mode 100644
index d1648a0cc6e..00000000000
--- a/lib/imap/providers/gmail.rb
+++ /dev/null
@@ -1,222 +0,0 @@
-# frozen_string_literal: true
-
-module Imap
- module Providers
- # Gmail has a special header for both labels (X-GM-LABELS) and their
- # threading system (X-GM-THRID). We need to monkey-patch Net::IMAP to
- # get access to these. Also the archiving functionality is custom,
- # all UIDs in a thread must have the \\Inbox label removed.
- #
- class Gmail < Generic
- X_GM_LABELS = "X-GM-LABELS"
- X_GM_THRID = "X-GM-THRID"
-
- def imap
- @imap ||= super.tap { |imap| apply_gmail_patch(imap) }
- end
-
- def emails(uids, fields, opts = {})
- # gmail has a special header for labels
- fields[fields.index("LABELS")] = X_GM_LABELS if fields.include?("LABELS")
-
- emails = super(uids, fields, opts)
-
- emails.each do |email|
- email["LABELS"] = Array(email["LABELS"])
-
- if email[X_GM_LABELS]
- email["LABELS"] << Array(email.delete(X_GM_LABELS))
- email["LABELS"].flatten!
- end
-
- email["LABELS"] << '\\Inbox' if @open_mailbox_name == "INBOX"
-
- email["LABELS"].uniq!
- end
-
- emails
- end
-
- def store(uid, attribute, old_set, new_set)
- attribute = X_GM_LABELS if attribute == "LABELS"
- super(uid, attribute, old_set, new_set)
- end
-
- def to_tag(label)
- # Label `\\Starred` is Gmail equivalent of :Flagged (both present)
- return "starred" if label == :Flagged
- return if label == "[Gmail]/All Mail"
-
- label = label.to_s.gsub("[Gmail]/", "")
- super(label)
- end
-
- def tag_to_flag(tag)
- return :Flagged if tag == "starred"
-
- super(tag)
- end
-
- def tag_to_label(tag)
- return '\\Important' if tag == "important"
- return '\\Starred' if tag == "starred"
-
- super(tag)
- end
-
- # All emails in the thread must be archived in Gmail for the thread
- # to get removed from the inbox
- def archive(uid)
- thread_id = thread_id_from_uid(uid)
- emails_to_archive = emails_in_thread(thread_id)
- emails_to_archive.each do |email|
- labels = email["LABELS"]
- new_labels = labels.reject { |l| l == "\\Inbox" }
- store(email["UID"], "LABELS", labels, new_labels)
- end
- ImapSyncLog.log(
- "Thread ID #{thread_id} (UID #{uid}) archived in Gmail mailbox for #{@username}",
- :debug,
- )
- end
-
- # Though Gmail considers the email thread unarchived if the first email
- # has the \\Inbox label applied, we want to do this to all emails in the
- # thread to be consistent with archive behaviour.
- def unarchive(uid)
- thread_id = thread_id_from_uid(uid)
- emails_to_unarchive = emails_in_thread(thread_id)
- emails_to_unarchive.each do |email|
- labels = email["LABELS"]
- new_labels = labels.dup
- new_labels << "\\Inbox" if !new_labels.include?("\\Inbox")
- store(email["UID"], "LABELS", labels, new_labels)
- end
- ImapSyncLog.log(
- "Thread ID #{thread_id} (UID #{uid}) unarchived in Gmail mailbox for #{@username}",
- :debug,
- )
- end
-
- def thread_id_from_uid(uid)
- fetched = imap.uid_fetch(uid, [X_GM_THRID])
- raise "Thread not found for UID #{uid}!" if !fetched
-
- fetched.last.attr[X_GM_THRID]
- end
-
- def emails_in_thread(thread_id)
- uids_to_fetch = imap.uid_search("#{X_GM_THRID} #{thread_id}")
- emails(uids_to_fetch, %w[UID LABELS])
- end
-
- def trash_move(uid)
- thread_id = thread_id_from_uid(uid)
- email_uids_to_trash = emails_in_thread(thread_id).map { |e| e["UID"] }
-
- imap.uid_move(email_uids_to_trash, trash_mailbox)
- ImapSyncLog.log(
- "Thread ID #{thread_id} (UID #{uid}) trashed in Gmail mailbox for #{@username}",
- :debug,
- )
- { trash_uid_validity: open_trash_mailbox, email_uids_to_trash: email_uids_to_trash }
- end
-
- # Some mailboxes are just not useful or advisable to sync with. This is
- # used for the dropdown in the UI where we allow the user to select the
- # IMAP mailbox to sync with.
- def filter_mailboxes(mailboxes_with_attributes)
- mailboxes_with_attributes
- .reject { |mb| (mb.attr & %i[Drafts Sent Junk Flagged Trash]).any? }
- .map(&:name)
- end
-
- private
-
- def apply_gmail_patch(imap)
- class << imap.instance_variable_get("@parser")
- # Modified version of the original `msg_att` from here:
- # https://github.com/ruby/ruby/blob/1cc8ff001da217d0e98d13fe61fbc9f5547ef722/lib/net/imap.rb#L2346
- #
- # This is done so we can extract X-GM-LABELS, X-GM-MSGID, and
- # X-GM-THRID, all Gmail extended attributes.
- #
- def msg_att(n)
- match(T_LPAR)
- attr = {}
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- next
- end
- case token.value
- when /\A(?:ENVELOPE)\z/ni
- name, val = envelope_data
- when /\A(?:FLAGS)\z/ni
- name, val = flags_data
- when /\A(?:INTERNALDATE)\z/ni
- name, val = internaldate_data
- when /\A(?:RFC822(?:\.HEADER|\.TEXT)?)\z/ni
- name, val = rfc822_text
- when /\A(?:RFC822\.SIZE)\z/ni
- name, val = rfc822_size
- when /\A(?:BODY(?:STRUCTURE)?)\z/ni
- name, val = body_data
- when /\A(?:UID)\z/ni
- name, val = uid_data
- when /\A(?:MODSEQ)\z/ni
- name, val = modseq_data
-
- # Adding support for GMail extended attributes.
- when /\A(?:X-GM-LABELS)\z/ni
- name, val = label_data
- when /\A(?:X-GM-MSGID)\z/ni
- name, val = uid_data
- when /\A(?:X-GM-THRID)\z/ni
- name, val = uid_data
- # End custom support for Gmail.
- else
- parse_error("unknown attribute `%s' for {%d}", token.value, n)
- end
- attr[name] = val
- end
- attr
- end
-
- def label_data
- token = match(T_ATOM)
- name = token.value.upcase
-
- match(T_SPACE)
- match(T_LPAR)
-
- result = []
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- end
-
- token = lookahead
- if string_token?(token)
- result.push(string)
- else
- result.push(atom)
- end
- end
- [name, result]
- end
- end
- end
- end
- end
-end
diff --git a/lib/imap/sync.rb b/lib/imap/sync.rb
deleted file mode 100644
index 98ce2e834f0..00000000000
--- a/lib/imap/sync.rb
+++ /dev/null
@@ -1,484 +0,0 @@
-# frozen_string_literal: true
-
-require "net/imap"
-
-module Imap
- class Sync
- def initialize(group, opts = {})
- @group = group
- @provider = Imap::Providers::Detector.init_with_detected_provider(@group.imap_config)
- connect!
- end
-
- def connect!
- @provider.connect!
- end
-
- def disconnect!
- @provider.disconnect!
- end
-
- def disconnected?
- @provider.disconnected?
- end
-
- def can_idle?
- SiteSetting.enable_imap_idle && @provider.can?("IDLE")
- end
-
- def process(idle: false, import_limit: nil, old_emails_limit: nil, new_emails_limit: nil)
- raise "disconnected" if disconnected?
-
- import_limit ||= SiteSetting.imap_batch_import_email
- old_emails_limit ||= SiteSetting.imap_polling_old_emails
- new_emails_limit ||= SiteSetting.imap_polling_new_emails
-
- # IMAP server -> Discourse (download): discovers updates to old emails
- # (synced emails) and fetches new emails.
-
- # TODO: Use `Net::IMAP.encode_utf7(@group.imap_mailbox_name)`?
- @status = @provider.open_mailbox(@group.imap_mailbox_name)
-
- if @status[:uid_validity] != @group.imap_uid_validity
- # If UID validity changes, the whole mailbox must be synchronized (all
- # emails are considered new and will be associated to existent topics
- # in Email::Receiver by matching Message-Ids).
- ImapSyncLog.warn(
- "UIDVALIDITY = #{@status[:uid_validity]} does not match expected #{@group.imap_uid_validity}, invalidating IMAP cache and resyncing emails for mailbox #{@group.imap_mailbox_name}",
- @group,
- )
- @group.imap_last_uid = 0
- end
-
- if idle && !can_idle?
- ImapSyncLog.warn(
- "IMAP server for group cannot IDLE or imap idle site setting is disabled",
- @group,
- )
- idle = false
- end
-
- if idle
- raise "IMAP IDLE is disabled" if !SiteSetting.enable_imap_idle
-
- # Thread goes into sleep and it is better to return any connection
- # back to the pool.
- ActiveRecord::Base.connection_handler.clear_active_connections!
-
- idle_polling_mins = SiteSetting.imap_polling_period_mins.minutes.to_i
- ImapSyncLog.debug(
- "Going IDLE for #{idle_polling_mins} seconds to wait for more work",
- @group,
- db: false,
- )
-
- @provider
- .imap
- .idle(idle_polling_mins) do |resp|
- if resp.kind_of?(Net::IMAP::UntaggedResponse) && resp.name == "EXISTS"
- @provider.imap.idle_done
- end
- end
- end
-
- # Fetching UIDs of old (already imported into Discourse, but might need
- # update) and new (not downloaded yet) emails.
- if @group.imap_last_uid == 0
- old_uids = []
- new_uids = @provider.uids
- else
- old_uids = @provider.uids(to: @group.imap_last_uid) # 1 .. seen
- new_uids = @provider.uids(from: @group.imap_last_uid + 1) # seen+1 .. inf
- end
-
- # Sometimes, new_uids contains elements from old_uids.
- new_uids = new_uids - old_uids
-
- ImapSyncLog.debug(
- "Remote email server has #{old_uids.size} old emails and #{new_uids.size} new emails",
- @group,
- )
-
- all_old_uids_size = old_uids.size
- all_new_uids_size = new_uids.size
-
- @group.update_columns(
- imap_last_error: nil,
- imap_old_emails: all_old_uids_size,
- imap_new_emails: all_new_uids_size,
- )
-
- import_mode = import_limit > -1 && new_uids.size > import_limit
- old_uids = old_uids.sample(old_emails_limit).sort! if old_emails_limit > -1
- new_uids = new_uids[0..new_emails_limit - 1] if new_emails_limit > 0
-
- # if there are no old_uids that is OK, this could indicate that some
- # UIDs have been sent to the trash
- process_old_uids(old_uids)
-
- if new_uids.present?
- process_new_uids(new_uids, import_mode, all_old_uids_size, all_new_uids_size)
- end
-
- # Discourse -> IMAP server (upload): syncs updated flags and labels.
- sync_to_server
-
- { remaining: all_new_uids_size - new_uids.size }
- end
-
- def update_topic(email, incoming_email, opts = {})
- if !incoming_email || incoming_email.imap_sync || !incoming_email.topic ||
- incoming_email.post&.post_number != 1
- return
- end
-
- update_topic_archived_state(email, incoming_email, opts)
- update_topic_tags(email, incoming_email, opts)
- end
-
- private
-
- def process_old_uids(old_uids)
- ImapSyncLog.debug("Syncing #{old_uids.size} randomly-selected old emails", @group)
- emails = old_uids.empty? ? [] : @provider.emails(old_uids, %w[UID FLAGS LABELS ENVELOPE])
- emails.each do |email|
- incoming_email =
- IncomingEmail.find_by(
- imap_uid_validity: @status[:uid_validity],
- imap_uid: email["UID"],
- imap_group_id: @group.id,
- )
-
- if incoming_email.present?
- update_topic(email, incoming_email, mailbox_name: @group.imap_mailbox_name)
- else
- # try finding email by message-id instead, we may be able to set the uid etc.
- incoming_email =
- IncomingEmail
- .where(
- message_id: Email::MessageIdService.message_id_clean(email["ENVELOPE"].message_id),
- imap_uid: nil,
- imap_uid_validity: nil,
- )
- .where("to_addresses LIKE ?", "%#{@group.email_username}%")
- .first
-
- if incoming_email
- incoming_email.update(
- imap_uid_validity: @status[:uid_validity],
- imap_uid: email["UID"],
- imap_group_id: @group.id,
- )
- update_topic(email, incoming_email, mailbox_name: @group.imap_mailbox_name)
- else
- ImapSyncLog.warn(
- "Could not find old email (UIDVALIDITY = #{@status[:uid_validity]}, UID = #{email["UID"]})",
- @group,
- )
- end
- end
- end
-
- handle_missing_uids(old_uids)
- end
-
- def handle_missing_uids(old_uids)
- # If there are any UIDs for the mailbox missing from old_uids, this means they have been moved
- # to some other mailbox in the mail server. They could be possibly deleted. first we can check
- # if they have been deleted and if so delete the associated post/topic. then the remaining we
- # can just remove the imap details from the IncomingEmail table and if they end up back in the
- # original mailbox then they will be picked up in a future resync.
- existing_incoming =
- IncomingEmail
- .includes(:post)
- .where(imap_group_id: @group.id, imap_uid_validity: @status[:uid_validity])
- .where.not(imap_uid: nil)
-
- existing_uids = existing_incoming.map(&:imap_uid)
- missing_uids = existing_uids - old_uids
- missing_message_ids =
- existing_incoming
- .select { |incoming| missing_uids.include?(incoming.imap_uid) }
- .map(&:message_id)
-
- return if missing_message_ids.empty?
-
- # This can be done because Message-ID is unique on a mail server between mailboxes,
- # where the UID will have changed when moving into the Trash mailbox. We need to get
- # the new UID from the trash.
- potential_spam = []
- response = @provider.find_trashed_by_message_ids(missing_message_ids)
- existing_incoming.each do |incoming|
- matching_trashed =
- response.trashed_emails.find { |email| email.message_id == incoming.message_id }
-
- if !matching_trashed
- potential_spam << incoming
- next
- end
-
- # if we deleted the topic/post ourselves in discourse then the post will
- # not exist, and this sync is just updating the old UIDs to the new ones
- # in the trash, and we don't need to re-destroy the post
- if incoming.post
- ImapSyncLog.debug(
- "Deleting post ID #{incoming.post_id}, topic id #{incoming.topic_id}; email has been deleted on the IMAP server.",
- @group,
- )
- PostDestroyer.new(
- Discourse.system_user,
- incoming.post,
- context: I18n.t("staff_action_logs.imap_email_deleted"),
- ).destroy
- end
-
- # the email has moved mailboxes, we don't want to try trashing again next time
- ImapSyncLog.debug(
- "Updating incoming ID #{incoming.id} uid data FROM [UID #{incoming.imap_uid} | UIDVALIDITY #{incoming.imap_uid_validity}] TO [UID #{matching_trashed.uid} | UIDVALIDITY #{response.trash_uid_validity}] (TRASHED)",
- @group,
- )
- incoming.update(
- imap_uid_validity: response.trash_uid_validity,
- imap_uid: matching_trashed.uid,
- )
- end
-
- # This can be done because Message-ID is unique on a mail server between mailboxes,
- # where the UID will have changed when moving into the Trash mailbox. We need to get
- # the new UID from the spam.
- response = @provider.find_spam_by_message_ids(missing_message_ids)
- potential_spam.each do |incoming|
- matching_spam =
- response.spam_emails.find { |email| email.message_id == incoming.message_id }
-
- # if the email is not in the trash or spam then we don't know where it is... could
- # be in any mailbox on the server or could be permanently deleted.
- if !matching_spam
- ImapSyncLog.debug(
- "Email for incoming ID #{incoming.id} (#{incoming.message_id}) could not be found in the group mailbox, trash, or spam. It could be in another mailbox or permanently deleted.",
- @group,
- )
- incoming.update(imap_missing: true)
- next
- end
-
- # if we deleted the topic/post ourselves in discourse then the post will
- # not exist, and this sync is just updating the old UIDs to the new ones
- # in the spam, and we don't need to re-destroy the post
- if incoming.post
- ImapSyncLog.debug(
- "Deleting post ID #{incoming.post_id}, topic id #{incoming.topic_id}; email has been moved to spam on the IMAP server.",
- @group,
- )
- PostDestroyer.new(
- Discourse.system_user,
- incoming.post,
- context: I18n.t("staff_action_logs.imap_email_marked_as_spam"),
- ).destroy
- end
-
- # the email has moved mailboxes, we don't want to try marking as spam again next time
- ImapSyncLog.debug(
- "Updating incoming ID #{incoming.id} uid data FROM [UID #{incoming.imap_uid} | UIDVALIDITY #{incoming.imap_uid_validity}] TO [UID #{matching_spam.uid} | UIDVALIDITY #{response.spam_uid_validity}] (SPAM)",
- @group,
- )
- incoming.update(imap_uid_validity: response.spam_uid_validity, imap_uid: matching_spam.uid)
- end
- end
-
- def process_new_uids(new_uids, import_mode, all_old_uids_size, all_new_uids_size)
- ImapSyncLog.debug("Syncing #{new_uids.size} new emails (oldest first)", @group)
-
- emails = @provider.emails(new_uids, %w[UID FLAGS LABELS RFC822])
- processed = 0
-
- # TODO (maybe): We might need something here to exclusively handle
- # the UID of the incoming email, so we don't end up with a race condition
- # where the same UID is handled multiple times before the group imap_X
- # columns are updated.
- emails.each do |email|
- # Synchronously process emails because the order of emails matter
- # (for example replies must be processed after the original email
- # to have a topic where the reply can be posted).
- begin
- receiver =
- Email::Receiver.new(
- email["RFC822"],
- allow_auto_generated: true,
- import_mode: import_mode,
- destinations: [@group],
- imap_uid_validity: @status[:uid_validity],
- imap_uid: email["UID"],
- imap_group_id: @group.id,
- source: :imap,
- )
- receiver.process!
-
- update_topic(email, receiver.incoming_email, mailbox_name: @group.imap_mailbox_name)
- rescue Email::Receiver::ProcessingError => e
- ImapSyncLog.warn(
- "Could not process (UIDVALIDITY = #{@status[:uid_validity]}, UID = #{email["UID"]}): #{e.message}",
- @group,
- )
- end
-
- processed += 1
- @group.update_columns(
- imap_uid_validity: @status[:uid_validity],
- imap_last_uid: email["UID"],
- imap_old_emails: all_old_uids_size + processed,
- imap_new_emails: all_new_uids_size - processed,
- )
- end
- end
-
- def sync_to_server
- return if !SiteSetting.enable_imap_write
-
- to_sync = IncomingEmail.where(imap_sync: true, imap_group_id: @group.id)
- if to_sync.size > 0
- @provider.open_mailbox(@group.imap_mailbox_name, write: true)
- to_sync.each do |incoming_email|
- ImapSyncLog.debug(
- "Updating email on IMAP server for incoming email ID = #{incoming_email.id}, UID = #{incoming_email.imap_uid}",
- @group,
- )
- update_email(incoming_email)
- incoming_email.update(imap_sync: false)
- end
- end
- end
-
- def update_topic_archived_state(email, incoming_email, opts = {})
- topic = incoming_email.topic
-
- topic_is_archived = topic.group_archived_messages.size > 0
- email_is_archived = !email["LABELS"].include?('\\Inbox') && !email["LABELS"].include?("INBOX")
-
- if topic_is_archived && !email_is_archived
- ImapSyncLog.debug("Unarchiving topic ID #{topic.id}, email was unarchived", @group)
- GroupArchivedMessage.move_to_inbox!(@group.id, topic, skip_imap_sync: true)
- elsif !topic_is_archived && email_is_archived
- ImapSyncLog.debug("Archiving topic ID #{topic.id}, email was archived", @group)
- GroupArchivedMessage.archive!(@group.id, topic, skip_imap_sync: true)
- end
- end
-
- def update_topic_tags(email, incoming_email, opts = {})
- group_email_regex = @group.email_username_regex
- topic = incoming_email.topic
-
- tags = Set.new
-
- # "Plus" part from the destination email address
- to_addresses = incoming_email.to_addresses_split
- cc_addresses = incoming_email.cc_addresses_split
- (to_addresses + cc_addresses).each do |address|
- if plus_part = address&.scan(group_email_regex)&.first&.first
- tags.add("plus:#{plus_part[1..-1]}") if plus_part.length > 0
- end
- end
-
- # Mailbox name
- tags.add(@provider.to_tag(opts[:mailbox_name])) if opts[:mailbox_name]
-
- # Flags and labels
- email["FLAGS"].each { |flag| tags.add(@provider.to_tag(flag)) }
- email["LABELS"].each { |label| tags.add(@provider.to_tag(label)) }
-
- tags.subtract([nil, ""])
-
- return if !tagging_enabled?
-
- # TODO: Optimize tagging.
- # `DiscourseTagging.tag_topic_by_names` does a lot of lookups in the
- # database and some of them could be cached in this context.
- DiscourseTagging.tag_topic_by_names(topic, Guardian.new(Discourse.system_user), tags.to_a)
- end
-
- def update_email(incoming_email)
- return if !incoming_email || !incoming_email.imap_sync
-
- post = incoming_email.post
- if !post && incoming_email.post_id
- # post was likely deleted because topic was deleted, let's try get it
- post = Post.with_deleted.find(incoming_email.post_id)
- end
-
- # don't do any of these type of updates on anything but the OP in the
- # email thread -- archiving and deleting will be handled for the whole
- # thread depending on provider
- return if post&.post_number != 1
- topic = incoming_email.topic
-
- # if email is nil, the UID does not exist in the provider, meaning....
- #
- # A) the email has been deleted/moved to a different mailbox in the provider
- # B) the UID does not belong to the provider
- email = @provider.emails(incoming_email.imap_uid, %w[FLAGS LABELS]).first
- return if !email.present?
-
- labels = email["LABELS"]
- flags = email["FLAGS"]
- new_labels = []
- new_flags = []
-
- # Topic has been deleted if it is not present from the post, so we need
- # to trash the IMAP server email
- if !topic
- # no need to do anything further here, we will recognize the UIDs in the
- # mail server email thread have been trashed on next sync
- ImapSyncLog.debug(
- "Trashing UID #{incoming_email.imap_uid} (incoming ID #{incoming_email.id})",
- @group,
- )
- return @provider.trash(incoming_email.imap_uid)
- end
-
- # the topic is archived, and the archive should be reflected in the IMAP
- # server
- topic_archived = topic.group_archived_messages.any?
- if !topic_archived
- # TODO: This is needed right now so the store below does not take it
- # away again...ideally we should unarchive and store the tag-labels
- # at the same time.
- new_labels << "\\Inbox"
-
- ImapSyncLog.debug(
- "Unarchiving UID #{incoming_email.imap_uid} (incoming ID #{incoming_email.id})",
- @group,
- )
-
- # some providers need special handling for unarchiving too
- @provider.unarchive(incoming_email.imap_uid)
- else
- ImapSyncLog.debug(
- "Archiving UID #{incoming_email.imap_uid} (incoming ID #{incoming_email.id})",
- @group,
- )
-
- # some providers need special handling for archiving. this way we preserve
- # any new tag-labels, and archive, even though it may cause extra requests
- # to the IMAP server
- @provider.archive(incoming_email.imap_uid)
- end
-
- # Sync topic status and labels with email flags and labels.
- if tagging_enabled?
- tags = topic.tags.pluck(:name)
- new_flags = tags.map { |tag| @provider.tag_to_flag(tag) }.reject(&:blank?)
- new_labels =
- new_labels.concat(tags.map { |tag| @provider.tag_to_label(tag) }.reject(&:blank?))
- end
-
- # regardless of whether the topic needs to be archived we still update
- # the flags and the labels
- @provider.store(incoming_email.imap_uid, "FLAGS", flags, new_flags)
- @provider.store(incoming_email.imap_uid, "LABELS", labels, new_labels)
- end
-
- def tagging_enabled?
- Guardian.new(Discourse.system_user).can_tag_pms?
- end
- end
-end
diff --git a/lib/post_destroyer.rb b/lib/post_destroyer.rb
index 1fa57036fa8..7df726cb430 100644
--- a/lib/post_destroyer.rb
+++ b/lib/post_destroyer.rb
@@ -142,7 +142,6 @@ class PostDestroyer
@opts.slice(:context),
)
end
- update_imap_sync(@post, false)
if SiteSetting.tos_topic_id == @topic.id || SiteSetting.privacy_topic_id == @topic.id
Discourse.clear_urls!
end
@@ -255,7 +254,6 @@ class PostDestroyer
end
end
- update_imap_sync(@post, true) if @post.topic&.deleted_at
feature_users_in_the_topic if @post.topic
@post.publish_change_to_clients!(permanent? ? :destroyed : :deleted) if @post.topic
if @post.topic && @post.post_number == 1
@@ -508,13 +506,6 @@ class PostDestroyer
end
end
- def update_imap_sync(post, sync)
- return if !SiteSetting.enable_imap
- incoming = IncomingEmail.find_by(post_id: post.id, topic_id: post.topic_id)
- return if !incoming || !incoming.imap_uid
- incoming.update(imap_sync: sync)
- end
-
def update_post_counts(operator)
counts =
Post
diff --git a/lib/post_revisor.rb b/lib/post_revisor.rb
index 8dc4e63cea4..b375d6578a0 100644
--- a/lib/post_revisor.rb
+++ b/lib/post_revisor.rb
@@ -287,8 +287,6 @@ class PostRevisor
@silent = @opts[:silent] if @opts.has_key?(:silent)
@topic_changes.silent = @silent
- @post.incoming_email&.update(imap_sync: true) if @post.incoming_email&.imap_uid
-
old_raw = @post.raw
Post.transaction do
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb
index 6fabb3cea57..4822ea3d0e4 100644
--- a/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb
@@ -351,7 +351,6 @@ module DiscourseDataExplorer
"groups.default_notification_level": GroupUser.notification_levels,
"group_histories.action": GroupHistory.actions,
"group_users.notification_level": GroupUser.notification_levels,
- "imap_sync_logs.level": ImapSyncLog.levels,
"invites.emailed_status": Invite.emailed_status_types,
"notifications.notification_type": Notification.types,
"polls.results": Poll.results,
diff --git a/spec/fabricators/group_fabricator.rb b/spec/fabricators/group_fabricator.rb
index bbc4d5df0b6..b4e275b5ba7 100644
--- a/spec/fabricators/group_fabricator.rb
+++ b/spec/fabricators/group_fabricator.rb
@@ -7,22 +7,6 @@ Fabricator(:public_group, from: :group) do
public_exit true
end
-Fabricator(:imap_group, from: :group) do
- smtp_server "smtp.ponyexpress.com"
- smtp_port 587
- smtp_ssl_mode Group.smtp_ssl_modes[:starttls]
- smtp_enabled true
- imap_server "imap.ponyexpress.com"
- imap_port 993
- imap_ssl true
- imap_mailbox_name "All Mail"
- imap_uid_validity 0
- imap_last_uid 0
- imap_enabled true
- email_username "[email protected]"
- email_password "test"
-end
-
Fabricator(:smtp_group, from: :group) do
smtp_server "smtp.ponyexpress.com"
smtp_port 587
diff --git a/spec/fabricators/incoming_email_fabricator.rb b/spec/fabricators/incoming_email_fabricator.rb
index d60ea466fb3..a63574b89a5 100644
--- a/spec/fabricators/incoming_email_fabricator.rb
+++ b/spec/fabricators/incoming_email_fabricator.rb
@@ -5,7 +5,6 @@ Fabricator(:incoming_email) do
subject { sequence(:subject) { |n| "Hello world #{n}" } }
from_address { sequence(:from_address) { |n| "foo#{n}@example.com" } }
to_addresses { sequence(:to_addresses) { |n| "someone#{n}@else.com" } }
- imap_sync false
created_via 0
raw <<~EMAIL
diff --git a/spec/jobs/cleanup_imap_sync_log_spec.rb b/spec/jobs/cleanup_imap_sync_log_spec.rb
deleted file mode 100644
index 2ca22f17f98..00000000000
--- a/spec/jobs/cleanup_imap_sync_log_spec.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-# frozen_string_literal: true
-
-RSpec.describe Jobs::CleanupImapSyncLog do
- let(:job_class) { Jobs::CleanupImapSyncLog.new }
-
- it "deletes logs older than RETAIN_LOGS_DAYS" do
- log1 = ImapSyncLog.log("Test log 1", :debug)
- log2 = ImapSyncLog.log("Test log 2", :debug)
- log3 = ImapSyncLog.log("Test log 3", :debug)
-
- log2.update(created_at: 6.days.ago)
- log3.update(created_at: 7.days.ago)
-
- job_class.execute({})
-
- expect(ImapSyncLog.count).to eq(1)
- end
-
- it "does not write the log to the db if specified" do
- ImapSyncLog.debug("test", Fabricate(:group), db: false)
- expect(ImapSyncLog.count).to eq(0)
- end
-end
diff --git a/spec/jobs/regular/group_smtp_email_spec.rb b/spec/jobs/regular/group_smtp_email_spec.rb
index ae96cdb5dc5..cbab0070282 100644
--- a/spec/jobs/regular/group_smtp_email_spec.rb
+++ b/spec/jobs/regular/group_smtp_email_spec.rb
@@ -107,7 +107,7 @@ RSpec.describe Jobs::GroupSmtpEmail do
expect(email_log.message_id).to eq("discourse/post/#{post.id}@test.localhost")
end
- it "creates an IncomingEmail record with the correct details to avoid double processing IMAP" do
+ it "creates an IncomingEmail record with the correct details" do
job.execute(args)
expect(ActionMailer::Base.deliveries.count).to eq(1)
expect(ActionMailer::Base.deliveries.last.subject).to eq("Re: Help I need support")
@@ -220,28 +220,6 @@ RSpec.describe Jobs::GroupSmtpEmail do
end
end
- context "when the post in the argument is the OP" do
- let(:post_id) { post.topic.posts.first.id }
-
- context "when the group has imap enabled" do
- before { group.update!(imap_enabled: true) }
-
- it "aborts and does not send a group SMTP email; the OP is the one that sent the email in the first place" do
- expect { job.execute(args) }.not_to(change { EmailLog.count })
- expect(ActionMailer::Base.deliveries.count).to eq(0)
- end
- end
-
- context "when the group does not have imap enabled" do
- before { group.update!(imap_enabled: false) }
-
- it "sends the email as expected" do
- job.execute(args)
- expect(ActionMailer::Base.deliveries.count).to eq(1)
- end
- end
- end
-
context "when the post is deleted" do
it "aborts and adds a skipped email log" do
post.trash!
diff --git a/spec/lib/demon/email_sync_spec.rb b/spec/lib/demon/email_sync_spec.rb
deleted file mode 100644
index 0477d095595..00000000000
--- a/spec/lib/demon/email_sync_spec.rb
+++ /dev/null
@@ -1,53 +0,0 @@
-# frozen_string_literal: true
-
-RSpec.describe Demon::EmailSync do
- describe ".check_email_sync_heartbeat" do
- after do
- described_class.reset_demons
- described_class.test_cleanup
- end
-
- it "should restart email sync daemons when last heartbeat is older than the heartbeat interval" do
- track_log_messages do |logger|
- daemon = described_class.new(1)
- daemon.set_pid(999_999)
-
- described_class.set_demons({ "daemon" => daemon })
-
- Discourse.redis.set(
- described_class::HEARTBEAT_KEY,
- Time.now.to_i - described_class::HEARTBEAT_INTERVAL.to_i - 1,
- )
-
- daemon.expects(:restart)
-
- described_class.check_email_sync_heartbeat
-
- expect(logger.warnings.first).to eq(
- "EmailSync heartbeat test failed (last heartbeat was 61s ago), restarting",
- )
- end
- end
-
- it "should restart email sync daemons when memory usage exceeds the maximum allowed memory" do
- track_log_messages do |logger|
- daemon = described_class.new(1)
- daemon.set_pid(999_999)
-
- described_class.set_demons({ "daemon" => daemon })
-
- Discourse.redis.set(described_class::HEARTBEAT_KEY, Time.now.to_i)
-
- daemon.expects(:restart)
-
- # Set to negative value to fake that process is using too much memory
- described_class.expects(:max_allowed_email_sync_rss).returns(-1)
- described_class.check_email_sync_heartbeat
-
- expect(logger.warnings.first).to eq(
- "EmailSync is consuming too much memory (using: 0.00M) for '#{described_class::HOSTNAME}', restarting",
- )
- end
- end
- end
-end
diff --git a/spec/lib/email/receiver_spec.rb b/spec/lib/email/receiver_spec.rb
index a22d6c0de38..2536f5d3352 100644
--- a/spec/lib/email/receiver_spec.rb
+++ b/spec/lib/email/receiver_spec.rb
@@ -404,8 +404,8 @@ RSpec.describe Email::Receiver do
it "stores the created_via source against the incoming email" do
process(:text_reply, source: :handle_mail)
expect(IncomingEmail.last.created_via).to eq(IncomingEmail.created_via_types[:handle_mail])
- process(:text_and_html_reply, source: :imap)
- expect(IncomingEmail.last.created_via).to eq(IncomingEmail.created_via_types[:imap])
+ process(:text_and_html_reply, source: :pop3_poll)
+ expect(IncomingEmail.last.created_via).to eq(IncomingEmail.created_via_types[:pop3_poll])
end
it "stores the message_id of the incoming email against the post as outbound_message_id" do
diff --git a/spec/lib/imap/providers/detector_spec.rb b/spec/lib/imap/providers/detector_spec.rb
deleted file mode 100644
index 17b0c6cc519..00000000000
--- a/spec/lib/imap/providers/detector_spec.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-# frozen_string_literal: true
-
-RSpec.describe Imap::Providers::Detector do
- it "returns the gmail provider if the gmail imap server is used" do
- config = {
- server: "imap.gmail.com",
- port: 993,
- ssl: true,
- username: "[email protected]",
- password: "testpassword1",
- }
- expect(described_class.init_with_detected_provider(config)).to be_a(Imap::Providers::Gmail)
- end
-
- it "returns the generic provider if we don't have a special provider defined" do
- config = {
- server: "imap.yo.com",
- port: 993,
- ssl: true,
- username: "[email protected]",
- password: "testpassword1",
- }
- expect(described_class.init_with_detected_provider(config)).to be_a(Imap::Providers::Generic)
- end
-end
diff --git a/spec/lib/imap/providers/generic_spec.rb b/spec/lib/imap/providers/generic_spec.rb
deleted file mode 100644
index 4d8226b40a6..00000000000
--- a/spec/lib/imap/providers/generic_spec.rb
+++ /dev/null
@@ -1,203 +0,0 @@
-# frozen_string_literal: true
-
-RSpec.describe Imap::Providers::Generic do
- fab!(:username) { "[email protected]" }
- fab!(:password) { "test1!" }
- fab!(:provider) do
- described_class.new(
- "imap.generic.com",
- { port: 993, ssl: true, username: username, password: password },
- )
- end
- let(:dummy_mailboxes) do
- [
- Net::IMAP::MailboxList.new([], "/", "All Mail"),
- Net::IMAP::MailboxList.new([:Noselect], "/", "Other"),
- Net::IMAP::MailboxList.new([:Trash], "/", "Bin"),
- ]
- end
-
- let(:imap_stub) { stub }
- before { described_class.any_instance.stubs(:imap).returns(imap_stub) }
-
- describe "#connect!" do
- it "calls login with the provided username and password on the imap client" do
- imap_stub.expects(:login).with(username, password).once
- provider.connect!
- end
- end
-
- describe "#list_mailboxes" do
- before { imap_stub.expects(:list).with("", "*").returns(dummy_mailboxes) }
-
- it "does not return any mailboxes with the Noselect attribute" do
- expect(provider.list_mailboxes).not_to include("Other")
- end
-
- it "filters by the provided attribute" do
- expect(provider.list_mailboxes(:Trash)).to eq(["Bin"])
- end
-
- it "lists all mailboxes names" do
- expect(provider.list_mailboxes).to eq(["All Mail", "Bin"])
- end
- end
-
- describe "#trash_mailbox" do
- before do
- imap_stub.expects(:list).with("", "*").returns(dummy_mailboxes)
- Discourse.cache.delete("imap_trash_mailbox_#{provider.account_digest}")
- end
-
- it "returns the mailbox with the special-use attribute \Trash" do
- expect(provider.trash_mailbox).to eq("Bin")
- end
-
- it "caches the result based on the account username and server for 30 mins" do
- provider.trash_mailbox
- provider.expects(:list_mailboxes).never
- provider.trash_mailbox
- end
- end
-
- describe "#find_trashed_by_message_ids" do
- before do
- provider.stubs(:trash_mailbox).returns("Bin")
- imap_stub.stubs(:examine).with("Inbox").twice
- imap_stub.stubs(:responses).returns({ "UIDVALIDITY" => [1] })
- imap_stub.stubs(:examine).with("Bin")
- imap_stub.stubs(:responses).returns({ "UIDVALIDITY" => [9] })
- provider
- .expects(:emails)
- .with([4, 6], %w[UID ENVELOPE])
- .returns(
- [
- { "ENVELOPE" => stub(message_id: "<[email protected]>"), "UID" => 4 },
- { "ENVELOPE" => stub(message_id: "<[email protected]>"), "UID" => 6 },
- ],
- )
- end
-
-
- it "sends the message-id search in the correct format and returns the trashed emails and UIDVALIDITY" do
- provider.open_mailbox("Inbox")
- imap_stub
- .expects(:uid_search)
- .with(
- "OR OR HEADER Message-ID '<[email protected]>' HEADER Message-ID '<[email protected]>' HEADER Message-ID '<[email protected]>'",
- )
- .returns([4, 6])
- resp = provider.find_trashed_by_message_ids(message_ids)
-
- expect(resp.trashed_emails.map(&:message_id)).to match_array(
- )
- expect(resp.trash_uid_validity).to eq(9)
- end
- end
-
- describe "#trash" do
- it "stores the \Deleted flag on the UID and expunges" do
- provider.stubs(:can?).with("MOVE").returns(false)
- provider.expects(:store).with(78, "FLAGS", [], ['\Deleted'])
- imap_stub.expects(:expunge)
- provider.trash(78)
- end
-
- context "if the server supports MOVE" do
- it "calls trash_move which is implemented by the provider" do
- provider.stubs(:can?).with("MOVE").returns(true)
- provider.expects(:trash_move).with(78)
- provider.trash(78)
- end
- end
- end
-
- describe "#uids" do
- it "can search with from and to" do
- imap_stub.expects(:uid_search).once.with("UID 5:9")
- provider.uids(from: 5, to: 9)
- end
-
- it "can search with only from" do
- imap_stub.expects(:uid_search).once.with("UID 5:*")
- provider.uids(from: 5)
- end
-
- it "can search with only to" do
- imap_stub.expects(:uid_search).once.with("UID 1:9")
- provider.uids(to: 9)
- end
-
- it "can search all" do
- imap_stub.expects(:uid_search).once.with("ALL")
- provider.uids
- end
- end
-
- describe "#open_mailbox" do
- it "uses examine to get a readonly version of the mailbox" do
- imap_stub.expects(:examine).with("Inbox")
- imap_stub.expects(:responses).returns({ "UIDVALIDITY" => [1] })
- provider.open_mailbox("Inbox")
- end
-
- describe "write true" do
- context "if imap_write is disabled" do
- before { SiteSetting.enable_imap_write = false }
-
- it "raises an error" do
- expect { provider.open_mailbox("Inbox", write: true) }.to raise_error(
- Imap::Providers::WriteDisabledError,
- )
- end
- end
-
- context "if imap_write is enabled" do
- before { SiteSetting.enable_imap_write = true }
-
- it "does not raise an error and calls imap.select" do
- imap_stub.expects(:select).with("Inbox")
- imap_stub.expects(:responses).returns({ "UIDVALIDITY" => [1] })
- expect { provider.open_mailbox("Inbox", write: true) }.not_to raise_error
- end
- end
- end
- end
-
- describe "#emails" do
- let(:fields) { ["UID"] }
- let(:uids) { [99, 106] }
-
- it "returns empty array if uid_fetch does not find any matching emails by uid" do
- imap_stub.expects(:uid_fetch).with(uids, fields).returns(nil)
- expect(provider.emails(uids, fields)).to eq([])
- end
-
- it "returns an array of attributes" do
- imap_stub
- .expects(:uid_fetch)
- .with(uids, fields)
- .returns(
- [
- Net::IMAP::FetchData.new(1, { "UID" => 99 }),
- Net::IMAP::FetchData.new(1, { "UID" => 106 }),
- ],
- )
- expect(provider.emails(uids, fields)).to eq([{ "UID" => 99 }, { "UID" => 106 }])
- end
- end
-
- describe "#to_tag" do
- it "returns a label cleaned up so it can be used for a discourse tag" do
- expect(provider.to_tag("Some Label")).to eq("some-label")
- end
- end
-
- describe "#tag_to_label" do
- it "returns the tag as is by default" do
- expect(provider.tag_to_label("Support")).to eq("Support")
- end
- end
-end
diff --git a/spec/lib/imap/providers/gmail_spec.rb b/spec/lib/imap/providers/gmail_spec.rb
deleted file mode 100644
index 9ce1f9dad2a..00000000000
--- a/spec/lib/imap/providers/gmail_spec.rb
+++ /dev/null
@@ -1,81 +0,0 @@
-# frozen_string_literal: true
-
-RSpec.describe Imap::Providers::Gmail do
- fab!(:username) { "[email protected]" }
- fab!(:password) { "test1!" }
- fab!(:provider) do
- described_class.new(
- "imap.generic.com",
- { port: 993, ssl: true, username: username, password: password },
- )
- end
-
- let(:imap_stub) { stub }
- let(:x_gm_thrid) { Imap::Providers::Gmail::X_GM_THRID }
- let(:x_gm_labels) { Imap::Providers::Gmail::X_GM_LABELS }
- before { described_class.any_instance.stubs(:imap).returns(imap_stub) }
-
- describe "#store" do
- it "converts LABELS store to special X-GM-LABELS" do
- Imap::Providers::Generic
- .any_instance
- .expects(:store)
- .with(63, x_gm_labels, ["\\Inbox"], ["\\Inbox", "test"])
- provider.store(63, "LABELS", ["\\Inbox"], ["\\Inbox", "test"])
- end
- end
-
- describe "#tag_to_label" do
- it "converts important to special gmail label \\Important" do
- expect(provider.tag_to_label("important")).to eq("\\Important")
- end
-
- it "converts starred to special gmail label \\Starred" do
- expect(provider.tag_to_label("starred")).to eq("\\Starred")
- end
- end
-
- describe "#archive" do
- it "gets the thread ID for the UID, and removes the Inbox label from all UIDs in the thread" do
- main_uid = 78
- fake_thrid = "4398634986239754"
- imap_stub
- .expects(:uid_fetch)
- .with(main_uid, [x_gm_thrid])
- .returns([stub(attr: { x_gm_thrid => fake_thrid })])
- imap_stub.expects(:uid_search).with("#{x_gm_thrid} #{fake_thrid}").returns([79, 80])
- provider
- .expects(:emails)
- .with([79, 80], %w[UID LABELS])
- .returns(
- [
- { "UID" => 79, "LABELS" => ["\\Inbox", "seen"] },
- { "UID" => 80, "LABELS" => ["\\Inbox", "seen"] },
- ],
- )
- provider.expects(:store).with(79, "LABELS", ["\\Inbox", "seen"], ["seen"])
- provider.expects(:store).with(80, "LABELS", ["\\Inbox", "seen"], ["seen"])
-
- provider.archive(main_uid)
- end
- end
-
- describe "#filter_mailboxes" do
- it "filters down the gmail mailboxes to only show the relevant ones" do
- mailboxes_with_attr = [
- Net::IMAP::MailboxList.new([:Hasnochildren], "/", "INBOX"),
- Net::IMAP::MailboxList.new(%i[All Hasnochildren], "/", "[Gmail]/All Mail"),
- Net::IMAP::MailboxList.new(%i[Drafts Hasnochildren], "/", "[Gmail]/Drafts"),
- Net::IMAP::MailboxList.new(%i[Hasnochildren Important], "/", "[Gmail]/Important"),
- Net::IMAP::MailboxList.new(%i[Hasnochildren Sent], "/", "[Gmail]/Sent Mail"),
- Net::IMAP::MailboxList.new(%i[Hasnochildren Junk], "/", "[Gmail]/Spam"),
- Net::IMAP::MailboxList.new(%i[Flagged Hasnochildren], "/", "[Gmail]/Starred"),
- Net::IMAP::MailboxList.new(%i[Hasnochildren Trash], "/", "[Gmail]/Trash"),
- ]
-
- expect(provider.filter_mailboxes(mailboxes_with_attr)).to match_array(
- ["INBOX", "[Gmail]/All Mail", "[Gmail]/Important"],
- )
- end
- end
-end
diff --git a/spec/lib/imap/sync_spec.rb b/spec/lib/imap/sync_spec.rb
deleted file mode 100644
index bd3228e0310..00000000000
--- a/spec/lib/imap/sync_spec.rb
+++ /dev/null
@@ -1,607 +0,0 @@
-# frozen_string_literal: true
-
-require "imap/sync"
-
-RSpec.describe Imap::Sync do
- before do
- SiteSetting.tagging_enabled = true
- SiteSetting.pm_tags_allowed_for_groups = "1|2|3"
-
- SiteSetting.enable_imap = true
-
- Jobs.run_immediately!
- end
-
- let(:group) do
- Fabricate(
- :group,
- imap_server: "imap.gmail.com",
- imap_port: 993,
- email_username: "[email protected]",
- email_password: "password",
- imap_mailbox_name: "[Gmail]/All Mail",
- )
- end
-
- let(:sync_handler) { Imap::Sync.new(group) }
-
- before do
- mocked_imap_provider =
- MockedImapProvider.new(
- group.imap_server,
- port: group.imap_port,
- ssl: group.imap_ssl,
- username: group.email_username,
- password: group.email_password,
- )
- Imap::Providers::Detector.stubs(:init_with_detected_provider).returns(mocked_imap_provider)
- end
-
- describe "no previous sync" do
- let(:from) { "[email protected]" }
- let(:email_subject) { "Testing email post" }
- let(:message_id) { "#{SecureRandom.hex}@example.com" }
-
- let(:email) do
- EmailFabricator(
- from: from,
- to: group.email_username,
- subject: email_subject,
- message_id: message_id,
- )
- end
-
- before do
- provider = MockedImapProvider.any_instance
- provider.stubs(:open_mailbox).returns(uid_validity: 1)
- provider.stubs(:uids).with.returns([100])
- provider.stubs(:uids).with(to: 100).returns([100])
- provider.stubs(:uids).with(from: 101).returns([])
- provider.stubs(:emails).returns(
- [
- {
- "UID" => 100,
- "LABELS" => %w[\\Important test-label],
- "FLAGS" => %i[Seen],
- "RFC822" => email,
- },
- ],
- )
- end
-
- it "creates a topic from an incoming email" do
- expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
- Post.where(post_type: Post.types[:regular]).count
- }.by(1).and change { IncomingEmail.count }.by(1)
-
- expect(IncomingEmail.last.created_via).to eq(IncomingEmail.created_via_types[:imap])
-
- expect(group.imap_uid_validity).to eq(1)
- expect(group.imap_last_uid).to eq(100)
-
- topic = Topic.last
- expect(topic.title).to eq(email_subject)
- expect(topic.user.email).to eq(from)
- expect(topic.tags.pluck(:name)).to contain_exactly("seen", "important", "test-label")
-
- post = topic.first_post
- expect(post.raw).to eq("This is an email *body*. :smile:")
-
- incoming_email = post.incoming_email
- expect(incoming_email.raw.lines.map(&:strip)).to eq(email.lines.map(&:strip))
- expect(incoming_email.message_id).to eq(message_id)
- expect(incoming_email.from_address).to eq(from)
- expect(incoming_email.to_addresses).to eq(group.email_username)
- expect(incoming_email.imap_uid_validity).to eq(1)
- expect(incoming_email.imap_uid).to eq(100)
- expect(incoming_email.imap_sync).to eq(false)
- expect(incoming_email.imap_group_id).to eq(group.id)
- end
-
- context "when tagging not enabled" do
- before { SiteSetting.tagging_enabled = false }
-
- it "creates a topic from an incoming email but with no tags added" do
- expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
- Post.where(post_type: Post.types[:regular]).count
- }.by(1).and change { IncomingEmail.count }.by(1)
-
- expect(group.imap_uid_validity).to eq(1)
- expect(group.imap_last_uid).to eq(100)
-
- topic = Topic.last
- expect(topic.title).to eq(email_subject)
- expect(topic.user.email).to eq(from)
- expect(topic.tags).to eq([])
- end
- end
-
- it "does not duplicate topics" do
- expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
- Post.where(post_type: Post.types[:regular]).count
- }.by(1).and change { IncomingEmail.count }.by(1)
-
- expect { sync_handler.process }.to not_change { Topic.count }.and not_change {
- Post.where(post_type: Post.types[:regular]).count
- }.and not_change { IncomingEmail.count }
- end
-
- it "creates a new incoming email if the message ID does not match the receiver post id regex" do
- incoming_email = Fabricate(:incoming_email, message_id: message_id)
-
- expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
- Post.where(post_type: Post.types[:regular]).count
- }.by(1).and change { IncomingEmail.count }.by(1)
-
- last_incoming = IncomingEmail.where(message_id: message_id).last
- expect(last_incoming.message_id).to eq(message_id)
- expect(last_incoming.imap_uid_validity).to eq(1)
- expect(last_incoming.imap_uid).to eq(100)
- expect(last_incoming.imap_sync).to eq(false)
- expect(last_incoming.imap_group_id).to eq(group.id)
- end
-
- context "when the message id matches the receiver post id regex" do
- let(:message_id) { "discourse/post/[email protected]" }
- it "does not duplicate incoming email" do
- incoming_email = Fabricate(:incoming_email, message_id: message_id)
-
- expect { sync_handler.process }.to not_change { Topic.count }.and not_change {
- Post.where(post_type: Post.types[:regular]).count
- }.and not_change { IncomingEmail.count }
-
- incoming_email.reload
- expect(incoming_email.message_id).to eq(message_id)
- expect(incoming_email.imap_uid_validity).to eq(1)
- expect(incoming_email.imap_uid).to eq(100)
- expect(incoming_email.imap_sync).to eq(false)
- expect(incoming_email.imap_group_id).to eq(group.id)
- end
- end
- end
-
- describe "previous sync" do
- let(:email_subject) { "Testing email post" }
-
- let(:first_from) { "[email protected]" }
- let(:first_message_id) { SecureRandom.hex }
- let(:first_body) { "This is the first message of this exchange." }
-
- let(:second_from) { "[email protected]" }
- let(:second_message_id) { SecureRandom.hex }
- let(:second_body) { "<p>This is an <b>answer</b> to this message.</p>" }
-
- it "continues with new emails" do
- provider = MockedImapProvider.any_instance
- provider.stubs(:open_mailbox).returns(uid_validity: 1)
-
- provider.stubs(:uids).with.returns([100])
- provider
- .stubs(:emails)
- .with([100], %w[UID FLAGS LABELS RFC822], anything)
- .returns(
- [
- {
- "UID" => 100,
- "LABELS" => %w[\\Inbox],
- "FLAGS" => %i[Seen],
- "RFC822" =>
- EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: email_subject,
- body: first_body,
- ),
- },
- ],
- )
-
- expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
- Post.where(post_type: Post.types[:regular]).count
- }.by(1).and change { IncomingEmail.count }.by(1)
-
- topic = Topic.last
- expect(topic.title).to eq(email_subject)
- expect(GroupArchivedMessage.where(topic_id: topic.id).exists?).to eq(false)
-
- post = Post.where(post_type: Post.types[:regular]).last
- expect(post.user.email).to eq(first_from)
- expect(post.raw).to eq(first_body)
- expect(group.imap_uid_validity).to eq(1)
- expect(group.imap_last_uid).to eq(100)
-
- provider.stubs(:uids).with(to: 100).returns([100])
- provider.stubs(:uids).with(from: 101).returns([200])
- provider
- .stubs(:emails)
- .with([100], %w[UID FLAGS LABELS ENVELOPE], anything)
- .returns([{ "UID" => 100, "LABELS" => %w[\\Inbox], "FLAGS" => %i[Seen] }])
- provider
- .stubs(:emails)
- .with([200], %w[UID FLAGS LABELS RFC822], anything)
- .returns(
- [
- {
- "UID" => 200,
- "LABELS" => %w[\\Inbox],
- "FLAGS" => %i[Recent],
- "RFC822" =>
- EmailFabricator(
- message_id: SecureRandom.hex,
- in_reply_to: first_message_id,
- from: second_from,
- to: group.email_username,
- subject: "Re: #{email_subject}",
- body: second_body,
- ),
- },
- ],
- )
-
- expect { sync_handler.process }.to not_change { Topic.count }.and change {
- Post.where(post_type: Post.types[:regular]).count
- }.by(1).and change { IncomingEmail.count }.by(1)
-
- post = Post.where(post_type: Post.types[:regular]).last
- expect(post.user.email).to eq(second_from)
- expect(post.raw).to eq(second_body)
- expect(group.imap_uid_validity).to eq(1)
- expect(group.imap_last_uid).to eq(200)
-
- provider.stubs(:uids).with(to: 200).returns([100, 200])
- provider.stubs(:uids).with(from: 201).returns([])
- provider
- .stubs(:emails)
- .with([100, 200], %w[UID FLAGS LABELS ENVELOPE], anything)
- .returns(
- [
- { "UID" => 100, "LABELS" => %w[], "FLAGS" => %i[Seen] },
- { "UID" => 200, "LABELS" => %w[], "FLAGS" => %i[Recent] },
- ],
- )
-
- expect { sync_handler.process }.to not_change { Topic.count }.and not_change {
- Post.where(post_type: Post.types[:regular]).count
- }.and not_change { IncomingEmail.count }
-
- topic = Topic.last
- expect(topic.title).to eq(email_subject)
- expect(GroupArchivedMessage.where(topic_id: topic.id).exists?).to eq(true)
-
- expect(Topic.last.posts.where(post_type: Post.types[:regular]).count).to eq(2)
- end
-
- describe "detecting deleted emails and deleting the topic in discourse" do
- let(:provider) { MockedImapProvider.any_instance }
- before do
- provider.stubs(:open_mailbox).returns(uid_validity: 1)
-
- provider.stubs(:uids).with.returns([100])
- provider
- .stubs(:emails)
- .with([100], %w[UID FLAGS LABELS RFC822], anything)
- .returns(
- [
- {
- "UID" => 100,
- "LABELS" => %w[\\Inbox],
- "FLAGS" => %i[Seen],
- "RFC822" =>
- EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: email_subject,
- body: first_body,
- ),
- },
- ],
- )
- end
-
- it "detects previously synced UIDs are missing and deletes the posts if they are in the trash mailbox" do
- sync_handler.process
- incoming_100 = IncomingEmail.find_by(imap_uid: 100)
- provider.stubs(:uids).with.returns([])
-
- provider.stubs(:uids).with(to: 100).returns([])
- provider.stubs(:uids).with(from: 101).returns([])
- provider.stubs(:find_spam_by_message_ids).returns(stub(spam_emails: []))
- provider.stubs(:find_trashed_by_message_ids).returns(
- stub(
- trashed_emails: [stub(uid: 10, message_id: incoming_100.message_id)],
- trash_uid_validity: 99,
- ),
- )
- sync_handler.process
-
- incoming_100.reload
- expect(incoming_100.imap_uid_validity).to eq(99)
- expect(incoming_100.imap_uid).to eq(10)
- expect(Post.with_deleted.find(incoming_100.post_id).deleted_at).not_to eq(nil)
- expect(Topic.with_deleted.find(incoming_100.topic_id).deleted_at).not_to eq(nil)
- end
-
- it "detects previously synced UIDs are missing and deletes the posts if they are in the spam/junk mailbox" do
- sync_handler.process
- incoming_100 = IncomingEmail.find_by(imap_uid: 100)
- provider.stubs(:uids).with.returns([])
-
- provider.stubs(:uids).with(to: 100).returns([])
- provider.stubs(:uids).with(from: 101).returns([])
- provider.stubs(:find_trashed_by_message_ids).returns(stub(trashed_emails: []))
- provider.stubs(:find_spam_by_message_ids).returns(
- stub(
- spam_emails: [stub(uid: 10, message_id: incoming_100.message_id)],
- spam_uid_validity: 99,
- ),
- )
- sync_handler.process
-
- incoming_100.reload
- expect(incoming_100.imap_uid_validity).to eq(99)
- expect(incoming_100.imap_uid).to eq(10)
- expect(Post.with_deleted.find(incoming_100.post_id).deleted_at).not_to eq(nil)
- expect(Topic.with_deleted.find(incoming_100.topic_id).deleted_at).not_to eq(nil)
- end
-
- it "marks the incoming email as IMAP missing if it cannot be found in spam or trash" do
- sync_handler.process
- incoming_100 = IncomingEmail.find_by(imap_uid: 100)
- provider.stubs(:uids).with.returns([])
-
- provider.stubs(:uids).with(to: 100).returns([])
- provider.stubs(:uids).with(from: 101).returns([])
- provider.stubs(:find_trashed_by_message_ids).returns(stub(trashed_emails: []))
- provider.stubs(:find_spam_by_message_ids).returns(stub(spam_emails: []))
- sync_handler.process
-
- incoming_100.reload
- expect(incoming_100.imap_missing).to eq(true)
- end
-
- it "detects the topic being deleted on the discourse site and deletes on the IMAP server and
- does not attempt to delete again on discourse site when deleted already by us on the IMAP server" do
- SiteSetting.enable_imap_write = true
- sync_handler.process
- incoming_100 = IncomingEmail.find_by(imap_uid: 100)
- provider.stubs(:uids).with.returns([100])
-
- provider.stubs(:uids).with(to: 100).returns([100])
- provider.stubs(:uids).with(from: 101).returns([])
-
- PostDestroyer.new(
- Discourse.system_user,
- incoming_100.post,
- context: "Automated testing",
- ).destroy
- provider
- .stubs(:emails)
- .with([100], %w[UID FLAGS LABELS ENVELOPE], anything)
- .returns(
- [
- {
- "UID" => 100,
- "LABELS" => %w[\\Inbox],
- "FLAGS" => %i[Seen],
- "RFC822" =>
- EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: email_subject,
- body: first_body,
- ),
- },
- ],
- )
- provider
- .stubs(:emails)
- .with(100, %w[FLAGS LABELS])
- .returns([{ "LABELS" => %w[\\Inbox], "FLAGS" => %i[Seen] }])
-
- provider.expects(:trash).with(100)
- sync_handler.process
-
- provider.stubs(:uids).with.returns([])
-
- provider.stubs(:uids).with(to: 100).returns([])
- provider.stubs(:uids).with(from: 101).returns([])
- provider.stubs(:find_spam_by_message_ids).returns(stub(spam_emails: []))
- provider.stubs(:find_trashed_by_message_ids).returns(
- stub(
- trashed_emails: [stub(uid: 10, message_id: incoming_100.message_id)],
- trash_uid_validity: 99,
- ),
- )
- PostDestroyer.expects(:new).never
-
- sync_handler.process
-
- incoming_100.reload
- expect(incoming_100.imap_uid_validity).to eq(99)
- expect(incoming_100.imap_uid).to eq(10)
- end
- end
-
- describe "archiving emails" do
- let(:provider) { MockedImapProvider.any_instance }
- before do
- SiteSetting.enable_imap_write = true
- provider.stubs(:open_mailbox).returns(uid_validity: 1)
-
- provider.stubs(:uids).with.returns([100])
- provider
- .stubs(:emails)
- .with([100], %w[UID FLAGS LABELS RFC822], anything)
- .returns(
- [
- {
- "UID" => 100,
- "LABELS" => %w[\\Inbox],
- "FLAGS" => %i[Seen],
- "RFC822" =>
- EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: email_subject,
- body: first_body,
- ),
- },
- ],
- )
-
- sync_handler.process
- @incoming_email = IncomingEmail.find_by(message_id: first_message_id)
- @topic = @incoming_email.topic
-
- provider.stubs(:uids).with(to: 100).returns([100])
- provider.stubs(:uids).with(from: 101).returns([101])
- provider
- .stubs(:emails)
- .with([100], %w[UID FLAGS LABELS ENVELOPE], anything)
- .returns([{ "UID" => 100, "LABELS" => %w[\\Inbox], "FLAGS" => %i[Seen] }])
- provider.stubs(:emails).with([101], %w[UID FLAGS LABELS RFC822], anything).returns([])
- provider
- .stubs(:emails)
- .with(100, %w[FLAGS LABELS])
- .returns([{ "LABELS" => %w[\\Inbox], "FLAGS" => %i[Seen] }])
- end
-
- it "archives an email on the IMAP server when archived in discourse" do
- GroupArchivedMessage.archive!(group.id, @topic, skip_imap_sync: false)
- @incoming_email.update(imap_sync: true)
-
- provider.stubs(:store).with(100, "FLAGS", anything, anything)
- provider.stubs(:store).with(100, "LABELS", ["\\Inbox"], ["seen"])
-
- provider.expects(:archive).with(100)
- sync_handler.process
- end
-
- it "does not archive email if not archived in discourse, it unarchives it instead" do
- @incoming_email.update(imap_sync: true)
- provider.stubs(:store).with(100, "FLAGS", anything, anything)
- provider.stubs(:store).with(100, "LABELS", ["\\Inbox"], ["\\Inbox", "seen"])
-
- provider.expects(:archive).with(100).never
- provider.expects(:unarchive).with(100)
- sync_handler.process
- end
- end
- end
-
- describe "invalidated previous sync" do
- let(:email_subject) { "Testing email post" }
-
- let(:first_from) { "[email protected]" }
- let(:first_message_id) { SecureRandom.hex }
- let(:first_body) { "This is the first message of this exchange." }
-
- let(:second_from) { "[email protected]" }
- let(:second_message_id) { SecureRandom.hex }
- let(:second_body) { "<p>This is an <b>answer</b> to this message.</p>" }
-
- # TODO: Improve the invalidating flow for mailbox change. This is a destructive
- # action so it should not be done often.
- xit "is updated" do
- provider = MockedImapProvider.any_instance
-
- provider.stubs(:open_mailbox).returns(uid_validity: 1)
- provider.stubs(:uids).with.returns([100, 200])
- provider
- .stubs(:emails)
- .with([100, 200], %w[UID FLAGS LABELS RFC822], anything)
- .returns(
- [
- {
- "UID" => 100,
- "LABELS" => %w[\\Inbox],
- "FLAGS" => %i[Seen],
- "RFC822" =>
- EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: email_subject,
- body: first_body,
- ),
- },
- {
- "UID" => 200,
- "LABELS" => %w[\\Inbox],
- "FLAGS" => %i[Recent],
- "RFC822" =>
- EmailFabricator(
- message_id: second_message_id,
- in_reply_to: first_message_id,
- from: second_from,
- to: group.email_username,
- subject: "Re: #{email_subject}",
- body: second_body,
- ),
- },
- ],
- )
-
- expect { sync_handler.process }.to change { Topic.count }.by(1).and change {
- Post.where(post_type: Post.types[:regular]).count
- }.by(2).and change { IncomingEmail.count }.by(2)
-
- imap_data = Topic.last.incoming_email.pluck(:imap_uid_validity, :imap_uid, :imap_group_id)
- expect(imap_data).to contain_exactly([1, 100, group.id], [1, 200, group.id])
-
- provider.stubs(:open_mailbox).returns(uid_validity: 2)
- provider.stubs(:uids).with.returns([111, 222])
- provider
- .stubs(:emails)
- .with([111, 222], %w[UID FLAGS LABELS RFC822], anything)
- .returns(
- [
- {
- "UID" => 111,
- "LABELS" => %w[\\Inbox],
- "FLAGS" => %i[Seen],
- "RFC822" =>
- EmailFabricator(
- message_id: first_message_id,
- from: first_from,
- to: group.email_username,
- cc: second_from,
- subject: email_subject,
- body: first_body,
- ),
- },
- {
- "UID" => 222,
- "LABELS" => %w[\\Inbox],
- "FLAGS" => %i[Recent],
- "RFC822" =>
- EmailFabricator(
- message_id: second_message_id,
- in_reply_to: first_message_id,
- from: second_from,
- to: group.email_username,
- subject: "Re: #{email_subject}",
- body: second_body,
- ),
- },
- ],
- )
-
- expect { sync_handler.process }.to not_change { Topic.count }.and not_change {
- Post.where(post_type: Post.types[:regular]).count
- }.and not_change { IncomingEmail.count }
-
- imap_data = Topic.last.incoming_email.pluck(:imap_uid_validity, :imap_uid, :imap_group_id)
- expect(imap_data).to contain_exactly([2, 111, group.id], [2, 222, group.id])
- end
- end
-end
diff --git a/spec/lib/post_destroyer_spec.rb b/spec/lib/post_destroyer_spec.rb
index b0698b59424..7cfb726763d 100644
--- a/spec/lib/post_destroyer_spec.rb
+++ b/spec/lib/post_destroyer_spec.rb
@@ -374,15 +374,6 @@ RSpec.describe PostDestroyer do
expect(post.like_count).to eq(2)
expect(post.custom_fields["deleted_public_actions"]).to be_nil
end
-
- it "unmarks the matching incoming email for imap sync" do
- SiteSetting.enable_imap = true
- incoming =
- Fabricate(:incoming_email, imap_sync: true, post: post, topic: post.topic, imap_uid: 99)
- PostDestroyer.new(moderator, post).recover
- incoming.reload
- expect(incoming.imap_sync).to eq(false)
- end
end
describe "basic destroying" do
@@ -881,28 +872,6 @@ RSpec.describe PostDestroyer do
end
end
- describe "incoming email and imap sync" do
- fab!(:incoming) { Fabricate(:incoming_email, post: post, topic: post.topic) }
-
- it "does nothing if imap not enabled" do
- IncomingEmail.expects(:find_by).never
- PostDestroyer.new(moderator, post).destroy
- end
-
- it "does nothing if the incoming email has no imap_uid" do
- SiteSetting.enable_imap = true
- PostDestroyer.new(moderator, post).destroy
- expect(incoming.reload.imap_sync).to eq(false)
- end
-
- it "sets imap_sync to true for the matching incoming" do
- SiteSetting.enable_imap = true
- incoming.update(imap_uid: 999)
- PostDestroyer.new(moderator, post).destroy
- expect(incoming.reload.imap_sync).to eq(true)
- end
- end
-
context "with a reply" do
fab!(:reply) { Fabricate(:basic_reply, user: coding_horror, topic: post.topic) }
let!(:post_reply) { PostReply.create(post_id: post.id, reply_post_id: reply.id) }
diff --git a/spec/mailers/group_smtp_mailer_spec.rb b/spec/mailers/group_smtp_mailer_spec.rb
index 6a0fd46769d..1831875669d 100644
--- a/spec/mailers/group_smtp_mailer_spec.rb
+++ b/spec/mailers/group_smtp_mailer_spec.rb
@@ -12,10 +12,6 @@ RSpec.describe GroupSmtpMailer do
smtp_port: 587,
smtp_ssl_mode: Group.smtp_ssl_modes[:starttls],
smtp_enabled: true,
- imap_server: "imap.gmail.com",
- imap_port: 993,
- imap_ssl: true,
- imap_enabled: true,
email_username: "[email protected]",
email_password: "super$secret$password",
)
@@ -53,35 +49,12 @@ RSpec.describe GroupSmtpMailer do
before do
SiteSetting.enable_smtp = true
- SiteSetting.enable_imap = true
Jobs.run_immediately!
SiteSetting.manual_polling_enabled = true
SiteSetting.reply_by_email_address = "test+%{reply_key}@test.com"
SiteSetting.reply_by_email_enabled = true
end
- it "sends an email for first post when IMAP is disabled" do
- staged = Fabricate(:staged)
- group.update(imap_enabled: false)
-
- PostCreator.create!(
- user,
- skip_validations: true,
- title: "Hello from John",
- archetype: Archetype.private_message,
- target_usernames: staged.username,
- target_group_names: group.name,
- raw: raw,
- )
-
- expect(ActionMailer::Base.deliveries.size).to eq(1)
-
- sent_mail = ActionMailer::Base.deliveries[0]
- expect(sent_mail.to).to contain_exactly(staged.email)
- expect(sent_mail.subject).to eq("Hello from John")
- expect(sent_mail.to_s).to include(raw)
- end
-
it "sends an email as reply" do
post = PostCreator.create(user, topic_id: receiver.incoming_email.topic.id, raw: raw)
@@ -155,7 +128,7 @@ RSpec.describe GroupSmtpMailer do
SiteSetting.reply_by_email_enabled = true
end
- it "uses the correct IMAP/SMTP reply to address and does not create a post reply key" do
+ it "uses the correct SMTP reply to address and does not create a post reply key" do
post = PostCreator.create(user, topic_id: receiver.incoming_email.topic.id, raw: raw)
expect(ActionMailer::Base.deliveries.size).to eq(1)
@@ -167,16 +140,6 @@ RSpec.describe GroupSmtpMailer do
expect(sent_mail.from).to contain_exactly("[email protected]")
end
- context "when IMAP is disabled for the group" do
- before { group.update(imap_enabled: false) }
-
- it "does send the email" do
- post = PostCreator.create(user, topic_id: receiver.incoming_email.topic.id, raw: raw)
-
- expect(ActionMailer::Base.deliveries.size).to eq(1)
- end
- end
-
context "when SMTP is disabled for the group" do
before { group.update(smtp_enabled: false) }
diff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rb
index 5a4dfbcfd78..3728a37671a 100644
--- a/spec/models/group_spec.rb
+++ b/spec/models/group_spec.rb
@@ -1359,83 +1359,6 @@ RSpec.describe Group do
end
end
- describe "IMAP" do
- let(:group) { Fabricate(:group) }
- let(:mocked_imap_provider) do
- MockedImapProvider.new(
- group.imap_server,
- port: group.imap_port,
- ssl: group.imap_ssl,
- username: group.email_username,
- password: group.email_password,
- )
- end
-
- def mock_imap
- Imap::Providers::Detector.stubs(:init_with_detected_provider).returns(mocked_imap_provider)
- end
-
- def configure_imap
- group.update(
- imap_server: "imap.gmail.com",
- imap_port: 993,
- imap_ssl: true,
- imap_enabled: true,
- email_username: "[email protected]",
- email_password: "testPassword1!",
- )
- end
-
- def enable_imap
- SiteSetting.enable_imap = true
- mocked_imap_provider.stubs(:connect!)
- mocked_imap_provider.stubs(:list_mailboxes_with_attributes).returns(
- [stub(attr: [], name: "Inbox")],
- )
- mocked_imap_provider.stubs(:list_mailboxes).returns(["Inbox"])
- mocked_imap_provider.stubs(:disconnect!)
- end
-
- before { Discourse.redis.del("group_imap_mailboxes_#{group.id}") }
-
- describe "#imap_mailboxes" do
- it "returns an empty array if group imap is not configured" do
- expect(group.imap_mailboxes).to eq([])
- end
-
- it "returns an empty array and does not contact IMAP server if group imap is configured but the setting is disabled" do
- configure_imap
- Imap::Providers::Detector.expects(:init_with_detected_provider).never
- expect(group.imap_mailboxes).to eq([])
- end
-
- it "logs the imap error if one occurs" do
- configure_imap
- mock_imap
- SiteSetting.enable_imap = true
- mocked_imap_provider.stubs(:connect!).raises(Net::IMAP::NoResponseError)
- group.imap_mailboxes
- expect(group.reload.imap_last_error).not_to eq(nil)
- end
-
- it "returns a list of mailboxes from the IMAP provider" do
- configure_imap
- mock_imap
- enable_imap
- expect(group.imap_mailboxes).to eq(["Inbox"])
- end
-
- it "caches the login and mailbox fetch" do
- configure_imap
- mock_imap
- enable_imap
- group.imap_mailboxes
- Imap::Providers::Detector.expects(:init_with_detected_provider).never
- group.imap_mailboxes
- end
- end
- end
-
describe "Unicode usernames and group names" do
before { SiteSetting.unicode_usernames = true }
@@ -1644,23 +1567,6 @@ RSpec.describe Group do
expect(group.reload.smtp_updated_at).not_to eq_time(old_updated_at)
end
- it "enables imap and records the change" do
- group.update(
- imap_port: 587,
- imap_ssl: true,
- imap_server: "imap.gmail.com",
- email_username: "[email protected]",
- email_password: "password",
- )
-
- group.record_email_setting_changes!(user)
- group.reload
-
- expect(group.imap_enabled).to eq(true)
- expect(group.imap_updated_at).not_to eq(nil)
- expect(group.imap_updated_by).to eq(user)
- end
-
it "disables smtp and records the change" do
group.update(
smtp_port: 587,
@@ -1689,34 +1595,6 @@ RSpec.describe Group do
expect(group.smtp_updated_at).not_to eq(nil)
expect(group.smtp_updated_by).to eq(user)
end
-
- it "disables imap and records the change" do
- group.update(
- imap_port: 587,
- imap_ssl: true,
- imap_server: "imap.gmail.com",
- email_username: "[email protected]",
- email_password: "password",
- )
-
- group.record_email_setting_changes!(user)
- group.reload
-
- group.update(
- imap_port: nil,
- imap_ssl: false,
- imap_server: nil,
- email_username: nil,
- email_password: nil,
- )
-
- group.record_email_setting_changes!(user)
- group.reload
-
- expect(group.imap_enabled).to eq(false)
- expect(group.imap_updated_at).not_to eq(nil)
- expect(group.imap_updated_by).to eq(user)
- end
end
describe "#find_by_email" do
diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb
index d479244acff..feb5c2925dd 100644
--- a/spec/models/topic_spec.rb
+++ b/spec/models/topic_spec.rb
@@ -3508,7 +3508,7 @@ RSpec.describe Topic do
fab!(:group) do
Fabricate(
:group,
- smtp_server: "imap.gmail.com",
+ smtp_server: "smtp.gmail.com",
smtp_port: 587,
email_username: "[email protected]",
email_password: "[email protected]",
diff --git a/spec/requests/api/schemas/json/group_response.json b/spec/requests/api/schemas/json/group_response.json
index 61cf8910c39..5a3c34aac2b 100644
--- a/spec/requests/api/schemas/json/group_response.json
+++ b/spec/requests/api/schemas/json/group_response.json
@@ -176,48 +176,6 @@
"null"
]
},
- "imap_enabled": {
- "type": "boolean"
- },
- "imap_updated_at": {
- "type": [
- "string",
- "null"
- ]
- },
- "imap_updated_by": {
- "type": [
- "object",
- "null"
- ]
- },
- "imap_server": {
- "type": [
- "string",
- "null"
- ]
- },
- "imap_port": {
- "type": [
- "string",
- "null"
- ]
- },
- "imap_ssl": {
- "type": [
- "string",
- "null"
- ]
- },
- "imap_mailbox_name": {
- "type": "string"
- },
- "imap_mailboxes": {
- "type": "array",
- "items": {
-
- }
- },
"email_username": {
"type": [
"string",
@@ -236,24 +194,6 @@
"null"
]
},
- "imap_last_error": {
- "type": [
- "string",
- "null"
- ]
- },
- "imap_old_emails": {
- "type": [
- "string",
- "null"
- ]
- },
- "imap_new_emails": {
- "type": [
- "string",
- "null"
- ]
- },
"message_count": {
"type": "integer"
},
@@ -364,16 +304,8 @@
"smtp_server",
"smtp_port",
"smtp_ssl_mode",
- "imap_server",
- "imap_port",
- "imap_ssl",
- "imap_mailbox_name",
- "imap_mailboxes",
"email_username",
"email_password",
- "imap_last_error",
- "imap_old_emails",
- "imap_new_emails",
"message_count",
"allow_unknown_sender_topic_replies",
"watching_category_ids",
diff --git a/spec/requests/groups_controller_spec.rb b/spec/requests/groups_controller_spec.rb
index 072869313d1..18b89f061ff 100644
--- a/spec/requests/groups_controller_spec.rb
+++ b/spec/requests/groups_controller_spec.rb
@@ -2838,39 +2838,6 @@ RSpec.describe GroupsController do
end
end
- context "when validating imap" do
- let(:protocol) { "imap" }
- let(:username) { "[email protected]" }
- let(:password) { "password" }
- let(:domain) { nil }
- let(:ssl) { true }
- let(:ssl_mode) { nil }
- let(:host) { "imap.somemailsite.com" }
- let(:port) { 993 }
-
- it "validates with the correct TLS settings" do
- EmailSettingsValidator.expects(:validate_imap).with(has_entries(ssl: true))
- post "/groups/#{group.id}/test_email_settings.json", params: params
- expect(response.status).to eq(200)
- end
-
- context "when an error is raised" do
- before do
- EmailSettingsValidator.expects(:validate_imap).raises(
- Net::IMAP::NoResponseError,
- stub(data: stub(text: "Invalid credentials")),
- )
- end
- it "uses the friendly error message functionality to return the message to the user" do
- post "/groups/#{group.id}/test_email_settings.json", params: params
- expect(response.status).to eq(422)
- expect(response.parsed_body["errors"]).to include(
- I18n.t("email_settings.imap_authentication_error"),
- )
- end
- end
- end
-
describe "global param validation and rate limit" do
let(:protocol) { "smtp" }
let(:host) { "smtp.gmail.com" }
@@ -2885,9 +2852,7 @@ RSpec.describe GroupsController do
it "raises an invalid params error" do
post "/groups/#{group.id}/test_email_settings.json", params: params
expect(response.status).to eq(400)
- expect(response.parsed_body["errors"].first).to match(
- /Valid protocols to test are smtp and imap/,
- )
+ expect(response.parsed_body["errors"].first).to match(/Valid protocol to test is smtp/)
end
end
diff --git a/spec/services/email_settings_exception_handler_spec.rb b/spec/services/email_settings_exception_handler_spec.rb
index 1fe25376bbc..c81ea06f9dd 100644
--- a/spec/services/email_settings_exception_handler_spec.rb
+++ b/spec/services/email_settings_exception_handler_spec.rb
@@ -9,20 +9,6 @@ RSpec.describe EmailSettingsExceptionHandler do
)
end
- it "formats a Net::IMAP::NoResponseError for invalid credentials" do
- exception = Net::IMAP::NoResponseError.new(stub(data: stub(text: "Invalid credentials")))
- expect(described_class.friendly_exception_message(exception, "imap.test.com")).to eq(
- I18n.t("email_settings.imap_authentication_error"),
- )
- end
-
- it "formats a general Net::IMAP::NoResponseError" do
- exception = Net::IMAP::NoResponseError.new(stub(data: stub(text: "NO bad problem (Failure)")))
- expect(described_class.friendly_exception_message(exception, "imap.test.com")).to eq(
- I18n.t("email_settings.imap_no_response_error", message: "NO bad problem"),
- )
- end
-
it "formats a Net::SMTPAuthenticationError" do
exception = Net::SMTPAuthenticationError.new("invalid credentials")
expect(described_class.friendly_exception_message(exception, "smtp.test.com")).to eq(
diff --git a/spec/services/email_settings_validator_spec.rb b/spec/services/email_settings_validator_spec.rb
index e3dd9ab77db..ba9bd0672fd 100644
--- a/spec/services/email_settings_validator_spec.rb
+++ b/spec/services/email_settings_validator_spec.rb
@@ -4,69 +4,6 @@ RSpec.describe EmailSettingsValidator do
let(:username) { "[email protected]" }
let(:password) { "mbdtf" }
- describe "#validate_imap" do
- let(:host) { "imap.gmail.com" }
- let(:port) { 993 }
-
- let(:net_imap_stub) do
- obj = mock()
- obj.stubs(:login).returns(true)
- obj
- end
-
- before { Net::IMAP.stubs(:new).returns(net_imap_stub) }
-
- it "is valid if no error is raised" do
- net_imap_stub.stubs(:logout).returns(true)
- net_imap_stub.stubs(:disconnect).returns(true)
- expect {
- described_class.validate_imap(
- host: host,
- port: port,
- username: username,
- password: password,
- )
- }.not_to raise_error
- end
-
- it "is invalid if an error is raised" do
- net_imap_stub.stubs(:login).raises(
- Net::IMAP::NoResponseError,
- stub(data: stub(text: "no response")),
- )
- expect {
- described_class.validate_imap(
- host: host,
- port: port,
- username: username,
- password: password,
- debug: true,
- )
- }.to raise_error(Net::IMAP::NoResponseError)
- end
-
- it "logs a warning if debug: true passed in and still raises the error" do
- net_imap_stub.stubs(:login).raises(
- Net::IMAP::NoResponseError,
- stub(data: stub(text: "no response")),
- )
- Rails
- .logger
- .expects(:warn)
- .with(regexp_matches(/\[EmailSettingsValidator\] Error encountered/))
- .at_least_once
- expect {
- described_class.validate_imap(
- host: host,
- port: port,
- username: username,
- password: password,
- debug: true,
- )
- }.to raise_error(Net::IMAP::NoResponseError)
- end
- end
-
describe "#validate_pop3" do
let(:host) { "pop.gmail.com" }
let(:port) { 995 }
diff --git a/spec/services/post_alerter_spec.rb b/spec/services/post_alerter_spec.rb
index ddfbf723b0f..f862432ed30 100644
--- a/spec/services/post_alerter_spec.rb
+++ b/spec/services/post_alerter_spec.rb
@@ -2457,13 +2457,9 @@ RSpec.describe PostAlerter do
smtp_server: "smtp.gmail.com",
smtp_port: 587,
smtp_ssl_mode: Group.smtp_ssl_modes[:starttls],
- imap_server: "imap.gmail.com",
- imap_port: 993,
- imap_ssl: true,
email_username: "[email protected]",
email_password: "password",
smtp_enabled: true,
- imap_enabled: true,
)
end
diff --git a/spec/services/problem_check/group_email_credentials_spec.rb b/spec/services/problem_check/group_email_credentials_spec.rb
index 5c9681d3208..ed64d0ba33e 100644
--- a/spec/services/problem_check/group_email_credentials_spec.rb
+++ b/spec/services/problem_check/group_email_credentials_spec.rb
@@ -1,14 +1,12 @@
# frozen_string_literal: true
require "net/smtp"
-require "net/imap"
RSpec.describe ProblemCheck::GroupEmailCredentials do
subject(:check) { described_class.new(target) }
- fab!(:group1) { Fabricate(:group, smtp_enabled: false, imap_enabled: false) }
- fab!(:smtp_group) { Fabricate(:smtp_group, name: "smtp_group", imap_enabled: true) }
- fab!(:imap_group) { Fabricate(:imap_group, name: "imap_group", smtp_enabled: false) }
+ fab!(:group1) { Fabricate(:group, smtp_enabled: false) }
+ fab!(:smtp_group) { Fabricate(:smtp_group, name: "smtp_group") }
describe "#call" do
context "when SMTP is disabled for the site" do
@@ -23,25 +21,10 @@ RSpec.describe ProblemCheck::GroupEmailCredentials do
end
end
- context "when IMAP is disabled for the site" do
- before { SiteSetting.enable_imap = false }
+ context "when SMTP is enabled for the site" do
+ before { SiteSetting.enable_smtp = true }
- context "with an IMAP-enabled group" do
- let(:target) { imap_group.name }
-
- it "does not report a problem" do
- expect(check).to be_chill_about_it
- end
- end
- end
-
- context "when SMTP and IMAP are enabled for the site" do
- before do
- SiteSetting.enable_smtp = true
- SiteSetting.enable_imap = true
- end
-
- context "when the group has no SMTP or IMAP enabled" do
+ context "when the group has no SMTP enabled" do
let(:target) { group1.name }
it "does not report a problem" do
@@ -59,7 +42,6 @@ RSpec.describe ProblemCheck::GroupEmailCredentials do
.then
.returns(true)
.at_least_once
- EmailSettingsValidator.stubs(:validate_imap).returns(true)
expect(check).to have_a_problem.with_priority("high").with_message(
I18n.t(
@@ -72,28 +54,6 @@ RSpec.describe ProblemCheck::GroupEmailCredentials do
)
end
end
-
- context "when IMAP error check fails" do
- let(:target) { imap_group.name }
-
- it "registers a problem with the group's IMAP settings error" do
- EmailSettingsValidator.stubs(:validate_smtp).returns(true)
- EmailSettingsValidator
- .expects(:validate_imap)
- .raises(Net::IMAP::NoResponseError.new(stub(data: stub(text: "Invalid credentials"))))
- .once
-
- expect(check).to have_a_problem.with_priority("high").with_message(
- I18n.t(
- "dashboard.problem.group_email_credentials",
- base_path: Discourse.base_path,
- group_name: imap_group.name,
- group_full_name: imap_group.full_name,
- error: I18n.t("email_settings.imap_authentication_error", message: "bad credentials"),
- ),
- )
- end
- end
end
end
end
diff --git a/spec/support/imap_helper.rb b/spec/support/imap_helper.rb
deleted file mode 100644
index 4ae5482d7bb..00000000000
--- a/spec/support/imap_helper.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-# frozen_string_literal: true
-
-class MockedImapProvider < Imap::Providers::Gmail
- def connect!
- end
-
- def disconnect!
- end
-
- def open_mailbox(mailbox_name, write: false)
- end
-
- def labels
- ["INBOX"]
- end
-end
-
-def EmailFabricator(options)
- email = +""
- email += "Date: Sat, 31 Mar 2018 17:50:19 -0700\n"
- email += "From: #{options[:from] || "Dan <[email protected]>"}\n"
- email += "To: #{options[:to] || "Joffrey <[email protected]>"}\n"
- email += "Cc: #{options[:cc]}\n" if options[:cc]
- email += "In-Reply-To: #{options[:in_reply_to]}\n" if options[:in_reply_to]
- email += "References: #{options[:in_reply_to]}\n" if options[:in_reply_to]
- email += "Message-ID: <#{options[:message_id]}>\n" if options[:message_id]
- email += "Subject: #{options[:subject] || "This is a test email subject"}\n"
- email += "MIME-Version: 1.0\n"
- email += "Content-Type: #{options[:content_type] || "text/plain;\n charset=UTF-8"}\n"
- email += "Content-Transfer-Encoding: 7bit\n"
- email += "\n#{options[:body] || "This is an email *body*. :smile:"}"
- email
-end