updates
[akkoma] / lib / mix / tasks / pleroma / uploads.ex
1 defmodule Mix.Tasks.Pleroma.Uploads do
2 use Mix.Task
3 alias Pleroma.{Upload, Uploaders.Local}
4 alias Mix.Tasks.Pleroma.Common
5 require Logger
6
7 @log_every 50
8 @shortdoc "Migrate uploads from local to remote storage"
9 @doc """
10 Manages uploads
11 ## Migrate uploads from local to remote storage
12
13 """
14 def run(["migrate_local", target_uploader | args]) do
15 delete? = Enum.member?(args, "--delete")
16 Common.start_pleroma()
17 local_path = Pleroma.Config.get!([Local, :uploads])
18 uploader = Module.concat(Pleroma.Uploaders, target_uploader)
19
20 unless Code.ensure_loaded?(uploader) do
21 raise("The uploader #{inspect(uploader)} is not an existing/loaded module.")
22 end
23
24 target_enabled? = Pleroma.Config.get([Upload, :uploader]) == uploader
25
26 unless target_enabled? do
27 Pleroma.Config.put([Upload, :uploader], uploader)
28 end
29
30 Mix.shell().info("Migrating files from local #{local_path} to #{to_string(uploader)}")
31
32 if delete? do
33 Mix.shell().info(
34 "Attention: uploaded files will be deleted, hope you have backups! (--delete ; cancel with ^C)"
35 )
36
37 :timer.sleep(:timer.seconds(5))
38 end
39
40 uploads =
41 File.ls!(local_path)
42 |> Enum.map(fn id ->
43 root_path = Path.join(local_path, id)
44
45 cond do
46 File.dir?(root_path) ->
47 files = for file <- File.ls!(root_path), do: {id, file, Path.join([root_path, file])}
48
49 case List.first(files) do
50 {id, file, path} ->
51 {%Pleroma.Upload{id: id, name: file, path: id <> "/" <> file, tempfile: path},
52 root_path}
53
54 _ ->
55 nil
56 end
57
58 File.exists?(root_path) ->
59 file = Path.basename(id)
60 hash = Path.rootname(id)
61 {%Pleroma.Upload{id: hash, name: file, path: file, tempfile: root_path}, root_path}
62
63 true ->
64 nil
65 end
66 end)
67 |> Enum.filter(& &1)
68
69 total_count = length(uploads)
70 Mix.shell().info("Found #{total_count} uploads")
71
72 uploads
73 |> Task.async_stream(
74 fn {upload, root_path} ->
75 case Upload.store(upload, uploader: uploader, filters: [], size_limit: nil) do
76 {:ok, _} ->
77 if delete?, do: File.rm_rf!(root_path)
78 Logger.debug("uploaded: #{inspect(upload.path)} #{inspect(upload)}")
79 :ok
80
81 error ->
82 Mix.shell().error("failed to upload #{inspect(upload.path)}: #{inspect(error)}")
83 end
84 end,
85 timeout: 150_000
86 )
87 |> Stream.chunk_every(@log_every)
88 |> Enum.reduce(0, fn done, count ->
89 count = count + length(done)
90 Mix.shell().info("Uploaded #{count}/#{total_count} files")
91 count
92 end)
93
94 Mix.shell().info("Done!")
95 end
96 end