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.Export do
9 alias Pleroma.Web.ActivityPub.ActivityPub
10 alias Pleroma.Web.ActivityPub.Transmogrifier
11 alias Pleroma.Web.ActivityPub.UserView
15 @files ['actor.json', 'outbox.json', 'likes.json', 'bookmarks.json']
18 with {:ok, path} <- create_dir(user),
19 :ok <- actor(path, user),
20 :ok <- statuses(path, user),
21 :ok <- likes(path, user),
22 :ok <- bookmarks(path, user),
23 {:ok, zip_path} <- :zip.create('#{path}.zip', @files, cwd: path),
24 {:ok, _} <- File.rm_rf(path) do
29 defp actor(dir, user) do
31 UserView.render("user.json", %{user: user})
32 |> Map.merge(%{"likes" => "likes.json", "bookmarks" => "bookmarks.json"})
34 File.write(dir <> "/actor.json", json)
38 defp create_dir(user) do
39 datetime = Calendar.NaiveDateTime.Format.iso8601_basic(NaiveDateTime.utc_now())
40 dir = Path.join(System.tmp_dir!(), "archive-#{user.id}-#{datetime}")
42 with :ok <- File.mkdir(dir), do: {:ok, dir}
45 defp write_header(file, name) do
50 "@context": "https://www.w3.org/ns/activitystreams",
52 "type": "OrderedCollection",
58 defp write(query, dir, name, fun) do
59 path = dir <> "/#{name}.json"
61 with {:ok, file} <- File.open(path, [:write, :utf8]),
62 :ok <- write_header(file, name) do
63 counter = :counters.new(1, [])
66 |> Pleroma.RepoStreamer.chunk_stream(100)
67 |> Stream.each(fn items ->
68 Enum.each(items, fn i ->
69 with {:ok, str} <- fun.(i),
70 :ok <- IO.write(file, str <> ",\n") do
71 :counters.add(counter, 1, 1)
77 total = :counters.get(counter, 1)
79 with :ok <- :file.pwrite(file, {:eof, -2}, "\n],\n \"totalItems\": #{total}}") do
85 defp bookmarks(dir, %{id: user_id} = _user) do
87 |> where(user_id: ^user_id)
88 |> join(:inner, [b], activity in assoc(b, :activity))
89 |> select([b, a], %{id: b.id, object: fragment("(?)->>'object'", a.data)})
90 |> write(dir, "bookmarks", fn a -> {:ok, "\"#{a.object}\""} end)
93 defp likes(dir, user) do
95 |> Activity.Queries.by_actor()
96 |> Activity.Queries.by_type("Like")
97 |> select([like], %{id: like.id, object: fragment("(?)->>'object'", like.data)})
98 |> write(dir, "likes", fn a -> {:ok, "\"#{a.object}\""} end)
101 defp statuses(dir, user) do
104 |> Map.put(:type, ["Create", "Announce"])
105 |> Map.put(:blocking_user, user)
106 |> Map.put(:muting_user, user)
107 |> Map.put(:reply_filtering_user, user)
108 |> Map.put(:announce_filtering_user, user)
109 |> Map.put(:user, user)
111 [[user.ap_id], User.following(user), Pleroma.List.memberships(user)]
113 |> ActivityPub.fetch_activities_query(opts)
114 |> write(dir, "outbox", fn a ->
115 with {:ok, activity} <- Transmogrifier.prepare_outgoing(a.data) do
116 activity |> Map.delete("@context") |> Jason.encode()