Introduce the group activity section

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel 2021-02-24 19:06:48 +01:00
parent d0567f783d
commit 3fe64a4389
No known key found for this signature in database
GPG Key ID: A061B9DDE0CA0773
70 changed files with 3224 additions and 70 deletions

View File

@ -261,7 +261,7 @@ config :mobilizon, :anonymous,
config :mobilizon, Oban,
repo: Mobilizon.Storage.Repo,
log: false,
queues: [default: 10, search: 5, mailers: 10, background: 5],
queues: [default: 10, search: 5, mailers: 10, background: 5, activity: 5],
plugins: [
{Oban.Plugins.Cron,
crontab: [

View File

@ -0,0 +1,119 @@
<template>
<div class="activity-item">
<b-icon :icon="'chat'" :type="iconColor" />
<div class="subject">
<i18n :path="translation" tag="p">
<router-link
v-if="activity.object"
slot="discussion"
:to="{
name: RouteName.DISCUSSION,
params: { slug: subjectParams.discussion_slug },
}"
>{{ subjectParams.discussion_title }}</router-link
>
<b v-else slot="discussion">{{ subjectParams.discussion_title }}</b>
<router-link
v-if="activity.object && subjectParams.old_discussion_title"
slot="old_discussion"
:to="{
name: RouteName.DISCUSSION,
params: { slug: subjectParams.discussion_slug },
}"
>{{ subjectParams.old_discussion_title }}</router-link
>
<b
v-else-if="subjectParams.old_discussion_title"
slot="old_discussion"
>{{ subjectParams.old_discussion_title }}</b
>
<popover-actor-card
:actor="activity.author"
:inline="true"
slot="profile"
>
<b>
{{
$t("@{username}", {
username: usernameWithDomain(activity.author),
})
}}</b
></popover-actor-card
></i18n
>
<small class="has-text-grey activity-date">{{
activity.insertedAt | formatTimeString
}}</small>
</div>
</div>
</template>
<script lang="ts">
import { usernameWithDomain } from "@/types/actor";
import { ActivityDiscussionSubject } from "@/types/enums";
import { Component } from "vue-property-decorator";
import RouteName from "../../router/name";
import PopoverActorCard from "../Account/PopoverActorCard.vue";
import ActivityMixin from "../../mixins/activity";
import { mixins } from "vue-class-component";
@Component({
components: {
PopoverActorCard,
},
})
export default class DiscussionActivityItem extends mixins(ActivityMixin) {
usernameWithDomain = usernameWithDomain;
RouteName = RouteName;
ActivityDiscussionSubject = ActivityDiscussionSubject;
get translation(): string | undefined {
switch (this.activity.subject) {
case ActivityDiscussionSubject.DISCUSSION_CREATED:
if (this.isAuthorCurrentActor) {
return "You created the discussion {discussion}.";
}
return "{profile} created the discussion {discussion}.";
case ActivityDiscussionSubject.DISCUSSION_REPLIED:
if (this.isAuthorCurrentActor) {
return "You replied to the discussion {discussion}.";
}
return "{profile} replied to the discussion {discussion}.";
case ActivityDiscussionSubject.DISCUSSION_RENAMED:
if (this.isAuthorCurrentActor) {
return "You renamed the discussion from {old_discussion} to {discussion}.";
}
return "{profile} renamed the discussion from {old_discussion} to {discussion}.";
case ActivityDiscussionSubject.DISCUSSION_ARCHIVED:
if (this.isAuthorCurrentActor) {
return "You archived the discussion {discussion}.";
}
return "{profile} archived the discussion {discussion}.";
case ActivityDiscussionSubject.DISCUSSION_DELETED:
if (this.isAuthorCurrentActor) {
return "You deleted the discussion {discussion}.";
}
return "{profile} deleted the discussion {discussion}.";
default:
return undefined;
}
}
get iconColor(): string | undefined {
switch (this.activity.subject) {
case ActivityDiscussionSubject.DISCUSSION_CREATED:
case ActivityDiscussionSubject.DISCUSSION_REPLIED:
return "is-success";
case ActivityDiscussionSubject.DISCUSSION_RENAMED:
case ActivityDiscussionSubject.DISCUSSION_ARCHIVED:
return "is-grey";
case ActivityDiscussionSubject.DISCUSSION_DELETED:
return "is-danger";
default:
return undefined;
}
}
}
</script>
<style lang="scss" scoped>
@import "./activity.scss";
</style>

View File

@ -0,0 +1,93 @@
<template>
<div class="activity-item">
<b-icon :icon="'calendar'" :type="iconColor" />
<div class="subject">
<i18n :path="translation" tag="p">
<router-link
slot="event"
v-if="activity.object"
:to="{
name: RouteName.EVENT,
params: { uuid: subjectParams.event_uuid },
}"
>{{ subjectParams.event_title }}</router-link
>
<b v-else slot="event">{{ subjectParams.event_title }}</b>
<popover-actor-card
:actor="activity.author"
:inline="true"
slot="profile"
>
<b>
{{
$t("@{username}", {
username: usernameWithDomain(activity.author),
})
}}</b
></popover-actor-card
></i18n
>
<small class="has-text-grey activity-date">{{
activity.insertedAt | formatTimeString
}}</small>
</div>
</div>
</template>
<script lang="ts">
import { usernameWithDomain } from "@/types/actor";
import { ActivityEventSubject } from "@/types/enums";
import { mixins } from "vue-class-component";
import { Component } from "vue-property-decorator";
import RouteName from "../../router/name";
import PopoverActorCard from "../Account/PopoverActorCard.vue";
import ActivityMixin from "../../mixins/activity";
@Component({
components: {
PopoverActorCard,
},
})
export default class EventActivityItem extends mixins(ActivityMixin) {
ActivityEventSubject = ActivityEventSubject;
usernameWithDomain = usernameWithDomain;
RouteName = RouteName;
get translation(): string | undefined {
switch (this.activity.subject) {
case ActivityEventSubject.EVENT_CREATED:
if (this.isAuthorCurrentActor) {
return "You created the event {event}.";
}
return "The event {event} was created by {profile}.";
case ActivityEventSubject.EVENT_UPDATED:
if (this.isAuthorCurrentActor) {
return "You updated the event {event}.";
}
return "The event {event} was updated by {profile}.";
case ActivityEventSubject.EVENT_DELETED:
if (this.isAuthorCurrentActor) {
return "You deleted the event {event}.";
}
return "The event {event} was deleted by {profile}.";
default:
return undefined;
}
}
get iconColor(): string | undefined {
switch (this.activity.subject) {
case ActivityEventSubject.EVENT_CREATED:
return "is-success";
case ActivityEventSubject.EVENT_UPDATED:
return "is-grey";
case ActivityEventSubject.EVENT_DELETED:
return "is-danger";
default:
return undefined;
}
}
}
</script>
<style lang="scss" scoped>
@import "./activity.scss";
</style>

View File

@ -0,0 +1,183 @@
<template>
<div class="activity-item">
<b-icon :icon="'cog'" :type="iconColor" />
<div class="subject">
<i18n :path="translation" tag="p">
<router-link
v-if="activity.object"
slot="group"
:to="{
name: RouteName.GROUP,
params: { preferredUsername: usernameWithDomain(activity.object) },
}"
>{{ subjectParams.group_name }}</router-link
>
<b v-else slot="post">{{ subjectParams.group_name }}</b>
<popover-actor-card
:actor="activity.author"
:inline="true"
slot="profile"
>
<b>
{{
$t("@{username}", {
username: usernameWithDomain(activity.author),
})
}}</b
></popover-actor-card
></i18n
>
<i18n
:path="detail"
v-for="detail in details"
:key="detail"
tag="p"
class="has-text-grey"
>
<popover-actor-card
:actor="activity.author"
:inline="true"
slot="profile"
>
<b>
{{
$t("@{username}", {
username: usernameWithDomain(activity.author),
})
}}</b
></popover-actor-card
>
<router-link
v-if="activity.object"
slot="group"
:to="{
name: RouteName.GROUP,
params: { preferredUsername: usernameWithDomain(activity.object) },
}"
>{{ subjectParams.group_name }}</router-link
>
<b v-else slot="post">{{ subjectParams.group_name }}</b>
<b v-if="subjectParams.old_group_name" slot="old_group_name">{{
subjectParams.old_group_name
}}</b>
</i18n>
<small class="has-text-grey activity-date">{{
activity.insertedAt | formatTimeString
}}</small>
</div>
</div>
</template>
<script lang="ts">
import { usernameWithDomain } from "@/types/actor";
import { ActivityGroupSubject, GroupVisibility, Openness } from "@/types/enums";
import { Component } from "vue-property-decorator";
import RouteName from "../../router/name";
import PopoverActorCard from "../Account/PopoverActorCard.vue";
import ActivityMixin from "../../mixins/activity";
import { mixins } from "vue-class-component";
@Component({
components: {
PopoverActorCard,
},
})
export default class GroupActivityItem extends mixins(ActivityMixin) {
usernameWithDomain = usernameWithDomain;
RouteName = RouteName;
ActivityGroupSubject = ActivityGroupSubject;
get translation(): string | undefined {
switch (this.activity.subject) {
case ActivityGroupSubject.GROUP_CREATED:
if (this.isAuthorCurrentActor) {
return "You created the group {group}.";
}
return "{profile} created the group {group}.";
case ActivityGroupSubject.GROUP_UPDATED:
if (this.isAuthorCurrentActor) {
return "You updated the group {group}.";
}
return "{profile} updated the group {group}.";
default:
return undefined;
}
}
get iconColor(): string | undefined {
switch (this.activity.subject) {
case ActivityGroupSubject.GROUP_CREATED:
return "is-success";
case ActivityGroupSubject.GROUP_UPDATED:
return "is-grey";
default:
return undefined;
}
}
get details(): string[] {
let details = [];
const changes = this.subjectParams.group_changes.split(",");
if (changes.includes("name") && this.subjectParams.old_group_name) {
details.push("{old_group_name} was renamed to {group}.");
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (changes.includes("visibility") && this.activity.object.visibility) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
switch (this.activity.object.visibility) {
case GroupVisibility.PRIVATE:
details.push("Visibility was set to private.");
break;
case GroupVisibility.PUBLIC:
details.push("Visibility was set to public.");
break;
default:
details.push("Visibility was set to an unknown value.");
break;
}
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (changes.includes("openness") && this.activity.object.openness) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
switch (this.activity.object.openness) {
case Openness.INVITE_ONLY:
details.push("The group can now only be joined with an invite.");
break;
case Openness.OPEN:
details.push("The group can now be joined by anyone.");
break;
default:
details.push("Unknown value for the openness setting.");
break;
}
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (changes.includes("address") && this.activity.object.physicalAddress) {
details.push("The group's physical address was changed.");
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (changes.includes("avatar") && this.activity.object.avatar) {
details.push("The group's avatar was changed.");
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (changes.includes("banner") && this.activity.object.banner) {
details.push("The group's banner was changed.");
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (changes.includes("summary") && this.activity.object.summary) {
details.push("The group's short description was changed.");
}
return details;
}
}
</script>
<style lang="scss" scoped>
@import "./activity.scss";
</style>

View File

@ -0,0 +1,233 @@
<template>
<div class="activity-item">
<b-icon :icon="icon" :type="iconColor" />
<div class="subject">
<i18n :path="translation" tag="p">
<popover-actor-card
v-if="activity.object"
:actor="activity.object.actor"
:inline="true"
slot="member"
>
<b>
{{
$t("@{username}", {
username: usernameWithDomain(activity.object.actor),
})
}}</b
></popover-actor-card
>
<b slot="member" v-else>{{
subjectParams.member_preferred_username
}}</b>
<popover-actor-card
:actor="activity.author"
:inline="true"
slot="profile"
>
<b>
{{
$t("@{username}", {
username: usernameWithDomain(activity.author),
})
}}</b
></popover-actor-card
></i18n
>
<small class="has-text-grey activity-date">{{
activity.insertedAt | formatTimeString
}}</small>
</div>
</div>
</template>
<script lang="ts">
import { usernameWithDomain } from "@/types/actor";
import { ActivityMemberSubject, MemberRole } from "@/types/enums";
import { Component } from "vue-property-decorator";
import RouteName from "../../router/name";
import PopoverActorCard from "../Account/PopoverActorCard.vue";
import ActivityMixin from "../../mixins/activity";
import { mixins } from "vue-class-component";
export const MEMBER_ROLE_VALUE: Record<string, number> = {
[MemberRole.MEMBER]: 20,
[MemberRole.MODERATOR]: 50,
[MemberRole.ADMINISTRATOR]: 90,
[MemberRole.CREATOR]: 100,
};
@Component({
components: {
PopoverActorCard,
},
})
export default class MemberActivityItem extends mixins(ActivityMixin) {
usernameWithDomain = usernameWithDomain;
RouteName = RouteName;
ActivityMemberSubject = ActivityMemberSubject;
get translation(): string | undefined {
switch (this.activity.subject) {
case ActivityMemberSubject.MEMBER_REQUEST:
if (this.isAuthorCurrentActor) {
return "You requested to join the group.";
}
return "{member} requested to join the group.";
case ActivityMemberSubject.MEMBER_INVITED:
if (this.isAuthorCurrentActor) {
return "You invited {member}.";
}
return "{member} was invited by {profile}.";
case ActivityMemberSubject.MEMBER_ADDED:
if (this.isAuthorCurrentActor) {
return "You added the member {member}.";
}
return "{profile} added the member {member}.";
case ActivityMemberSubject.MEMBER_UPDATED:
if (this.subjectParams.member_role && this.subjectParams.old_role) {
return this.roleUpdate;
}
if (this.isAuthorCurrentActor) {
return "You updated the member {member}.";
}
return "{profile} updated the member {member}.";
case ActivityMemberSubject.MEMBER_REMOVED:
if (this.isAuthorCurrentActor) {
return "You excluded member {member}.";
}
return "{profile} excluded member {member}.";
case ActivityMemberSubject.MEMBER_QUIT:
return "{profile} quit the group.";
case ActivityMemberSubject.MEMBER_REJECTED_INVITATION:
return "{member} rejected the invitation to join the group.";
case ActivityMemberSubject.MEMBER_ACCEPTED_INVITATION:
if (this.isAuthorCurrentActor) {
return "You accepted the invitation to join the group.";
}
return "{member} accepted the invitation to join the group.";
default:
return undefined;
}
}
get icon(): string {
switch (this.activity.subject) {
case ActivityMemberSubject.MEMBER_REQUEST:
case ActivityMemberSubject.MEMBER_ADDED:
case ActivityMemberSubject.MEMBER_INVITED:
case ActivityMemberSubject.MEMBER_ACCEPTED_INVITATION:
return "account-multiple-plus";
case ActivityMemberSubject.MEMBER_REMOVED:
case ActivityMemberSubject.MEMBER_REJECTED_INVITATION:
case ActivityMemberSubject.MEMBER_QUIT:
return "account-multiple-minus";
case ActivityMemberSubject.MEMBER_UPDATED:
default:
return "account-multiple";
}
}
get iconColor(): string | undefined {
switch (this.activity.subject) {
case ActivityMemberSubject.MEMBER_ADDED:
case ActivityMemberSubject.MEMBER_INVITED:
case ActivityMemberSubject.MEMBER_JOINED:
case ActivityMemberSubject.MEMBER_APPROVED:
case ActivityMemberSubject.MEMBER_ACCEPTED_INVITATION:
return "is-success";
case ActivityMemberSubject.MEMBER_REQUEST:
case ActivityMemberSubject.MEMBER_UPDATED:
return "is-grey";
case ActivityMemberSubject.MEMBER_REMOVED:
case ActivityMemberSubject.MEMBER_REJECTED_INVITATION:
case ActivityMemberSubject.MEMBER_QUIT:
return "is-danger";
default:
return undefined;
}
}
get roleUpdate(): string | undefined {
if (
Object.keys(MEMBER_ROLE_VALUE).includes(this.subjectParams.member_role) &&
Object.keys(MEMBER_ROLE_VALUE).includes(this.subjectParams.old_role)
) {
if (
MEMBER_ROLE_VALUE[this.subjectParams.member_role] >
MEMBER_ROLE_VALUE[this.subjectParams.old_role]
) {
switch (this.subjectParams.member_role) {
case MemberRole.MODERATOR:
if (this.isAuthorCurrentActor) {
return "You promoted {member} to moderator.";
}
if (this.isObjectMemberCurrentActor) {
return "You were promoted to moderator by {profile}.";
}
return "{profile} promoted {member} to moderator.";
case MemberRole.ADMINISTRATOR:
if (this.isAuthorCurrentActor) {
return "You promoted {member} to administrator.";
}
if (this.isObjectMemberCurrentActor) {
return "You were promoted to administrator by {profile}.";
}
return "{profile} promoted {member} to administrator.";
default:
if (this.isAuthorCurrentActor) {
return "You promoted the member {member} to an unknown role.";
}
if (this.isObjectMemberCurrentActor) {
return "You were promoted to an unknown role by {profile}.";
}
return "{profile} promoted {member} to an unknown role.";
}
} else {
switch (this.subjectParams.member_role) {
case MemberRole.MODERATOR:
if (this.isAuthorCurrentActor) {
return "You demoted {member} to moderator.";
}
if (this.isObjectMemberCurrentActor) {
return "You were demoted to moderator by {profile}.";
}
return "{profile} demoted {member} to moderator.";
case MemberRole.MEMBER:
if (this.isAuthorCurrentActor) {
return "You demoted {member} to simple member.";
}
if (this.isObjectMemberCurrentActor) {
return "You were demoted to simple member by {profile}.";
}
return "{profile} demoted {member} to simple member.";
default:
if (this.isAuthorCurrentActor) {
return "You demoted the member {member} to an unknown role.";
}
if (this.isObjectMemberCurrentActor) {
return "You were demoted to an unknown role by {profile}.";
}
return "{profile} demoted {member} to an unknown role.";
}
}
} else {
if (this.isAuthorCurrentActor) {
return "You updated the member {member}.";
}
return "{profile} updated the member {member}";
}
}
get isObjectMemberCurrentActor(): boolean {
return (
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.activity?.object?.actor?.id === this.currentActor?.id &&
this.currentActor?.id !== undefined
);
}
}
</script>
<style lang="scss" scoped>
@import "./activity.scss";
</style>

View File

@ -0,0 +1,93 @@
<template>
<div class="activity-item">
<b-icon :icon="'bullhorn'" :type="iconColor" />
<div class="subject">
<i18n :path="translation" tag="p">
<router-link
v-if="activity.object"
slot="post"
:to="{
name: RouteName.POST,
params: { slug: subjectParams.post_slug },
}"
>{{ subjectParams.post_title }}</router-link
>
<b v-else slot="post">{{ subjectParams.post_title }}</b>
<popover-actor-card
:actor="activity.author"
:inline="true"
slot="profile"
>
<b>
{{
$t("@{username}", {
username: usernameWithDomain(activity.author),
})
}}</b
></popover-actor-card
></i18n
>
<small class="has-text-grey activity-date">{{
activity.insertedAt | formatTimeString
}}</small>
</div>
</div>
</template>
<script lang="ts">
import { usernameWithDomain } from "@/types/actor";
import { ActivityPostSubject } from "@/types/enums";
import { Component } from "vue-property-decorator";
import RouteName from "../../router/name";
import PopoverActorCard from "../Account/PopoverActorCard.vue";
import ActivityMixin from "../../mixins/activity";
import { mixins } from "vue-class-component";
@Component({
components: {
PopoverActorCard,
},
})
export default class PostActivityItem extends mixins(ActivityMixin) {
usernameWithDomain = usernameWithDomain;
RouteName = RouteName;
ActivityPostSubject = ActivityPostSubject;
get translation(): string | undefined {
switch (this.activity.subject) {
case ActivityPostSubject.POST_CREATED:
if (this.isAuthorCurrentActor) {
return "You created the post {post}.";
}
return "The post {post} was created by {profile}.";
case ActivityPostSubject.POST_UPDATED:
if (this.isAuthorCurrentActor) {
return "You updated the post {post}.";
}
return "The post {post} was updated by {profile}.";
case ActivityPostSubject.POST_DELETED:
if (this.isAuthorCurrentActor) {
return "You deleted the post {post}.";
}
return "The post {post} was deleted by {profile}.";
default:
return undefined;
}
}
get iconColor(): string | undefined {
switch (this.activity.subject) {
case ActivityPostSubject.POST_CREATED:
return "is-success";
case ActivityPostSubject.POST_UPDATED:
return "is-grey";
case ActivityPostSubject.POST_DELETED:
return "is-danger";
default:
return undefined;
}
}
}
</script>
<style lang="scss" scoped>
@import "./activity.scss";
</style>

View File

@ -0,0 +1,189 @@
<template>
<div class="activity-item">
<b-icon :icon="'link'" :type="iconColor" />
<div class="subject">
<i18n :path="translation" tag="p">
<router-link v-if="activity.object" slot="resource" :to="path">{{
subjectParams.resource_title
}}</router-link>
<b v-else slot="resource">{{ subjectParams.resource_title }}</b>
<router-link v-if="activity.object" slot="new_path" :to="path">{{
parentDirectory
}}</router-link>
<b v-else slot="new_path">{{ parentDirectory }}</b>
<router-link
v-if="activity.object && subjectParams.old_resource_title"
slot="old_resource_title"
:to="path"
>{{ subjectParams.old_resource_title }}</router-link
>
<b
v-else-if="subjectParams.old_resource_title"
slot="old_resource_title"
>{{ subjectParams.old_resource_title }}</b
>
<popover-actor-card
:actor="activity.author"
:inline="true"
slot="profile"
>
<b>
{{
$t("@{username}", {
username: usernameWithDomain(activity.author),
})
}}</b
></popover-actor-card
></i18n
>
<small class="has-text-grey activity-date">{{
activity.insertedAt | formatTimeString
}}</small>
</div>
</div>
</template>
<script lang="ts">
import { usernameWithDomain } from "@/types/actor";
import { ActivityResourceSubject } from "@/types/enums";
import { Component } from "vue-property-decorator";
import RouteName from "../../router/name";
import PopoverActorCard from "../Account/PopoverActorCard.vue";
import ActivityMixin from "../../mixins/activity";
import { mixins } from "vue-class-component";
import { Location } from "vue-router";
@Component({
components: {
PopoverActorCard,
},
})
export default class ResourceActivityItem extends mixins(ActivityMixin) {
usernameWithDomain = usernameWithDomain;
RouteName = RouteName;
get translation(): string | undefined {
switch (this.activity.subject) {
case ActivityResourceSubject.RESOURCE_CREATED:
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (this.activity?.object?.type === "folder") {
if (this.isAuthorCurrentActor) {
return "You created the folder {resource}.";
}
return "{profile} created the folder {resource}.";
}
if (this.isAuthorCurrentActor) {
return "You created the resource {resource}.";
}
return "{profile} created the resource {resource}.";
case ActivityResourceSubject.RESOURCE_MOVED:
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (this.activity?.object?.type === "folder") {
if (this.parentDirectory === null) {
if (this.isAuthorCurrentActor) {
return "You moved the folder {resource} to the root folder.";
}
return "{profile} moved the folder {resource} to the root folder.";
}
if (this.isAuthorCurrentActor) {
return "You moved the folder {resource} into {new_path}.";
}
return "{profile} moved the folder {resource} into {new_path}.";
}
if (this.parentDirectory === null) {
if (this.isAuthorCurrentActor) {
return "You moved the resource {resource} to the root folder.";
}
return "{profile} moved the resource {resource} to the root folder.";
}
if (this.isAuthorCurrentActor) {
return "You moved the resource {resource} into {new_path}.";
}
return "{profile} moved the resource {resource} into {new_path}.";
case ActivityResourceSubject.RESOURCE_UPDATED:
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (this.activity?.object?.type === "folder") {
if (this.isAuthorCurrentActor) {
return "You renamed the folder from {old_resource_title} to {resource}.";
}
return "{profile} renamed the folder from {old_resource_title} to {resource}.";
}
if (this.isAuthorCurrentActor) {
return "You renamed the resource from {old_resource_title} to {resource}.";
}
return "{profile} renamed the resource from {old_resource_title} to {resource}.";
case ActivityResourceSubject.RESOURCE_DELETED:
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (this.activity?.object?.type === "folder") {
if (this.isAuthorCurrentActor) {
return "You deleted the folder {resource}.";
}
return "{profile} deleted the folder {resource}.";
}
if (this.isAuthorCurrentActor) {
return "You deleted the resource {resource}.";
}
return "{profile} deleted the resource {resource}.";
default:
return undefined;
}
}
get iconColor(): string | undefined {
switch (this.activity.subject) {
case ActivityResourceSubject.RESOURCE_CREATED:
return "is-success";
case ActivityResourceSubject.RESOURCE_MOVED:
case ActivityResourceSubject.RESOURCE_UPDATED:
return "is-grey";
case ActivityResourceSubject.RESOURCE_DELETED:
return "is-danger";
default:
return undefined;
}
}
get path(): Location {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
let path = this.parentPath(this.activity?.object?.path);
if (path === "") {
return {
name: RouteName.RESOURCE_FOLDER_ROOT,
params: {
preferredUsername: usernameWithDomain(this.activity.group),
},
};
}
return {
name: RouteName.RESOURCE_FOLDER,
params: {
path,
preferredUsername: usernameWithDomain(this.activity.group),
},
};
}
get parentDirectory(): string | undefined | null {
if (this.subjectParams.resource_path) {
const parentPath = this.parentPath(this.subjectParams.resource_path);
const directory = parentPath.split("/");
return directory.pop();
}
return null;
}
parentPath(parent: string): string {
let path = parent.split("/");
path.pop();
return path.join("/").replace(/^\//, "");
}
}
</script>
<style lang="scss" scoped>
@import "./activity.scss";
</style>

View File

@ -0,0 +1,30 @@
<template>
<div class="activity-item">
<span>
<b-skeleton circle width="32px" height="32px"></b-skeleton>
</span>
<div class="subject">
<div class="content">
<p>
<b-skeleton active></b-skeleton>
<b-skeleton active class="datetime"></b-skeleton>
</p>
</div>
</div>
</div>
</template>
<style lang="scss" scoped>
@import "./activity.scss";
div.activity-item {
flex: 1;
.subject {
flex: 1;
max-width: 600px;
.content p > div:last-child {
max-width: 50px;
}
}
}
</style>

View File

@ -0,0 +1,21 @@
.activity-item {
display: flex;
span.icon {
width: 2em;
height: 2em;
box-sizing: border-box;
border-radius: 50%;
background: #fff;
border: 2px solid;
z-index: 2;
flex-shrink: 0;
&.has-text-grey {
border-color: $grey;
}
}
.subject {
padding: 0.25rem 0 0 0.5rem;
}
}

View File

@ -58,8 +58,14 @@ export default class ResourceItem extends Vue {
mapServiceTypeToIcon = mapServiceTypeToIcon;
get urlHostname(): string {
return new URL(this.resource.resourceUrl).hostname.replace(/^(www\.)/, "");
get urlHostname(): string | undefined {
if (this.resource?.resourceUrl) {
return new URL(this.resource.resourceUrl).hostname.replace(
/^(www\.)/,
""
);
}
return undefined;
}
}
</script>

View File

@ -26,6 +26,7 @@
</span>
{{ $t("Parent folder") }}
</a>
<template v-if="resource.children">
<a
class="panel-block"
v-for="element in resource.children.elements"
@ -50,9 +51,10 @@
<em v-else> {{ $t("(this link)") }}</em>
</span>
</a>
</template>
<p
class="panel-block content has-text-grey has-text-centered"
v-if="resource.children.total === 0"
v-if="resource.children && resource.children.total === 0"
>
{{ $t("No resources in this folder") }}
</p>

View File

@ -0,0 +1,28 @@
<template>
<div class="observer" />
</template>
<script lang="ts">
import "intersection-observer";
import { Component, Prop, Vue } from "vue-property-decorator";
@Component
export default class Observer extends Vue {
@Prop({ required: false, default: () => ({}) }) options!: Record<string, any>;
observer!: IntersectionObserver;
mounted(): void {
this.observer = new IntersectionObserver(([entry]) => {
if (entry && entry.isIntersecting) {
this.$emit("intersect");
}
}, this.options);
this.observer.observe(this.$el);
}
destroyed(): void {
this.observer.disconnect();
}
}
</script>

View File

@ -321,3 +321,98 @@ export const REFRESH_PROFILE = gql`
}
}
`;
export const GROUP_TIMELINE = gql`
query GroupTimeline(
$preferredUsername: String!
$type: ActivityType
$page: Int
$limit: Int
) {
group(preferredUsername: $preferredUsername) {
id
preferredUsername
domain
name
activity(type: $type, page: $page, limit: $limit) {
total
elements {
id
insertedAt
subject
subjectParams {
key
value
}
type
author {
id
preferredUsername
name
domain
avatar {
id
url
}
}
group {
id
preferredUsername
}
object {
... on Event {
id
title
}
... on Post {
id
title
}
... on Member {
id
actor {
id
name
preferredUsername
domain
avatar {
id
url
}
}
}
... on Resource {
id
title
path
type
}
... on Discussion {
id
title
slug
}
... on Group {
id
preferredUsername
domain
name
summary
visibility
openness
physicalAddress {
id
}
banner {
id
}
avatar {
id
}
}
}
}
}
}
}
`;

View File

@ -859,5 +859,101 @@
"Last published events": "Last published events",
"On {instance}": "On {instance}",
"Close events": "Close events",
"Within {number} kilometers of {place}": "|Within one kilometer of {place}|Within {number} kilometers of {place}"
"Within {number} kilometers of {place}": "|Within one kilometer of {place}|Within {number} kilometers of {place}",
"@{username}": "@{username}",
"Yesterday": "Yesterday",
"You created the event {event}.": "You created the event {event}.",
"The event {event} was created by {profile}.": "The event {event} was created by {profile}.",
"You updated the event {event}.": "You updated the event {event}.",
"The event {event} was updated by {profile}.": "The event {event} was updated by {profile}.",
"You deleted the event {event}.": "You deleted the event {event}.",
"The event {event} was deleted by {profile}.": "The event {event} was deleted by {profile}.",
"You created the post {post}.": "You created the post {post}.",
"The post {post} was created by {profile}.": "The post {post} was created by {profile}.",
"You updated the post {post}.": "You updated the post {post}.",
"The post {post} was updated by {profile}.": "The post {post} was updated by {profile}.",
"You deleted the post {post}.": "You deleted the post {post}.",
"The post {post} was deleted by {profile}.": "The post {post} was deleted by {profile}.",
"No more activity to display.": "No more activity to display.",
"There is no activity yet. Start doing some things to see activity appear here.": "There is no activity yet. Start doing some things to see activity appear here.",
"{group} activity timeline": "{group} activity timeline",
"You promoted {member} to moderator.": "You promoted {member} to moderator.",
"You promoted {member} to administrator.": "You promoted {member} to administrator.",
"You promoted the member {member} to an unknown role.": "You promoted the member {member} to an unknown role.",
"You demoted {member} to moderator.": "You demoted {member} to moderator.",
"You demoted {member} to simple member.": "You demoted {member} to simple member.",
"You demoted the member {member} to an unknown role.": "You demoted the member {member} to an unknown role.",
"You updated the member {member}.": "You updated the member {member}.",
"{profile} updated the member {member}.": "{profile} updated the member {member}.",
"{profile} promoted {member} to moderator.": "{profile} promoted {member} to moderator.",
"{profile} promoted {member} to administrator.": "{profile} promoted {member} to administrator.",
"{profile} promoted {member} to an unknown role.": "{profile} promoted {member} to an unknown role.",
"{profile} demoted {member} to moderator.": "{profile} demoted {member} to moderator.",
"{profile} demoted {member} to simple member.": "{profile} demoted {member} to simple member.",
"{profile} demoted {member} to an unknown role.": "{profile} demoted {member} to an unknown role.",
"You requested to join the group.": "You requested to join the group.",
"{member} requested to join the group.": "{member} requested to join the group.",
"You invited {member}.": "You invited {member}.",
"{member} was invited by {profile}.": "{member} was invited by {profile}.",
"You added the member {member}.": "You added the member {member}.",
"{profile} added the member {member}.": "{profile} added the member {member}.",
"{member} rejected the invitation to join the group.": "{member} rejected the invitation to join the group.",
"{member} accepted the invitation to join the group.": "{member} accepted the invitation to join the group.",
"You excluded member {member}.": "You excluded member {member}.",
"{profile} excluded member {member}.": "{profile} excluded member {member}.",
"You accepted the invitation to join the group.": "You accepted the invitation to join the group.",
"You were promoted to moderator by {profile}.": "You were promoted to moderator by {profile}.",
"You were promoted to administrator by {profile}.": "You were promoted to administrator by {profile}.",
"You were promoted to an unknown role by {profile}.": "You were promoted to an unknown role by {profile}.",
"You were demoted to moderator by {profile}.": "You were demoted to moderator by {profile}.",
"You were demoted to simple member by {profile}.": "You were demoted to simple member by {profile}.",
"You were demoted to an unknown role by {profile}.": "You were demoted to an unknown role by {profile}.",
"{profile} quit the group.": "{profile} quit the group.",
"You created the folder {resource}.": "You created the folder {resource}.",
"{profile} created the folder {resource}.": "{profile} created the folder {resource}.",
"You created the resource {resource}.": "You created the resource {resource}.",
"{profile} created the resource {resource}.": "{profile} created the resource {resource}.",
"You moved the folder {resource} to the root folder.": "You moved the folder {resource} to the root folder.",
"{profile} moved the folder {resource} to the root folder.": "{profile} moved the folder {resource} to the root folder.",
"You moved the folder {resource} into {new_path}.": "You moved the folder {resource} into {new_path}.",
"{profile} moved the folder {resource} into {new_path}.": "{profile} moved the folder {resource} into {new_path}.",
"You moved the resource {resource} to the root folder.": "You moved the resource {resource} to the root folder.",
"{profile} moved the resource {resource} to the root folder.": "{profile} moved the resource {resource} to the root folder.",
"You moved the resource {resource} into {new_path}.": "You moved the resource {resource} into {new_path}.",
"{profile} moved the resource {resource} into {new_path}.": "{profile} moved the resource {resource} into {new_path}.",
"You renamed the folder from {old_resource_title} to {resource}.": "You renamed the folder from {old_resource_title} to {resource}.",
"{profile} renamed the folder from {old_resource_title} to {resource}.": "{profile} renamed the folder from {old_resource_title} to {resource}.",
"You renamed the resource from {old_resource_title} to {resource}.": "You renamed the resource from {old_resource_title} to {resource}.",
"{profile} renamed the resource from {old_resource_title} to {resource}.": "{profile} renamed the resource from {old_resource_title} to {resource}.",
"You deleted the folder {resource}.": "You deleted the folder {resource}.",
"{profile} deleted the folder {resource}.": "{profile} deleted the folder {resource}.",
"You deleted the resource {resource}.": "You deleted the resource {resource}.",
"{profile} deleted the resource {resource}.": "{profile} deleted the resource {resource}.",
"Activity": "Activity",
"Load more activities": "Load more activities",
"You created the discussion {discussion}.": "You created the discussion {discussion}.",
"{profile} created the discussion {discussion}.": "{profile} created the discussion {discussion}.",
"You replied to the discussion {discussion}.": "You replied to the discussion {discussion}.",
"{profile} replied to the discussion {discussion}.": "{profile} replied to the discussion {discussion}.",
"You renamed the discussion from {old_discussion} to {discussion}.": "You renamed the discussion from {old_discussion} to {discussion}.",
"{profile} renamed the discussion from {old_discussion} to {discussion}.": "{profile} renamed the discussion from {old_discussion} to {discussion}.",
"You archived the discussion {discussion}.": "You archived the discussion {discussion}.",
"{profile} archived the discussion {discussion}.": "{profile} archived the discussion {discussion}.",
"You deleted the discussion {discussion}.": "You deleted the discussion {discussion}.",
"{profile} deleted the discussion {discussion}.": "{profile} deleted the discussion {discussion}.",
"You created the group {group}.": "You created the group {group}.",
"{profile} created the group {group}.": "{profile} created the group {group}.",
"You updated the group {group}.": "You updated the group {group}.",
"{profile} updated the group {group}.": "{profile} updated the group {group}.",
"{old_group_name} was renamed to {group}.": "{old_group_name} was renamed to {group}.",
"Visibility was set to private.": "Visibility was set to private.",
"Visibility was set to public.": "Visibility was set to public.",
"Visibility was set to an unknown value.": "Visibility was set to an unknown value.",
"The group can now only be joined with an invite.": "The group can now only be joined with an invite.",
"The group can now be joined by anyone.": "The group can now be joined by anyone.",
"Unknown value for the openness setting.": "Unknown value for the openness setting.",
"The group's physical address was changed.": "The group's physical address was changed.",
"The group's avatar was changed.": "The group's avatar was changed.",
"The group's banner was changed.": "The group's banner was changed.",
"The group's short description was changed.": "The group's short description was changed."
}

View File

@ -954,5 +954,100 @@
"Last published events": "Derniers événements publiés",
"On {instance}": "Sur {instance}",
"Close events": "Événements proches",
"Within {number} kilometers of {place}": "|Dans un rayon d'un kilomètre de {place}|Dans un rayon de {number} kilomètres de {place}"
"Within {number} kilometers of {place}": "|Dans un rayon d'un kilomètre de {place}|Dans un rayon de {number} kilomètres de {place}",
"Yesterday": "Hier",
"You created the event {event}.": "Vous avez créé l'événement {event}.",
"The event {event} was created by {profile}.": "L'événement {event} a été créé par {profile}.",
"You updated the event {event}.": "Vous avez mis à jour l'événement {event}.",
"The event {event} was updated by {profile}.": "L'événement {event} à été mis à jour par {profile}.",
"You deleted the event {event}.": "Vous avez supprimé l'événement {event}.",
"The event {event} was deleted by {profile}.": "L'événement {event} a été supprimé par {profile}.",
"You created the post {post}.": "Vous avez créé le billet {post}.",
"The post {post} was created by {profile}.": "Le billet {post} a été créé par {profile}.",
"You updated the post {post}.": "Vous avez mis à jour le billet {post}.",
"The post {post} was updated by {profile}.": "Le billet {post} a été mis à jour par {profile}.",
"You deleted the post {post}.": "Vous avez supprimé le billet {post}.",
"The post {post} was deleted by {profile}.": "Le billet {post} a été supprimé par {profile}.",
"No more activity to display.": "Il n'y a plus d'activités à afficher.",
"There is no activity yet. Start doing some things to see activity appear here.": "Il n'y a pas encore d'activité. Commencez par effectuer des actions pour voir des éléments s'afficher ici.",
"{group} activity timeline": "Timeline de l'activité de {group}",
"You promoted {member} to moderator.": "Vous avez promu {member} en tant que modérateur⋅ice.",
"You promoted {member} to administrator.": "Vous avez promu {member} en tant qu'adminstrateur⋅ice.",
"You promoted the member {member} to an unknown role.": "Vous avez promu le ou la membre {member} à un role inconnu.",
"You demoted {member} to moderator.": "Vous avez rétrogradé {member} en tant que modérateur⋅ice.",
"You demoted {member} to simple member.": "Vous avez rétrogradé {member} en tant que simple membre.",
"You demoted the member {member} to an unknown role.": "Vous avez rétrogradé le membre {member} à un role inconnu.",
"You updated the member {member}.": "Vous avez mis à jour le ou la membre {member}.",
"{profile} updated the member {member}.": "{profile} a mis à jour le ou la membre {member}.",
"{profile} promoted {member} to moderator.": "{profile} a promu {member} en tant que modérateur⋅ice.",
"{profile} promoted {member} to administrator.": "{profile} a promu {member} en tant qu'administrateur⋅ice.",
"{profile} promoted {member} to an unknown role.": "{profile} a promu {member} à un role inconnu.",
"{profile} demoted {member} to moderator.": "{profile} a rétrogradé {member} en tant que modérateur⋅ice.",
"{profile} demoted {member} to simple member.": "{profile} a rétrogradé {member} en tant que simple membre.",
"{profile} demoted {member} to an unknown role.": "{profile} a rétrogradé {member} à un role inconnu.",
"You requested to join the group.": "Vous avez demandé à rejoindre le groupe.",
"{member} requested to join the group.": "{member} a demandé à rejoindre le groupe.",
"You invited {member}.": "Vous avez invité {member}.",
"{member} was invited by {profile}.": "{member} a été invité⋅e par {profile}.",
"You added the member {member}.": "Vous avez ajouté le ou la membre {member}.",
"{profile} added the member {member}.": "{profile} a ajouté le ou la membre {member}.",
"{member} rejected the invitation to join the group.": "{member} a refusé l'invitation à se joindre au groupe.",
"{member} accepted the invitation to join the group.": "{member} a accepté l'invitation à se joindre au groupe.",
"You excluded member {member}.": "Vous avez exclu le ou la membre {member}.",
"{profile} excluded member {member}.": "{profile} a exclu le ou la membre {member}.",
"You accepted the invitation to join the group.": "Vous avez accepté l'invitation à vous joindre au groupe.",
"You were promoted to moderator by {profile}.": "Vous avez été promu⋅e modérateur⋅ice par {profile}.",
"You were promoted to administrator by {profile}.": "Vous avez été promu⋅e administrateur⋅ice par {profile}.",
"You were promoted to an unknown role by {profile}.": "Vous avez été promu⋅e à un role inconnu par {profile}.",
"You were demoted to moderator by {profile}.": "Vous avez été rétrogradé⋅e modérateur⋅ice par {profile}.",
"You were demoted to simple member by {profile}.": "Vous avez été rétrogradé⋅e simple membre par {profile}.",
"You were demoted to an unknown role by {profile}.": "Vous avez été rétrogradé⋅e à un role inconnu par {profile}.",
"{profile} quit the group.": "{profile} a quitté le groupe.",
"You created the folder {resource}.": "Vous avez créé le dossier {resource}.",
"{profile} created the folder {resource}.": "{profile} a créé le dossier {resource}.",
"You created the resource {resource}.": "Vous avez créé la ressource {resource}.",
"{profile} created the resource {resource}.": "{profile} a créé la ressource {resource}.",
"You moved the folder {resource} to the root folder.": "Vous avez déplacé le dossier {resource} dans le dossier racine.",
"{profile} moved the folder {resource} to the root folder.": "{profile} a déplacé le dossier {resource} dans le dossier racine.",
"You moved the folder {resource} into {new_path}.": "Vous avez déplacé le dossier {resource} dans {new_path}.",
"{profile} moved the folder {resource} into {new_path}.": "{profile} a déplacé le dossier {resource} dans {new_path}.",
"You moved the resource {resource} to the root folder.": "Vous avez déplacé la ressource {resource} dans le dossier racine.",
"{profile} moved the resource {resource} to the root folder.": "{profile} a déplacé la ressource {resource} dans le dossier racine.",
"You moved the resource {resource} into {new_path}.": "Vous avez déplacé la ressource {resource} dans {new_path}.",
"{profile} moved the resource {resource} into {new_path}.": "{profile} a déplacé la ressource {resource} dans {new_path}.",
"You renamed the folder from {old_resource_title} to {resource}.": "Vous avez renommé le dossier {old_resource_title} en {resource}.",
"{profile} renamed the folder from {old_resource_title} to {resource}.": "{profile} a renommé le dossier {old_resource_title} en {resource}.",
"You renamed the resource from {old_resource_title} to {resource}.": "Vous avez renommé la ressource {old_resource_title} en {resource}.",
"{profile} renamed the resource from {old_resource_title} to {resource}.": "{profile} a renommé la ressource {old_resource_title} en {resource}.",
"You deleted the folder {resource}.": "Vous avez supprimé le dossier {resource}.",
"{profile} deleted the folder {resource}.": "{profile} a supprimé le dossier {resource}.",
"You deleted the resource {resource}.": "Vous avez supprimé la ressource {resource}.",
"{profile} deleted the resource {resource}.": "{profile} a supprimé la ressource {resource}.",
"Activity": "Activité",
"Load more activities": "Charger plus d'activités",
"You created the discussion {discussion}.": "Vous avez créé la discussion {discussion}.",
"{profile} created the discussion {discussion}.": "{profile} a créé la discussion {discussion}.",
"You replied to the discussion {discussion}.": "Vous avez répondu à la discussion {discussion}.",
"{profile} replied to the discussion {discussion}.": "{profile} a répondu à la discussion {discussion}.",
"You renamed the discussion from {old_discussion} to {discussion}.": "Vous avez renommé la discussion {old_discussion} en {discussion}.",
"{profile} renamed the discussion from {old_discussion} to {discussion}.": "{profile} a renommé la discussion {old_discussion} en {discussion}.",
"You archived the discussion {discussion}.": "Vous avez archivé la discussion {discussion}.",
"{profile} archived the discussion {discussion}.": "{profile} a archivé la discussion {discussion}.",
"You deleted the discussion {discussion}.": "Vous avez supprimé la discussion {discussion}.",
"{profile} deleted the discussion {discussion}.": "{profile} a supprimé la discussion {discussion}.",
"You created the group {group}.": "Vous avez créé le groupe {group}.",
"{profile} created the group {group}.": "{profile} a créé le groupe {group}.",
"You updated the group {group}.": "Vous avez mis à jour le groupe {group}.",
"{profile} updated the group {group}.": "{profile} a mis à jour le groupe {group}.",
"{old_group_name} was renamed to {group}.": "{old_group_name} a été renommé en {group}.",
"Visibility was set to private.": "La visibilité a été définie à privée.",
"Visibility was set to public.": "La visibilité a été définie à public.",
"Visibility was set to an unknown value.": "La visibilité a été définie à une valeur inconnue.",
"The group can now only be joined with an invite.": "Le groupe peut maintenant être rejoint uniquement sur invitation.",
"The group can now be joined by anyone.": "Le groupe peut maintenant être rejoint par n'importe qui.",
"Unknown value for the openness setting.": "Valeur inconnue pour le paramètre d'ouverture.",
"The group's physical address was changed.": "L'adresse physique du groupe a été changée.",
"The group's avatar was changed.": "L'avatar du groupe a été changé.",
"The group's banner was changed.": "La bannière du groupe a été changée.",
"The group's short description was changed.": "La description courte du groupe a été changée."
}

31
js/src/mixins/activity.ts Normal file
View File

@ -0,0 +1,31 @@
import { CURRENT_ACTOR_CLIENT } from "@/graphql/actor";
import { IActivity } from "@/types/activity.model";
import { IActor } from "@/types/actor";
import { Component, Prop, Vue } from "vue-property-decorator";
@Component({
apollo: {
currentActor: CURRENT_ACTOR_CLIENT,
},
})
export default class ActivityMixin extends Vue {
@Prop({ required: true, type: Object }) activity!: IActivity;
currentActor!: IActor;
get subjectParams(): Record<string, string> {
return this.activity.subjectParams.reduce(
(acc: Record<string, string>, { key, value }) => {
acc[key] = value;
return acc;
},
{}
);
}
get isAuthorCurrentActor(): boolean {
return (
this.activity.author.id === this.currentActor.id &&
this.currentActor.id !== undefined
);
}
}

View File

@ -18,6 +18,7 @@ export enum GroupsRouteName {
POSTS = "POSTS",
GROUP_EVENTS = "GROUP_EVENTS",
GROUP_JOIN = "GROUP_JOIN",
TIMELINE = "TIMELINE",
}
const resourceFolder = (): Promise<EsModuleComponent> =>
@ -145,4 +146,12 @@ export const groupsRoutes: RouteConfig[] = [
name: GroupsRouteName.GROUP_JOIN,
meta: { requiredAuth: false },
},
{
path: "/@:preferredUsername/timeline",
name: GroupsRouteName.TIMELINE,
component: (): Promise<EsModuleComponent> =>
import("@/views/Group/Timeline.vue"),
props: true,
meta: { requiredAuth: true },
},
];

View File

@ -0,0 +1,33 @@
import { IActor, IGroup } from "./actor";
import { IMember } from "./actor/member.model";
import {
ActivityDiscussionSubject,
ActivityEventSubject,
ActivityGroupSubject,
ActivityMemberSubject,
ActivityPostSubject,
ActivityResourceSubject,
ActivityType,
} from "./enums";
import { IEvent } from "./event.model";
import { IPost } from "./post.model";
import { IResource } from "./resource";
export type ActivitySubject =
| ActivityEventSubject
| ActivityPostSubject
| ActivityMemberSubject
| ActivityResourceSubject
| ActivityDiscussionSubject
| ActivityGroupSubject;
export interface IActivity {
id: string;
type: ActivityType;
subject: ActivitySubject;
subjectParams: { key: string; value: string }[];
author: IActor;
group: IGroup;
object: IEvent | IPost | IGroup | IMember | IResource;
insertedAt: string;
}

View File

@ -10,6 +10,7 @@ import { Address } from "../address.model";
import { ActorType, Openness } from "../enums";
import type { IMember } from "./member.model";
import type { ITodoList } from "../todolist";
import { IActivity } from "../activity.model";
export interface IGroup extends IActor {
members: Paginate<IMember>;
@ -20,6 +21,7 @@ export interface IGroup extends IActor {
physicalAddress: IAddress;
openness: Openness;
manuallyApprovesFollowers: boolean;
activity: Paginate<IActivity>;
}
export class Group extends Actor implements IGroup {
@ -41,6 +43,7 @@ export class Group extends Actor implements IGroup {
this.patch(hash);
}
activity: Paginate<IActivity> = { elements: [], total: 0 };
openness: Openness = Openness.INVITE_ONLY;

View File

@ -182,3 +182,56 @@ export enum GroupVisibility {
export enum AddressSearchType {
ADMINISTRATIVE = "ADMINISTRATIVE",
}
export enum ActivityType {
EVENT = "EVENT",
POST = "POST",
MEMBER = "MEMBER",
RESOURCE = "RESOURCE",
DISCUSSION = "DISCUSSION",
GROUP = "GROUP",
}
export enum ActivityEventSubject {
EVENT_CREATED = "event_created",
EVENT_UPDATED = "event_updated",
EVENT_DELETED = "event_deleted",
}
export enum ActivityPostSubject {
POST_CREATED = "post_created",
POST_UPDATED = "post_updated",
POST_DELETED = "post_deleted",
}
export enum ActivityMemberSubject {
MEMBER_REQUEST = "member_request",
MEMBER_INVITED = "member_invited",
MEMBER_ACCEPTED_INVITATION = "member_accepted_invitation",
MEMBER_REJECTED_INVITATION = "member_rejected_invitation",
MEMBER_ADDED = "member_added",
MEMBER_JOINED = "member_joined",
MEMBER_APPROVED = "member_approved",
MEMBER_UPDATED = "member_updated",
MEMBER_REMOVED = "member_removed",
MEMBER_QUIT = "member_quit",
}
export enum ActivityResourceSubject {
RESOURCE_CREATED = "resource_created",
RESOURCE_UPDATED = "resource_renamed",
RESOURCE_MOVED = "resource_moved",
RESOURCE_DELETED = "resource_deleted",
}
export enum ActivityDiscussionSubject {
DISCUSSION_CREATED = "discussion_created",
DISCUSSION_REPLIED = "discussion_replied",
DISCUSSION_RENAMED = "discussion_renamed",
DISCUSSION_ARCHIVED = "discussion_archived",
DISCUSSION_DELETED = "discussion_deleted",
}
export enum ActivityGroupSubject {
GROUP_CREATED = "group_created",
GROUP_UPDATED = "group_updated",
}

View File

@ -86,6 +86,10 @@ $colors: map-merge(
$link,
$link-invert,
),
"grey": (
$grey,
findColorInvert($grey),
),
)
);

View File

@ -497,13 +497,11 @@ const DEFAULT_LIMIT_NUMBER_OF_PLACES = 10;
},
metaInfo() {
return {
// if no subcomponents specify a metaInfo.title, this title will be used
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
title: (this.isUpdate
? this.$t("Event edition")
: this.$t("Event creation")) as string,
// all titles will be injected into this template
titleTemplate: "%s | Mobilizon",
};
},

View File

@ -737,11 +737,9 @@ import { IParticipant } from "../../types/participant.model";
},
metaInfo() {
return {
// if no subcomponents specify a metaInfo.title, this title will be used
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
title: this.eventTitle,
// all titles will be injected into this template
titleTemplate: "%s | Mobilizon",
meta: [
// eslint-disable-next-line @typescript-eslint/ban-ts-comment

View File

@ -186,9 +186,7 @@ import Subtitle from "../../components/Utils/Subtitle.vue";
},
metaInfo() {
return {
// if no subcomponents specify a metaInfo.title, this title will be used
title: this.$t("My events") as string,
// all titles will be injected into this template
titleTemplate: "%s | Mobilizon",
};
},

View File

@ -57,14 +57,27 @@
<b-skeleton v-else :animated="true" />
<br />
<div class="buttons">
<router-link
<b-button
outlined
icon-left="timeline-text"
v-if="isCurrentActorAGroupMember"
tag="router-link"
:to="{
name: RouteName.TIMELINE,
params: { preferredUsername: usernameWithDomain(group) },
}"
>{{ $t("Activity") }}</b-button
>
<b-button
outlined
icon-left="cog"
v-if="isCurrentActorAGroupAdmin"
tag="router-link"
:to="{
name: RouteName.GROUP_PUBLIC_SETTINGS,
params: { preferredUsername: usernameWithDomain(group) },
}"
class="button is-outlined"
>{{ $t("Group settings") }}</router-link
>{{ $t("Group settings") }}</b-button
>
</div>
</div>
@ -506,11 +519,9 @@ import ReportModal from "../../components/Report/ReportModal.vue";
},
metaInfo() {
return {
// if no subcomponents specify a metaInfo.title, this title will be used
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
title: this.groupTitle,
// all titles will be injected into this template
titleTemplate: "%s | Mobilizon",
meta: [
// eslint-disable-next-line @typescript-eslint/ban-ts-comment

View File

@ -104,9 +104,7 @@ import RouteName from "../../router/name";
},
metaInfo() {
return {
// if no subcomponents specify a metaInfo.title, this title will be used
title: this.$t("My groups") as string,
// all titles will be injected into this template
titleTemplate: "%s | Mobilizon",
};
},

View File

@ -49,4 +49,7 @@ export default class Settings extends mixins(GroupMixin) {
aside.section {
padding-top: 1rem;
}
.container.section {
background: $white;
}
</style>

View File

@ -0,0 +1,320 @@
<template>
<div class="container section">
<nav class="breadcrumb" aria-label="breadcrumbs">
<ul v-if="group">
<li>
<router-link
:to="{
name: RouteName.GROUP,
params: { preferredUsername: usernameWithDomain(group) },
}"
>{{ group.name }}</router-link
>
</li>
<li>
<router-link
:to="{
name: RouteName.TIMELINE,
params: { preferredUsername: usernameWithDomain(group) },
}"
>{{ $t("Activity") }}</router-link
>
</li>
</ul>
</nav>
<section class="timeline">
<transition-group name="timeline-list" tag="div">
<div
class="day"
v-for="[date, activityItems] in Object.entries(activities)"
:key="date"
>
<b-skeleton
v-if="date.search(/skeleton/) !== -1"
width="300px"
height="48px"
/>
<h2 class="is-size-3 has-text-weight-bold" v-else-if="isToday(date)">
<span v-tooltip="$options.filters.formatDateString(date)">
{{ $t("Today") }}
</span>
</h2>
<h2
class="is-size-3 has-text-weight-bold"
v-else-if="isYesterday(date)"
>
<span v-tooltip="$options.filters.formatDateString(date)">{{
$t("Yesterday")
}}</span>
</h2>
<h2 v-else class="is-size-3 has-text-weight-bold">
{{ date | formatDateString }}
</h2>
<ul>
<li v-for="activityItem in activityItems" :key="activityItem.id">
<skeleton-activity-item v-if="activityItem.skeleton" />
<component
v-else
:is="component(activityItem.type)"
:activity="activityItem"
/>
</li>
</ul></div
></transition-group>
<empty-content
icon="timeline-text"
v-if="
!$apollo.loading &&
activity.elements.length > 0 &&
activity.elements.length >= activity.total
"
>
{{ $t("No more activity to display.") }}
</empty-content>
<empty-content
v-if="!$apollo.loading && activities.size === 0"
icon="timeline-text"
>
{{
$t(
"There is no activity yet. Start doing some things to see activity appear here."
)
}}
</empty-content>
<observer @intersect="loadMore" />
<b-button
v-if="activity.elements.length < activity.total"
@click="loadMore"
>{{ $t("Load more activities") }}</b-button
>
</section>
</div>
</template>
<script lang="ts">
import { GROUP_TIMELINE } from "@/graphql/group";
import { IGroup, usernameWithDomain } from "@/types/actor";
import { ActivityType } from "@/types/enums";
import { Paginate } from "@/types/paginate";
import { Component, Prop, Vue } from "vue-property-decorator";
import { IActivity } from "../../types/activity.model";
import Observer from "../../components/Utils/Observer.vue";
import SkeletonActivityItem from "../../components/Activity/SkeletonActivityItem.vue";
import RouteName from "../../router/name";
const PAGINATION_LIMIT = 25;
const SKELETON_DAY_ITEMS = 2;
const SKELETON_ITEMS_PER_DAY = 5;
type IActivitySkeleton = IActivity | { skeleton: string };
@Component({
apollo: {
group: {
query: GROUP_TIMELINE,
variables() {
return {
preferredUsername: this.preferredUsername,
page: 1,
limit: PAGINATION_LIMIT,
};
},
},
},
components: {
Observer,
SkeletonActivityItem,
"event-activity-item": () =>
import("../../components/Activity/EventActivityItem.vue"),
"post-activity-item": () =>
import("../../components/Activity/PostActivityItem.vue"),
"member-activity-item": () =>
import("../../components/Activity/MemberActivityItem.vue"),
"resource-activity-item": () =>
import("../../components/Activity/ResourceActivityItem.vue"),
"discussion-activity-item": () =>
import("../../components/Activity/DiscussionActivityItem.vue"),
"group-activity-item": () =>
import("../../components/Activity/GroupActivityItem.vue"),
"empty-content": () => import("../../components/Utils/EmptyContent.vue"),
},
metaInfo() {
return {
title: this.$t("{group} activity timeline", {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
group: this.group?.name,
}) as string,
titleTemplate: "%s | Mobilizon",
};
},
})
export default class Timeline extends Vue {
@Prop({ required: true, type: String }) preferredUsername!: string;
group!: IGroup;
RouteName = RouteName;
usernameWithDomain = usernameWithDomain;
get activity(): Paginate<IActivitySkeleton> {
if (this.group) {
return this.group.activity;
}
return {
total: 0,
elements: this.skeletons.map((skeleton) => ({
skeleton,
})),
};
}
page = 1;
limit = PAGINATION_LIMIT;
component(type: ActivityType): string | undefined {
switch (type) {
case ActivityType.EVENT:
return "event-activity-item";
case ActivityType.POST:
return "post-activity-item";
case ActivityType.MEMBER:
return "member-activity-item";
case ActivityType.RESOURCE:
return "resource-activity-item";
case ActivityType.DISCUSSION:
return "discussion-activity-item";
case ActivityType.GROUP:
return "group-activity-item";
}
}
get skeletons(): string[] {
return [...Array(SKELETON_DAY_ITEMS)]
.map((_, i) => {
return [...Array(SKELETON_ITEMS_PER_DAY)].map((_a, j) => {
return `${i}-${j}`;
});
})
.flat();
}
async loadMore(): Promise<void> {
if (this.page * PAGINATION_LIMIT >= this.activity.total) {
return;
}
this.page++;
try {
await this.$apollo.queries.group.fetchMore({
variables: {
page: this.page,
limit: PAGINATION_LIMIT,
},
updateQuery: (previousResult, { fetchMoreResult }) => {
if (!fetchMoreResult) return previousResult;
const newActivities = fetchMoreResult.group.activity.elements;
const newTotal = fetchMoreResult.group.activity.total;
return {
group: {
...previousResult.group,
activity: {
__typename: previousResult.group.activity.__typename,
total: newTotal,
elements: [
...previousResult.group.activity.elements,
...newActivities,
],
},
},
};
},
});
} catch (e) {
console.error(e);
}
}
get activities(): Record<string, IActivitySkeleton[]> {
return this.activity.elements.reduce(
(acc: Record<string, IActivitySkeleton[]>, elem) => {
let key;
if (this.isIActivity(elem)) {
const insertedAt = new Date(elem.insertedAt);
insertedAt.setHours(0);
insertedAt.setMinutes(0);
insertedAt.setSeconds(0);
insertedAt.setMilliseconds(0);
key = insertedAt.toISOString();
} else {
key = `skeleton-${elem.skeleton.split("-")[0]}`;
}
const existing = acc[key];
if (existing) {
acc[key] = [...existing, ...[elem]];
} else {
acc[key] = [elem];
}
return acc;
},
{}
);
}
isIActivity(object: IActivitySkeleton): object is IActivity {
return !("skeleton" in object);
}
getRandomInt(min: number, max: number): number {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
isToday(dateString: string): boolean {
const now = new Date();
const date = new Date(dateString);
return (
now.getFullYear() === date.getFullYear() &&
now.getMonth() === date.getMonth() &&
now.getDate() === date.getDate()
);
}
isYesterday(dateString: string): boolean {
const date = new Date(dateString);
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
return (
yesterday.getFullYear() === date.getFullYear() &&
yesterday.getMonth() === date.getMonth() &&
yesterday.getDate() === date.getDate()
);
}
}
</script>
<style lang="scss" scoped>
.container.section {
background: $white;
}
.timeline {
ul {
// padding: 0.5rem 0;
margin: 0;
list-style: none;
position: relative;
&::before {
content: "";
height: 100%;
width: 1px;
background-color: #d9d9d9;
position: absolute;
top: 0;
left: 1rem;
}
li {
display: flex;
margin: 0.5rem 0;
}
}
}
</style>

View File

@ -407,11 +407,9 @@ import Subtitle from "../components/Utils/Subtitle.vue";
},
metaInfo() {
return {
// if no subcomponents specify a metaInfo.title, this title will be used
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
title: this.instanceName,
// all titles will be injected into this template
titleTemplate: "%s | Mobilizon",
};
},

View File

@ -128,11 +128,9 @@ const POSTS_PAGE_LIMIT = 10;
},
metaInfo() {
return {
// if no subcomponents specify a metaInfo.title, this title will be used
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
title: this.$t("My groups") as string,
// all titles will be injected into this template
titleTemplate: "%s | Mobilizon",
};
},

View File

@ -254,9 +254,7 @@ const GROUP_PAGE_LIMIT = 10;
},
metaInfo() {
return {
// if no subcomponents specify a metaInfo.title, this title will be used
title: this.$t("Explore events") as string,
// all titles will be injected into this template
titleTemplate: "%s | Mobilizon",
};
},

View File

@ -156,9 +156,7 @@ import AuthProviders from "../../components/User/AuthProviders.vue";
},
metaInfo() {
return {
// if no subcomponents specify a metaInfo.title, this title will be used
title: this.$t("Login on Mobilizon!") as string,
// all titles will be injected into this template
titleTemplate: "%s | Mobilizon",
};
},

View File

@ -203,11 +203,9 @@ import AuthProviders from "../../components/User/AuthProviders.vue";
components: { Subtitle, AuthProviders },
metaInfo() {
return {
// if no subcomponents specify a metaInfo.title, this title will be used
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
title: this.title,
// all titles will be injected into this template
titleTemplate: "%s | Mobilizon",
};
},

View File

@ -459,6 +459,7 @@ defmodule Mobilizon.Federation.ActivityPub do
Map.get(additional, :force_member_removal, false) ||
!Actors.is_only_administrator?(member_id, group_id)},
{:delete, {:ok, %Member{} = member}} <- {:delete, Actors.delete_member(member)},
Mobilizon.Service.Activity.Member.insert_activity(member, subject: "member_quit"),
leave_data <- %{
"to" => [group_members_url],
"cc" => [group_url],
@ -477,12 +478,17 @@ defmodule Mobilizon.Federation.ActivityPub do
def remove(
%Member{} = member,
%Actor{type: :Group, url: group_url, members_url: group_members_url},
%Actor{url: moderator_url},
%Actor{url: moderator_url} = moderator,
local,
_additional \\ %{}
) do
with {:ok, %Member{id: member_id}} <- Actors.update_member(member, %{role: :rejected}),
%Member{} = member <- Actors.get_member(member_id),
{:ok, _} <-
Mobilizon.Service.Activity.Member.insert_activity(member,
moderator: moderator,
subject: "member_removed"
),
:ok <- Group.send_notification_to_removed_member(member),
remove_data <- %{
"to" => [group_members_url],
@ -518,6 +524,11 @@ defmodule Mobilizon.Federation.ActivityPub do
invited_by_id: actor_id,
url: Map.get(additional, :url)
}),
{:ok, _} <-
Mobilizon.Service.Activity.Member.insert_activity(member,
moderator: actor,
subject: "member_invited"
),
invite_data <- %{
"type" => "Invite",
"attributedTo" => group_url,
@ -914,6 +925,10 @@ defmodule Mobilizon.Federation.ActivityPub do
defp accept_join(%Member{} = member, additional) do
with {:ok, %Member{} = member} <-
Actors.update_member(member, %{role: :member}),
{:ok, _} <-
Mobilizon.Service.Activity.Member.insert_activity(member,
subject: "member_approved"
),
_ <-
unless(is_nil(member.parent.domain),
do: Refresher.fetch_group(member.parent.url, member.actor)
@ -949,6 +964,10 @@ defmodule Mobilizon.Federation.ActivityPub do
%Actor{url: actor_url} <- Actors.get_actor(actor_id),
{:ok, %Member{id: member_id} = member} <-
Actors.update_member(member, %{role: :member}),
{:ok, _} <-
Mobilizon.Service.Activity.Member.insert_activity(member,
subject: "member_accepted_invitation"
),
accept_data <- %{
"type" => "Accept",
"attributedTo" => member.parent.url,
@ -1029,6 +1048,9 @@ defmodule Mobilizon.Federation.ActivityPub do
%Actor{url: actor_url} <- Actors.get_actor(actor_id),
{:ok, %Member{url: member_url, id: member_id} = member} <-
Actors.delete_member(member),
Mobilizon.Service.Activity.Member.insert_activity(member,
subject: "member_rejected_invitation"
),
accept_data <- %{
"type" => "Reject",
"actor" => actor_url,

View File

@ -7,6 +7,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Actors do
alias Mobilizon.Federation.ActivityPub.Types.Entity
alias Mobilizon.Federation.ActivityStream.Convertible
alias Mobilizon.GraphQL.API.Utils, as: APIUtils
alias Mobilizon.Service.Activity.Group, as: GroupActivity
alias Mobilizon.Service.Formatter.HTML
alias Mobilizon.Service.Notifications.Scheduler
alias Mobilizon.Web.Email.Follow, as: FollowMailer
@ -20,6 +21,11 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Actors do
def create(args, additional) do
with args <- prepare_args_for_actor(args),
{:ok, %Actor{} = actor} <- Actors.create_actor(args),
{:ok, _} <-
GroupActivity.insert_activity(actor,
subject: "group_created",
actor_id: args.creator_actor_id
),
actor_as_data <- Convertible.model_to_as(actor),
audience <- %{"to" => ["https://www.w3.org/ns/activitystreams#Public"], "cc" => []},
create_data <-
@ -32,6 +38,12 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Actors do
@spec update(Actor.t(), map, map) :: {:ok, Actor.t(), Activity.t()} | any
def update(%Actor{} = old_actor, args, additional) do
with {:ok, %Actor{} = new_actor} <- Actors.update_actor(old_actor, args),
{:ok, _} <-
GroupActivity.insert_activity(new_actor,
subject: "group_updated",
old_group: old_actor,
updater_actor: Map.get(args, :updater_actor)
),
actor_as_data <- Convertible.model_to_as(new_actor),
{:ok, true} <- Cachex.del(:activity_pub, "actor_#{new_actor.preferred_username}"),
audience <-
@ -112,6 +124,8 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Actors do
|> Map.get(:metadata, %{})
|> Map.update(:message, nil, &String.trim(HTML.strip_tags(&1)))
}),
{:ok, _} <-
Mobilizon.Service.Activity.Member.insert_activity(member, subject: "member_joined"),
Absinthe.Subscription.publish(Endpoint, actor, group_membership_changed: actor.id),
join_data <- %{
"type" => "Join",

View File

@ -7,6 +7,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Discussions do
alias Mobilizon.Federation.ActivityPub.Audience
alias Mobilizon.Federation.ActivityPub.Types.Entity
alias Mobilizon.Federation.ActivityStream.Convertible
alias Mobilizon.Service.Activity.Discussion, as: DiscussionActivity
alias Mobilizon.Web.Endpoint
import Mobilizon.Federation.ActivityPub.Utils, only: [make_create_data: 2, make_update_data: 2]
require Logger
@ -19,6 +20,11 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Discussions do
with %Discussion{} = discussion <- Discussions.get_discussion(discussion_id),
{:ok, %Discussion{last_comment_id: last_comment_id} = discussion} <-
Discussions.reply_to_discussion(discussion, args),
{:ok, _} <-
DiscussionActivity.insert_activity(discussion,
subject: "discussion_replied",
actor_id: Map.get(args, :creator_id, args.actor_id)
),
%Comment{} = last_comment <- Discussions.get_comment_with_preload(last_comment_id),
:ok <- maybe_publish_graphql_subscription(discussion),
comment_as_data <- Convertible.model_to_as(last_comment),
@ -35,6 +41,8 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Discussions do
def create(args, additional) do
with {:ok, %Discussion{} = discussion} <-
Discussions.create_discussion(args),
{:ok, _} <-
DiscussionActivity.insert_activity(discussion, subject: "discussion_created"),
discussion_as_data <- Convertible.model_to_as(discussion),
audience <-
Audience.calculate_to_and_cc_from_mentions(discussion),
@ -49,6 +57,11 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Discussions do
def update(%Discussion{} = old_discussion, args, additional) do
with {:ok, %Discussion{} = new_discussion} <-
Discussions.update_discussion(old_discussion, args),
{:ok, _} <-
DiscussionActivity.insert_activity(new_discussion,
subject: "discussion_renamed",
old_discussion: old_discussion
),
{:ok, true} <- Cachex.del(:activity_pub, "discussion_#{new_discussion.slug}"),
discussion_as_data <- Convertible.model_to_as(new_discussion),
audience <-
@ -71,7 +84,12 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Discussions do
_local,
_additionnal
) do
with {:ok, _} <- Discussions.delete_discussion(discussion) do
with {:ok, _} <- Discussions.delete_discussion(discussion),
{:ok, _} <-
DiscussionActivity.insert_activity(discussion,
subject: "discussion_deleted",
moderator: actor
) do
# This is just fake
activity_data = %{
"type" => "Delete",

View File

@ -10,6 +10,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Events do
alias Mobilizon.Federation.ActivityStream.Converter.Utils, as: ConverterUtils
alias Mobilizon.Federation.ActivityStream.Convertible
alias Mobilizon.GraphQL.API.Utils, as: APIUtils
alias Mobilizon.Service.Activity.Event, as: EventActivity
alias Mobilizon.Service.Formatter.HTML
alias Mobilizon.Service.Notifications.Scheduler
alias Mobilizon.Share
@ -24,6 +25,8 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Events do
def create(args, additional) do
with args <- prepare_args_for_event(args),
{:ok, %Event{} = event} <- EventsManager.create_event(args),
{:ok, _} <-
EventActivity.insert_activity(event, subject: "event_created"),
event_as_data <- Convertible.model_to_as(event),
audience <-
Audience.calculate_to_and_cc_from_mentions(event),
@ -38,6 +41,8 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Events do
def update(%Event{} = old_event, args, additional) do
with args <- prepare_args_for_event(args),
{:ok, %Event{} = new_event} <- EventsManager.update_event(old_event, args),
{:ok, _} <-
EventActivity.insert_activity(new_event, subject: "event_updated"),
{:ok, true} <- Cachex.del(:activity_pub, "event_#{new_event.uuid}"),
event_as_data <- Convertible.model_to_as(new_event),
audience <-
@ -66,6 +71,8 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Events do
with audience <-
Audience.calculate_to_and_cc_from_mentions(event),
{:ok, %Event{} = event} <- EventsManager.delete_event(event),
{:ok, _} <-
EventActivity.insert_activity(event, subject: "event_deleted"),
{:ok, true} <- Cachex.del(:activity_pub, "event_#{event.uuid}"),
{:ok, %Tombstone{} = _tombstone} <-
Tombstone.create_tombstone(%{uri: event.url, actor_id: actor.id}) do

View File

@ -4,13 +4,14 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Members do
alias Mobilizon.Actors.{Actor, Member}
alias Mobilizon.Federation.ActivityPub
alias Mobilizon.Federation.ActivityStream.Convertible
alias Mobilizon.Service.Activity.Member, as: MemberActivity
require Logger
import Mobilizon.Federation.ActivityPub.Utils, only: [make_update_data: 2]
def update(
%Member{parent: %Actor{id: group_id}, id: member_id, role: current_role} = member,
%Member{parent: %Actor{id: group_id}, id: member_id, role: current_role} = old_member,
%{role: updated_role} = args,
%{moderator: %Actor{url: moderator_url, id: moderator_id}} = additional
%{moderator: %Actor{url: moderator_url, id: moderator_id} = moderator} = additional
) do
with additional <- Map.delete(additional, :moderator),
{:has_rights_to_update_role, {:ok, %Member{role: moderator_role}}}
@ -19,7 +20,13 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Members do
{:is_only_admin, false} <-
{:is_only_admin, check_admins_left(member_id, group_id, current_role, updated_role)},
{:ok, %Member{} = member} <-
Actors.update_member(member, args),
Actors.update_member(old_member, args),
{:ok, _} <-
MemberActivity.insert_activity(member,
old_member: old_member,
moderator: moderator,
subject: "member_updated"
),
{:ok, true} <- Cachex.del(:activity_pub, "member_#{member_id}"),
member_as_data <-
Convertible.model_to_as(member),

View File

@ -7,6 +7,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Posts do
alias Mobilizon.Federation.ActivityStream.Converter.Utils, as: ConverterUtils
alias Mobilizon.Federation.ActivityStream.Convertible
alias Mobilizon.Posts.Post
alias Mobilizon.Service.Activity.Post, as: PostsActivity
require Logger
import Mobilizon.Federation.ActivityPub.Utils, only: [make_create_data: 2, make_update_data: 2]
@ -19,6 +20,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Posts do
with args <- Map.update(args, :tags, [], &ConverterUtils.fetch_tags/1),
{:ok, %Post{attributed_to_id: group_id, author_id: creator_id} = post} <-
Posts.create_post(args),
{:ok, _} <- PostsActivity.insert_activity(post, subject: "post_created"),
{:ok, %Actor{} = group} <- Actors.get_group_by_actor_id(group_id),
%Actor{} = creator <- Actors.get_actor(creator_id),
post_as_data <-
@ -40,6 +42,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Posts do
with args <- Map.update(args, :tags, [], &ConverterUtils.fetch_tags/1),
{:ok, %Post{attributed_to_id: group_id, author_id: creator_id} = post} <-
Posts.update_post(post, args),
{:ok, _} <- PostsActivity.insert_activity(post, subject: "post_updated"),
{:ok, true} <- Cachex.del(:activity_pub, "post_#{post.slug}"),
{:ok, %Actor{} = group} <- Actors.get_group_by_actor_id(group_id),
%Actor{} = creator <- Actors.get_actor(creator_id),
@ -76,6 +79,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Posts do
}
with {:ok, %Post{} = post} <- Posts.delete_post(post),
{:ok, _} <- PostsActivity.insert_activity(post, subject: "post_deleted"),
{:ok, true} <- Cachex.del(:activity_pub, "post_#{post.slug}"),
{:ok, %Tombstone{} = _tombstone} <-
Tombstone.create_tombstone(%{uri: post.url, actor_id: actor.id}) do

View File

@ -5,6 +5,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Resources do
alias Mobilizon.Federation.ActivityPub.Types.Entity
alias Mobilizon.Federation.ActivityStream.Convertible
alias Mobilizon.Resources.Resource
alias Mobilizon.Service.Activity.Resource, as: ResourceActivity
alias Mobilizon.Service.RichMedia.Parser
require Logger
@ -33,6 +34,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Resources do
with {:ok,
%Resource{actor_id: group_id, creator_id: creator_id, parent_id: parent_id} = resource} <-
Resources.create_resource(args),
{:ok, _} <- ResourceActivity.insert_activity(resource, subject: "resource_created"),
{:ok, %Actor{} = group} <- Actors.get_group_by_actor_id(group_id),
%Actor{url: creator_url} = creator <- Actors.get_actor(creator_id),
resource_as_data <-
@ -63,7 +65,12 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Resources do
end
@impl Entity
def update(%Resource{} = old_resource, %{parent_id: _parent_id} = args, additional) do
def update(
%Resource{parent_id: old_parent_id} = old_resource,
%{parent_id: parent_id} = args,
additional
)
when old_parent_id != parent_id do
move(old_resource, args, additional)
end
@ -71,6 +78,11 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Resources do
def update(%Resource{} = old_resource, %{title: title} = _args, additional) do
with {:ok, %Resource{actor_id: group_id, creator_id: creator_id} = resource} <-
Resources.update_resource(old_resource, %{title: title}),
{:ok, _} <-
ResourceActivity.insert_activity(resource,
subject: "resource_renamed",
old_resource: old_resource
),
{:ok, %Actor{} = group} <- Actors.get_group_by_actor_id(group_id),
%Actor{url: creator_url} <- Actors.get_actor(creator_id),
resource_as_data <-
@ -100,6 +112,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Resources do
%Resource{actor_id: group_id, creator_id: creator_id, parent_id: new_parent_id} =
resource} <-
Resources.update_resource(old_resource, args),
{:ok, _} <- ResourceActivity.insert_activity(resource, subject: "resource_moved"),
old_parent <- Resources.get_resource(old_parent_id),
new_parent <- Resources.get_resource(new_parent_id),
{:ok, %Actor{} = group} <- Actors.get_group_by_actor_id(group_id),
@ -146,6 +159,7 @@ defmodule Mobilizon.Federation.ActivityPub.Types.Resources do
}
with {:ok, _resource} <- Resources.delete_resource(resource),
{:ok, _} <- ResourceActivity.insert_activity(resource, subject: "resource_deleted"),
{:ok, true} <- Cachex.del(:activity_pub, "resource_#{resource.id}") do
{:ok, activity_data, actor, resource}
end

View File

@ -0,0 +1,85 @@
defmodule Mobilizon.GraphQL.Resolvers.Activity do
@moduledoc """
Handles the activity-related GraphQL calls.
"""
import Mobilizon.Users.Guards
alias Mobilizon.{Activities, Actors, Discussions, Events, Posts, Resources, Users}
alias Mobilizon.Activities.Activity
alias Mobilizon.Actors.Actor
alias Mobilizon.Events.Event
alias Mobilizon.Storage.Page
alias Mobilizon.Users.User
require Logger
def group_activity(%Actor{type: :Group, id: group_id}, %{page: page, limit: limit}, %{
context: %{current_user: %User{role: role} = user}
}) do
with {:actor, %Actor{id: actor_id} = _actor} <- {:actor, Users.get_actor_for_user(user)},
{:member, true} <- {:member, Actors.is_member?(actor_id, group_id) or is_moderator(role)} do
%Page{total: total, elements: elements} =
Activities.list_activities_for_group(group_id, actor_id, [], page, limit)
elements =
Enum.map(elements, fn %Activity{} = activity ->
activity
|> Map.update(:subject_params, %{}, &transform_params/1)
|> Map.put(:object, get_object(activity))
end)
{:ok, %Page{total: total, elements: elements}}
else
{:member, false} ->
{:error, :unauthorized}
end
end
def group_activity(_, _, _) do
{:error, :unauthenticated}
end
defp get_object(%Activity{object_type: object_type, object_id: object_id}) do
get_object(object_type, object_id)
end
defp get_object(_, nil), do: nil
defp get_object(:event, event_id) do
case Events.get_event(event_id) do
{:ok, %Event{} = event} -> event
_ -> nil
end
end
defp get_object(:post, post_id) do
Posts.get_post(post_id)
end
defp get_object(:member, member_id) do
Actors.get_member(member_id)
end
defp get_object(:resource, resource_id) do
Resources.get_resource(resource_id)
end
defp get_object(:discussion, discussion_id) do
Discussions.get_discussion(discussion_id)
end
defp get_object(:group, group_id) do
Actors.get_actor(group_id)
end
@spec transform_params(map()) :: list()
defp transform_params(params) do
Enum.map(params, fn {key, value} -> %{key: key, value: transform_value(value)} end)
end
defp transform_value(value) when is_list(value) do
Enum.join(value, ",")
end
defp transform_value(value), do: value
end

View File

@ -29,6 +29,7 @@ defmodule Mobilizon.GraphQL.Schema do
import_types(Schema.Custom.UUID)
import_types(Schema.Custom.Point)
import_types(Schema.ActivityType)
import_types(Schema.UserType)
import_types(Schema.MediaType)
import_types(Schema.ActorInterface)

View File

@ -0,0 +1,78 @@
defmodule Mobilizon.GraphQL.Schema.ActivityType do
@moduledoc """
Schema representation for Activity
"""
use Absinthe.Schema.Notation
alias Mobilizon.Actors.{Actor, Member}
alias Mobilizon.Discussions.Discussion
alias Mobilizon.Events.Event
alias Mobilizon.Posts.Post
alias Mobilizon.Resources.Resource
enum :activity_type do
value(:event, description: "Activities concerning events")
value(:post, description: "Activities concerning posts")
value(:discussion, description: "Activities concerning discussions")
value(:resource, description: "Activities concerning resources")
value(:group, description: "Activities concerning group settings")
value(:member, description: "Activities concerning members")
end
object :activity_param_item do
field(:key, :string)
field(:value, :string)
end
interface :activity_object do
field(:id, :id)
resolve_type(fn
%Event{}, _ ->
:event
%Post{}, _ ->
:post
%Actor{type: "Group"}, _ ->
:group
%Member{}, _ ->
:member
%Resource{}, _ ->
:resource
%Discussion{}, _ ->
:discussion
%Actor{type: :Group}, _ ->
:group
_, _ ->
nil
end)
end
@desc """
A paginated list of activity items
"""
object :paginated_activity_list do
field(:elements, list_of(:activity), description: "A list of activities")
field(:total, :integer, description: "The total number of elements in the list")
end
object :activity do
field(:id, :id, description: "The activity item ID")
field(:inserted_at, :datetime, description: "When was the activity inserted")
field(:priority, :integer)
field(:type, :activity_type)
field(:subject, :string)
field(:subject_params, list_of(:activity_param_item))
field(:message, :string)
field(:message_params, list_of(:activity_param_item))
field(:object, :activity_object)
field(:author, :actor)
field(:group, :group)
end
end

View File

@ -10,6 +10,7 @@ defmodule Mobilizon.GraphQL.Schema.Actors.GroupType do
alias Mobilizon.Addresses
alias Mobilizon.GraphQL.Resolvers.{
Activity,
Discussion,
Followers,
Group,
@ -28,7 +29,7 @@ defmodule Mobilizon.GraphQL.Schema.Actors.GroupType do
Represents a group of actors
"""
object :group do
interfaces([:actor, :interactable])
interfaces([:actor, :interactable, :activity_object])
field(:id, :id, description: "Internal ID for this group")
field(:url, :string, description: "The ActivityPub actor's URL")
@ -142,6 +143,19 @@ defmodule Mobilizon.GraphQL.Schema.Actors.GroupType do
resolve(&Followers.find_followers_for_group/3)
description("A paginated list of the followers this group has")
end
field :activity, :paginated_activity_list do
arg(:page, :integer,
default_value: 1,
description: "The page in the paginated activity items list"
)
arg(:limit, :integer, default_value: 10, description: "The limit of activity items per page")
arg(:type, :activity_type, description: "Filter by type of activity")
resolve(&Activity.group_activity/3)
description("The group activity")
end
end
@desc """

View File

@ -10,6 +10,7 @@ defmodule Mobilizon.GraphQL.Schema.Actors.MemberType do
Represents a member of a group
"""
object :member do
interfaces([:activity_object])
field(:id, :id, description: "The member's ID")
field(:parent, :group, description: "Of which the profile is member")
field(:actor, :person, description: "Which profile is member of")

View File

@ -11,6 +11,7 @@ defmodule Mobilizon.GraphQL.Schema.Discussions.DiscussionType do
@desc "A discussion"
object :discussion do
interfaces([:activity_object])
field(:id, :id, description: "Internal ID for this discussion")
field(:title, :string, description: "The title for this discussion")
field(:slug, :string, description: "The slug for the discussion")

View File

@ -17,7 +17,7 @@ defmodule Mobilizon.GraphQL.Schema.EventType do
@desc "An event"
object :event do
interfaces([:action_log_object, :interactable])
interfaces([:action_log_object, :interactable, :activity_object])
field(:id, :id, description: "Internal ID for this event")
field(:uuid, :uuid, description: "The Event UUID")
field(:url, :string, description: "The ActivityPub Event URL")

View File

@ -7,6 +7,7 @@ defmodule Mobilizon.GraphQL.Schema.PostType do
@desc "A post"
object :post do
interfaces([:activity_object])
field(:id, :id, description: "The post's ID")
field(:title, :string, description: "The post's title")
field(:slug, :string, description: "The post's slug")

View File

@ -9,6 +9,7 @@ defmodule Mobilizon.GraphQL.Schema.ResourceType do
@desc "A resource"
object :resource do
interfaces([:activity_object])
field(:id, :id, description: "The resource's ID")
field(:title, :string, description: "The resource's title")
field(:summary, :string, description: "The resource's summary")

View File

@ -0,0 +1,148 @@
defmodule Mobilizon.Activities do
@moduledoc """
The Activities context.
"""
import Ecto.Query, warn: false
import EctoEnum
alias Mobilizon.Activities.Activity
alias Mobilizon.Actors.Member
alias Mobilizon.Storage.{Page, Repo}
defenum(Priority,
very_low: 10,
low: 20,
medium: 30,
high: 40,
very_high: 50
)
@activity_types ["event", "post", "discussion", "resource", "group", "member"]
@event_activity_subjects ["event_created", "event_updated", "event_deleted", "comment_posted"]
@post_activity_subjects ["post_created", "post_updated", "post_deleted"]
@discussion_activity_subjects [
"discussion_created",
"discussion_replied",
"discussion_renamed",
"discussion_archived",
"discussion_deleted"
]
@resource_activity_subjects [
"resource_created",
"resource_renamed",
"resource_moved",
"resource_deleted"
]
@member_activity_subjects [
"member_request",
"member_invited",
"member_accepted_invitation",
"member_rejected_invitation",
"member_added",
"member_joined",
"member_approved",
"member_updated",
"member_removed",
"member_quit"
]
@settings_activity_subjects ["group_created", "group_updated"]
@subjects @event_activity_subjects ++
@post_activity_subjects ++
@discussion_activity_subjects ++
@resource_activity_subjects ++
@member_activity_subjects ++ @settings_activity_subjects
@object_type ["event", "actor", "post", "discussion", "resource", "member", "group"]
defenum(Type, @activity_types)
defenum(Subject, @subjects)
defenum(ObjectType, @object_type)
@doc """
Returns the list of activities.
## Examples
iex> list_activities()
[%Activity{}, ...]
"""
def list_activities do
Repo.all(Activity)
end
@spec list_activities_for_group(
integer() | String.t(),
Keyword.t(),
integer() | nil,
integer() | nil
) :: Page.t()
def list_activities_for_group(
group_id,
actor_asking_id,
filters \\ [],
page \\ nil,
limit \\ nil
) do
Activity
|> where([a], a.group_id == ^group_id)
|> join(:inner, [a], m in Member,
on: m.parent_id == a.group_id and m.actor_id == ^actor_asking_id
)
|> where([a, m], a.inserted_at >= m.member_since)
|> filter_object_type(Keyword.get(filters, :type))
|> order_by(desc: :inserted_at)
|> preload([:author, :group])
|> Page.build_page(page, limit)
end
@doc """
Gets a single activity.
Raises `Ecto.NoResultsError` if the Activity does not exist.
## Examples
iex> get_activity!(123)
%Activity{}
iex> get_activity!(456)
** (Ecto.NoResultsError)
"""
def get_activity!(id), do: Repo.get!(Activity, id)
@doc """
Creates a activity.
## Examples
iex> create_activity(%{field: value})
{:ok, %Activity{}}
iex> create_activity(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_activity(attrs \\ %{}) do
%Activity{}
|> Activity.changeset(attrs)
|> Repo.insert()
end
def object_types, do: @object_type
def subjects, do: @subjects
def activity_types, do: @activity_types
@spec filter_object_type(Query.t(), atom()) :: Query.t()
defp filter_object_type(query, :type) do
where(query, [q], q.type == ^:type)
end
defp filter_object_type(query, _) do
query
end
end

View File

@ -0,0 +1,77 @@
defmodule Mobilizon.Activities.Activity do
@moduledoc """
Any activity for users
"""
use Ecto.Schema
import Ecto.Changeset
alias Mobilizon.Activities.{ObjectType, Priority, Subject, Type}
alias Mobilizon.Actors.Actor
@required_attrs [:type, :subject, :author_id, :group_id, :inserted_at]
@optional_attrs [
:priority,
:subject_params,
:message,
:message_params,
:object_type,
:object_id
]
@attrs @required_attrs ++ @optional_attrs
@type t :: %__MODULE__{
priority: Priority.t(),
type: Type.t(),
subject: Subject.t(),
subject_params: map(),
message: String.t(),
message_params: map(),
object_type: ObjectType.t(),
object_id: String.t(),
author: Actor.t(),
group: Actor.t()
}
schema "activities" do
field(:priority, Priority, default: :medium)
field(:type, Type)
field(:subject, Subject)
field(:subject_params, :map, default: %{})
field(:message, :string)
field(:message_params, :map, default: %{})
field(:object_type, ObjectType)
field(:object_id, :string)
field(:inserted_at, :utc_datetime)
belongs_to(:author, Actor)
belongs_to(:group, Actor)
end
@doc false
def changeset(activity, attrs) do
activity
|> cast(attrs, @attrs)
|> validate_required(@required_attrs)
|> stringify_params(:subject_params)
|> stringify_params(:message_params)
end
defp stringify_params(changeset, attr) do
stringified_params =
changeset
|> get_change(attr, %{})
|> Enum.map(fn {key, value} -> {key, stringify_struct(value)} end)
|> Map.new()
put_change(changeset, attr, stringified_params)
end
defp stringify_struct(%_{} = struct) do
association_fields = struct.__struct__.__schema__(:associations)
struct
|> Map.from_struct()
|> Map.drop(association_fields ++ [:__meta__])
end
defp stringify_struct(smth), do: smth
end

View File

@ -66,6 +66,7 @@ defmodule Mobilizon.Actors do
Gets a single actor.
"""
@spec get_actor(integer | String.t()) :: Actor.t() | nil
def get_actor(nil), do: nil
def get_actor(id), do: Repo.get(Actor, id)
@doc """
@ -860,7 +861,7 @@ defmodule Mobilizon.Actors do
end
@doc """
Returns the list of members for a group.
Returns a paginated list of members for a group.
"""
@spec list_members_for_group(Actor.t(), list(atom()), integer | nil, integer | nil) :: Page.t()
def list_members_for_group(
@ -882,6 +883,13 @@ defmodule Mobilizon.Actors do
|> Repo.all()
end
@spec list_internal_actors_members_for_group(Actor.t(), list()) :: list(Actor.t())
def list_internal_actors_members_for_group(%Actor{id: group_id, type: :Group}, roles \\ []) do
group_id
|> group_internal_member_actor_query(roles)
|> Repo.all()
end
@doc """
Returns a paginated list of administrator members for a group.
"""
@ -1512,6 +1520,16 @@ defmodule Mobilizon.Actors do
|> select([m, _a], m)
end
@spec group_internal_member_actor_query(integer(), list()) :: Ecto.Query.t()
defp group_internal_member_actor_query(group_id, role) do
Member
|> where([m], m.parent_id == ^group_id)
|> filter_member_role(role)
|> join(:inner, [m], a in Actor, on: m.actor_id == a.id)
|> where([_m, a], is_nil(a.domain))
|> select([_m, a], a)
end
@spec group_internal_member_query(integer()) :: Ecto.Query.t()
defp group_internal_member_query(group_id) do
Member
@ -1523,13 +1541,13 @@ defmodule Mobilizon.Actors do
end
@spec filter_member_role(Ecto.Query.t(), list(atom()) | atom()) :: Ecto.Query.t()
def filter_member_role(query, []), do: query
defp filter_member_role(query, []), do: query
def filter_member_role(query, roles) when is_list(roles) do
defp filter_member_role(query, roles) when is_list(roles) do
where(query, [m], m.role in ^roles)
end
def filter_member_role(query, role) when is_atom(role) do
defp filter_member_role(query, role) when is_atom(role) do
from(m in query, where: m.role == ^role)
end

View File

@ -25,6 +25,7 @@ defmodule Mobilizon.Actors.Member do
schema "members" do
field(:role, MemberRole, default: :member)
field(:url, :string)
field(:member_since, :utc_datetime)
embeds_one :metadata, Metadata, on_replace: :delete do
# TODO : Use this space to put notes when someone is invited / requested to join
@ -64,6 +65,7 @@ defmodule Mobilizon.Actors.Member do
|> cast(attrs, @attrs)
|> cast_embed(:metadata, with: &metadata_changeset/2)
|> ensure_url()
|> update_member_since()
|> validate_required(@required_attrs)
# On both parent_id and actor_id
|> unique_constraint(:parent_id, name: :members_actor_parent_unique_index)
@ -98,4 +100,29 @@ defmodule Mobilizon.Actors.Member do
|> put_change(:id, uuid)
|> put_change(:url, "#{Endpoint.url()}/member/#{uuid}")
end
@spec update_member_since(Ecto.Changeset.t()) :: Ecto.Changeset.t()
defp update_member_since(%Ecto.Changeset{data: data} = changeset) do
new_role = get_change(changeset, :role)
cond do
new_role in [
:member,
:moderator,
:administrator,
:creator
] ->
put_change(
changeset,
:member_since,
DateTime.truncate(data.member_since || DateTime.utc_now(), :second)
)
new_role in [:invited, :not_approved, :rejected] ->
put_change(changeset, :member_since, nil)
true ->
changeset
end
end
end

View File

@ -115,7 +115,10 @@ defmodule Mobilizon.Resources do
Multi.new()
|> do_find_parent_path(Map.get(attrs, :parent_id))
|> Multi.insert(:insert, fn %{find_parent_path: path} ->
Resource.changeset(%Resource{}, Map.put(attrs, :path, "#{path}/#{attrs.title}"))
Resource.changeset(
%Resource{},
Map.put(attrs, :path, "#{path}/#{String.replace(attrs.title, "/", "")}")
)
end)
|> Repo.transaction()
|> case do
@ -142,7 +145,11 @@ defmodule Mobilizon.Resources do
|> update_children(resource, attrs)
|> Multi.update(:update, fn %{find_parent_path: path} ->
title = Map.get(attrs, :title, old_title)
Resource.changeset(resource, Map.put(attrs, :path, "#{path}/#{title}"))
Resource.changeset(
resource,
Map.put(attrs, :path, "#{path}/#{String.replace(title, "/", "")}")
)
end)
|> Repo.transaction()
|> case do

View File

@ -0,0 +1,7 @@
defmodule Mobilizon.Service.Activity do
@moduledoc """
Behavior for Activity creators
"""
@callback insert_activity(entity :: struct(), options :: map()) :: {:ok, Oban.Job.t()}
end

View File

@ -0,0 +1,51 @@
defmodule Mobilizon.Service.Activity.Discussion do
@moduledoc """
Insert a discussion activity
"""
alias Mobilizon.Actors
alias Mobilizon.Discussions.Discussion
alias Mobilizon.Service.Activity
alias Mobilizon.Service.Workers.ActivityBuilder
@behaviour Activity
@impl Activity
def insert_activity(discussion, options \\ [])
def insert_activity(
%Discussion{creator_id: creator_id, actor_id: actor_id} = discussion,
options
)
when not is_nil(creator_id) do
creator = Actors.get_actor(creator_id)
group = Actors.get_actor(actor_id)
subject = Keyword.fetch!(options, :subject)
author = Keyword.get(options, :moderator, creator)
author_id = Keyword.get(options, :actor_id, author.id)
old_discussion = Keyword.get(options, :old_discussion)
ActivityBuilder.enqueue(:build_activity, %{
"type" => "discussion",
"subject" => subject,
"subject_params" => subject_params(discussion, subject, old_discussion),
"group_id" => group.id,
"author_id" => author_id,
"object_type" => "discussion",
"object_id" => if(subject != "discussion_deleted", do: to_string(discussion.id), else: nil),
"inserted_at" => DateTime.utc_now()
})
end
def insert_activity(_, _), do: {:ok, nil}
@spec subject_params(Discussion.t(), String.t() | nil, Discussion.t() | nil) :: map()
defp subject_params(%Discussion{} = discussion, "discussion_renamed", old_discussion) do
discussion
|> subject_params(nil, nil)
|> Map.put(:old_discussion_title, old_discussion.title)
end
defp subject_params(%Discussion{} = discussion, _, _) do
%{discussion_slug: discussion.slug, discussion_title: discussion.title}
end
end

View File

@ -0,0 +1,39 @@
defmodule Mobilizon.Service.Activity.Event do
@moduledoc """
Insert an event activity
"""
alias Mobilizon.Actors
alias Mobilizon.Events.Event
alias Mobilizon.Service.Activity
alias Mobilizon.Service.Workers.ActivityBuilder
@behaviour Activity
@impl Activity
def insert_activity(event, options \\ [])
def insert_activity(
%Event{attributed_to_id: attributed_to_id, organizer_actor_id: organizer_actor_id} =
event,
options
)
when not is_nil(attributed_to_id) do
actor = Actors.get_actor(organizer_actor_id)
group = Actors.get_actor(attributed_to_id)
subject = Keyword.fetch!(options, :subject)
ActivityBuilder.enqueue(:build_activity, %{
"type" => "event",
"subject" => subject,
"subject_params" => %{event_uuid: event.uuid, event_title: event.title},
"group_id" => group.id,
"author_id" => actor.id,
"object_type" => "event",
"object_id" => if(subject != "event_deleted", do: to_string(event.id), else: nil),
"inserted_at" => DateTime.utc_now()
})
end
@impl Activity
def insert_activity(_, _), do: {:ok, nil}
end

View File

@ -0,0 +1,150 @@
defmodule Mobilizon.Service.Activity.Group do
@moduledoc """
Insert a group setting activity
"""
alias Mobilizon.Actors
alias Mobilizon.Actors.Actor
alias Mobilizon.Service.Activity
alias Mobilizon.Service.Workers.ActivityBuilder
@behaviour Activity
@impl Activity
def insert_activity(group, options \\ [])
def insert_activity(
%Actor{type: :Group, id: group_id},
options
) do
with %Actor{type: :Group} = group <- Actors.get_actor(group_id),
subject when not is_nil(subject) <- Keyword.get(options, :subject),
actor_id <- Keyword.get(options, :actor_id),
default_updater_actor <- Actors.get_actor(actor_id),
%Actor{id: actor_id} <-
Keyword.get(options, :updater_actor, default_updater_actor),
old_group <- Keyword.get(options, :old_group) do
ActivityBuilder.enqueue(:build_activity, %{
"type" => "group",
"subject" => subject,
"subject_params" => subject_params(group, subject, old_group),
"group_id" => group.id,
"author_id" => actor_id,
"object_type" => "group",
"object_id" => to_string(group.id),
"inserted_at" => DateTime.utc_now()
})
else
_ -> {:ok, nil}
end
end
def insert_activity(_, _), do: {:ok, nil}
@spec subject_params(Actor.t(), String.t() | nil, Actor.t() | nil) :: map()
defp subject_params(%Actor{} = group, "group_updated", %Actor{} = old_group) do
group
|> subject_params(nil, nil)
|> maybe_put_old_name_if_updated(old_group.name, group.name)
|> maybe_put_summary_change_if_updated(old_group.summary, group.summary)
|> maybe_put_old_visibility_if_updated(old_group.visibility, group.visibility)
|> maybe_put_old_openness_if_updated(old_group.openness, group.openness)
|> maybe_put_address_change_if_updated(
old_group.physical_address_id,
group.physical_address_id
)
|> maybe_put_avatar_change_if_updated(
old_group.avatar,
group.avatar
)
|> maybe_put_banner_change_if_updated(
old_group.banner,
group.banner
)
|> maybe_put_manually_approves_followers_change_if_updated(
old_group.manually_approves_followers,
group.manually_approves_followers
)
end
defp subject_params(
%Actor{preferred_username: preferred_username, domain: domain, name: name},
_,
_
) do
%{
group_preferred_username: preferred_username,
group_name: name,
group_domain: domain,
group_changes: []
}
end
@spec maybe_put_old_name_if_updated(map(), String.t(), String.t()) :: map()
defp maybe_put_old_name_if_updated(params, old_group_name, new_group_name)
when old_group_name != new_group_name do
params
|> Map.update(:group_changes, [], fn changes -> changes ++ [:name] end)
|> Map.put(:old_group_name, old_group_name)
end
defp maybe_put_old_name_if_updated(params, _, _), do: params
defp maybe_put_summary_change_if_updated(params, old_summary, new_summary)
when old_summary != new_summary do
Map.update(params, :group_changes, [], fn changes -> changes ++ [:summary] end)
end
defp maybe_put_summary_change_if_updated(params, _, _), do: params
defp maybe_put_old_visibility_if_updated(params, old_group_visibility, new_group_visibility)
when old_group_visibility != new_group_visibility do
params
|> Map.update(:group_changes, [], fn changes -> changes ++ [:visibility] end)
|> Map.put(:old_group_visibility, old_group_visibility)
end
defp maybe_put_old_visibility_if_updated(params, _, _), do: params
defp maybe_put_old_openness_if_updated(params, old_group_openness, new_group_openness)
when old_group_openness != new_group_openness do
params
|> Map.update(:group_changes, [], fn changes -> changes ++ [:openness] end)
|> Map.put(:old_group_openness, old_group_openness)
end
defp maybe_put_old_openness_if_updated(params, _, _), do: params
defp maybe_put_address_change_if_updated(params, old_address_id, new_address_id)
when old_address_id != new_address_id do
Map.update(params, :group_changes, [], fn changes -> changes ++ [:address] end)
end
defp maybe_put_address_change_if_updated(params, _, _), do: params
defp maybe_put_avatar_change_if_updated(params, old_avatar, new_avatar)
when old_avatar != new_avatar do
Map.update(params, :group_changes, [], fn changes -> changes ++ [:avatar] end)
end
defp maybe_put_avatar_change_if_updated(params, _, _), do: params
defp maybe_put_banner_change_if_updated(params, old_banner, new_banner)
when old_banner != new_banner do
Map.update(params, :group_changes, [], fn changes -> changes ++ [:banner] end)
end
defp maybe_put_banner_change_if_updated(params, _, _), do: params
defp maybe_put_manually_approves_followers_change_if_updated(
params,
old_group_manually_approves_followers,
new_group_manually_approves_followers
)
when old_group_manually_approves_followers != new_group_manually_approves_followers do
params
|> Map.update(:group_changes, [], fn changes -> changes ++ [:manually_approves_followers] end)
|> Map.put(:old_group_manually_approves_followers, old_group_manually_approves_followers)
end
defp maybe_put_manually_approves_followers_change_if_updated(params, _, _), do: params
end

View File

@ -0,0 +1,97 @@
defmodule Mobilizon.Service.Activity.Member do
@moduledoc """
Insert a member activity
"""
alias Mobilizon.Actors
alias Mobilizon.Actors.{Actor, Member}
alias Mobilizon.Service.Activity
alias Mobilizon.Service.Workers.ActivityBuilder
@behaviour Activity
@impl Activity
def insert_activity(member, options \\ [])
def insert_activity(
%Member{parent_id: parent_id, id: member_id} = new_member,
options
) do
subject = Keyword.get(options, :subject)
with author_id <- get_author(new_member, options),
object_id <- if(subject == "member_removed", do: nil, else: to_string(member_id)) do
ActivityBuilder.enqueue(:build_activity, %{
"type" => "member",
"subject" => subject,
"subject_params" => get_subject_params(new_member, options),
"group_id" => parent_id,
"author_id" => author_id,
"object_type" => "member",
"object_id" => object_id,
"inserted_at" => DateTime.utc_now()
})
end
end
def insert_activity(_, _), do: {:ok, nil}
@spec get_author(Member.t(), Member.t() | nil) :: String.t() | integer()
defp get_author(%Member{actor_id: actor_id}, options) do
moderator = Keyword.get(options, :moderator)
if is_nil(moderator) do
actor_id
else
moderator.id
end
end
@spec get_subject_params(Member.t(), Keyword.t()) :: map()
defp get_subject_params(%Member{actor: actor, role: role, id: member_id}, options) do
# We may need to preload the member to make sure the actor exists
actor =
case actor do
%Actor{} = actor ->
actor
_ ->
case Actors.get_member(member_id) do
%Member{actor: actor} -> actor
_ -> nil
end
end
moderator = Keyword.get(options, :moderator)
old_member = Keyword.get(options, :old_member)
subject_params = %{
member_role: String.upcase(to_string(role))
}
subject_params =
if(is_nil(actor),
do: subject_params,
else:
Map.put(
subject_params,
:member_preferred_username,
Actor.preferred_username_and_domain(actor)
)
)
subject_params =
if(is_nil(old_member),
do: subject_params,
else: Map.put(subject_params, :old_role, String.upcase(to_string(old_member.role)))
)
if is_nil(moderator),
do: subject_params,
else:
Map.put(
subject_params,
:moderator_preferred_username,
Actor.preferred_username_and_domain(moderator)
)
end
end

View File

@ -0,0 +1,37 @@
defmodule Mobilizon.Service.Activity.Post do
@moduledoc """
Insert an post activity
"""
alias Mobilizon.Actors
alias Mobilizon.Posts.Post
alias Mobilizon.Service.Activity
alias Mobilizon.Service.Workers.ActivityBuilder
@behaviour Activity
@impl Activity
def insert_activity(post, options \\ [])
def insert_activity(
%Post{attributed_to_id: attributed_to_id, author_id: author_id} = post,
options
)
when not is_nil(attributed_to_id) do
author = Actors.get_actor(author_id)
group = Actors.get_actor(attributed_to_id)
subject = Keyword.fetch!(options, :subject)
ActivityBuilder.enqueue(:build_activity, %{
"type" => "post",
"subject" => subject,
"subject_params" => %{post_slug: post.slug, post_title: post.title},
"group_id" => group.id,
"author_id" => author.id,
"object_type" => "post",
"object_id" => if(subject != "post_deleted", do: to_string(post.id), else: nil),
"inserted_at" => DateTime.utc_now()
})
end
def insert_activity(_, _), do: {:ok, nil}
end

View File

@ -0,0 +1,50 @@
defmodule Mobilizon.Service.Activity.Resource do
@moduledoc """
Insert an resource activity
"""
alias Mobilizon.Actors
alias Mobilizon.Resources.Resource
alias Mobilizon.Service.Activity
alias Mobilizon.Service.Workers.ActivityBuilder
@behaviour Activity
@impl Activity
def insert_activity(resource, options \\ [])
def insert_activity(
%Resource{actor_id: actor_id, creator_id: creator_id} = resource,
options
)
when not is_nil(actor_id) do
actor = Actors.get_actor(creator_id)
group = Actors.get_actor(actor_id)
subject = Keyword.fetch!(options, :subject)
old_resource = Keyword.get(options, :old_resource)
ActivityBuilder.enqueue(:build_activity, %{
"type" => "resource",
"subject" => subject,
"subject_params" => subject_params(resource, subject, old_resource),
"group_id" => group.id,
"author_id" => actor.id,
"object_type" => "resource",
"object_id" => if(subject != "resource_deleted", do: to_string(resource.id), else: nil),
"inserted_at" => DateTime.utc_now()
})
end
@impl Activity
def insert_activity(_, _), do: {:ok, nil}
@spec subject_params(Resource.t(), String.t() | nil, Resource.t() | nil) :: map()
defp subject_params(%Resource{} = resource, "resource_renamed", old_resource) do
resource
|> subject_params(nil, nil)
|> Map.put(:old_resource_title, old_resource.title)
end
defp subject_params(%Resource{path: path, title: title}, _, _) do
%{resource_path: path, resource_title: title}
end
end

View File

@ -0,0 +1,22 @@
defmodule Mobilizon.Service.Workers.ActivityBuilder do
@moduledoc """
Worker to insert activity items in users feeds
"""
alias Mobilizon.Activities
alias Mobilizon.Activities.Activity
use Mobilizon.Service.Workers.Helper, queue: "activity"
@impl Oban.Worker
def perform(%Job{args: args}) do
with {"build_activity", args} <- Map.pop(args, "op") do
build_activity(args)
end
end
@spec build_activity(map()) :: {:ok, Activity.t()}
def build_activity(args) do
Activities.create_activity(args)
end
end

View File

@ -10,7 +10,10 @@ defmodule Mobilizon.Web.Endpoint do
use Absinthe.Phoenix.Endpoint
plug(Mobilizon.Web.Plugs.SetLocalePlug)
if Application.fetch_env!(:mobilizon, :env) !== :dev do
plug(Mobilizon.Web.Plugs.HTTPSecurityPlug)
end
# For e2e tests
if Application.get_env(:mobilizon, :sql_sandbox) do

View File

@ -104,7 +104,7 @@ defmodule Mobilizon.Mixfile do
{:bamboo_smtp, "~> 3.0"},
{:geolix, "~> 2.0"},
{:geolix_adapter_mmdb2, "~> 0.6.0"},
{:absinthe, "~> 1.6"},
{:absinthe, "~> 1.5.0"},
{:absinthe_phoenix, "~> 2.0.1"},
{:absinthe_plug, "~> 1.5.0"},
{:dataloader, "~> 1.0.6"},

View File

@ -1,5 +1,5 @@
%{
"absinthe": {:hex, :absinthe, "1.6.3", "f8c7a581fa2382bde1adadd405f5caf6597623b48d160367f759d0d6e6292f84", [:mix], [{:dataloader, "~> 1.0.0", [hex: :dataloader, repo: "hexpm", optional: true]}, {:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}, {:nimble_parsec, "~> 0.5 or ~> 1.0", [hex: :nimble_parsec, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "4a11192165fb3b7566ffdd86eccd12f0a87158b0b18c00e0400899e8df0225ea"},
"absinthe": {:hex, :absinthe, "1.5.5", "22b26228f56dc6a1074c52cea9c64e869a0cb2427403bcf9056c422d36c66292", [:mix], [{:dataloader, "~> 1.0.0", [hex: :dataloader, repo: "hexpm", optional: true]}, {:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}, {:nimble_parsec, "~> 0.5 or ~> 1.0", [hex: :nimble_parsec, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "41e79ed4bffbab4986493ff4120c948d59871fd08ad5e31195129ce3c01aad58"},
"absinthe_phoenix": {:hex, :absinthe_phoenix, "2.0.1", "112cb3468db2748a85bd8bd3f4d6d33f37408a96cb170077026ace96ddb1bab2", [:mix], [{:absinthe, "~> 1.5", [hex: :absinthe, repo: "hexpm", optional: false]}, {:absinthe_plug, "~> 1.5", [hex: :absinthe_plug, repo: "hexpm", optional: false]}, {:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.5", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.13", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.0", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}], "hexpm", "e773adc876fbc84fb05a82e125d9c263f129520b36e5576554ffcb8cf49db445"},
"absinthe_plug": {:hex, :absinthe_plug, "1.5.5", "be913e77df1947ffb654a1cf1a90e28d84dc23241f6404053750bae513ccd52b", [:mix], [{:absinthe, "~> 1.5", [hex: :absinthe, repo: "hexpm", optional: false]}, {:plug, "~> 1.4", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "6c366615d9422444774206aff3448bb9cfb4e849e0c9a94a275085097bc67509"},
"argon2_elixir": {:hex, :argon2_elixir, "2.4.0", "2a22ea06e979f524c53b42b598fc6ba38cdcbc977a155e33e057732cfb1fb311", [:make, :mix], [{:comeonin, "~> 5.3", [hex: :comeonin, repo: "hexpm", optional: false]}, {:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "4ea82e183cf8e7f66dab1f767fedcfe6a195e140357ef2b0423146b72e0a551d"},

View File

@ -0,0 +1,20 @@
defmodule Mobilizon.Storage.Repo.Migrations.AddActivityTable do
use Ecto.Migration
def change do
create table(:activities) do
add(:priority, :integer, null: false)
add(:type, :string, null: false)
add(:author_id, references(:actors, on_delete: :delete_all), null: false)
add(:group_id, references(:actors, on_delete: :delete_all), null: false)
add(:subject, :string, null: false)
add(:subject_params, :map, null: false)
add(:message, :string)
add(:message_params, :map)
add(:object_type, :string)
add(:object_id, :string)
timestamps(updated_at: false, type: :utc_datetime)
end
end
end

View File

@ -0,0 +1,34 @@
defmodule Mobilizon.Storage.Repo.Migrations.AddMemberSinceToMembers do
use Ecto.Migration
def up do
alter table(:members) do
add(:member_since, :utc_datetime)
end
flush()
%Postgrex.Result{rows: rows} =
Ecto.Adapters.SQL.query!(
Mobilizon.Storage.Repo,
"SELECT id, role FROM members"
)
Enum.each(rows, fn [id, role] ->
if role in ["member", "moderator", "administrator", "creator"] do
Ecto.Adapters.SQL.query!(
Mobilizon.Storage.Repo,
"UPDATE members SET member_since = '#{DateTime.to_iso8601(DateTime.utc_now())}' WHERE id = '#{
Ecto.UUID.cast!(id)
}'"
)
end
end)
end
def down do
alter table(:members) do
remove(:member_since)
end
end
end

View File

@ -0,0 +1,260 @@
defmodule Mobilizon.GraphQL.Resolvers.ActivityTest do
use Mobilizon.Web.ConnCase
import Mobilizon.Factory
alias Mobilizon.{Activities, Posts}
alias Mobilizon.Activities.Activity
alias Mobilizon.Actors.Actor
alias Mobilizon.Service.Activity.Event, as: EventActivity
alias Mobilizon.Service.Activity.Post, as: PostActivity
alias Mobilizon.GraphQL.AbsintheHelpers
setup %{conn: conn} do
group = insert(:group)
{:ok, conn: conn, group: group}
end
describe "Resolver: List activities for group" do
@group_activities_query """
query GroupTimeline(
$preferredUsername: String!
$type: ActivityType
$page: Int
$limit: Int
) {
group(preferredUsername: $preferredUsername) {
id
preferredUsername
domain
name
activity(type: $type, page: $page, limit: $limit) {
total
elements {
id
insertedAt
subject
subjectParams {
key
value
}
type
author {
id
preferredUsername
name
domain
avatar {
id
url
}
}
group {
id
preferredUsername
}
object {
... on Event {
id
title
}
... on Post {
id
title
}
... on Member {
id
actor {
id
name
preferredUsername
domain
avatar {
id
url
}
}
}
... on Resource {
id
title
path
type
}
... on Discussion {
id
title
slug
}
... on Group {
id
preferredUsername
domain
name
summary
visibility
openness
physicalAddress {
id
}
banner {
id
}
avatar {
id
}
}
}
}
}
}
}
"""
test "without being logged-in", %{
conn: conn,
group: %Actor{preferred_username: preferred_username}
} do
res =
conn
|> AbsintheHelpers.graphql_query(
query: @group_activities_query,
variables: %{preferredUsername: preferred_username}
)
assert hd(res["errors"])["message"] == "unauthenticated"
end
test "without being a member", %{
conn: conn,
group: %Actor{preferred_username: preferred_username}
} do
user = insert(:user)
insert(:actor, user: user)
res =
conn
|> auth_conn(user)
|> AbsintheHelpers.graphql_query(
query: @group_activities_query,
variables: %{preferredUsername: preferred_username}
)
assert hd(res["errors"])["message"] == "unauthorized"
end
test "without being a validated member", %{
conn: conn,
group: %Actor{preferred_username: preferred_username} = group
} do
user = insert(:user)
actor = insert(:actor, user: user)
insert(:member, parent: group, actor: actor, role: :not_approved)
res =
conn
|> auth_conn(user)
|> AbsintheHelpers.graphql_query(
query: @group_activities_query,
variables: %{preferredUsername: preferred_username}
)
assert hd(res["errors"])["message"] == "unauthorized"
end
test "group_activity/3 list group activities", %{
conn: conn,
group: %Actor{preferred_username: preferred_username, id: group_id} = group
} do
user = insert(:user)
actor = insert(:actor, user: user)
insert(:member,
parent: group,
actor: actor,
role: :member,
member_since: DateTime.truncate(DateTime.utc_now(), :second)
)
event = insert(:event, attributed_to: group, organizer_actor: actor)
EventActivity.insert_activity(event, subject: "event_created")
assert %{success: 1, failure: 0} == Oban.drain_queue(queue: :activity)
assert Activities.list_activities() |> length() == 1
[%Activity{author_id: author_id, group_id: activity_group_id}] =
Activities.list_activities()
assert author_id == actor.id
assert activity_group_id == group_id
res =
conn
|> auth_conn(user)
|> AbsintheHelpers.graphql_query(
query: @group_activities_query,
variables: %{preferredUsername: preferred_username}
)
assert res["errors"] == nil
assert res["data"]["group"]["id"] == to_string(group_id)
assert res["data"]["group"]["activity"]["total"] == 1
activity = hd(res["data"]["group"]["activity"]["elements"])
assert activity["object"]["id"] == to_string(event.id)
assert activity["subject"] == "event_created"
assert Enum.find(activity["subjectParams"], &(&1["key"] == "event_title"))["value"] ==
event.title
assert Enum.find(activity["subjectParams"], &(&1["key"] == "event_uuid"))["value"] ==
event.uuid
end
test "group_activity/3 list group activities from deleted object", %{
conn: conn,
group: %Actor{preferred_username: preferred_username, id: group_id} = group
} do
user = insert(:user)
actor = insert(:actor, user: user)
insert(:member,
parent: group,
actor: actor,
role: :member,
member_since: DateTime.truncate(DateTime.utc_now(), :second)
)
post = insert(:post, attributed_to: group, author: actor)
PostActivity.insert_activity(post, subject: "post_created")
Process.sleep(1000)
Posts.delete_post(post)
PostActivity.insert_activity(post, subject: "post_deleted")
assert %{success: 2, failure: 0} == Oban.drain_queue(queue: :activity)
assert Activities.list_activities() |> length() == 2
res =
conn
|> auth_conn(user)
|> AbsintheHelpers.graphql_query(
query: @group_activities_query,
variables: %{preferredUsername: preferred_username}
)
assert res["errors"] == nil
assert res["data"]["group"]["id"] == to_string(group_id)
assert res["data"]["group"]["activity"]["total"] == 2
[delete_activity, create_activity] = res["data"]["group"]["activity"]["elements"]
assert create_activity["object"] == nil
assert create_activity["subject"] == "post_created"
assert Enum.find(create_activity["subjectParams"], &(&1["key"] == "post_title"))["value"] ==
post.title
assert Enum.find(create_activity["subjectParams"], &(&1["key"] == "post_slug"))["value"] ==
post.slug
assert delete_activity["object"] == nil
assert delete_activity["subject"] == "post_deleted"
end
end
end

View File

@ -0,0 +1,91 @@
defmodule Mobilizon.ActivitiesTest do
use Mobilizon.DataCase
alias Mobilizon.Activities
import Mobilizon.Factory
describe "activities" do
alias Mobilizon.Activities.Activity
@valid_attrs %{
message: "some message",
message_params: %{},
type: "event",
object_id: "some object_id",
subject: "event_created",
subject_params: %{}
}
@invalid_attrs %{
message: nil,
object_id: nil,
subject: nil
}
setup do
actor = insert(:actor)
group = insert(:group)
{:ok, actor: actor, group: group}
end
def activity_fixture(attrs \\ %{}) do
{:ok, activity} =
attrs
|> Enum.into(@valid_attrs)
|> Activities.create_activity()
activity
end
test "list_activities/0 returns all activities", %{actor: actor, group: group} do
activity =
activity_fixture(%{
group_id: group.id,
author_id: actor.id,
inserted_at: DateTime.utc_now()
})
assert Activities.list_activities() == [activity]
end
test "get_activity!/1 returns the activity with given id", %{actor: actor, group: group} do
activity =
activity_fixture(%{
author_id: actor.id,
group_id: group.id,
inserted_at: DateTime.utc_now()
})
assert Activities.get_activity!(activity.id) == activity
end
test "create_activity/1 with valid data creates a activity", %{actor: actor, group: group} do
assert {:ok, %Activity{} = activity} =
Activities.create_activity(
@valid_attrs
|> Map.put(:group_id, group.id)
|> Map.put(:author_id, actor.id)
|> Map.put(:inserted_at, DateTime.utc_now())
)
assert activity.message == "some message"
assert activity.message_params == %{}
assert activity.object_id == "some object_id"
assert activity.subject == :event_created
assert activity.subject_params == %{}
end
test "create_activity/1 with invalid data returns error changeset", %{
actor: actor,
group: group
} do
assert {:error, %Ecto.Changeset{}} =
Activities.create_activity(
@invalid_attrs
|> Map.put(:author_id, actor.id)
|> Map.put(:group_id, group.id)
|> Map.put(:inserted_at, DateTime.utc_now())
)
end
end
end

View File

@ -409,4 +409,20 @@ defmodule Mobilizon.Factory do
url: Routes.page_url(Endpoint, :discussion, group.preferred_username, slug)
}
end
def mobilizon_activity_factory do
group = build(:group)
actor = build(:actor)
event = build(:event, organizer_actor: actor, attributed_to: group)
%Mobilizon.Activities.Activity{
type: :event,
subject: :event_created,
subject_params: %{event: event},
author: actor,
group: group,
object_type: :event,
object_id: to_string(event.id)
}
end
end