Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add calendar subscription URLs to user preferences (#38598)

Rafael dos Santos Silvacda4b34e2c7c
diff --git a/app/assets/stylesheets/common/base/user.scss b/app/assets/stylesheets/common/base/user.scss
index 4d6ff3548c2..36276050693 100644
--- a/app/assets/stylesheets/common/base/user.scss
+++ b/app/assets/stylesheets/common/base/user.scss
@@ -1471,3 +1471,69 @@
width: 100%;
}
}
+
+.user-preferences .form-vertical:has(.calendar-subscriptions) {
+ width: 750px;
+}
+
+.calendar-subscriptions {
+ &__description {
+ color: var(--primary-medium);
+ margin-bottom: 1em;
+ }
+
+ &__warning {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ margin-bottom: 1em;
+ }
+
+ &__urls {
+ margin-top: 1em;
+ }
+
+ &__active-status {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ color: var(--success);
+ font-weight: bold;
+ margin-bottom: 1em;
+ }
+
+ &__actions {
+ display: flex;
+ gap: 0.5em;
+ margin-top: 1em;
+ }
+}
+
+.calendar-subscription-url {
+ padding: 0.75em 1em;
+ margin-bottom: 0.75em;
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ background: var(--secondary);
+
+ &__header {
+ margin-bottom: 0.5em;
+ }
+
+ &__label {
+ font-weight: bold;
+ }
+
+ &__description {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ margin-left: 0.25em;
+ }
+
+ &__actions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.5em;
+ }
+}
diff --git a/app/controllers/calendar_subscriptions_controller.rb b/app/controllers/calendar_subscriptions_controller.rb
new file mode 100644
index 00000000000..d0c7d1e7258
--- /dev/null
+++ b/app/controllers/calendar_subscriptions_controller.rb
@@ -0,0 +1,87 @@
+# frozen_string_literal: true
+
+class CalendarSubscriptionsController < ApplicationController
+ requires_login
+
+ CLIENT_ID = "calendar-subscriptions"
+
+ before_action :rate_limit_create, only: :create
+
+ def show
+ render json: { has_subscription: find_calendar_api_key.present?, feeds: feed_names }
+ end
+
+ def create
+ revoke_existing_key!
+
+ client =
+ UserApiKeyClient.find_or_create_by!(client_id: CLIENT_ID) do |c|
+ c.application_name = I18n.t("calendar_subscriptions.application_name")
+ end
+
+ scopes = build_scopes
+ api_key = client.keys.create!(user_id: current_user.id, scopes: scopes)
+ raw_key = api_key.key
+
+ render json: { key: raw_key, urls: build_urls(raw_key) }
+ end
+
+ def destroy
+ revoke_existing_key!
+ head :no_content
+ end
+
+ private
+
+ def find_calendar_api_key
+ UserApiKey
+ .active
+ .joins(:client)
+ .where(user_id: current_user.id, user_api_key_clients: { client_id: CLIENT_ID })
+ .first
+ end
+
+ def revoke_existing_key!
+ find_calendar_api_key&.update!(revoked_at: Time.zone.now)
+ end
+
+ def build_scopes
+ scope_names = ["bookmarks_calendar"] + plugin_feeds.map { |f| f[:scope] }
+ all_scopes = UserApiKeyScope.all_scopes
+ scope_names.uniq.filter_map do |name|
+ if all_scopes.key?(name.to_sym)
+ UserApiKeyScope.new(name: name)
+ else
+ Rails.logger.warn("Calendar subscription feed references unknown scope: #{name}. Skipping.")
+ nil
+ end
+ end
+ end
+
+ def build_urls(raw_key)
+ base = Discourse.base_url
+ username = current_user.username_lower
+
+ urls = { bookmarks: "#{base}/u/#{username}/bookmarks.ics?user_api_key=#{raw_key}" }
+
+ plugin_feeds.each do |feed|
+ urls[feed[:name].to_sym] = feed[:url].call(base, current_user, raw_key)
+ end
+
+ urls
+ end
+
+ def feed_names
+ names = ["bookmarks"]
+ names += plugin_feeds.map { |f| f[:name] }
+ names
+ end
+
+ def plugin_feeds
+ @plugin_feeds ||= DiscoursePluginRegistry.calendar_subscription_feeds
+ end
+
+ def rate_limit_create
+ RateLimiter.new(current_user, "calendar-subscriptions-create", 5, 1.minute).performed!
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 47a99728d05..7f5563cfaa1 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -1924,6 +1924,24 @@ en:
apps: "Apps"
navigation_menu: "Navigation menu"
upcoming_changes: "Upcoming changes"
+ calendar_subscriptions: "Calendar"
+
+ calendar_subscriptions:
+ description: "Generate subscription URLs to sync with your favourite calendar app (Google Calendar, Apple Calendar, Outlook, etc.). These URLs are private links to calendar events for your account (bookmark reminders, calendar events, etc). You can always revoke or renew the generated subscription URLs. "
+ generate: "Generate Subscription URLs"
+ regenerate: "Regenerate URLs"
+ regenerate_confirm: "This will invalidate your existing calendar subscription URLs. Any calendar apps using the old URLs will stop receiving updates. Continue?"
+ revoke: "Revoke Subscription"
+ revoke_confirm: "This will revoke your calendar subscription URLs. Any calendar apps using them will stop receiving updates. Continue?"
+ urls_warning: "The subscription URLs are ready! Click the buttons below to link them to your calendar app. Note: these URLs are shown only once."
+ bookmarks: "Bookmark Reminders"
+ bookmarks_description: "Your bookmarks with reminder dates"
+ copy: "Copy URL"
+ copied: "Copied!"
+ add_to_google: "Google Calendar"
+ add_to_outlook: "Microsoft Outlook"
+ add_to_apple: "Apple Calendar"
+ active_subscription: "You have an active calendar subscription."
change_password:
success: "(email sent)"
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 2b3208de1b4..9cc8f53a693 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -1247,6 +1247,9 @@ en:
every_month: "every month"
every_six_months: "every six months"
+ calendar_subscriptions:
+ application_name: "Calendar Subscriptions"
+
user_api_key:
title: 'Authorize "%{application_name}"'
authorize: "Authorize"
diff --git a/config/routes.rb b/config/routes.rb
index 0f735fb51a0..22f9529f319 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -827,6 +827,10 @@ Discourse::Application.routes.draw do
:constraints => {
username: RouteFormat.username,
}
+ get "#{root_path}/:username/preferences/calendar-subscriptions" => "users#preferences",
+ :constraints => {
+ username: RouteFormat.username,
+ }
post "#{root_path}/:username/preferences/email" => "users_email#create",
:constraints => {
username: RouteFormat.username,
@@ -1860,6 +1864,10 @@ Discourse::Application.routes.draw do
get "/user-api-key-client" => "user_api_key_clients#show"
post "/user-api-key-client" => "user_api_key_clients#create"
+ get "/calendar-subscriptions" => "calendar_subscriptions#show"
+ post "/calendar-subscriptions" => "calendar_subscriptions#create"
+ delete "/calendar-subscriptions" => "calendar_subscriptions#destroy"
+
get "/safe-mode" => "safe_mode#index"
post "/safe-mode" => "safe_mode#enter", :as => "safe_mode_enter"
diff --git a/frontend/discourse/app/components/calendar-subscription-url.gjs b/frontend/discourse/app/components/calendar-subscription-url.gjs
new file mode 100644
index 00000000000..4f42fa0dbc8
--- /dev/null
+++ b/frontend/discourse/app/components/calendar-subscription-url.gjs
@@ -0,0 +1,79 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import icon from "discourse/helpers/d-icon";
+import { clipboardCopy } from "discourse/lib/utilities";
+import { i18n } from "discourse-i18n";
+
+export default class CalendarSubscriptionUrl extends Component {
+ @tracked copied = false;
+
+ get webcalUrl() {
+ return this.args.url.replace(/^https?:\/\//, "webcal://");
+ }
+
+ get googleCalendarUrl() {
+ return `https://calendar.google.com/calendar/r?cid=${encodeURIComponent(this.webcalUrl)}`;
+ }
+
+ get outlookCalendarUrl() {
+ return `https://outlook.live.com/owa?path=/calendar/action/compose&rru=addsubscription&url=${encodeURIComponent(this.args.url)}&name=${encodeURIComponent(this.args.label)}`;
+ }
+
+ @action
+ async copy(e) {
+ e.preventDefault();
+ await clipboardCopy(this.args.url);
+ this.copied = true;
+ setTimeout(() => (this.copied = false), 2000);
+ }
+
+ <template>
+ <div class="calendar-subscription-url">
+ <div class="calendar-subscription-url__header">
+ <span class="calendar-subscription-url__label">{{@label}}</span>
+ <span
+ class="calendar-subscription-url__description"
+ >{{@description}}</span>
+ </div>
+
+ <div class="calendar-subscription-url__actions">
+ <a
+ href={{@url}}
+ {{on "click" this.copy}}
+ class="btn btn-default btn-small"
+ >
+ {{icon (if this.copied "check" "copy")}}
+ {{if
+ this.copied
+ (i18n "user.calendar_subscriptions.copied")
+ (i18n "user.calendar_subscriptions.copy")
+ }}
+ </a>
+ <a
+ href={{this.googleCalendarUrl}}
+ target="_blank"
+ rel="noopener noreferrer"
+ class="btn btn-flat btn-small"
+ >
+ {{icon "fab-google"}}
+ {{i18n "user.calendar_subscriptions.add_to_google"}}
+ </a>
+ <a
+ href={{this.outlookCalendarUrl}}
+ target="_blank"
+ rel="noopener noreferrer"
+ class="btn btn-flat btn-small"
+ >
+ {{icon "fab-microsoft"}}
+ {{i18n "user.calendar_subscriptions.add_to_outlook"}}
+ </a>
+ <a href={{this.webcalUrl}} class="btn btn-flat btn-small">
+ {{icon "fab-apple"}}
+ {{i18n "user.calendar_subscriptions.add_to_apple"}}
+ </a>
+ </div>
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/routes/app-route-map.js b/frontend/discourse/app/routes/app-route-map.js
index 4636eb34273..357611872ce 100644
--- a/frontend/discourse/app/routes/app-route-map.js
+++ b/frontend/discourse/app/routes/app-route-map.js
@@ -174,6 +174,7 @@ export default function () {
this.route("interface");
this.route("apps");
this.route("navigation-menu");
+ this.route("calendar-subscriptions");
this.route("email");
this.route("second-factor");
diff --git a/frontend/discourse/app/routes/preferences/calendar-subscriptions.js b/frontend/discourse/app/routes/preferences/calendar-subscriptions.js
new file mode 100644
index 00000000000..d35d8faaf1c
--- /dev/null
+++ b/frontend/discourse/app/routes/preferences/calendar-subscriptions.js
@@ -0,0 +1,7 @@
+import RestrictedUserRoute from "discourse/routes/restricted-user";
+
+export default class PreferencesCalendarSubscriptions extends RestrictedUserRoute {
+ setupController(controller, user) {
+ controller.set("model", user);
+ }
+}
diff --git a/frontend/discourse/app/templates/preferences.gjs b/frontend/discourse/app/templates/preferences.gjs
index 033c230df01..f5fc3445904 100644
--- a/frontend/discourse/app/templates/preferences.gjs
+++ b/frontend/discourse/app/templates/preferences.gjs
@@ -94,6 +94,15 @@ export default <template>
<span>{{i18n "user.preferences_nav.navigation_menu"}}</span>
</DNavigationItem>
+ <DNavigationItem
+ @route="preferences.calendar-subscriptions"
+ @ariaCurrentContext="subNav"
+ class="user-nav__preferences-calendar-subscriptions"
+ >
+ {{icon "calendar-days"}}
+ <span>{{i18n "user.preferences_nav.calendar_subscriptions"}}</span>
+ </DNavigationItem>
+
<PluginOutlet
@name="user-preferences-nav-under-interface"
@connectorTagName="div"
diff --git a/frontend/discourse/app/templates/preferences/calendar-subscriptions.gjs b/frontend/discourse/app/templates/preferences/calendar-subscriptions.gjs
new file mode 100644
index 00000000000..d64b84b21e4
--- /dev/null
+++ b/frontend/discourse/app/templates/preferences/calendar-subscriptions.gjs
@@ -0,0 +1,144 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import CalendarSubscriptionUrl from "discourse/components/calendar-subscription-url";
+import DButton from "discourse/components/d-button";
+import PluginOutlet from "discourse/components/plugin-outlet";
+import icon from "discourse/helpers/d-icon";
+import lazyHash from "discourse/helpers/lazy-hash";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { eq } from "discourse/truth-helpers";
+import { i18n } from "discourse-i18n";
+
+export default class CalendarSubscriptions extends Component {
+ @service dialog;
+
+ @tracked hasSubscription = null;
+ @tracked urls = null;
+ @tracked loading = false;
+
+ constructor() {
+ super(...arguments);
+ this.loadStatus();
+ }
+
+ async loadStatus() {
+ try {
+ const result = await ajax("/calendar-subscriptions.json");
+ this.hasSubscription = result.has_subscription;
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ async generateUrls() {
+ this.loading = true;
+ try {
+ const result = await ajax("/calendar-subscriptions.json", {
+ type: "POST",
+ });
+ this.urls = result.urls;
+ this.hasSubscription = true;
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ regenerateUrls() {
+ this.dialog.confirm({
+ message: i18n("user.calendar_subscriptions.regenerate_confirm"),
+ didConfirm: () => this.generateUrls(),
+ });
+ }
+
+ @action
+ revokeSubscription() {
+ this.dialog.confirm({
+ message: i18n("user.calendar_subscriptions.revoke_confirm"),
+ didConfirm: async () => {
+ try {
+ await ajax("/calendar-subscriptions.json", {
+ type: "DELETE",
+ });
+ this.hasSubscription = false;
+ this.urls = null;
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ },
+ });
+ }
+
+ <template>
+ <div class="calendar-subscriptions">
+ <p class="calendar-subscriptions__description">
+ {{i18n "user.calendar_subscriptions.description"}}
+ </p>
+
+ {{#if this.urls}}
+ <div class="calendar-subscriptions__urls">
+ <div class="alert alert-info calendar-subscriptions__warning">
+ {{icon "triangle-exclamation"}}
+ {{i18n "user.calendar_subscriptions.urls_warning"}}
+ </div>
+
+ <CalendarSubscriptionUrl
+ @label={{i18n "user.calendar_subscriptions.bookmarks"}}
+ @description={{i18n
+ "user.calendar_subscriptions.bookmarks_description"
+ }}
+ @url={{this.urls.bookmarks}}
+ />
+
+ <PluginOutlet
+ @name="calendar-subscriptions-feeds"
+ @outletArgs={{lazyHash urls=this.urls}}
+ />
+
+ <div class="calendar-subscriptions__actions">
+ <DButton
+ @action={{this.revokeSubscription}}
+ @label="user.calendar_subscriptions.revoke"
+ class="btn-danger"
+ />
+ </div>
+ </div>
+ {{else if this.hasSubscription}}
+ <div class="calendar-subscriptions__active">
+ <p class="calendar-subscriptions__active-status">
+ {{icon "check"}}
+ {{i18n "user.calendar_subscriptions.active_subscription"}}
+ </p>
+ <div class="calendar-subscriptions__actions">
+ <DButton
+ @action={{this.regenerateUrls}}
+ @icon="arrows-rotate"
+ @label="user.calendar_subscriptions.regenerate"
+ @isLoading={{this.loading}}
+ class="btn-primary"
+ />
+ <DButton
+ @action={{this.revokeSubscription}}
+ @label="user.calendar_subscriptions.revoke"
+ class="btn-danger"
+ />
+ </div>
+ </div>
+ {{else if (eq this.hasSubscription false)}}
+ <DButton
+ @action={{this.generateUrls}}
+ @icon="calendar-days"
+ @label="user.calendar_subscriptions.generate"
+ @isLoading={{this.loading}}
+ class="btn-primary"
+ />
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/lib/discourse_plugin_registry.rb b/lib/discourse_plugin_registry.rb
index a17e1455332..6404d3f505a 100644
--- a/lib/discourse_plugin_registry.rb
+++ b/lib/discourse_plugin_registry.rb
@@ -131,6 +131,8 @@ class DiscoursePluginRegistry
define_filtered_register :flag_applies_to_types
+ define_filtered_register :calendar_subscription_feeds
+
define_filtered_register :custom_filter_mappings
define_filtered_register :reviewable_types do |singleton|
diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rb
index 6f77dc7660e..0a098428fb5 100644
--- a/lib/plugin/instance.rb
+++ b/lib/plugin/instance.rb
@@ -1052,6 +1052,24 @@ class Plugin::Instance
)
end
+ # Register an additional calendar subscription feed that appears in the user's
+ # calendar subscription preferences. Each feed needs a name (unique key),
+ # user API key scope name, and a lambda that builds the URL given (base_url, user, key).
+ #
+ # Example:
+ # register_calendar_subscription_feed(
+ # name: "all_events",
+ # scope: "discourse-calendar:events_calendar",
+ # description_key: "discourse_calendar.preferences.all_events_description",
+ # url: ->(base_url, user, key) { "#{base_url}/events.ics?user_api_key=#{key}" }
+ # )
+ def register_calendar_subscription_feed(name:, scope:, description_key:, url:)
+ DiscoursePluginRegistry.register_calendar_subscription_feed(
+ { name: name, scope: scope, description_key: description_key, url: url },
+ self,
+ )
+ end
+
# Register a new demon process to be forked by the Unicorn master.
# The demon_class should inherit from Demon::Base.
# With great power comes great responsibility - this method should
diff --git a/lib/svg_sprite.rb b/lib/svg_sprite.rb
index 4c866d6a813..7d519e28701 100644
--- a/lib/svg_sprite.rb
+++ b/lib/svg_sprite.rb
@@ -124,6 +124,7 @@ module SvgSprite
fab-instagram
fab-linkedin-in
fab-linux
+ fab-microsoft
fab-markdown
fab-threads
fab-threads-square
diff --git a/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb b/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb
index e8cb3ddf27e..509967442e4 100644
--- a/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb
+++ b/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb
@@ -164,6 +164,7 @@ module DiscoursePostEvent
:post_id,
:category_id,
:include_subcategories,
+ :include_interested,
:limit,
:attending_user,
:before,
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/connectors/calendar-subscriptions-feeds/event-feeds.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/connectors/calendar-subscriptions-feeds/event-feeds.gjs
new file mode 100644
index 00000000000..c24ca47a80c
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/connectors/calendar-subscriptions-feeds/event-feeds.gjs
@@ -0,0 +1,24 @@
+import CalendarSubscriptionUrl from "discourse/components/calendar-subscription-url";
+import { i18n } from "discourse-i18n";
+
+<template>
+ {{#if @outletArgs.urls.all_events}}
+ <CalendarSubscriptionUrl
+ @label={{i18n "discourse_calendar.preferences.all_events"}}
+ @description={{i18n
+ "discourse_calendar.preferences.all_events_description"
+ }}
+ @url={{@outletArgs.urls.all_events}}
+ />
+ {{/if}}
+
+ {{#if @outletArgs.urls.my_events}}
+ <CalendarSubscriptionUrl
+ @label={{i18n "discourse_calendar.preferences.my_events"}}
+ @description={{i18n
+ "discourse_calendar.preferences.my_events_description"
+ }}
+ @url={{@outletArgs.urls.my_events}}
+ />
+ {{/if}}
+</template>
diff --git a/plugins/discourse-calendar/config/locales/client.en.yml b/plugins/discourse-calendar/config/locales/client.en.yml
index 658825df773..bbbfbe17f71 100644
--- a/plugins/discourse-calendar/config/locales/client.en.yml
+++ b/plugins/discourse-calendar/config/locales/client.en.yml
@@ -28,6 +28,11 @@ en:
label: Topic ID
discourse_calendar:
invite_user_notification: "%{username} invited you to: %{description}"
+ preferences:
+ all_events: "Discourse Calendar - All Events"
+ all_events_description: "All forum events"
+ my_events: "Discourse Calendar - My Events"
+ my_events_description: "Events you are going to or interested in"
on_holiday: "On Holiday"
disable_holiday: "Disable"
enable_holiday: "Enable"
diff --git a/plugins/discourse-calendar/config/locales/server.en.yml b/plugins/discourse-calendar/config/locales/server.en.yml
index 329ff0a03ff..9fb92445942 100644
--- a/plugins/discourse-calendar/config/locales/server.en.yml
+++ b/plugins/discourse-calendar/config/locales/server.en.yml
@@ -1,4 +1,8 @@
en:
+ user_api_key:
+ scopes:
+ "discourse-calendar:events_calendar": "Read calendar events feed"
+
reports:
currently_away:
title: Users currently away
diff --git a/plugins/discourse-calendar/lib/discourse_post_event/event_finder.rb b/plugins/discourse-calendar/lib/discourse_post_event/event_finder.rb
index a36594a56e4..b23a36fdf29 100644
--- a/plugins/discourse-calendar/lib/discourse_post_event/event_finder.rb
+++ b/plugins/discourse-calendar/lib/discourse_post_event/event_finder.rb
@@ -62,17 +62,27 @@ module DiscoursePostEvent
attending_user = User.find_by(username_lower: params[:attending_user].downcase)
return events.none if !attending_user
+ statuses = [DiscoursePostEvent::Invitee.statuses[:going]]
+ if params[:include_interested].present? &&
+ can_include_interested?(guardian, user, attending_user)
+ statuses << DiscoursePostEvent::Invitee.statuses[:interested]
+ end
+
events =
events.joins(:invitees).where(
discourse_post_event_invitees: {
user_id: attending_user.id,
- status: DiscoursePostEvent::Invitee.statuses[:going],
+ status: statuses,
},
)
guardian.is_admin? ? events : apply_privacy_restrictions(events, user)
end
+ def self.can_include_interested?(guardian, user, attending_user)
+ guardian.is_admin? || user&.id == attending_user.id
+ end
+
def self.apply_privacy_restrictions(events, user)
private_status = DiscoursePostEvent::Event.statuses[:private]
diff --git a/plugins/discourse-calendar/plugin.rb b/plugins/discourse-calendar/plugin.rb
index 0a5859f0b11..cf3921c3a1d 100644
--- a/plugins/discourse-calendar/plugin.rb
+++ b/plugins/discourse-calendar/plugin.rb
@@ -149,6 +149,29 @@ after_initialize do
formats: :ics,
)
+ add_user_api_key_scope :events_calendar,
+ methods: :get,
+ actions: "discourse_post_event/events#index",
+ formats: :ics
+
+ register_calendar_subscription_feed(
+ name: "all_events",
+ scope: "discourse-calendar:events_calendar",
+ description_key: "discourse_calendar.preferences.all_events_description",
+ url: ->(base_url, _user, key) do
+ "#{base_url}/discourse-post-event/events.ics?user_api_key=#{key}"
+ end,
+ )
+
+ register_calendar_subscription_feed(
+ name: "my_events",
+ scope: "discourse-calendar:events_calendar",
+ description_key: "discourse_calendar.preferences.my_events_description",
+ url: ->(base_url, user, key) do
+ "#{base_url}/discourse-post-event/events.ics?attending_user=#{user.username_lower}&include_interested=true&user_api_key=#{key}"
+ end,
+ )
+
reloadable_patch do
ExportCsvController.prepend(DiscoursePostEvent::ExportCsvControllerExtension)
Jobs::ExportCsvFile.prepend(DiscoursePostEvent::ExportPostEventCsvReportExtension)
diff --git a/plugins/discourse-calendar/spec/requests/calendar_subscriptions_spec.rb b/plugins/discourse-calendar/spec/requests/calendar_subscriptions_spec.rb
new file mode 100644
index 00000000000..20c9fe9b291
--- /dev/null
+++ b/plugins/discourse-calendar/spec/requests/calendar_subscriptions_spec.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+describe "Calendar subscription feeds" do
+ fab!(:user)
+
+ before do
+ SiteSetting.calendar_enabled = true
+ SiteSetting.discourse_post_event_enabled = true
+ end
+
+ it "includes event feeds when calendar plugin is enabled" do
+ sign_in(user)
+ post "/calendar-subscriptions.json"
+ expect(response.status).to eq(200)
+
+ body = response.parsed_body
+ expect(body["urls"]["all_events"]).to include("/discourse-post-event/events.ics")
+ expect(body["urls"]["my_events"]).to include("attending_user=#{user.username_lower}")
+ expect(body["urls"]["my_events"]).to include("include_interested=true")
+ expect(body["urls"]["bookmarks"]).to include("/u/#{user.username_lower}/bookmarks.ics")
+ end
+
+ it "includes the events_calendar scope on the key" do
+ sign_in(user)
+ post "/calendar-subscriptions.json"
+
+ api_key =
+ UserApiKey.joins(:client).find_by(
+ user_id: user.id,
+ user_api_key_clients: {
+ client_id: CalendarSubscriptionsController::CLIENT_ID,
+ },
+ )
+ expect(api_key.scopes.map(&:name)).to contain_exactly(
+ "discourse-calendar:events_calendar",
+ "bookmarks_calendar",
+ )
+ end
+
+ it "lists all available feeds" do
+ sign_in(user)
+ get "/calendar-subscriptions.json"
+
+ expect(response.parsed_body["feeds"]).to contain_exactly("bookmarks", "all_events", "my_events")
+ end
+end
diff --git a/plugins/discourse-calendar/spec/requests/events_controller_spec.rb b/plugins/discourse-calendar/spec/requests/events_controller_spec.rb
index c25dd3f924a..5aeab2f1d29 100644
--- a/plugins/discourse-calendar/spec/requests/events_controller_spec.rb
+++ b/plugins/discourse-calendar/spec/requests/events_controller_spec.rb
@@ -118,6 +118,64 @@ module DiscoursePostEvent
expect(body).to include("BEGIN:VEVENT")
expect(body).to include("END:VEVENT")
end
+
+ context "when include_interested is requested for an attending user" do
+ fab!(:target_user, :user)
+ fab!(:going_event) do
+ Fabricate(:event, original_starts_at: 1.day.from_now, name: "Going Event")
+ end
+ fab!(:interested_event) do
+ Fabricate(:event, original_starts_at: 2.days.from_now, name: "Interested Event")
+ end
+
+ let(:events_params) { { attending_user: target_user.username, include_interested: true } }
+
+ before do
+ going_event.create_invitees(
+ [{ user_id: target_user.id, status: Invitee.statuses[:going] }],
+ )
+ interested_event.create_invitees(
+ [{ user_id: target_user.id, status: Invitee.statuses[:interested] }],
+ )
+ end
+
+ it "does not expose interested events to anonymous requests" do
+ get "/discourse-post-event/events.json", params: events_params
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["events"].pluck("id")).to contain_exactly(going_event.id)
+ end
+
+ it "includes interested events for the same authenticated user" do
+ sign_in(target_user)
+
+ get "/discourse-post-event/events.json", params: events_params
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["events"].pluck("id")).to contain_exactly(
+ going_event.id,
+ interested_event.id,
+ )
+ end
+
+ it "includes interested events for the owner's user api key feed" do
+ user_api_key =
+ Fabricate(
+ :user_api_key,
+ user: target_user,
+ scopes: [
+ Fabricate.build(:user_api_key_scope, name: "discourse-calendar:events_calendar"),
+ ],
+ )
+
+ get "/discourse-post-event/events.ics",
+ params: events_params.merge(user_api_key: user_api_key.key)
+
+ expect(response.status).to eq(200)
+ expect(response.body).to include("SUMMARY:Going Event")
+ expect(response.body).to include("SUMMARY:Interested Event")
+ end
+ end
end
context "with an existing post" do
diff --git a/spec/requests/calendar_subscriptions_controller_spec.rb b/spec/requests/calendar_subscriptions_controller_spec.rb
new file mode 100644
index 00000000000..3461ba5c624
--- /dev/null
+++ b/spec/requests/calendar_subscriptions_controller_spec.rb
@@ -0,0 +1,192 @@
+# frozen_string_literal: true
+
+RSpec.describe CalendarSubscriptionsController do
+ fab!(:user)
+
+ describe "#show" do
+ it "requires login" do
+ get "/calendar-subscriptions.json"
+ expect(response.status).to eq(403)
+ end
+
+ it "returns has_subscription: false when no key exists" do
+ sign_in(user)
+ get "/calendar-subscriptions.json"
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["has_subscription"]).to eq(false)
+ end
+
+ it "returns has_subscription: true when an active key exists" do
+ sign_in(user)
+ post "/calendar-subscriptions.json"
+
+ get "/calendar-subscriptions.json"
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["has_subscription"]).to eq(true)
+ end
+
+ it "returns available feed names" do
+ sign_in(user)
+ get "/calendar-subscriptions.json"
+ expect(response.parsed_body["feeds"]).to include("bookmarks")
+ end
+ end
+
+ describe "#create" do
+ it "requires login" do
+ post "/calendar-subscriptions.json"
+ expect(response.status).to eq(403)
+ end
+
+ it "creates a key and returns bookmarks URL" do
+ sign_in(user)
+ post "/calendar-subscriptions.json"
+ expect(response.status).to eq(200)
+
+ body = response.parsed_body
+ expect(body["key"]).to be_present
+ expect(body["urls"]["bookmarks"]).to include("/u/#{user.username_lower}/bookmarks.ics")
+ expect(body["urls"]["bookmarks"]).to include("user_api_key=#{body["key"]}")
+ end
+
+ it "creates a UserApiKey with bookmarks_calendar scope" do
+ sign_in(user)
+ post "/calendar-subscriptions.json"
+
+ api_key =
+ UserApiKey.joins(:client).find_by(
+ user_id: user.id,
+ user_api_key_clients: {
+ client_id: CalendarSubscriptionsController::CLIENT_ID,
+ },
+ )
+ expect(api_key).to be_present
+ expect(api_key.scopes.map(&:name)).to include("bookmarks_calendar")
+ end
+
+ it "revokes existing key when creating a new one" do
+ sign_in(user)
+
+ post "/calendar-subscriptions.json"
+ first_key_hash =
+ UserApiKey
+ .joins(:client)
+ .find_by(
+ user_id: user.id,
+ user_api_key_clients: {
+ client_id: CalendarSubscriptionsController::CLIENT_ID,
+ },
+ )
+ .key_hash
+
+ post "/calendar-subscriptions.json"
+
+ old_key = UserApiKey.find_by(key_hash: first_key_hash)
+ expect(old_key.revoked_at).to be_present
+
+ new_key =
+ UserApiKey
+ .active
+ .joins(:client)
+ .find_by(
+ user_id: user.id,
+ user_api_key_clients: {
+ client_id: CalendarSubscriptionsController::CLIENT_ID,
+ },
+ )
+ expect(new_key).to be_present
+ expect(new_key.key_hash).not_to eq(first_key_hash)
+ end
+
+ context "with plugin feeds registered" do
+ let(:feed_entry) do
+ {
+ name: "test_feed",
+ scope: "bookmarks_calendar",
+ description_key: "test.description",
+ url: ->(base_url, _user, key) { "#{base_url}/test.ics?user_api_key=#{key}" },
+ }
+ end
+
+ let(:plugin) { Plugin::Instance.new }
+
+ before { DiscoursePluginRegistry.register_calendar_subscription_feed(feed_entry, plugin) }
+
+ after do
+ DiscoursePluginRegistry._raw_calendar_subscription_feeds.reject! do |h|
+ h[:value] == feed_entry
+ end
+ end
+
+ it "includes plugin feed URLs" do
+ sign_in(user)
+ post "/calendar-subscriptions.json"
+
+ body = response.parsed_body
+ expect(body["urls"]["test_feed"]).to include("/test.ics")
+ expect(body["urls"]["bookmarks"]).to be_present
+ end
+ end
+
+ context "with plugin feeds referencing unregistered scopes" do
+ let(:feed_entry) do
+ {
+ name: "bad_feed",
+ scope: "nonexistent_scope",
+ description_key: "test.description",
+ url: ->(base_url, _user, key) { "#{base_url}/test.ics?user_api_key=#{key}" },
+ }
+ end
+
+ let(:plugin) { Plugin::Instance.new }
+
+ before { DiscoursePluginRegistry.register_calendar_subscription_feed(feed_entry, plugin) }
+
+ after do
+ DiscoursePluginRegistry._raw_calendar_subscription_feeds.reject! do |h|
+ h[:value] == feed_entry
+ end
+ end
+
+ it "skips the unknown scope and still creates the key" do
+ sign_in(user)
+ post "/calendar-subscriptions.json"
+ expect(response.status).to eq(200)
+
+ api_key =
+ UserApiKey.joins(:client).find_by(
+ user_id: user.id,
+ user_api_key_clients: {
+ client_id: CalendarSubscriptionsController::CLIENT_ID,
+ },
+ )
+ expect(api_key.scopes.map(&:name)).to eq(["bookmarks_calendar"])
+ end
+ end
+ end
+
+ describe "#destroy" do
+ it "requires login" do
+ delete "/calendar-subscriptions.json"
+ expect(response.status).to eq(403)
+ end
+
+ it "revokes the existing subscription key" do
+ sign_in(user)
+ post "/calendar-subscriptions.json"
+ expect(response.status).to eq(200)
+
+ delete "/calendar-subscriptions.json"
+ expect(response.status).to eq(204)
+
+ get "/calendar-subscriptions.json"
+ expect(response.parsed_body["has_subscription"]).to eq(false)
+ end
+
+ it "succeeds even when no key exists" do
+ sign_in(user)
+ delete "/calendar-subscriptions.json"
+ expect(response.status).to eq(204)
+ end
+ end
+end