xrforge/manyfold/root/hook.d/experience_updated/500-mastodon-post2image.rb

96 lines
2.6 KiB
Ruby
Executable file

#!/usr/bin/env ruby
require 'json'
require 'rss'
require 'open-uri'
require 'cgi'
require_relative './../../xrforge.rb'
# Check if a filename is provided
if ARGV.length != 1
puts "Usage: #{$0} <path/to/experience/somefile.xxx>"
exit 1
end
filename = ARGV[0]
# dont run for each file-update
if ! filename.end_with?("datapackage.json")
exit 0
end
begin
# Change the directory
Dir.chdir( File.dirname(filename) )
# Read and parse the JSON file
data = JSON.parse( File.read( "datapackage.json" ) )
data['keywords'].any? do |tag|
if tag.match?(/@.*@.*\./) # scan for activitypub handle (@foo@mastodon.online e.g.)
APHandle = tag
end
end
if ! APHandle # nothing to do
exit 0
end
APHandle = "@vladh@merveilles.town"
logfile = File.join( File.dirname(filename), ".xrforge/log.txt" )
XRForge.log("✅ starting Mastodon post2image", logfile)
parts = APHandle.split("@")
server = parts[2].sub(/@/,"")
rssUrl = "https://#{server}/@#{parts[1]}.rss"
XRForge.log("✅ checking #{rssUrl}", logfile)
feed = RSS::Parser.parse(URI.open(rssUrl, 'User-Agent' => 'Ruby-RSS-Client'))
puts feed.channel.title
puts feed.channel.link
first_item = feed.items.first
if first_item
description = CGI.unescapeHTML(first_item.description.to_s).gsub(/<[^>]*>/, '')
description = description.length > 150 ? description = description[0,200] + " (..)" : description
else
XRForge.log("❌ did not find post", logfile)
exit 0
end
puts description
# look for first image
MEDIA_REGEX = /<media:content url=['"]([^'"]+)['"]/
img = feed.to_s.match(MEDIA_REGEX)
if img and img[1] and img[1].match(/(png|jpg)/)
imgurl = img[1]
end
text = "\n\"#{description}\"\n\n~ #{feed.channel.title}\n#{feed.channel.link}"
textFile = ".xrforge/mastodon-post.txt"
File.open(textFile,'w') do |file|
file.puts text
end
cmd = "magick -size 800x800 -background white -pointsize 48 -interline-spacing 10 -fill \\#555 -gravity center -font /usr/local/lib/ruby/3.4.0/rdoc/generator/template/darkfish/fonts/Lato-Regular.ttf caption:@#{textFile} mastodon-post.png"
puts cmd
system(cmd)
XRForge.log(" ", logfile)
rescue OpenURI::HTTPError => e
# Handle HTTP errors (e.g., 404 not found, 403 forbidden)
puts "Error fetching feed: #{e.message}"
exit
rescue => e
# Handle other parsing or connection errors
puts "An error occurred: #{e.message}"
rescue Errno::ENOENT
puts "File #{filename} not found"
rescue JSON::ParserError
puts "Error parsing JSON from #{filename}"
rescue => e
puts "An error occurred: #{e.message}"
end