1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.User.Backup do
10 import Pleroma.Web.Gettext
12 require Pleroma.Constants
14 alias Pleroma.Activity
15 alias Pleroma.Bookmark
18 alias Pleroma.Web.ActivityPub.ActivityPub
19 alias Pleroma.Web.ActivityPub.Transmogrifier
20 alias Pleroma.Web.ActivityPub.UserView
21 alias Pleroma.Workers.BackupWorker
24 field(:content_type, :string)
25 field(:file_name, :string)
26 field(:file_size, :integer, default: 0)
27 field(:processed, :boolean, default: false)
29 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
34 def create(user, admin_id \\ nil) do
35 with :ok <- validate_limit(user, admin_id),
36 {:ok, backup} <- user |> new() |> Repo.insert() do
37 BackupWorker.process(backup, admin_id)
42 rand_str = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
43 datetime = Calendar.NaiveDateTime.Format.iso8601_basic(NaiveDateTime.utc_now())
44 name = "archive-#{user.nickname}-#{datetime}-#{rand_str}.zip"
48 content_type: "application/zip",
54 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
56 with :ok <- uploader.delete_file(Path.join("backups", backup.file_name)) do
61 defp validate_limit(_user, admin_id) when is_binary(admin_id), do: :ok
63 defp validate_limit(user, nil) do
64 case get_last(user.id) do
65 %__MODULE__{inserted_at: inserted_at} ->
66 days = Pleroma.Config.get([__MODULE__, :limit_days])
67 diff = Timex.diff(NaiveDateTime.utc_now(), inserted_at, :days)
75 "Last export was less than a day ago",
76 "Last export was less than %{days} days ago",
87 def get_last(user_id) do
89 |> where(user_id: ^user_id)
90 |> order_by(desc: :id)
95 def list(%User{id: user_id}) do
97 |> where(user_id: ^user_id)
98 |> order_by(desc: :id)
102 def remove_outdated(%__MODULE__{id: latest_id, user_id: user_id}) do
104 |> where(user_id: ^user_id)
105 |> where([b], b.id != ^latest_id)
107 |> Enum.each(&BackupWorker.delete/1)
110 def get(id), do: Repo.get(__MODULE__, id)
112 def process(%__MODULE__{} = backup) do
113 with {:ok, zip_file} <- export(backup),
114 {:ok, %{size: size}} <- File.stat(zip_file),
115 {:ok, _upload} <- upload(backup, zip_file) do
117 |> cast(%{file_size: size, processed: true}, [:file_size, :processed])
122 @files ['actor.json', 'outbox.json', 'likes.json', 'bookmarks.json']
123 def export(%__MODULE__{} = backup) do
124 backup = Repo.preload(backup, :user)
125 name = String.trim_trailing(backup.file_name, ".zip")
128 with :ok <- File.mkdir(dir),
129 :ok <- actor(dir, backup.user),
130 :ok <- statuses(dir, backup.user),
131 :ok <- likes(dir, backup.user),
132 :ok <- bookmarks(dir, backup.user),
134 :zip.create(String.to_charlist(dir <> ".zip"), @files, cwd: String.to_charlist(dir)),
135 {:ok, _} <- File.rm_rf(dir) do
136 {:ok, to_string(zip_path)}
141 dir = Pleroma.Config.get([__MODULE__, :dir]) || System.tmp_dir!()
145 def upload(%__MODULE__{} = backup, zip_path) do
146 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
148 upload = %Pleroma.Upload{
149 name: backup.file_name,
151 content_type: backup.content_type,
152 path: Path.join("backups", backup.file_name)
155 with {:ok, _} <- Pleroma.Uploaders.Uploader.put_file(uploader, upload),
156 :ok <- File.rm(zip_path) do
161 defp actor(dir, user) do
163 UserView.render("user.json", %{user: user})
164 |> Map.merge(%{"likes" => "likes.json", "bookmarks" => "bookmarks.json"})
166 File.write(Path.join(dir, "actor.json"), json)
170 defp write_header(file, name) do
175 "@context": "https://www.w3.org/ns/activitystreams",
176 "id": "#{name}.json",
177 "type": "OrderedCollection",
184 defp write(query, dir, name, fun) do
185 path = Path.join(dir, "#{name}.json")
187 with {:ok, file} <- File.open(path, [:write, :utf8]),
188 :ok <- write_header(file, name) do
191 |> Pleroma.Repo.chunk_stream(100)
192 |> Enum.reduce(0, fn i, acc ->
193 with {:ok, data} <- fun.(i),
194 {:ok, str} <- Jason.encode(data),
195 :ok <- IO.write(file, str <> ",\n") do
202 with :ok <- :file.pwrite(file, {:eof, -2}, "\n],\n \"totalItems\": #{total}}") do
208 defp bookmarks(dir, %{id: user_id} = _user) do
210 |> where(user_id: ^user_id)
211 |> join(:inner, [b], activity in assoc(b, :activity))
212 |> select([b, a], %{id: b.id, object: fragment("(?)->>'object'", a.data)})
213 |> write(dir, "bookmarks", fn a -> {:ok, a.object} end)
216 defp likes(dir, user) do
218 |> Activity.Queries.by_actor()
219 |> Activity.Queries.by_type("Like")
220 |> select([like], %{id: like.id, object: fragment("(?)->>'object'", like.data)})
221 |> write(dir, "likes", fn a -> {:ok, a.object} end)
224 defp statuses(dir, user) do
227 |> Map.put(:type, ["Create", "Announce"])
228 |> Map.put(:actor_id, user.ap_id)
231 [Pleroma.Constants.as_public(), user.ap_id],
232 User.following(user),
233 Pleroma.List.memberships(user)
236 |> ActivityPub.fetch_activities_query(opts)
237 |> write(dir, "outbox", fn a ->
238 with {:ok, activity} <- Transmogrifier.prepare_outgoing(a.data) do
239 {:ok, Map.delete(activity, "@context")}