A platform for community discussion. Free, open, simple.
FEATURE: Add a voice usage report to Rewind (#44435)
Rafael dos Santos Silvae490b65d47e7
diff --git a/plugins/discourse-rewind/app/services/discourse_rewind/action/voice_usage.rb b/plugins/discourse-rewind/app/services/discourse_rewind/action/voice_usage.rbnew file mode 100644index 00000000000..b1e7c914487--- /dev/null+++ b/plugins/discourse-rewind/app/services/discourse_rewind/action/voice_usage.rb@@ -0,0 +1,144 @@+# frozen_string_literal: true++module DiscourseRewind+ module Action+ class VoiceUsage < BaseReport+ MINIMUM_SECONDS = 1.hour.to_i+ TOP_LIMIT = 3++ # A session with no end is either live or was never swept; either way+ # its real length is unknown, so it counts as a short call.+ UNENDED_SESSION_CAP = "30 minutes"++ FakeData = {+ data: {+ total_seconds: 310_440,+ call_count: 214,+ top_rooms: [+ { room_id: 1, name: "Game night", slug: "game-night", seconds: 147_600 },+ { room_id: 2, name: "Coworking", slug: "coworking", seconds: 82_800 },+ { room_id: 3, name: "Town hall", slug: "town-hall", seconds: 21_600 },+ ],+ top_contacts: [+ {+ user: {+ id: 2,+ username: "sam",+ name: "Sam",+ avatar_template: "/letter_avatar_proxy/v4/letter/s/8c91d9/{size}.png",+ },+ seconds: 133_200,+ },+ {+ user: {+ id: 3,+ username: "alex",+ name: "Alex",+ avatar_template: "/letter_avatar_proxy/v4/letter/a/e47774/{size}.png",+ },+ seconds: 64_800,+ },+ {+ user: {+ id: 4,+ username: "jo",+ name: "Jo",+ avatar_template: "/letter_avatar_proxy/v4/letter/j/3ab54a/{size}.png",+ },+ seconds: 25_200,+ },+ ],+ },+ identifier: "voice-usage",+ }++ def call+ return FakeData if should_use_fake_data?++ sessions = Voice::Session.where(user_id: user.id, joined_at: date)+ total_seconds, call_count =+ sessions.pick(Arel.sql("COALESCE(SUM(#{duration_sql}), 0)::bigint"), Arel.sql("COUNT(*)"))++ return if total_seconds < MINIMUM_SECONDS++ {+ data: {+ total_seconds:,+ call_count:,+ top_rooms: top_rooms(sessions),+ top_contacts:,+ },+ identifier: "voice-usage",+ }+ end++ def self.filter_for_viewer(report, guardian:, for_user:)+ top_rooms = report[:data][:top_rooms]+ visible_room_ids = Voice::Room.visible_to(guardian).where(id: top_rooms.pluck(:room_id)).ids++ report.deep_merge(+ data: {+ top_rooms: top_rooms.select { |room| room[:room_id].in?(visible_room_ids) },+ # Co-presence spans private rooms and calls, so who someone talks+ # to stays with them.+ top_contacts: guardian.is_me?(for_user) ? report[:data][:top_contacts] : [],+ },+ )+ end++ def self.enabled?+ plugin_enabled?("voice")+ end++ private++ def duration_sql+ <<~SQL+ EXTRACT(EPOCH FROM (+ COALESCE(+ voice_sessions.left_at,+ LEAST(CURRENT_TIMESTAMP, voice_sessions.joined_at + INTERVAL '#{UNENDED_SESSION_CAP}')+ ) - voice_sessions.joined_at+ ))+ SQL+ end++ def top_rooms(sessions)+ sessions+ .joins(:room)+ .merge(Voice::Room.persistent)+ .group("voice_rooms.id", "voice_rooms.name", "voice_rooms.slug")+ .order(Arel.sql("SUM(#{duration_sql}) DESC"), "voice_rooms.id")+ .limit(TOP_LIMIT)+ .pluck(+ "voice_rooms.id",+ "voice_rooms.name",+ "voice_rooms.slug",+ Arel.sql("SUM(#{duration_sql})::bigint"),+ )+ .map { |room_id, name, slug, seconds| { room_id:, name:, slug:, seconds: } }+ end++ def top_contacts+ # Over-fetch to leave headroom for contacts dropped below (bots, deleted users).+ contact_seconds =+ Voice::CoPresence+ .where("user_id_1 = :id OR user_id_2 = :id", id: user.id)+ .where(date: date.first.to_date..date.last.to_date)+ .group(Arel.sql("CASE WHEN user_id_1 = #{user.id} THEN user_id_2 ELSE user_id_1 END"))+ .order(Arel.sql("SUM(total_seconds) DESC"))+ .limit(TOP_LIMIT * 3)+ .sum(:total_seconds)++ users = User.real.where(id: contact_seconds.keys).index_by(&:id)++ contact_seconds+ .filter_map do |contact_id, seconds|+ next if !(contact = users[contact_id])+ { user: BasicUserSerializer.new(contact, root: false).as_json, seconds: }+ end+ .first(TOP_LIMIT)+ end+ end+ end+enddiff --git a/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rb b/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rbindex d233f332dd1..8ce83336e92 100644--- a/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rb+++ b/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rb@@ -43,6 +43,7 @@ module DiscourseRewindAction::TimeOfDayActivity,Action::NewUserInteractions,Action::ChatUsage,+ Action::VoiceUsage,Action::AiUsage,Action::Assignments,Action::Invites,diff --git a/plugins/discourse-rewind/assets/javascripts/discourse/components/reports/voice-usage.gjs b/plugins/discourse-rewind/assets/javascripts/discourse/components/reports/voice-usage.gjsnew file mode 100644index 00000000000..4c494c6f699--- /dev/null+++ b/plugins/discourse-rewind/assets/javascripts/discourse/components/reports/voice-usage.gjs@@ -0,0 +1,113 @@+import Component from "@glimmer/component";+import { concat, hash } from "@ember/helper";+import getURL from "discourse/lib/get-url";+import { userPath } from "discourse/lib/url";+import dBoundAvatarTemplate from "discourse/ui-kit/helpers/d-bound-avatar-template";+import { i18n } from "discourse-i18n";+import { i18nForOwner } from "discourse/plugins/discourse-rewind/discourse/lib/rewind-i18n";++function airtime(seconds) {+ const hours = Math.floor(seconds / 3600);+ if (hours > 0) {+ return i18n("discourse_rewind.reports.voice_usage.hours", { count: hours });+ }+ return i18n("discourse_rewind.reports.voice_usage.minutes", {+ count: Math.floor(seconds / 60),+ });+}++export default class VoiceUsage extends Component {+ get subtitleText() {+ return i18nForOwner(+ "discourse_rewind.reports.voice_usage.subtitle",+ this.args.isOwnRewind,+ { username: this.args.user?.username }+ );+ }++ get callCountText() {+ return i18n("discourse_rewind.reports.voice_usage.call_count", {+ count: this.args.report.data.call_count,+ });+ }++ <template>+ <div class="rewind-report-page --voice-usage">+ <div class="phone-bill">+ <div class="phone-bill__header">+ <div class="phone-bill__title">+ {{i18n "discourse_rewind.reports.voice_usage.title"}}+ </div>+ <div class="phone-bill__subtitle">{{this.subtitleText}}</div>+ </div>++ <div class="phone-bill__total">+ <div class="phone-bill__total-label">+ {{i18n "discourse_rewind.reports.voice_usage.total_airtime"}}+ </div>+ <div class="phone-bill__total-value">+ {{airtime @report.data.total_seconds}}+ </div>+ <div class="phone-bill__total-calls">{{this.callCountText}}</div>+ </div>++ {{#if @report.data.top_contacts.length}}+ <div class="phone-bill__section">+ <div class="phone-bill__section-title">+ {{i18n "discourse_rewind.reports.voice_usage.top_contacts"}}+ </div>+ <ol class="phone-bill__items">+ {{#each @report.data.top_contacts as |contact|}}+ <li class="phone-bill__item">+ <a+ class="phone-bill__item-name"+ href={{userPath contact.user.username}}+ >+ {{dBoundAvatarTemplate+ contact.user.avatar_template+ "tiny"+ (hash title=contact.user.username)+ }}+ @{{contact.user.username}}+ </a>+ <span class="phone-bill__item-leader"></span>+ <span class="phone-bill__item-value">+ {{airtime contact.seconds}}+ </span>+ </li>+ {{/each}}+ </ol>+ </div>+ {{/if}}++ {{#if @report.data.top_rooms.length}}+ <div class="phone-bill__section">+ <div class="phone-bill__section-title">+ {{i18n "discourse_rewind.reports.voice_usage.top_rooms"}}+ </div>+ <ol class="phone-bill__items">+ {{#each @report.data.top_rooms as |room|}}+ <li class="phone-bill__item">+ <a+ class="phone-bill__item-name"+ href={{getURL (concat "/voice/r/" room.slug)}}+ >+ {{room.name}}+ </a>+ <span class="phone-bill__item-leader"></span>+ <span class="phone-bill__item-value">+ {{airtime room.seconds}}+ </span>+ </li>+ {{/each}}+ </ol>+ </div>+ {{/if}}++ <div class="phone-bill__footer">+ {{i18n "discourse_rewind.reports.voice_usage.amount_due"}}+ </div>+ </div>+ </div>+ </template>+}diff --git a/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjs b/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjsindex 725ee9a3aba..908882833f0 100644--- a/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjs+++ b/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjs@@ -33,6 +33,7 @@ import Reactions from "discourse/plugins/discourse-rewind/discourse/components/rimport ReadingTime from "discourse/plugins/discourse-rewind/discourse/components/reports/reading-time";import TimeOfDayActivity from "discourse/plugins/discourse-rewind/discourse/components/reports/time-of-day-activity";import TopWords from "discourse/plugins/discourse-rewind/discourse/components/reports/top-words";+import VoiceUsage from "discourse/plugins/discourse-rewind/discourse/components/reports/voice-usage";import WritingAnalysis from "discourse/plugins/discourse-rewind/discourse/components/reports/writing-analysis";const REPORT_COMPONENTS = {@@ -51,6 +52,7 @@ const REPORT_COMPONENTS = {"reading-time": ReadingTime,"time-of-day-activity": TimeOfDayActivity,"top-words": TopWords,+ "voice-usage": VoiceUsage,"writing-analysis": WritingAnalysis,};diff --git a/plugins/discourse-rewind/assets/stylesheets/common/_index.scss b/plugins/discourse-rewind/assets/stylesheets/common/_index.scssindex 162a33565dc..4f38203d0ea 100644--- a/plugins/discourse-rewind/assets/stylesheets/common/_index.scss+++ b/plugins/discourse-rewind/assets/stylesheets/common/_index.scss@@ -23,3 +23,4 @@@import "ai-usage";@import "assignments";@import "invites";+@import "voice-usage";diff --git a/plugins/discourse-rewind/assets/stylesheets/common/voice-usage.scss b/plugins/discourse-rewind/assets/stylesheets/common/voice-usage.scssnew file mode 100644index 00000000000..3985aa1556e--- /dev/null+++ b/plugins/discourse-rewind/assets/stylesheets/common/voice-usage.scss@@ -0,0 +1,130 @@+.--voice-usage {+ .phone-bill {+ position: relative;+ width: 100%;+ max-width: 420px;+ margin: 1em auto 2em;+ padding: 1.5em 1.5em 2em;+ box-sizing: border-box;+ background: var(--rewind-beige);+ color: var(--rewind-black);+ font-family: "Courier New", Courier, monospace;+ font-size: var(--font-down-1);+ box-shadow: 4px 4px 0 rgb(0 0 0 / 0.3);+ transform: rotate(-1deg);+ z-index: 9; // above the scanlines++ // Torn-paper bottom edge.+ &::after {+ content: "";+ position: absolute;+ left: 0;+ right: 0;+ bottom: -10px;+ height: 10px;+ background:+ linear-gradient(-45deg, transparent 7px, var(--rewind-beige) 0),+ linear-gradient(45deg, transparent 7px, var(--rewind-beige) 0);+ background-size: 14px 10px;+ }+ }++ .phone-bill__header {+ text-align: center;+ padding-bottom: 1em;+ border-bottom: 2px dashed var(--rewind-grey);+ }++ .phone-bill__title {+ font-size: var(--font-up-3);+ font-weight: bold;+ letter-spacing: 0.15em;+ text-transform: uppercase;+ }++ .phone-bill__subtitle {+ color: var(--rewind-grey);+ }++ .phone-bill__total {+ text-align: center;+ padding: 1em 0;+ border-bottom: 2px dashed var(--rewind-grey);+ }++ .phone-bill__total-label {+ text-transform: uppercase;+ letter-spacing: 0.1em;+ }++ .phone-bill__total-value {+ font-size: var(--font-up-5);+ font-weight: bold;+ line-height: 1.2;+ }++ .phone-bill__total-calls {+ color: var(--rewind-grey);+ }++ .phone-bill__section {+ padding: 1em 0 0;+ }++ .phone-bill__section-title {+ font-weight: bold;+ text-transform: uppercase;+ margin-bottom: 0.5em;+ }++ .phone-bill__items {+ list-style: none;+ margin: 0;+ padding: 0;+ }++ .phone-bill__item {+ display: flex;+ align-items: baseline;+ gap: 0.5em;+ padding: 0.2em 0;+ }++ .phone-bill__item-name {+ display: inline-flex;+ align-items: center;+ gap: 0.35em;+ min-width: 0;+ overflow: hidden;+ color: var(--rewind-black);+ text-overflow: ellipsis;+ white-space: nowrap;++ &:hover {+ text-decoration: underline;+ }++ .avatar {+ flex-shrink: 0;+ }+ }++ .phone-bill__item-leader {+ flex: 1;+ min-width: 1em;+ border-bottom: 2px dotted var(--rewind-light-grey);+ }++ .phone-bill__item-value {+ flex-shrink: 0;+ font-weight: bold;+ }++ .phone-bill__footer {+ margin-top: 1.5em;+ padding-top: 1em;+ border-top: 2px dashed var(--rewind-grey);+ text-align: center;+ font-weight: bold;+ }+}diff --git a/plugins/discourse-rewind/config/locales/client.en.yml b/plugins/discourse-rewind/config/locales/client.en.ymlindex 8caae1c198b..a21483b1cc6 100644--- a/plugins/discourse-rewind/config/locales/client.en.yml+++ b/plugins/discourse-rewind/config/locales/client.en.yml@@ -129,6 +129,23 @@ en:message_4: "Your average message length was <strong>%{length}</strong> characters"message_5: "Your favorite channels:"dancing_baby_alt: "Dancing baby"+ voice_usage:+ title: Phone bill+ subtitle: Your voice call statement+ subtitle_others: "%{username}'s voice call statement"+ total_airtime: Total airtime+ call_count:+ one: "across %{count} call"+ other: "across %{count} calls"+ top_contacts: Most talked with+ top_rooms: Favorite rooms+ hours:+ one: "%{count} hr"+ other: "%{count} hrs"+ minutes:+ one: "%{count} min"+ other: "%{count} mins"+ amount_due: "Amount due: nothing, calls are on the house"invites:guest_book_title: Guest Bookguest_book_subtitle: Your Community Invitationsdiff --git a/plugins/discourse-rewind/spec/actions/voice_usage_spec.rb b/plugins/discourse-rewind/spec/actions/voice_usage_spec.rbnew file mode 100644index 00000000000..89144f6ec71--- /dev/null+++ b/plugins/discourse-rewind/spec/actions/voice_usage_spec.rb@@ -0,0 +1,99 @@+# frozen_string_literal: true++RSpec.describe DiscourseRewind::Action::VoiceUsage do+ fab!(:user)+ fab!(:friend, :user)+ fab!(:public_room) { Fabricate(:voice_room, public: true) }+ fab!(:private_room, :voice_room)++ before { SiteSetting.voice_enabled = true }++ def fabricate_session(room:, joined_at:, duration:)+ Fabricate(:voice_session, user:, room:, joined_at:, left_at: duration && joined_at + duration)+ end++ describe ".call" do+ it "returns nothing when there is too little airtime to show" do+ fabricate_session(room: public_room, joined_at: random_datetime, duration: 10.minutes)++ expect(call_report).to be_nil+ end++ it "returns the airtime, favorite rooms and most frequent contacts" do+ fabricate_session(room: public_room, joined_at: random_datetime, duration: 2.hours)+ fabricate_session(room: private_room, joined_at: random_datetime, duration: 1.hour)+ fabricate_session(+ room: Fabricate(:voice_ephemeral_room),+ joined_at: random_datetime,+ duration: 1.hour,+ )+ fabricate_session(room: public_room, joined_at: 2.years.ago, duration: 5.hours)+ Voice::CoPresence.create!(+ user_id_1: [user.id, friend.id].min,+ user_id_2: [user.id, friend.id].max,+ date: random_datetime.to_date,+ total_seconds: 1.hour.to_i,+ session_count: 1,+ )++ expect(call_report[:data]).to eq(+ total_seconds: 4.hours.to_i,+ call_count: 3,+ top_rooms: [+ {+ room_id: public_room.id,+ name: public_room.name,+ slug: public_room.slug,+ seconds: 2.hours.to_i,+ },+ {+ room_id: private_room.id,+ name: private_room.name,+ slug: private_room.slug,+ seconds: 1.hour.to_i,+ },+ ],+ top_contacts: [+ { user: BasicUserSerializer.new(friend, root: false).as_json, seconds: 1.hour.to_i },+ ],+ )+ end++ it "caps sessions that never ended" do+ fabricate_session(room: public_room, joined_at: random_datetime, duration: 1.hour)+ fabricate_session(room: public_room, joined_at: random_datetime, duration: nil)++ expect(call_report[:data][:total_seconds]).to eq(90.minutes.to_i)+ end+ end++ describe ".filter_for_viewer" do+ let(:report) do+ {+ data: {+ top_rooms: [public_room, private_room].map { |room| { room_id: room.id } },+ top_contacts: [{ user: { id: friend.id }, seconds: 1 }],+ },+ }+ end++ it "keeps everything the owner can see" do+ private_room.room_memberships.create!(user:)++ filtered = described_class.filter_for_viewer(report, guardian: user.guardian, for_user: user)++ expect(filtered).to eq(report)+ end++ it "hides contacts and rooms other viewers cannot see" do+ filtered =+ described_class.filter_for_viewer(+ report,+ guardian: Fabricate(:user).guardian,+ for_user: user,+ )++ expect(filtered[:data]).to eq(top_rooms: [{ room_id: public_room.id }], top_contacts: [])+ end+ end+end