dmails: factor out spam detector service.

This commit is contained in:
evazion
2019-08-23 18:59:28 -05:00
parent 7ab701c19a
commit 06ff249530
6 changed files with 79 additions and 14 deletions

View File

@@ -58,13 +58,11 @@ class DmailsController < ApplicationController
def spam
@dmail = Dmail.find(params[:id])
@dmail.update_column(:is_spam, true)
@dmail.spam!
end
def ham
@dmail = Dmail.find(params[:id])
@dmail.update_column(:is_spam, false)
@dmail.ham!
end
private

View File

@@ -0,0 +1,44 @@
# https://github.com/joshfrench/rakismet
# https://akismet.com/development/api/#comment-check
class SpamDetector
include Rakismet::Model
attr_accessor :user, :user_ip, :content, :comment_type
rakismet_attrs author: proc { user.name },
author_email: proc { user.email },
blog_lang: "en",
blog_charset: "UTF-8",
comment_type: :comment_type,
content: :content,
user_ip: :user_ip
def self.enabled?
Danbooru.config.rakismet_key.present? && Danbooru.config.rakismet_url.present? && !Rails.env.test?
end
# rakismet raises an exception if the api key or url aren't configured
def self.working?
Rakismet.validate_key
rescue
false
end
def initialize(record)
case record
when Dmail
@user = record.from
@content = record.body
@comment_type = "message"
@user_ip = record.creator_ip_addr.to_s
else
raise ArgumentError
end
end
def spam?
return false if !SpamDetector.enabled?
return false if user.is_gold?
super
end
end

View File

@@ -6,8 +6,6 @@ class Dmail < ApplicationRecord
AUTOBAN_WINDOW = 24.hours
AUTOBAN_DURATION = 3
include Rakismet::Model
validates_presence_of :title, :body, on: :create
validate :validate_sender_is_not_banned, on: :create
@@ -20,8 +18,6 @@ class Dmail < ApplicationRecord
after_create :update_recipient
after_commit :send_email, on: :create
rakismet_attrs author: proc { from.name }, author_email: proc { from.email }, content: proc { title + "\n\n" + body }, user_ip: proc { creator_ip_addr.to_s }
concerning :SpamMethods do
class_methods do
def is_spammer?(user)
@@ -41,9 +37,7 @@ class Dmail < ApplicationRecord
end
def spam?
return false if Danbooru.config.rakismet_key.blank?
return false if from.is_gold?
super()
SpamDetector.new(self).spam?
end
end