~cytrogen/masto-fe

ref: 4fe2d7cb59f4622ff8af2f048b883f413e87c68e masto-fe/app/services/backup_service.rb -rw-r--r-- 5.5 KiB
4fe2d7cb — Daniel M Brasil Fix HTTP 500 in `/api/v1/emails/check_confirmation` (#25595) 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# frozen_string_literal: true

require 'zip'

class BackupService < BaseService
  include Payloadable
  include ContextHelper

  attr_reader :account, :backup

  def call(backup)
    @backup  = backup
    @account = backup.user.account

    build_archive!
  end

  private

  def build_outbox_json!(file)
    skeleton = serialize(collection_presenter, ActivityPub::CollectionSerializer)
    skeleton[:@context] = full_context
    skeleton[:orderedItems] = ['!PLACEHOLDER!']
    skeleton = Oj.dump(skeleton)
    prepend, append = skeleton.split('"!PLACEHOLDER!"')
    add_comma = false

    file.write(prepend)

    account.statuses.with_includes.reorder(nil).find_in_batches do |statuses|
      file.write(',') if add_comma
      add_comma = true

      file.write(statuses.map do |status|
        item = serialize_payload(ActivityPub::ActivityPresenter.from_status(status), ActivityPub::ActivitySerializer)
        item.delete('@context')

        unless item[:type] == 'Announce' || item[:object][:attachment].blank?
          item[:object][:attachment].each do |attachment|
            attachment[:url] = Addressable::URI.parse(attachment[:url]).path.delete_prefix('/system/')
          end
        end

        Oj.dump(item)
      end.join(','))

      GC.start
    end

    file.write(append)
  end

  def build_archive!
    tmp_file = Tempfile.new(%w(archive .zip))

    Zip::File.open(tmp_file, create: true) do |zipfile|
      dump_outbox!(zipfile)
      dump_media_attachments!(zipfile)
      dump_likes!(zipfile)
      dump_bookmarks!(zipfile)
      dump_actor!(zipfile)
    end

    archive_filename = "#{['archive', Time.now.utc.strftime('%Y%m%d%H%M%S'), SecureRandom.hex(16)].join('-')}.zip"

    @backup.dump      = ActionDispatch::Http::UploadedFile.new(tempfile: tmp_file, filename: archive_filename)
    @backup.processed = true
    @backup.save!
  ensure
    tmp_file.close
    tmp_file.unlink
  end

  def dump_media_attachments!(zipfile)
    MediaAttachment.attached.where(account: account).reorder(nil).find_in_batches do |media_attachments|
      media_attachments.each do |m|
        path = m.file&.path
        next unless path

        path = path.gsub(%r{\A.*/system/}, '')
        path = path.gsub(%r{\A/+}, '')
        download_to_zip(zipfile, m.file, path)
      end

      GC.start
    end
  end

  def dump_outbox!(zipfile)
    zipfile.get_output_stream('outbox.json') do |io|
      build_outbox_json!(io)
    end
  end

  def dump_actor!(zipfile)
    actor = serialize(account, ActivityPub::ActorSerializer)

    actor[:icon][:url]  = "avatar#{File.extname(actor[:icon][:url])}"  if actor[:icon]
    actor[:image][:url] = "header#{File.extname(actor[:image][:url])}" if actor[:image]
    actor[:outbox]      = 'outbox.json'
    actor[:likes]       = 'likes.json'
    actor[:bookmarks]   = 'bookmarks.json'

    download_to_zip(zipfile, account.avatar, "avatar#{File.extname(account.avatar.path)}") if account.avatar.exists?
    download_to_zip(zipfile, account.header, "header#{File.extname(account.header.path)}") if account.header.exists?

    json = Oj.dump(actor)

    zipfile.get_output_stream('actor.json') do |io|
      io.write(json)
    end
  end

  def dump_likes!(zipfile)
    skeleton = serialize(ActivityPub::CollectionPresenter.new(id: 'likes.json', type: :ordered, size: 0, items: []), ActivityPub::CollectionSerializer)
    skeleton.delete(:totalItems)
    skeleton[:orderedItems] = ['!PLACEHOLDER!']
    skeleton = Oj.dump(skeleton)
    prepend, append = skeleton.split('"!PLACEHOLDER!"')

    zipfile.get_output_stream('likes.json') do |io|
      io.write(prepend)

      add_comma = false

      Status.reorder(nil).joins(:favourites).includes(:account).merge(account.favourites).find_in_batches do |statuses|
        io.write(',') if add_comma
        add_comma = true

        io.write(statuses.map do |status|
          Oj.dump(ActivityPub::TagManager.instance.uri_for(status))
        end.join(','))

        GC.start
      end

      io.write(append)
    end
  end

  def dump_bookmarks!(zipfile)
    skeleton = serialize(ActivityPub::CollectionPresenter.new(id: 'bookmarks.json', type: :ordered, size: 0, items: []), ActivityPub::CollectionSerializer)
    skeleton.delete(:totalItems)
    skeleton[:orderedItems] = ['!PLACEHOLDER!']
    skeleton = Oj.dump(skeleton)
    prepend, append = skeleton.split('"!PLACEHOLDER!"')

    zipfile.get_output_stream('bookmarks.json') do |io|
      io.write(prepend)

      add_comma = false
      Status.reorder(nil).joins(:bookmarks).includes(:account).merge(account.bookmarks).find_in_batches do |statuses|
        io.write(',') if add_comma
        add_comma = true

        io.write(statuses.map do |status|
          Oj.dump(ActivityPub::TagManager.instance.uri_for(status))
        end.join(','))

        GC.start
      end

      io.write(append)
    end
  end

  def collection_presenter
    ActivityPub::CollectionPresenter.new(
      id: 'outbox.json',
      type: :ordered,
      size: account.statuses_count,
      items: []
    )
  end

  def serialize(object, serializer)
    ActiveModelSerializers::SerializableResource.new(
      object,
      serializer: serializer,
      adapter: ActivityPub::Adapter
    ).as_json
  end

  CHUNK_SIZE = 1.megabyte

  def download_to_zip(zipfile, attachment, filename)
    adapter = Paperclip.io_adapters.for(attachment)

    zipfile.get_output_stream(filename) do |io|
      while (buffer = adapter.read(CHUNK_SIZE))
        io.write(buffer)
      end
    end
  rescue Errno::ENOENT, Seahorse::Client::NetworkingError => e
    Rails.logger.warn "Could not backup file #{filename}: #{e}"
  end
end