summaryrefslogtreecommitdiff
path: root/lib/mix/tasks/migrate_local_uploads.ex
blob: 8f9e210c00c904a6ca9212c4f49e81f93624bb5c (plain)
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
defmodule Mix.Tasks.MigrateLocalUploads do
  use Mix.Task
  import Mix.Ecto
  alias Pleroma.{Upload, Uploaders.Local, Uploaders.S3}
  require Logger

  @log_every 50
  @shortdoc "Migrate uploads from local to remote storage"

  def run([target_uploader | args]) do
    delete? = Enum.member?(args, "--delete")
    Application.ensure_all_started(:pleroma)

    local_path = Pleroma.Config.get!([Local, :uploads])
    uploader = Module.concat(Pleroma.Uploaders, target_uploader)

    unless Code.ensure_loaded?(uploader) do
      raise("The uploader #{inspect(uploader)} is not an existing/loaded module.")
    end

    target_enabled? = Pleroma.Config.get([Upload, :uploader]) == uploader

    unless target_enabled? do
      Pleroma.Config.put([Upload, :uploader], uploader)
    end

    Logger.info("Migrating files from local #{local_path} to #{to_string(uploader)}")

    if delete? do
      Logger.warn(
        "Attention: uploaded files will be deleted, hope you have backups! (--delete ; cancel with ^C)"
      )

      :timer.sleep(:timer.seconds(5))
    end

    uploads =
      File.ls!(local_path)
      |> Enum.map(fn id ->
        root_path = Path.join(local_path, id)

        cond do
          File.dir?(root_path) ->
            files = for file <- File.ls!(root_path), do: {id, file, Path.join([root_path, file])}

            case List.first(files) do
              {id, file, path} ->
                {%Pleroma.Upload{id: id, name: file, path: id <> "/" <> file, tempfile: path},
                 root_path}

              _ ->
                nil
            end

          File.exists?(root_path) ->
            file = Path.basename(id)
            [hash, ext] = String.split(id, ".")
            {%Pleroma.Upload{id: hash, name: file, path: file, tempfile: root_path}, root_path}

          true ->
            nil
        end
      end)
      |> Enum.filter(& &1)

    total_count = length(uploads)
    Logger.info("Found #{total_count} uploads")

    uploads
    |> Task.async_stream(
      fn {upload, root_path} ->
        case Upload.store(upload, uploader: uploader, filters: [], size_limit: nil) do
          {:ok, _} ->
            if delete?, do: File.rm_rf!(root_path)
            Logger.debug("uploaded: #{inspect(upload.path)} #{inspect(upload)}")
            :ok

          error ->
            Logger.error("failed to upload #{inspect(upload.path)}: #{inspect(error)}")
        end
      end,
      timeout: 150_000
    )
    |> Stream.chunk_every(@log_every)
    |> Enum.reduce(0, fn done, count ->
      count = count + length(done)
      Logger.info("Uploaded #{count}/#{total_count} files")
      count
    end)

    Logger.info("Done!")
  end

  def run(_) do
    Logger.error("Usage: migrate_local_uploads S3|Swift [--delete]")
  end
end