DEV: Use current-user service wherever possible (#26901)

This commit is contained in:
Jarek Radosz 2024-05-07 22:19:42 +02:00 committed by GitHub
parent e992cf1507
commit b49fc052eb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 104 additions and 79 deletions

View File

@ -3,7 +3,6 @@ import { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
import { extractError } from "discourse/lib/ajax-error";
import PreloadStore from "discourse/lib/preload-store";
import User from "discourse/models/user";
import DiscourseRoute from "discourse/routes/discourse";
import getURL from "discourse-common/lib/get-url";
import { bind } from "discourse-common/utils/decorators";
@ -15,6 +14,7 @@ import BackupStatus from "admin/models/backup-status";
const LOG_CHANNEL = "/admin/backups/logs";
export default class AdminBackupsRoute extends DiscourseRoute {
@service currentUser;
@service dialog;
@service router;
@service messageBus;
@ -43,7 +43,7 @@ export default class AdminBackupsRoute extends DiscourseRoute {
@bind
onMessage(log) {
if (log.message === "[STARTED]") {
User.currentProp("hideReadOnlyAlert", true);
this.currentUser.set("hideReadOnlyAlert", true);
this.controllerFor("adminBackups").set("model.isOperationRunning", true);
this.controllerFor("adminBackupsLogs").get("logs").clear();
} else if (log.message === "[FAILED]") {
@ -54,7 +54,7 @@ export default class AdminBackupsRoute extends DiscourseRoute {
})
);
} else if (log.message === "[SUCCESS]") {
User.currentProp("hideReadOnlyAlert", false);
this.currentUser.set("hideReadOnlyAlert", false);
this.controllerFor("adminBackups").set("model.isOperationRunning", false);
if (log.operation === "restore") {
// redirect to homepage when the restore is done (session might be lost)

View File

@ -7,12 +7,12 @@ import { isEmpty } from "@ember/utils";
import optionalService from "discourse/lib/optional-service";
import { prioritizeNameInUx } from "discourse/lib/settings";
import CanCheckEmails from "discourse/mixins/can-check-emails";
import User from "discourse/models/user";
import getURL from "discourse-common/lib/get-url";
import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n";
export default Controller.extend(CanCheckEmails, {
currentUser: service(),
router: service(),
dialog: service(),
userNotifications: controller("user-notifications"),
@ -20,8 +20,7 @@ export default Controller.extend(CanCheckEmails, {
@discourseComputed("model.username")
viewingSelf(username) {
let currentUser = this.currentUser;
return currentUser && username === currentUser.get("username");
return this.currentUser && username === this.currentUser?.get("username");
},
@discourseComputed("viewingSelf", "model.profile_hidden")
@ -144,7 +143,7 @@ export default Controller.extend(CanCheckEmails, {
@discourseComputed()
canInviteToForum() {
return User.currentProp("can_invite_to_forum");
return this.currentUser?.get("can_invite_to_forum");
},
canDeleteUser: and("model.can_be_deleted", "model.can_delete_all_posts"),

View File

@ -7,7 +7,6 @@ import PermissionType from "discourse/models/permission-type";
import RestModel from "discourse/models/rest";
import Site from "discourse/models/site";
import Topic from "discourse/models/topic";
import User from "discourse/models/user";
import { getOwnerWithFallback } from "discourse-common/lib/get-owner";
import getURL from "discourse-common/lib/get-url";
import discourseComputed from "discourse-common/utils/decorators";
@ -773,9 +772,9 @@ export default class Category extends RestModel {
}
setNotification(notification_level) {
User.currentProp(
this.currentUser.set(
"muted_category_ids",
User.current().calculateMutedIds(
this.currentUser.calculateMutedIds(
notification_level,
this.id,
"muted_category_ids"
@ -785,7 +784,7 @@ export default class Category extends RestModel {
const url = `/category/${this.id}/notifications`;
return ajax(url, { data: { notification_level }, type: "POST" }).then(
(data) => {
User.current().set(
this.currentUser.set(
"indirectly_muted_category_ids",
data.indirectly_muted_category_ids
);

View File

@ -1,6 +1,7 @@
import { get } from "@ember/object";
import { and, equal, not, or } from "@ember/object/computed";
import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { isEmpty } from "@ember/utils";
import { Promise } from "rsvp";
import { ajax } from "discourse/lib/ajax";
@ -10,7 +11,6 @@ import DiscourseURL from "discourse/lib/url";
import { highlightPost } from "discourse/lib/utilities";
import RestModel from "discourse/models/rest";
import { loadTopicView } from "discourse/models/topic";
import User from "discourse/models/user";
import deprecated from "discourse-common/lib/deprecated";
import { deepMerge } from "discourse-common/lib/object";
import discourseComputed from "discourse-common/utils/decorators";
@ -34,6 +34,9 @@ export function resetLastEditNotificationClick() {
}
export default class PostStream extends RestModel {
@service currentUser;
@service store;
posts = null;
stream = null;
userFilters = null;
@ -745,10 +748,9 @@ export default class PostStream extends RestModel {
return this.findPostsByIds(this._loadingPostIds, opts)
.then((posts) => {
this._loadingPostIds = null;
const ignoredUsers =
User.current() && User.current().get("ignored_users");
const ignoredUsers = this.currentUser?.ignored_users;
posts.forEach((p) => {
if (ignoredUsers && ignoredUsers.includes(p.username)) {
if (ignoredUsers?.includes(p.username)) {
this.stream.removeObject(p.id);
return;
}
@ -1270,7 +1272,7 @@ export default class PostStream extends RestModel {
}
_initUserModels(post) {
post.user = User.create({
post.user = this.store.createRecord("user", {
id: post.user_id,
username: post.username,
});
@ -1280,7 +1282,9 @@ export default class PostStream extends RestModel {
}
if (post.mentioned_users) {
post.mentioned_users = post.mentioned_users.map((u) => User.create(u));
post.mentioned_users = post.mentioned_users.map((u) =>
this.store.createRecord("user", u)
);
}
}

View File

@ -1,5 +1,6 @@
import EmberObject, { get } from "@ember/object";
import { and, equal, not, or } from "@ember/object/computed";
import { service } from "@ember/service";
import { isEmpty } from "@ember/utils";
import { Promise } from "rsvp";
import { resolveShareUrl } from "discourse/helpers/share-url";
@ -102,6 +103,8 @@ export default class Post extends RestModel {
return ajax(`/posts/${postId}/raw-email.json`);
}
@service currentUser;
customShare = null;
@equal("trust_level", 0) new_user;
@ -115,12 +118,7 @@ export default class Post extends RestModel {
@discourseComputed("url", "customShare")
shareUrl(url) {
if (this.customShare) {
return this.customShare;
}
const user = User.current();
return resolveShareUrl(url, user);
return this.customShare || resolveShareUrl(url, this.currentUser);
}
@discourseComputed("name", "username")
@ -438,7 +436,7 @@ export default class Post extends RestModel {
}
updateLikeCount(count, userId, eventType) {
let ownAction = User.current()?.id === userId;
let ownAction = this.currentUser?.id === userId;
let ownLike = ownAction && eventType === "liked";
let current_actions_summary = this.get("actions_summary");
let likeActionID = Site.current().post_action_types.find(

View File

@ -1,11 +1,11 @@
import EmberObject, { get } from "@ember/object";
import { service } from "@ember/service";
import { isEmpty } from "@ember/utils";
import { NotificationLevels } from "discourse/lib/notification-levels";
import PreloadStore from "discourse/lib/preload-store";
import DiscourseURL from "discourse/lib/url";
import Category from "discourse/models/category";
import Site from "discourse/models/site";
import User from "discourse/models/user";
import { deepEqual, deepMerge } from "discourse-common/lib/object";
import discourseComputed, { bind } from "discourse-common/utils/decorators";
@ -48,6 +48,10 @@ function hasMutedTags(topicTags, mutedTags, siteSettings) {
}
export default class TopicTrackingState extends EmberObject {
@service currentUser;
@service messageBus;
@service siteSettings;
messageCount = 0;
init() {
@ -994,13 +998,12 @@ export default class TopicTrackingState extends EmberObject {
}
if (["new_topic", "latest"].includes(data.message_type)) {
const mutedCategoryIds = User.currentProp("muted_category_ids")?.concat(
User.currentProp("indirectly_muted_category_ids")
const mutedCategoryIds = this.currentUser?.muted_category_ids?.concat(
this.currentUser?.indirectly_muted_category_ids
);
if (
mutedCategoryIds &&
mutedCategoryIds.includes(data.payload.category_id) &&
mutedCategoryIds?.includes(data.payload.category_id) &&
!this.isUnmutedTopic(data.topic_id)
) {
return;
@ -1008,9 +1011,13 @@ export default class TopicTrackingState extends EmberObject {
}
if (["new_topic", "latest"].includes(data.message_type)) {
const mutedTags = User.currentProp("muted_tags");
if (hasMutedTags(data.payload.tags, mutedTags, this.siteSettings)) {
if (
hasMutedTags(
data.payload.tags,
this.currentUser?.muted_tags,
this.siteSettings
)
) {
return;
}
}

View File

@ -1,5 +1,6 @@
import EmberObject, { computed } from "@ember/object";
import { alias, and, equal, notEmpty, or } from "@ember/object/computed";
import { service } from "@ember/service";
import { Promise } from "rsvp";
import { resolveShareUrl } from "discourse/helpers/share-url";
import { ajax } from "discourse/lib/ajax";
@ -16,7 +17,6 @@ import ActionSummary from "discourse/models/action-summary";
import Bookmark from "discourse/models/bookmark";
import RestModel from "discourse/models/rest";
import Site from "discourse/models/site";
import User from "discourse/models/user";
import { flushMap } from "discourse/services/store";
import deprecated from "discourse-common/lib/deprecated";
import getURL from "discourse-common/lib/get-url";
@ -291,6 +291,9 @@ export default class Topic extends RestModel {
await applyModelTransformations("topic", topics);
}
@service currentUser;
@service siteSettings;
message = null;
errorLoading = false;
@ -493,8 +496,7 @@ export default class Topic extends RestModel {
@discourseComputed("url")
shareUrl(url) {
const user = User.current();
return resolveShareUrl(url, user);
return resolveShareUrl(url, this.currentUser);
}
@discourseComputed("id", "slug")

View File

@ -1,8 +1,8 @@
import { equal, or } from "@ember/object/computed";
import { service } from "@ember/service";
import { userPath } from "discourse/lib/url";
import { postUrl } from "discourse/lib/utilities";
import RestModel from "discourse/models/rest";
import User from "discourse/models/user";
import UserActionGroup from "discourse/models/user-action-group";
import discourseComputed from "discourse-common/utils/decorators";
import Category from "./category";
@ -82,6 +82,8 @@ export default class UserAction extends RestModel {
return collapsed;
}
@service currentUser;
@or("name", "username") presentName;
@or("target_name", "target_username") targetDisplayName;
@or("acting_name", "acting_username") actingDisplayName;
@ -133,12 +135,12 @@ export default class UserAction extends RestModel {
@discourseComputed("username")
sameUser(username) {
return username === User.currentProp("username");
return username === this.currentUser?.get("username");
}
@discourseComputed("target_username")
targetUser(targetUsername) {
return targetUsername === User.currentProp("username");
return targetUsername === this.currentUser?.get("username");
}
@discourseComputed("target_username")

View File

@ -1,3 +1,4 @@
import { service } from "@ember/service";
import { userPath } from "discourse/lib/url";
import { postUrl } from "discourse/lib/utilities";
import {
@ -5,14 +6,15 @@ import {
NEW_TOPIC_KEY,
} from "discourse/models/composer";
import RestModel from "discourse/models/rest";
import User from "discourse/models/user";
import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n";
export default class UserDraft extends RestModel {
@service currentUser;
@discourseComputed("draft_username")
editableDraft(draftUsername) {
return draftUsername === User.currentProp("username");
return draftUsername === this.currentUser?.get("username");
}
@discourseComputed("username_lower")

View File

@ -983,9 +983,8 @@ export default class User extends RestModel.extend(Evented) {
}
updateNotificationLevel({ level, expiringAt = null, actingUser = null }) {
if (!actingUser) {
actingUser = User.current();
}
actingUser ||= User.current();
return ajax(`${userPath(this.username)}/notification_level.json`, {
type: "PUT",
data: {

View File

@ -1,14 +1,16 @@
import { action } from "@ember/object";
import { service } from "@ember/service";
import { resetCachedTopicList } from "discourse/lib/cached-topic-list";
import User from "discourse/models/user";
import DiscourseRoute from "discourse/routes/discourse";
/**
The parent route for all discovery routes.
**/
export default class DiscoveryRoute extends DiscourseRoute {
@service currentUser;
@service router;
@service session;
@service site;
queryParams = {
filter: { refreshModel: true },
@ -24,11 +26,11 @@ export default class DiscoveryRoute extends DiscourseRoute {
if (
(url === "/" || url === "/latest" || url === "/categories") &&
!transition.targetName.includes("discovery.top") &&
User.currentProp("user_option.should_be_redirected_to_top")
this.currentUser?.get("user_option.should_be_redirected_to_top")
) {
User.currentProp("user_option.should_be_redirected_to_top", false);
this.currentUser?.get("user_option.should_be_redirected_to_top", false);
const period =
User.currentProp("user_option.redirected_to_top.period") || "all";
this.currentUser?.get("user_option.redirected_to_top.period") || "all";
this.router.replaceWith("discovery.top", {
queryParams: {
period,

View File

@ -1,6 +1,6 @@
import { getOwner } from "@ember/owner";
import { click, visit } from "@ember/test-helpers";
import { test } from "qunit";
import User from "discourse/models/user";
import userFixtures from "discourse/tests/fixtures/user-fixtures";
import {
acceptance,
@ -15,7 +15,8 @@ acceptance("User Card - Show Local Time", function (needs) {
needs.settings({ display_local_time_in_user_card: true });
test("user card local time - does not update timezone for another user", async function (assert) {
User.current().user_option.timezone = "Australia/Brisbane";
const currentUser = getOwner(this).lookup("service:current-user");
currentUser.user_option.timezone = "Australia/Brisbane";
await visit("/t/internationalization-localization/280");
await click('a[data-user-card="charlie"]');

View File

@ -4,7 +4,6 @@ import { setupTest } from "ember-qunit";
import { module, test } from "qunit";
import sinon from "sinon";
import Post from "discourse/models/post";
import User from "discourse/models/user";
import pretender, { response } from "discourse/tests/helpers/create-pretender";
function buildStream(id, stream) {
@ -894,14 +893,16 @@ module("Unit | Model | post-stream", function (hooks) {
test("triggerNewPostInStream for ignored posts", async function (assert) {
const postStream = buildStream.call(this, 280, [1]);
const store = getOwner(this).lookup("service:store");
User.resetCurrent(
store.createRecord("user", {
username: "eviltrout",
name: "eviltrout",
id: 321,
ignored_users: ["ignored-user"],
})
);
const user = store.createRecord("user", {
username: "eviltrout",
name: "eviltrout",
id: 321,
ignored_users: ["ignored-user"],
});
getOwner(this).unregister("service:current-user");
getOwner(this).register("service:current-user", user, {
instantiate: false,
});
postStream.appendPost(
store.createRecord("post", { id: 1, post_number: 1 })

View File

@ -1,5 +1,5 @@
import { getOwner } from "@ember/application";
import { getProperties } from "@ember/object";
import { getOwner } from "@ember/owner";
import { setupTest } from "ember-qunit";
import MessageBus from "message-bus-client";
import { module, test } from "qunit";
@ -7,7 +7,6 @@ import sinon from "sinon";
import { NotificationLevels } from "discourse/lib/notification-levels";
import DiscourseURL from "discourse/lib/url";
import Category from "discourse/models/category";
import TopicTrackingState from "discourse/models/topic-tracking-state";
import User from "discourse/models/user";
import {
fakeTime,
@ -27,7 +26,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("bulk loading states only calls onStateChange callback once", function (assert) {
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
let stateCallbackCalled = 0;
trackingState.onStateChange(() => {
@ -44,7 +43,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("tag counts", function (assert) {
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
trackingState.loadStates([
{
@ -118,7 +117,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("tag counts - with total", function (assert) {
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
trackingState.loadStates([
{
@ -202,7 +201,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("forEachTracked", function (assert) {
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
trackingState.loadStates([
{
@ -278,7 +277,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("sync - delayed new topics for backend list are removed", function (assert) {
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
trackingState.loadStates([{ last_read_post_number: null, topic_id: 111 }]);
trackingState.updateSeen(111, 7);
@ -301,7 +300,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("sync - delayed unread topics for backend list are marked seen", function (assert) {
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
trackingState.loadStates([{ last_read_post_number: null, topic_id: 111 }]);
trackingState.updateSeen(111, 7);
@ -331,7 +330,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("sync - remove topic from state for performance if it is seen and has no unread or new posts and there are too many tracked topics in memory", function (assert) {
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
trackingState.loadStates([{ topic_id: 111 }, { topic_id: 222 }]);
trackingState.set("_trackedTopicLimit", 1);
@ -390,7 +389,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("sync - no changes to state", function (assert) {
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
trackingState.loadStates([
{ topic_id: 111, last_read_post_number: null },
@ -424,7 +423,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("sync - updates state to match list topic for unseen and unread/new topics", function (assert) {
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
trackingState.loadStates([
{ topic_id: 111, last_read_post_number: 0 },
@ -482,7 +481,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("sync - states missing from the topic list are updated based on the selected filter", function (assert) {
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
trackingState.loadStates([
{
topic_id: 111,
@ -519,7 +518,9 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("establishChannels - /delete MessageBus channel payloads processed", async function (assert) {
const trackingState = TopicTrackingState.create({ messageBus: MessageBus });
const trackingState = this.store.createRecord("topic-tracking-state", {
messageBus: MessageBus,
});
trackingState.establishChannels();
trackingState.loadStates([
@ -544,7 +545,9 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("establishChannels - /recover MessageBus channel payloads processed", async function (assert) {
const trackingState = TopicTrackingState.create({ messageBus: MessageBus });
const trackingState = this.store.createRecord("topic-tracking-state", {
messageBus: MessageBus,
});
trackingState.establishChannels();
trackingState.loadStates([
@ -574,7 +577,9 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
sinon.stub(DiscourseURL, "redirectTo");
const trackingState = TopicTrackingState.create({ messageBus: MessageBus });
const trackingState = this.store.createRecord("topic-tracking-state", {
messageBus: MessageBus,
});
trackingState.establishChannels();
trackingState.loadStates([
{
@ -597,7 +602,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
test("subscribe to category", function (assert) {
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
trackingState.trackIncoming("c/feature/2/l/latest");
@ -686,7 +691,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
});
sinon.stub(Category, "list").returns([foo, bar, baz]);
const trackingState = TopicTrackingState.create();
const trackingState = this.store.createRecord("topic-tracking-state");
assert.deepEqual(Array.from(trackingState.getSubCategoryIds(1)), [1, 2, 3]);
assert.deepEqual(Array.from(trackingState.getSubCategoryIds(2)), [2, 3]);
assert.deepEqual(Array.from(trackingState.getSubCategoryIds(3)), [3]);
@ -719,7 +724,9 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
muted_category_ids: [4],
});
const trackingState = TopicTrackingState.create({ currentUser });
const trackingState = this.store.createRecord("topic-tracking-state", {
currentUser,
});
assert.strictEqual(trackingState.countNew({ categoryId: 1 }), 0);
assert.strictEqual(trackingState.countNew({ categoryId: 2 }), 0);
@ -800,7 +807,9 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
muted_category_ids: [],
});
const trackingState = TopicTrackingState.create({ currentUser });
const trackingState = this.store.createRecord("topic-tracking-state", {
currentUser,
});
trackingState.trackMutedOrUnmutedTopic({
topic_id: 1,
@ -850,7 +859,7 @@ module("Unit | Model | topic-tracking-state | /unread", function (hooks) {
});
User.resetCurrent(this.currentUser);
this.trackingState = TopicTrackingState.create({
this.trackingState = store.createRecord("topic-tracking-state", {
currentUser: this.currentUser,
messageBus: MessageBus,
siteSettings,
@ -1103,7 +1112,7 @@ module("Unit | Model | topic-tracking-state | /new", function (hooks) {
});
User.resetCurrent(this.currentUser);
this.trackingState = TopicTrackingState.create({
this.trackingState = store.createRecord("topic-tracking-state", {
currentUser: this.currentUser,
messageBus: MessageBus,
siteSettings,