Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ services:
- REDIS_PORT=6379
- FEDIFY_KV_STORE_TYPE=redis
- JWKS_REFETCH_COOLDOWN_MS=0
# Keeps the tests from requesting posts from tags.pub
- HASHTAG_SERVICE_DOMAIN=
command: pnpm build:watch
depends_on:
migrate-testing:
Expand Down
3 changes: 3 additions & 0 deletions docs/env-vars.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ This ActivityPub service uses a variety of environment variables to configure it
- Only used in `production` environments with a CDN (i.e Fastly)
- Example: `max-age=60, stale-while-revalidate=300, stale-if-error=0`
- `FORCE_INTERNAL_ACTIVITY_DELIVERY` - Set to `true` to force internal activities to be delivered via the Fediverse
- `HASHTAG_SERVICE_DOMAIN` - Domain of a global hashtag service with one account per hashtag (default: `tags.pub`)
- Hashtag feeds also show recent posts from across the network, imported from the hashtag's account (e.g. `@ghost@tags.pub` for `#ghost`) at most every 15 minutes
- Set to an empty value to turn the import off, so hashtag feeds only show posts that reached this server

## Database Configuration

Expand Down
33 changes: 33 additions & 0 deletions features/hashtags.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
Feature: Hashtags

Scenario: Hashtags in a created note are tagged and linked to existing tag pages
Given we are followed by "Alice"
And the site has a tag page for "ghost"
When we create a note "Note" with the content
"""
Hello #Ghost and #coffee
"""
Then "Note" is sent to "Alice" with the hashtags
| name | href |
| #Ghost | https://self.test/tag/ghost/ |
| #coffee | |
And "Note" has the content "<p>Hello <a href=\"https://self.test/tag/ghost/\" class=\"mention hashtag\" rel=\"tag\">#<span>Ghost</span></a> and #coffee</p>"

Scenario: Incoming notes are listed under their hashtags
Given we are following "Alice"
And a "Create(Note)" Activity "Note1" by "Alice" with the hashtag "#Fediverse"
When "Alice" sends "Note1" to the Inbox
Then the note "Note1" is in the hashtag feed for "#Fediverse"

Scenario: Hashtags can be searched
Given we are following "Alice"
And a "Create(Note)" Activity "Note1" by "Alice" with the hashtag "#Fediverse"
And "Alice" sends "Note1" to the Inbox
And the note "Note1" is in the hashtag feed for "fediverse"
When an authenticated request is made to "/.ghost/activitypub/v1/actions/search?query=%23Fedi"
Then the request is accepted
And the search results contain the hashtag "fediverse"

Scenario: Invalid hashtags are rejected
When an authenticated request is made to "/.ghost/activitypub/v1/feed/hashtag/not%20valid"
Then the request is rejected with a 400
94 changes: 94 additions & 0 deletions features/step_definitions/hashtag_steps.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { Given, Then } from '@cucumber/cucumber';

import assert from 'node:assert';

import { waitForAPObjectInFeed } from '../support/feed.js';
import { createActivity, createObject } from '../support/fixtures.js';
import { waitForRequest } from '../support/request.js';
import { parseActivityString } from '../support/steps.js';
import { getGhostWiremock } from '../support/wiremock.js';

Given('the site has a tag page for {string}', async (tag) => {
await getGhostWiremock().register(
{ method: 'HEAD', endpoint: `/tag/${tag}/` },
{ status: 200 },
);
});

Given(
'a {string} Activity {string} by {string} with the hashtag {string}',
async function (activityDef, name, actorName, hashtag) {
const { activity: activityType, object: objectType } =
parseActivityString(activityDef);
const actor = this.actors[actorName];
const href = `https://fake-external-activitypub.test/tags/${hashtag.slice(1)}`;

const object = await createObject(
objectType,
actor,
`<p>Hello <a href="${href}" class="mention hashtag" rel="tag">#<span>${hashtag.slice(1)}</span></a></p>`,
[{ type: 'Hashtag', name: hashtag, href }],
null,
{
// `Hashtag` is not part of the ActivityStreams context, so
// servers like Mastodon define it themselves
'@context': [
'https://www.w3.org/ns/activitystreams',
'https://w3id.org/security/data-integrity/v1',
{ Hashtag: 'as:Hashtag' },
],
},
);
const activity = await createActivity(activityType, object, actor);

this.activities[name] = activity;
this.objects[name] = object;
},
);

Then(
'{string} is sent to {string} with the hashtags',
async function (objectName, actorName, table) {
const object = this.objects[objectName];
const inbox = new URL(this.actors[actorName].inbox);

const call = await waitForRequest(
'POST',
inbox.pathname,
(call) => JSON.parse(call.request.body).object.id === object.id,
);
const sentObject = JSON.parse(call.request.body).object;
const tags = Array.isArray(sentObject.tag)
? sentObject.tag
: [sentObject.tag];

assert.deepStrictEqual(
tags
.filter((tag) => tag?.type === 'Hashtag')
.map((tag) => ({ name: tag.name, href: tag.href ?? '' })),
table.hashes(),
);
},
);

Then(
'the note {string} is in the hashtag feed for {string}',
async function (noteName, hashtag) {
const note = this.objects[noteName];

const found = await waitForAPObjectInFeed(
note.id,
`https://self.test/.ghost/activitypub/v1/feed/hashtag/${encodeURIComponent(hashtag)}`,
);
assert(found);
},
);

Then(
'the search results contain the hashtag {string}',
async function (hashtag) {
const json = await this.response.clone().json();

assert.deepEqual(json.hashtags, [{ name: hashtag }]);
},
);
2 changes: 2 additions & 0 deletions features/support/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,13 @@ export async function reset() {
'feeds',
'follows',
'ghost_ap_post_mappings',
'hashtags',
'key_value',
'likes',
'mentions',
'notifications',
'outboxes',
'post_hashtags',
'posts',
'reposts',
'sites',
Expand Down
2 changes: 2 additions & 0 deletions migrate/migrations/000085_add-hashtags.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
DROP TABLE post_hashtags;
DROP TABLE hashtags;
25 changes: 25 additions & 0 deletions migrate/migrations/000085_add-hashtags.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
CREATE TABLE hashtags (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
created_at TIMESTAMP(6) NULL DEFAULT CURRENT_TIMESTAMP(6),

name VARCHAR(255) NOT NULL,
name_hash BINARY(32) GENERATED ALWAYS AS (UNHEX(SHA2(name, 256))) STORED,

UNIQUE KEY uk_hashtags_name_hash (name_hash),
KEY idx_hashtags_name (name)
);

CREATE TABLE post_hashtags (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
created_at TIMESTAMP(6) NULL DEFAULT CURRENT_TIMESTAMP(6),

post_id INT UNSIGNED NOT NULL,
hashtag_id INT UNSIGNED NOT NULL,
published_at TIMESTAMP(6) NOT NULL,

UNIQUE KEY uk_post_hashtags_hashtag_post (hashtag_id, post_id),
KEY idx_post_hashtags_hashtag_published_at (hashtag_id, published_at),

FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
FOREIGN KEY (hashtag_id) REFERENCES hashtags(id) ON DELETE CASCADE
);
26 changes: 25 additions & 1 deletion migrate/schema.sql
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
-- Generated by `pnpm schema:dump` from migrations up to 84
-- Generated by `pnpm schema:dump` from migrations up to 85
-- For reference only. It is not applied to any database.
-- Do not edit by hand, add a migration instead.

Expand Down Expand Up @@ -197,6 +197,16 @@ CREATE TABLE `ghost_ap_post_mappings` (
UNIQUE KEY `ap_id_hash` (`ap_id_hash`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

CREATE TABLE `hashtags` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`created_at` timestamp(6) NULL DEFAULT CURRENT_TIMESTAMP(6),
`name` varchar(255) NOT NULL,
`name_hash` binary(32) GENERATED ALWAYS AS (unhex(sha2(`name`,256))) STORED,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_hashtags_name_hash` (`name_hash`),
KEY `idx_hashtags_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

CREATE TABLE `key_value` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`key` varchar(768) DEFAULT NULL,
Expand Down Expand Up @@ -283,6 +293,20 @@ CREATE TABLE `outboxes` (
CONSTRAINT `outboxes_ibfk_3` FOREIGN KEY (`author_id`) REFERENCES `accounts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

CREATE TABLE `post_hashtags` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`created_at` timestamp(6) NULL DEFAULT CURRENT_TIMESTAMP(6),
`post_id` int unsigned NOT NULL,
`hashtag_id` int unsigned NOT NULL,
`published_at` timestamp(6) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_post_hashtags_hashtag_post` (`hashtag_id`,`post_id`),
KEY `idx_post_hashtags_hashtag_published_at` (`hashtag_id`,`published_at`),
KEY `post_id` (`post_id`),
CONSTRAINT `post_hashtags_ibfk_1` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE,
CONSTRAINT `post_hashtags_ibfk_2` FOREIGN KEY (`hashtag_id`) REFERENCES `hashtags` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

CREATE TABLE `posts` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`uuid` char(36) NOT NULL DEFAULT (uuid()),
Expand Down
6 changes: 6 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ import {
type GCloudPubSubPushMessageQueue,
} from '@/mq/gcloud-pubsub-push/mq';
import type { NotificationEventService } from '@/notification/notification-event.service';
import type { HashtagPostsImportService } from '@/post/hashtag-posts-import.service';
import { HashtagPostsImportRequestedEvent } from '@/post/hashtag-posts-import-requested.event';
import { PostCreatedEvent } from '@/post/post-created.event';
import { PostDeletedEvent } from '@/post/post-deleted.event';
import { PostDerepostedEvent } from '@/post/post-dereposted.event';
Expand Down Expand Up @@ -270,6 +272,9 @@ container.resolve<GhostPostService>('ghostPostService').init();
container
.resolve<PostInteractionCountsService>('postInteractionCountsService')
.init();
container
.resolve<HashtagPostsImportService>('hashtagPostsImportService')
.init();
container.resolve<BlueskyEventService>('blueskyEventService').init();

// Register all events with the event serializer
Expand All @@ -284,6 +289,7 @@ for (const event of [
AccountUpdatedEvent,
DomainBlockedEvent,
DomainUnblockedEvent,
HashtagPostsImportRequestedEvent,
NotificationsReadEvent,
PostCreatedEvent,
PostDeletedEvent,
Expand Down
17 changes: 17 additions & 0 deletions src/configuration/registrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ import { AccountSearchView } from '@/http/api/views/account.search.view';
import { AccountView } from '@/http/api/views/account.view';
import { BlocksView } from '@/http/api/views/blocks.view';
import { ExploreView } from '@/http/api/views/explore.view';
import { HashtagSearchView } from '@/http/api/views/hashtag.search.view';
import { RecommendationsView } from '@/http/api/views/recommendations.view';
import { ReplyChainView } from '@/http/api/views/reply.chain.view';
import { TopicView } from '@/http/api/views/topic.view';
Expand All @@ -88,9 +89,11 @@ import { ModerationService } from '@/moderation/moderation.service';
import { GCloudPubSubPushMessageQueue } from '@/mq/gcloud-pubsub-push/mq';
import { NotificationService } from '@/notification/notification.service';
import { NotificationEventService } from '@/notification/notification-event.service';
import { HashtagPostsImportService } from '@/post/hashtag-posts-import.service';
import { KnexPostRepository } from '@/post/post.repository.knex';
import { PostService } from '@/post/post.service';
import { PostInteractionCountsService } from '@/post/post-interaction-counts.service';
import { TagPageService } from '@/post/tag-page.service';
import { getFullTopic, initPubSubClient } from '@/pubsub';
import { SiteService } from '@/site/site.service';
import { GCPStorageAdapter } from '@/storage/adapters/gcp-storage-adapter';
Expand Down Expand Up @@ -381,6 +384,7 @@ export function registerDependencies(
asClass(AccountMoveService).singleton(),
);
container.register('postService', asClass(PostService).singleton());
container.register('tagPageService', asClass(TagPageService).singleton());
container.register('userService', asClass(UserService).singleton());
container.register(
'ghostPostService',
Expand All @@ -390,6 +394,15 @@ export function registerDependencies(
'postInteractionCountsService',
asClass(PostInteractionCountsService).singleton(),
);
// Unset means tags.pub, an empty value turns the import off
container.register(
'hashtagServiceDomain',
asValue((process.env.HASHTAG_SERVICE_DOMAIN ?? 'tags.pub') || null),
);
container.register(
'hashtagPostsImportService',
asClass(HashtagPostsImportService).singleton(),
);
container.register('nodeInfoService', asClass(NodeInfoService).singleton());
container.register(
'ghostService',
Expand Down Expand Up @@ -444,6 +457,10 @@ export function registerDependencies(
'accountSearchView',
asClass(AccountSearchView).singleton(),
);
container.register(
'hashtagSearchView',
asClass(HashtagSearchView).singleton(),
);
container.register('blocksView', asClass(BlocksView).singleton());
container.register('replyChainView', asClass(ReplyChainView).singleton());

Expand Down
Loading