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