Browse Source

Sanitize content before tweet

master
aeris 5 years ago
parent
commit
966b7554a2
  1. 10
      lib/cross-post.rb
  2. 9
      lib/cross-post/mastodon.rb
  3. 39
      lib/cross-post/twitter.rb

10
lib/cross-post.rb

@ -2,6 +2,7 @@ require 'cross-post/config'
require 'cross-post/mastodon'
require 'cross-post/twitter'
require 'open-uri'
require 'logger'
# Force OpenURI#open to return a TempFile and not a StringIO
OpenURI::Buffer.send :remove_const, 'StringMax'
@ -9,6 +10,15 @@ OpenURI::Buffer.const_set 'StringMax', 0
class CrossPost
LOGGER = Logger.new STDERR
LOGGER.level = Logger.const_get ENV.fetch('LOG', 'INFO')
LOGGER.formatter = proc do |severity, time, _, msg|
time = time.strftime '%Y-%m-%dT%H:%M:%S.%6N'.freeze
"#{time} #{severity} #{msg}\n"
end
attr_reader :mastodon, :twitter
def initialize
@config = Config.new
@mastodon = Mastodon.new @config

9
lib/cross-post/mastodon.rb

@ -1,5 +1,6 @@
require 'mastodon'
require 'sanitize'
require 'awesome_print'
class CrossPost
class Mastodon
@ -18,11 +19,13 @@ class CrossPost
case object
when ::Mastodon::Status
next if reject? object
twitter.post object
LOGGER.info { 'Receiving status' }
LOGGER.debug { status.ap }
twitter.post_status object
end
rescue => e
#$stderr.puts e
raise
LOGGER.error e
#raise
end
end
end

39
lib/cross-post/twitter.rb

@ -1,5 +1,7 @@
require 'twitter'
require 'twitter-text'
require 'sanitize'
require 'cgi'
class CrossPost
class Twitter
@ -14,21 +16,11 @@ class CrossPost
@stream = ::Twitter::Streaming::Client.new config
end
def post(status)
content = Sanitize.clean status.content
last = nil
parts = split content
attachments = status.media_attachments
media = attachments.collect do |f|
f = open f.url
begin
@client.upload f
ensure
f.close
f.unlink
end
end
def post(content, media = [])
media = media.collect { |f| @client.upload f }
parts = split content
last = nil
unless media.empty?
first, *parts = parts
@ -37,6 +29,23 @@ class CrossPost
parts.each { |p| last = @client.update p, in_reply_to_status: last }
end
def post_status(status)
content = Sanitize.clean status.content
content = CGI.unescape_html content
media = status.media_attachments.collect { |f| open f.url }
LOGGER.info { 'Sending to twitter' }
LOGGER.debug { " Content: #{content}" }
LOGGER.debug { " Attachments: #{media.size}" }
self.post content, media
media.each do |f|
f.close
f.unlink
end
end
private
def split(text)

Loading…
Cancel
Save