Skip to content

Commit

Permalink
Merge pull request #185 from cre-ne-jp/sync-topic-when-join
Browse files Browse the repository at this point in the history
IRC: 接続時に NumericReply よりチャンネル TOPIC のメタデータを取得し、データベースに保存する
  • Loading branch information
ochaochaocha3 authored Aug 19, 2020
2 parents b469d77 + 2aa23a6 commit fb77bd3
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/ircs/irc_bot.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def run(root_path, argv)

@logger = new_logger(log_level)
config = load_config(config_id, options[:mode])
plugins = load_plugins(%w(ChannelSync SaveLog KickBack Version UserInterface Part Ctcp))
plugins = load_plugins(%w(ChannelSync SaveLog KickBack Version UserInterface Part Ctcp TopicSync))

status_server = StatusServer.new(
Rails.application.config.irc_bot_status.socket_path,
Expand Down
67 changes: 67 additions & 0 deletions lib/ircs/plugins/topic_sync.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# vim: fileencoding=utf-8

require_relative 'base'

module LogArchiver
module Plugin
# JOIN したチャンネルの TOPIC がデータベースに保存されているか確認する
class TopicSync < Base
include Cinch::Plugin

set(plugin_name: 'TopicSync')

listen_to(333, method: :get_topic_metadata)

# チャンネルに JOIN したときの Numeric Reply 333 から、
# チャンネルが作成されたタイムスタンプと作成者を取得する
# @param [Cinch::Message] m
# @return [void]
def get_topic_metadata(m)
return if m.channel.topic == ''

_, nick, user, host = m.params[2].match(/\A(.+)!(.+)@(.+)\z/).to_a

begin
timestamp = Time.zone.at(m.params[3].to_i)
rescue
@log.warn("#{m.channel}: TOPIC 設定日時の取得に失敗しました。")
return
end

save_topic(m.channel, nick, user, host, timestamp)
end

private

# TOPIC を保存する
# @params [Cinch::Target] m_channel
# @params [String] nick
# @params [String] user
# @params [String] host
# @params [Time] timestamp
# @return [void]
def save_topic(m_channel, nick, user, host, timestamp)
synchronize(RECORD_MESSAGE) do
ActiveRecord::Base.connection_pool.with_connection do
channel = ::Channel.find_by(name: m_channel.name[1..-1],
logging_enabled: true)
next nil unless channel

ActiveRecord::Base.transaction do
irc_user = IrcUser.find_or_create_by!(user: user, host: host)
channel.topics.find_or_create_by!(
timestamp: timestamp,
nick: nick,
message: m_channel.topic
) do |topic|
topic.irc_user = irc_user
end
ChannelLastSpeech.refresh!(channel)
MessageDate.find_or_create_by!(channel: channel, date: timestamp)
end
end
end
end
end
end
end

0 comments on commit fb77bd3

Please sign in to comment.