mirror of
https://0xacab.org/sutty/sutty
synced 2024-11-22 23:56:22 +00:00
78 lines
1.7 KiB
Ruby
78 lines
1.7 KiB
Ruby
|
# frozen_string_literal: true
|
||
|
|
||
|
require 'httparty'
|
||
|
|
||
|
# Listas de bloqueo y sus URLs de descarga
|
||
|
class ActivityPub
|
||
|
class Fediblock < ApplicationRecord
|
||
|
class Client
|
||
|
include ::HTTParty
|
||
|
|
||
|
# @param url [String]
|
||
|
# @return [HTTParty::Response]
|
||
|
def get(url)
|
||
|
self.class.get(url, parser: csv_parser)
|
||
|
end
|
||
|
|
||
|
# Procesa el CSV
|
||
|
#
|
||
|
# @return [Proc]
|
||
|
def csv_parser
|
||
|
@csv_parser ||=
|
||
|
begin
|
||
|
require 'csv'
|
||
|
|
||
|
proc do |body, _|
|
||
|
CSV.parse(body, headers: true)
|
||
|
end
|
||
|
end
|
||
|
end
|
||
|
end
|
||
|
|
||
|
class FediblockDownloadError < ::StandardError; end
|
||
|
|
||
|
validates_presence_of :title, :url, :download_url, :format
|
||
|
validates_inclusion_of :format, in: %w[mastodon fediblock]
|
||
|
|
||
|
HOSTNAME_HEADERS = {
|
||
|
'mastodon' => '#domain',
|
||
|
'fediblock' => 'domain'
|
||
|
}
|
||
|
|
||
|
def client
|
||
|
@client ||= Client.new
|
||
|
end
|
||
|
|
||
|
# Descarga la lista y crea las instancias con el estado necesario
|
||
|
def process!
|
||
|
response = client.get(download_url)
|
||
|
|
||
|
raise FediblockDownloadError unless response.ok?
|
||
|
|
||
|
Fediblock.transaction do
|
||
|
csv = response.parsed_response
|
||
|
process_csv! csv
|
||
|
|
||
|
update(instances: csv.map { |r| r[hostname_header] })
|
||
|
end
|
||
|
end
|
||
|
|
||
|
private
|
||
|
|
||
|
def hostname_header
|
||
|
HOSTNAME_HEADERS[format]
|
||
|
end
|
||
|
|
||
|
# Crea o encuentra instancias que ya existían y las bloquea
|
||
|
#
|
||
|
# @param csv [CSV::Table]
|
||
|
def process_csv!(csv)
|
||
|
csv.each do |row|
|
||
|
ActivityPub::Instance.find_or_create_by(hostname: row[hostname_header]).tap do |i|
|
||
|
i.block! if i.may_block?
|
||
|
end
|
||
|
end
|
||
|
end
|
||
|
end
|
||
|
end
|