diff --git a/lib/pinchflat/utils/number_utils.ex b/lib/pinchflat/utils/number_utils.ex index 4a8404b..b7128f8 100644 --- a/lib/pinchflat/utils/number_utils.ex +++ b/lib/pinchflat/utils/number_utils.ex @@ -13,4 +13,27 @@ defmodule Pinchflat.Utils.NumberUtils do |> max(minimum) |> min(maximum) end + + @doc """ + Converts a number to a human readable byte size. Can take a precision + option to specify the number of decimal places to round to. + + Returns {integer(), String.t()} + """ + def human_byte_size(number, opts \\ []) + def human_byte_size(nil, opts), do: human_byte_size(0, opts) + + def human_byte_size(number, opts) do + precision = Keyword.get(opts, :precision, 2) + suffixes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] + base = 1024 + + Enum.reduce_while(suffixes, {number / 1.0, "B"}, fn suffix, {value, _} -> + if value < base do + {:halt, {Float.round(value, precision), suffix}} + else + {:cont, {value / base, suffix}} + end + end) + end end diff --git a/lib/pinchflat_web/controllers/pages/page_controller.ex b/lib/pinchflat_web/controllers/pages/page_controller.ex index 60dd2d8..495c31c 100644 --- a/lib/pinchflat_web/controllers/pages/page_controller.ex +++ b/lib/pinchflat_web/controllers/pages/page_controller.ex @@ -20,14 +20,14 @@ defmodule PinchflatWeb.Pages.PageController do end defp render_home_page(conn) do + downloaded_media_items = where(MediaQuery.new(), ^MediaQuery.downloaded()) + conn |> render(:home, media_profile_count: Repo.aggregate(MediaProfile, :count, :id), source_count: Repo.aggregate(Source, :count, :id), - media_item_count: - MediaQuery.new() - |> where(^MediaQuery.downloaded()) - |> Repo.aggregate(:count, :id) + media_item_size: Repo.aggregate(downloaded_media_items, :sum, :media_size_bytes), + media_item_count: Repo.aggregate(downloaded_media_items, :count, :id) ) end diff --git a/lib/pinchflat_web/controllers/pages/page_html.ex b/lib/pinchflat_web/controllers/pages/page_html.ex index 16f7731..bdd0b10 100644 --- a/lib/pinchflat_web/controllers/pages/page_html.ex +++ b/lib/pinchflat_web/controllers/pages/page_html.ex @@ -1,5 +1,13 @@ defmodule PinchflatWeb.Pages.PageHTML do use PinchflatWeb, :html + alias Pinchflat.Utils.NumberUtils + embed_templates "page_html/*" + + def readable_media_filesize(media_filesize) do + {num, suffix} = NumberUtils.human_byte_size(media_filesize, precision: 1) + + "#{Float.round(num)} #{suffix}" + end end diff --git a/lib/pinchflat_web/controllers/pages/page_html/home.html.heex b/lib/pinchflat_web/controllers/pages/page_html/home.html.heex index c0ecb82..ea5b661 100644 --- a/lib/pinchflat_web/controllers/pages/page_html/home.html.heex +++ b/lib/pinchflat_web/controllers/pages/page_html/home.html.heex @@ -1,4 +1,4 @@ -