1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Backup do
11 require Pleroma.Constants
13 alias Pleroma.Activity
14 alias Pleroma.Bookmark
17 alias Pleroma.Web.ActivityPub.ActivityPub
18 alias Pleroma.Web.ActivityPub.Transmogrifier
19 alias Pleroma.Web.ActivityPub.UserView
20 alias Pleroma.Workers.BackupWorker
23 field(:content_type, :string)
24 field(:file_name, :string)
25 field(:file_size, :integer, default: 0)
26 field(:processed, :boolean, default: false)
28 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
33 def create(user, admin_user_id \\ nil) do
34 with :ok <- validate_email_enabled(),
35 :ok <- validate_user_email(user),
36 :ok <- validate_limit(user),
37 {:ok, backup} <- user |> new() |> Repo.insert() do
38 BackupWorker.process(backup, admin_user_id)
43 rand_str = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
44 datetime = Calendar.NaiveDateTime.Format.iso8601_basic(NaiveDateTime.utc_now())
45 name = "archive-#{user.nickname}-#{datetime}-#{rand_str}.zip"
49 content_type: "application/zip",
55 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
57 with :ok <- uploader.delete_file("backups/" <> backup.file_name) do
62 defp validate_limit(user) do
63 case get_last(user.id) do
64 %__MODULE__{inserted_at: inserted_at} ->
65 days = Pleroma.Config.get([Pleroma.Backup, :limit_days])
66 diff = Timex.diff(NaiveDateTime.utc_now(), inserted_at, :days)
71 {:error, "Last export was less than #{days} days ago"}
79 defp validate_email_enabled do
80 if Pleroma.Config.get([Pleroma.Emails.Mailer, :enabled]) do
83 {:error, "Backups require enabled email"}
87 defp validate_user_email(%User{email: nil}), do: {:error, "Email is required"}
88 defp validate_user_email(%User{email: email}) when is_binary(email), do: :ok
90 def get_last(user_id) do
92 |> where(user_id: ^user_id)
93 |> order_by(desc: :id)
98 def list(%User{id: user_id}) do
100 |> where(user_id: ^user_id)
101 |> order_by(desc: :id)
105 def remove_outdated(%__MODULE__{id: latest_id, user_id: user_id}) do
107 |> where(user_id: ^user_id)
108 |> where([b], b.id != ^latest_id)
110 |> Enum.each(&BackupWorker.delete/1)
113 def get(id), do: Repo.get(__MODULE__, id)
115 def process(%__MODULE__{} = backup) do
116 with {:ok, zip_file} <- export(backup),
117 {:ok, %{size: size}} <- File.stat(zip_file),
118 {:ok, _upload} <- upload(backup, zip_file) do
120 |> cast(%{file_size: size, processed: true}, [:file_size, :processed])
125 @files ['actor.json', 'outbox.json', 'likes.json', 'bookmarks.json']
126 def export(%__MODULE__{} = backup) do
127 backup = Repo.preload(backup, :user)
128 name = String.trim_trailing(backup.file_name, ".zip")
131 with :ok <- File.mkdir(dir),
132 :ok <- actor(dir, backup.user),
133 :ok <- statuses(dir, backup.user),
134 :ok <- likes(dir, backup.user),
135 :ok <- bookmarks(dir, backup.user),
136 {:ok, zip_path} <- :zip.create(String.to_charlist(dir <> ".zip"), @files, cwd: dir),
137 {:ok, _} <- File.rm_rf(dir) do
138 {:ok, :binary.list_to_bin(zip_path)}
143 dir = Pleroma.Config.get([__MODULE__, :dir]) || System.tmp_dir!()
147 def upload(%__MODULE__{} = backup, zip_path) do
148 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
150 upload = %Pleroma.Upload{
151 name: backup.file_name,
153 content_type: backup.content_type,
154 path: "backups/" <> backup.file_name
157 with {:ok, _} <- Pleroma.Uploaders.Uploader.put_file(uploader, upload),
158 :ok <- File.rm(zip_path) do
163 defp actor(dir, user) do
165 UserView.render("user.json", %{user: user})
166 |> Map.merge(%{"likes" => "likes.json", "bookmarks" => "bookmarks.json"})
168 File.write(dir <> "/actor.json", json)
172 defp write_header(file, name) do
177 "@context": "https://www.w3.org/ns/activitystreams",
178 "id": "#{name}.json",
179 "type": "OrderedCollection",
186 defp write(query, dir, name, fun) do
187 path = dir <> "/#{name}.json"
189 with {:ok, file} <- File.open(path, [:write, :utf8]),
190 :ok <- write_header(file, name) do
191 counter = :counters.new(1, [])
194 |> Pleroma.Repo.chunk_stream(100)
196 with {:ok, str} <- fun.(i),
197 :ok <- IO.write(file, str <> ",\n") do
198 :counters.add(counter, 1, 1)
202 total = :counters.get(counter, 1)
204 with :ok <- :file.pwrite(file, {:eof, -2}, "\n],\n \"totalItems\": #{total}}") do
210 defp bookmarks(dir, %{id: user_id} = _user) do
212 |> where(user_id: ^user_id)
213 |> join(:inner, [b], activity in assoc(b, :activity))
214 |> select([b, a], %{id: b.id, object: fragment("(?)->>'object'", a.data)})
215 |> write(dir, "bookmarks", fn a -> {:ok, "\"#{a.object}\""} end)
218 defp likes(dir, user) do
220 |> Activity.Queries.by_actor()
221 |> Activity.Queries.by_type("Like")
222 |> select([like], %{id: like.id, object: fragment("(?)->>'object'", like.data)})
223 |> write(dir, "likes", fn a -> {:ok, "\"#{a.object}\""} end)
226 defp statuses(dir, user) do
229 |> Map.put(:type, ["Create", "Announce"])
230 |> Map.put(:actor_id, user.ap_id)
233 [Pleroma.Constants.as_public(), user.ap_id],
234 User.following(user),
235 Pleroma.List.memberships(user)
238 |> ActivityPub.fetch_activities_query(opts)
239 |> write(dir, "outbox", fn a ->
240 with {:ok, activity} <- Transmogrifier.prepare_outgoing(a.data) do
241 activity |> Map.delete("@context") |> Jason.encode()