instance_media_attachments_measure.rb 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # frozen_string_literal: true
  2. class Admin::Metrics::Measure::InstanceMediaAttachmentsMeasure < Admin::Metrics::Measure::BaseMeasure
  3. include Admin::Metrics::Measure::QueryHelper
  4. include ActionView::Helpers::NumberHelper
  5. def self.with_params?
  6. true
  7. end
  8. def key
  9. 'instance_media_attachments'
  10. end
  11. def unit
  12. 'bytes'
  13. end
  14. def value_to_human_value(value)
  15. number_to_human_size(value)
  16. end
  17. def total_in_time_range?
  18. false
  19. end
  20. protected
  21. def perform_total_query
  22. domain = params[:domain]
  23. domain = Instance.by_domain_and_subdomains(params[:domain]).select(:domain) if params[:include_subdomains]
  24. MediaAttachment.joins(:account).merge(Account.where(domain: domain)).sum('COALESCE(file_file_size, 0) + COALESCE(thumbnail_file_size, 0)')
  25. end
  26. def perform_previous_total_query
  27. nil
  28. end
  29. def sql_array
  30. [sql_query_string, { start_at: @start_at, end_at: @end_at, domain: params[:domain] }]
  31. end
  32. def sql_query_string
  33. <<~SQL.squish
  34. SELECT axis.*, (
  35. WITH new_media_attachments AS (
  36. SELECT COALESCE(media_attachments.file_file_size, 0) + COALESCE(media_attachments.thumbnail_file_size, 0) AS size
  37. FROM media_attachments
  38. INNER JOIN accounts ON accounts.id = media_attachments.account_id
  39. WHERE date_trunc('day', media_attachments.created_at)::date = axis.period
  40. AND #{account_domain_sql(params[:include_subdomains])}
  41. )
  42. SELECT SUM(size) FROM new_media_attachments
  43. ) AS value
  44. FROM (
  45. SELECT generate_series(date_trunc('day', :start_at::timestamp)::date, date_trunc('day', :end_at::timestamp)::date, interval '1 day') AS period
  46. ) AS axis
  47. SQL
  48. end
  49. def time_period
  50. (@start_at.to_date..@end_at.to_date)
  51. end
  52. def previous_time_period
  53. ((@start_at.to_date - length_of_period)..(@end_at.to_date - length_of_period))
  54. end
  55. def params
  56. @params.permit(:domain, :include_subdomains)
  57. end
  58. end