Skip to content

Instantly share code, notes, and snippets.

@joebuhlig
Created September 1, 2022 20:27
Show Gist options
  • Save joebuhlig/e5661f552522266eaf97838cfde88f6b to your computer and use it in GitHub Desktop.
Save joebuhlig/e5661f552522266eaf97838cfde88f6b to your computer and use it in GitHub Desktop.
#!/bin/env ruby
require '/opt/mastodon/config/environment.rb'
def create_attachment(user,media)
media_url = "https://bhlg-us.nyc3.cdn.digitaloceanspaces.com/#{media}"
puts media_url
unless File.directory?(File.dirname(media))
FileUtils.mkdir_p File.dirname(media)
end
begin
tempfile = open("/opt/mastodon/public/system/#{media}", 'wb') do |file|
file << URI.open(media_url).read
end
attachment = user.account.media_attachments.create!(file: File.new(tempfile))
attachment_id = attachment["id"]
File.delete(tempfile)
rescue
attachment_id = nil
end
return attachment_id
end
Status.destroy_all
user = User.find(1)
(1..8).each do |n|
json = JSON.parse(File.read("/opt/mastodon/public/system/exports/export-#{n}.json"))
json.each do |post|
puts post["id"]
next unless post["id"] > 8496
puts 'skipping' unless [2,6,7].include?(post["post_type_id"])
next unless [2,6,7].include?(post["post_type_id"])
media_ids = []
if post["metadata"] && post["metadata"]["photo"]
post["metadata"]["photo"].each do |photo|
media_id = create_attachment(user,photo)
media_ids.push(media_id)
puts media_ids
end
end
if post["metadata"] && post["metadata"]["video"]
post["metadata"]["video"].each do |video|
media_id = create_attachment(user,video)
media_ids.push(media_id)
puts media_ids
end
end
status = PostStatusService.new.call(user.account, text: ActionController::Base.helpers.strip_tags(post["raw_html"]), media_ids: media_ids)
status.created_at = DateTime.parse(post["published"])
status.save
puts status
end
end
@fcandi
Copy link

fcandi commented Feb 20, 2023

Hey, thanks for this code example. I am just writing my own import for Mastodon and your code helped me understand how to handle attachments :))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment