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
193 |> Pleroma.Repo.chunk_stream(100)
194 |> Enum.reduce(0, fn i, acc ->
195 with {:ok, str} <- fun.(i),
196 :ok <- IO.write(file, str <> ",\n") do
203 with :ok <- :file.pwrite(file, {:eof, -2}, "\n],\n \"totalItems\": #{total}}") do
209 defp bookmarks(dir, %{id: user_id} = _user) do
211 |> where(user_id: ^user_id)
212 |> join(:inner, [b], activity in assoc(b, :activity))
213 |> select([b, a], %{id: b.id, object: fragment("(?)->>'object'", a.data)})
214 |> write(dir, "bookmarks", fn a -> {:ok, "\"#{a.object}\""} end)
217 defp likes(dir, user) do
219 |> Activity.Queries.by_actor()
220 |> Activity.Queries.by_type("Like")
221 |> select([like], %{id: like.id, object: fragment("(?)->>'object'", like.data)})
222 |> write(dir, "likes", fn a -> {:ok, "\"#{a.object}\""} end)
225 defp statuses(dir, user) do
228 |> Map.put(:type, ["Create", "Announce"])
229 |> Map.put(:actor_id, user.ap_id)
232 [Pleroma.Constants.as_public(), user.ap_id],
233 User.following(user),
234 Pleroma.List.memberships(user)
237 |> ActivityPub.fetch_activities_query(opts)
238 |> write(dir, "outbox", fn a ->
239 with {:ok, activity} <- Transmogrifier.prepare_outgoing(a.data) do
240 activity |> Map.delete("@context") |> Jason.encode()