From 3fe64a438907f207966e3f9b6a169bb1f17c7361 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Wed, 24 Feb 2021 19:06:48 +0100 Subject: [PATCH] Introduce the group activity section Signed-off-by: Thomas Citharel --- config/config.exs | 2 +- .../Activity/DiscussionActivityItem.vue | 119 +++++++ .../components/Activity/EventActivityItem.vue | 93 +++++ .../components/Activity/GroupActivityItem.vue | 183 ++++++++++ .../Activity/MemberActivityItem.vue | 233 +++++++++++++ .../components/Activity/PostActivityItem.vue | 93 +++++ .../Activity/ResourceActivityItem.vue | 189 +++++++++++ .../Activity/SkeletonActivityItem.vue | 30 ++ js/src/components/Activity/activity.scss | 21 ++ js/src/components/Resource/ResourceItem.vue | 10 +- .../components/Resource/ResourceSelector.vue | 52 +-- js/src/components/Utils/Observer.vue | 28 ++ js/src/graphql/group.ts | 95 ++++++ js/src/i18n/en_US.json | 98 +++++- js/src/i18n/fr_FR.json | 97 +++++- js/src/mixins/activity.ts | 31 ++ js/src/router/groups.ts | 9 + js/src/types/activity.model.ts | 33 ++ js/src/types/actor/group.model.ts | 3 + js/src/types/enums.ts | 53 +++ js/src/variables.scss | 4 + js/src/views/Event/Edit.vue | 2 - js/src/views/Event/Event.vue | 2 - js/src/views/Event/MyEvents.vue | 2 - js/src/views/Group/Group.vue | 21 +- js/src/views/Group/MyGroups.vue | 2 - js/src/views/Group/Settings.vue | 3 + js/src/views/Group/Timeline.vue | 320 ++++++++++++++++++ js/src/views/Home.vue | 2 - js/src/views/Posts/List.vue | 2 - js/src/views/Search.vue | 2 - js/src/views/User/Login.vue | 2 - js/src/views/User/Register.vue | 2 - lib/federation/activity_pub/activity_pub.ex | 24 +- lib/federation/activity_pub/types/actors.ex | 14 + .../activity_pub/types/discussions.ex | 20 +- lib/federation/activity_pub/types/events.ex | 7 + lib/federation/activity_pub/types/members.ex | 13 +- lib/federation/activity_pub/types/posts.ex | 4 + .../activity_pub/types/resources.ex | 16 +- lib/graphql/resolvers/activity.ex | 85 +++++ lib/graphql/schema.ex | 1 + lib/graphql/schema/activity.ex | 78 +++++ lib/graphql/schema/actors/group.ex | 16 +- lib/graphql/schema/actors/member.ex | 1 + lib/graphql/schema/discussions/discussion.ex | 1 + lib/graphql/schema/event.ex | 2 +- lib/graphql/schema/post.ex | 1 + lib/graphql/schema/resource.ex | 1 + lib/mobilizon/activities/activities.ex | 148 ++++++++ lib/mobilizon/activities/activity.ex | 77 +++++ lib/mobilizon/actors/actors.ex | 26 +- lib/mobilizon/actors/member.ex | 27 ++ lib/mobilizon/resources/resources.ex | 11 +- lib/service/activity/activity.ex | 7 + lib/service/activity/discussion.ex | 51 +++ lib/service/activity/event.ex | 39 +++ lib/service/activity/group.ex | 150 ++++++++ lib/service/activity/member.ex | 97 ++++++ lib/service/activity/posts.ex | 37 ++ lib/service/activity/resource.ex | 50 +++ lib/service/workers/activity_builder.ex | 22 ++ lib/web/endpoint.ex | 5 +- mix.exs | 2 +- mix.lock | 2 +- .../20210215092515_add_activity_table.exs | 20 ++ ...0217164549_add_member_since_to_members.exs | 34 ++ test/graphql/resolvers/activity_test.exs | 260 ++++++++++++++ test/mobilizon/activities_test.exs | 91 +++++ test/support/factory.ex | 16 + 70 files changed, 3224 insertions(+), 70 deletions(-) create mode 100644 js/src/components/Activity/DiscussionActivityItem.vue create mode 100644 js/src/components/Activity/EventActivityItem.vue create mode 100644 js/src/components/Activity/GroupActivityItem.vue create mode 100644 js/src/components/Activity/MemberActivityItem.vue create mode 100644 js/src/components/Activity/PostActivityItem.vue create mode 100644 js/src/components/Activity/ResourceActivityItem.vue create mode 100644 js/src/components/Activity/SkeletonActivityItem.vue create mode 100644 js/src/components/Activity/activity.scss create mode 100644 js/src/components/Utils/Observer.vue create mode 100644 js/src/mixins/activity.ts create mode 100644 js/src/types/activity.model.ts create mode 100644 js/src/views/Group/Timeline.vue create mode 100644 lib/graphql/resolvers/activity.ex create mode 100644 lib/graphql/schema/activity.ex create mode 100644 lib/mobilizon/activities/activities.ex create mode 100644 lib/mobilizon/activities/activity.ex create mode 100644 lib/service/activity/activity.ex create mode 100644 lib/service/activity/discussion.ex create mode 100644 lib/service/activity/event.ex create mode 100644 lib/service/activity/group.ex create mode 100644 lib/service/activity/member.ex create mode 100644 lib/service/activity/posts.ex create mode 100644 lib/service/activity/resource.ex create mode 100644 lib/service/workers/activity_builder.ex create mode 100644 priv/repo/migrations/20210215092515_add_activity_table.exs create mode 100644 priv/repo/migrations/20210217164549_add_member_since_to_members.exs create mode 100644 test/graphql/resolvers/activity_test.exs create mode 100644 test/mobilizon/activities_test.exs diff --git a/config/config.exs b/config/config.exs index 7de920e5..0daf59ff 100644 --- a/config/config.exs +++ b/config/config.exs @@ -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: [ diff --git a/js/src/components/Activity/DiscussionActivityItem.vue b/js/src/components/Activity/DiscussionActivityItem.vue new file mode 100644 index 00000000..c05c145f --- /dev/null +++ b/js/src/components/Activity/DiscussionActivityItem.vue @@ -0,0 +1,119 @@ + + + diff --git a/js/src/components/Activity/EventActivityItem.vue b/js/src/components/Activity/EventActivityItem.vue new file mode 100644 index 00000000..f6a9eef6 --- /dev/null +++ b/js/src/components/Activity/EventActivityItem.vue @@ -0,0 +1,93 @@ + + + diff --git a/js/src/components/Activity/GroupActivityItem.vue b/js/src/components/Activity/GroupActivityItem.vue new file mode 100644 index 00000000..df90a869 --- /dev/null +++ b/js/src/components/Activity/GroupActivityItem.vue @@ -0,0 +1,183 @@ + + + diff --git a/js/src/components/Activity/MemberActivityItem.vue b/js/src/components/Activity/MemberActivityItem.vue new file mode 100644 index 00000000..1916a2ff --- /dev/null +++ b/js/src/components/Activity/MemberActivityItem.vue @@ -0,0 +1,233 @@ + + + diff --git a/js/src/components/Activity/PostActivityItem.vue b/js/src/components/Activity/PostActivityItem.vue new file mode 100644 index 00000000..a2a5a650 --- /dev/null +++ b/js/src/components/Activity/PostActivityItem.vue @@ -0,0 +1,93 @@ + + + diff --git a/js/src/components/Activity/ResourceActivityItem.vue b/js/src/components/Activity/ResourceActivityItem.vue new file mode 100644 index 00000000..d9de2c24 --- /dev/null +++ b/js/src/components/Activity/ResourceActivityItem.vue @@ -0,0 +1,189 @@ + + + diff --git a/js/src/components/Activity/SkeletonActivityItem.vue b/js/src/components/Activity/SkeletonActivityItem.vue new file mode 100644 index 00000000..c21f6fab --- /dev/null +++ b/js/src/components/Activity/SkeletonActivityItem.vue @@ -0,0 +1,30 @@ + + diff --git a/js/src/components/Activity/activity.scss b/js/src/components/Activity/activity.scss new file mode 100644 index 00000000..11bceeea --- /dev/null +++ b/js/src/components/Activity/activity.scss @@ -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; + } +} diff --git a/js/src/components/Resource/ResourceItem.vue b/js/src/components/Resource/ResourceItem.vue index 52b10939..f0d7c1a5 100644 --- a/js/src/components/Resource/ResourceItem.vue +++ b/js/src/components/Resource/ResourceItem.vue @@ -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; } } diff --git a/js/src/components/Resource/ResourceSelector.vue b/js/src/components/Resource/ResourceSelector.vue index 2b55571d..818a90f1 100644 --- a/js/src/components/Resource/ResourceSelector.vue +++ b/js/src/components/Resource/ResourceSelector.vue @@ -26,33 +26,35 @@ {{ $t("Parent folder") }} - - - - - - {{ element.title }} - - {{ $t("(this folder)") }} - {{ $t("(this link)") }} - - +

{{ $t("No resources in this folder") }}

diff --git a/js/src/components/Utils/Observer.vue b/js/src/components/Utils/Observer.vue new file mode 100644 index 00000000..49f24678 --- /dev/null +++ b/js/src/components/Utils/Observer.vue @@ -0,0 +1,28 @@ + + + diff --git a/js/src/graphql/group.ts b/js/src/graphql/group.ts index 84345a03..6b0baf8a 100644 --- a/js/src/graphql/group.ts +++ b/js/src/graphql/group.ts @@ -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 + } + } + } + } + } + } + } +`; diff --git a/js/src/i18n/en_US.json b/js/src/i18n/en_US.json index c03e07c4..46af5b3f 100644 --- a/js/src/i18n/en_US.json +++ b/js/src/i18n/en_US.json @@ -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." } diff --git a/js/src/i18n/fr_FR.json b/js/src/i18n/fr_FR.json index d0c26e18..f9cbfcfd 100644 --- a/js/src/i18n/fr_FR.json +++ b/js/src/i18n/fr_FR.json @@ -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." } diff --git a/js/src/mixins/activity.ts b/js/src/mixins/activity.ts new file mode 100644 index 00000000..fa8fa4f3 --- /dev/null +++ b/js/src/mixins/activity.ts @@ -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 { + return this.activity.subjectParams.reduce( + (acc: Record, { key, value }) => { + acc[key] = value; + return acc; + }, + {} + ); + } + + get isAuthorCurrentActor(): boolean { + return ( + this.activity.author.id === this.currentActor.id && + this.currentActor.id !== undefined + ); + } +} diff --git a/js/src/router/groups.ts b/js/src/router/groups.ts index 75d16ada..bb933d40 100644 --- a/js/src/router/groups.ts +++ b/js/src/router/groups.ts @@ -18,6 +18,7 @@ export enum GroupsRouteName { POSTS = "POSTS", GROUP_EVENTS = "GROUP_EVENTS", GROUP_JOIN = "GROUP_JOIN", + TIMELINE = "TIMELINE", } const resourceFolder = (): Promise => @@ -145,4 +146,12 @@ export const groupsRoutes: RouteConfig[] = [ name: GroupsRouteName.GROUP_JOIN, meta: { requiredAuth: false }, }, + { + path: "/@:preferredUsername/timeline", + name: GroupsRouteName.TIMELINE, + component: (): Promise => + import("@/views/Group/Timeline.vue"), + props: true, + meta: { requiredAuth: true }, + }, ]; diff --git a/js/src/types/activity.model.ts b/js/src/types/activity.model.ts new file mode 100644 index 00000000..f36cba7f --- /dev/null +++ b/js/src/types/activity.model.ts @@ -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; +} diff --git a/js/src/types/actor/group.model.ts b/js/src/types/actor/group.model.ts index c178f404..6489f252 100644 --- a/js/src/types/actor/group.model.ts +++ b/js/src/types/actor/group.model.ts @@ -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; @@ -20,6 +21,7 @@ export interface IGroup extends IActor { physicalAddress: IAddress; openness: Openness; manuallyApprovesFollowers: boolean; + activity: Paginate; } export class Group extends Actor implements IGroup { @@ -41,6 +43,7 @@ export class Group extends Actor implements IGroup { this.patch(hash); } + activity: Paginate = { elements: [], total: 0 }; openness: Openness = Openness.INVITE_ONLY; diff --git a/js/src/types/enums.ts b/js/src/types/enums.ts index 80f36a31..d7d6dbd0 100644 --- a/js/src/types/enums.ts +++ b/js/src/types/enums.ts @@ -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", +} diff --git a/js/src/variables.scss b/js/src/variables.scss index e68c0938..59f8c0d6 100644 --- a/js/src/variables.scss +++ b/js/src/variables.scss @@ -86,6 +86,10 @@ $colors: map-merge( $link, $link-invert, ), + "grey": ( + $grey, + findColorInvert($grey), + ), ) ); diff --git a/js/src/views/Event/Edit.vue b/js/src/views/Event/Edit.vue index e88e2f94..11eb9692 100644 --- a/js/src/views/Event/Edit.vue +++ b/js/src/views/Event/Edit.vue @@ -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", }; }, diff --git a/js/src/views/Event/Event.vue b/js/src/views/Event/Event.vue index 811c4f8f..a3a03c6a 100755 --- a/js/src/views/Event/Event.vue +++ b/js/src/views/Event/Event.vue @@ -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 diff --git a/js/src/views/Event/MyEvents.vue b/js/src/views/Event/MyEvents.vue index 2d48a6a5..eefba7a5 100644 --- a/js/src/views/Event/MyEvents.vue +++ b/js/src/views/Event/MyEvents.vue @@ -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", }; }, diff --git a/js/src/views/Group/Group.vue b/js/src/views/Group/Group.vue index a24942d1..1c1e0e6e 100644 --- a/js/src/views/Group/Group.vue +++ b/js/src/views/Group/Group.vue @@ -57,14 +57,27 @@
- {{ $t("Activity") }} + {{ $t("Group settings") }}{{ $t("Group settings") }}
@@ -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 diff --git a/js/src/views/Group/MyGroups.vue b/js/src/views/Group/MyGroups.vue index 9ee2cf5a..8fce67c8 100644 --- a/js/src/views/Group/MyGroups.vue +++ b/js/src/views/Group/MyGroups.vue @@ -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", }; }, diff --git a/js/src/views/Group/Settings.vue b/js/src/views/Group/Settings.vue index d14efea0..ddf664c2 100644 --- a/js/src/views/Group/Settings.vue +++ b/js/src/views/Group/Settings.vue @@ -49,4 +49,7 @@ export default class Settings extends mixins(GroupMixin) { aside.section { padding-top: 1rem; } +.container.section { + background: $white; +} diff --git a/js/src/views/Group/Timeline.vue b/js/src/views/Group/Timeline.vue new file mode 100644 index 00000000..50340c10 --- /dev/null +++ b/js/src/views/Group/Timeline.vue @@ -0,0 +1,320 @@ + + + diff --git a/js/src/views/Home.vue b/js/src/views/Home.vue index d5ba7ae8..952792bc 100644 --- a/js/src/views/Home.vue +++ b/js/src/views/Home.vue @@ -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", }; }, diff --git a/js/src/views/Posts/List.vue b/js/src/views/Posts/List.vue index e52c91a6..d186bcba 100644 --- a/js/src/views/Posts/List.vue +++ b/js/src/views/Posts/List.vue @@ -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", }; }, diff --git a/js/src/views/Search.vue b/js/src/views/Search.vue index 143fad90..6807b187 100644 --- a/js/src/views/Search.vue +++ b/js/src/views/Search.vue @@ -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", }; }, diff --git a/js/src/views/User/Login.vue b/js/src/views/User/Login.vue index 88c11e71..44f38cc5 100644 --- a/js/src/views/User/Login.vue +++ b/js/src/views/User/Login.vue @@ -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", }; }, diff --git a/js/src/views/User/Register.vue b/js/src/views/User/Register.vue index 9b02d28c..dd82c556 100644 --- a/js/src/views/User/Register.vue +++ b/js/src/views/User/Register.vue @@ -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", }; }, diff --git a/lib/federation/activity_pub/activity_pub.ex b/lib/federation/activity_pub/activity_pub.ex index 7aec827c..dd74f25e 100644 --- a/lib/federation/activity_pub/activity_pub.ex +++ b/lib/federation/activity_pub/activity_pub.ex @@ -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, diff --git a/lib/federation/activity_pub/types/actors.ex b/lib/federation/activity_pub/types/actors.ex index 66f7fd78..7496920d 100644 --- a/lib/federation/activity_pub/types/actors.ex +++ b/lib/federation/activity_pub/types/actors.ex @@ -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", diff --git a/lib/federation/activity_pub/types/discussions.ex b/lib/federation/activity_pub/types/discussions.ex index 57eb7703..f57af16e 100644 --- a/lib/federation/activity_pub/types/discussions.ex +++ b/lib/federation/activity_pub/types/discussions.ex @@ -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", diff --git a/lib/federation/activity_pub/types/events.ex b/lib/federation/activity_pub/types/events.ex index 2cd0a9d5..32e81429 100644 --- a/lib/federation/activity_pub/types/events.ex +++ b/lib/federation/activity_pub/types/events.ex @@ -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 diff --git a/lib/federation/activity_pub/types/members.ex b/lib/federation/activity_pub/types/members.ex index cb1c7ae9..a8151432 100644 --- a/lib/federation/activity_pub/types/members.ex +++ b/lib/federation/activity_pub/types/members.ex @@ -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), diff --git a/lib/federation/activity_pub/types/posts.ex b/lib/federation/activity_pub/types/posts.ex index 22b145a6..47a9a034 100644 --- a/lib/federation/activity_pub/types/posts.ex +++ b/lib/federation/activity_pub/types/posts.ex @@ -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 diff --git a/lib/federation/activity_pub/types/resources.ex b/lib/federation/activity_pub/types/resources.ex index c57afcb8..61157afc 100644 --- a/lib/federation/activity_pub/types/resources.ex +++ b/lib/federation/activity_pub/types/resources.ex @@ -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 diff --git a/lib/graphql/resolvers/activity.ex b/lib/graphql/resolvers/activity.ex new file mode 100644 index 00000000..aa6f7364 --- /dev/null +++ b/lib/graphql/resolvers/activity.ex @@ -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 diff --git a/lib/graphql/schema.ex b/lib/graphql/schema.ex index ceca7131..39ea5b39 100644 --- a/lib/graphql/schema.ex +++ b/lib/graphql/schema.ex @@ -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) diff --git a/lib/graphql/schema/activity.ex b/lib/graphql/schema/activity.ex new file mode 100644 index 00000000..9a03b3f7 --- /dev/null +++ b/lib/graphql/schema/activity.ex @@ -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 diff --git a/lib/graphql/schema/actors/group.ex b/lib/graphql/schema/actors/group.ex index 90588e99..83c2f9b6 100644 --- a/lib/graphql/schema/actors/group.ex +++ b/lib/graphql/schema/actors/group.ex @@ -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 """ diff --git a/lib/graphql/schema/actors/member.ex b/lib/graphql/schema/actors/member.ex index 5d68f985..d4b124e3 100644 --- a/lib/graphql/schema/actors/member.ex +++ b/lib/graphql/schema/actors/member.ex @@ -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") diff --git a/lib/graphql/schema/discussions/discussion.ex b/lib/graphql/schema/discussions/discussion.ex index 8312b4c6..849d6e4c 100644 --- a/lib/graphql/schema/discussions/discussion.ex +++ b/lib/graphql/schema/discussions/discussion.ex @@ -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") diff --git a/lib/graphql/schema/event.ex b/lib/graphql/schema/event.ex index e74760b8..f88ad3af 100644 --- a/lib/graphql/schema/event.ex +++ b/lib/graphql/schema/event.ex @@ -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") diff --git a/lib/graphql/schema/post.ex b/lib/graphql/schema/post.ex index 6df271fb..8c0d6203 100644 --- a/lib/graphql/schema/post.ex +++ b/lib/graphql/schema/post.ex @@ -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") diff --git a/lib/graphql/schema/resource.ex b/lib/graphql/schema/resource.ex index 320c3fce..8408da2d 100644 --- a/lib/graphql/schema/resource.ex +++ b/lib/graphql/schema/resource.ex @@ -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") diff --git a/lib/mobilizon/activities/activities.ex b/lib/mobilizon/activities/activities.ex new file mode 100644 index 00000000..84e8a7bd --- /dev/null +++ b/lib/mobilizon/activities/activities.ex @@ -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 diff --git a/lib/mobilizon/activities/activity.ex b/lib/mobilizon/activities/activity.ex new file mode 100644 index 00000000..08698d2e --- /dev/null +++ b/lib/mobilizon/activities/activity.ex @@ -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 diff --git a/lib/mobilizon/actors/actors.ex b/lib/mobilizon/actors/actors.ex index 306ac56a..e55f1070 100644 --- a/lib/mobilizon/actors/actors.ex +++ b/lib/mobilizon/actors/actors.ex @@ -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 diff --git a/lib/mobilizon/actors/member.ex b/lib/mobilizon/actors/member.ex index 23505462..e2481b0f 100644 --- a/lib/mobilizon/actors/member.ex +++ b/lib/mobilizon/actors/member.ex @@ -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 diff --git a/lib/mobilizon/resources/resources.ex b/lib/mobilizon/resources/resources.ex index b4cb43ae..c647c8d4 100644 --- a/lib/mobilizon/resources/resources.ex +++ b/lib/mobilizon/resources/resources.ex @@ -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 diff --git a/lib/service/activity/activity.ex b/lib/service/activity/activity.ex new file mode 100644 index 00000000..2632a01d --- /dev/null +++ b/lib/service/activity/activity.ex @@ -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 diff --git a/lib/service/activity/discussion.ex b/lib/service/activity/discussion.ex new file mode 100644 index 00000000..3b2c993c --- /dev/null +++ b/lib/service/activity/discussion.ex @@ -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 diff --git a/lib/service/activity/event.ex b/lib/service/activity/event.ex new file mode 100644 index 00000000..55b63d38 --- /dev/null +++ b/lib/service/activity/event.ex @@ -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 diff --git a/lib/service/activity/group.ex b/lib/service/activity/group.ex new file mode 100644 index 00000000..3adfb191 --- /dev/null +++ b/lib/service/activity/group.ex @@ -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 diff --git a/lib/service/activity/member.ex b/lib/service/activity/member.ex new file mode 100644 index 00000000..22255792 --- /dev/null +++ b/lib/service/activity/member.ex @@ -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 diff --git a/lib/service/activity/posts.ex b/lib/service/activity/posts.ex new file mode 100644 index 00000000..bd8a4553 --- /dev/null +++ b/lib/service/activity/posts.ex @@ -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 diff --git a/lib/service/activity/resource.ex b/lib/service/activity/resource.ex new file mode 100644 index 00000000..4eec72eb --- /dev/null +++ b/lib/service/activity/resource.ex @@ -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 diff --git a/lib/service/workers/activity_builder.ex b/lib/service/workers/activity_builder.ex new file mode 100644 index 00000000..87049a83 --- /dev/null +++ b/lib/service/workers/activity_builder.ex @@ -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 diff --git a/lib/web/endpoint.ex b/lib/web/endpoint.ex index ef5b9eb6..40b1aa74 100644 --- a/lib/web/endpoint.ex +++ b/lib/web/endpoint.ex @@ -10,7 +10,10 @@ defmodule Mobilizon.Web.Endpoint do use Absinthe.Phoenix.Endpoint plug(Mobilizon.Web.Plugs.SetLocalePlug) - plug(Mobilizon.Web.Plugs.HTTPSecurityPlug) + + 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 diff --git a/mix.exs b/mix.exs index b811bcd0..b9725324 100644 --- a/mix.exs +++ b/mix.exs @@ -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"}, diff --git a/mix.lock b/mix.lock index 4ca20211..305e3487 100644 --- a/mix.lock +++ b/mix.lock @@ -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"}, diff --git a/priv/repo/migrations/20210215092515_add_activity_table.exs b/priv/repo/migrations/20210215092515_add_activity_table.exs new file mode 100644 index 00000000..6c14c356 --- /dev/null +++ b/priv/repo/migrations/20210215092515_add_activity_table.exs @@ -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 diff --git a/priv/repo/migrations/20210217164549_add_member_since_to_members.exs b/priv/repo/migrations/20210217164549_add_member_since_to_members.exs new file mode 100644 index 00000000..d4eaaf11 --- /dev/null +++ b/priv/repo/migrations/20210217164549_add_member_since_to_members.exs @@ -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 diff --git a/test/graphql/resolvers/activity_test.exs b/test/graphql/resolvers/activity_test.exs new file mode 100644 index 00000000..b3d149fe --- /dev/null +++ b/test/graphql/resolvers/activity_test.exs @@ -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 diff --git a/test/mobilizon/activities_test.exs b/test/mobilizon/activities_test.exs new file mode 100644 index 00000000..e04990e0 --- /dev/null +++ b/test/mobilizon/activities_test.exs @@ -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 diff --git a/test/support/factory.ex b/test/support/factory.ex index 09a2f682..b38a8da4 100644 --- a/test/support/factory.ex +++ b/test/support/factory.ex @@ -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