-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathaccount.ts
More file actions
335 lines (291 loc) · 9.74 KB
/
account.ts
File metadata and controls
335 lines (291 loc) · 9.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import type { Federation } from '@fedify/fedify';
import type { Account } from 'account/account.entity';
import type { KnexAccountRepository } from 'account/account.repository.knex';
import type { AccountService } from 'account/account.service';
import type { FedifyContextFactory } from 'activitypub/fedify-context.factory';
import type { AppContext, ContextData } from 'app';
import { isHandle } from 'helpers/activitypub/actor';
import { lookupAPIdByHandle } from 'lookup-helpers';
import type { GetProfileDataResult, PostService } from 'post/post.service';
import type { AccountDTO } from './types';
import type {
AccountFollows,
AccountFollowsView,
} from './views/account.follows.view';
import type { AccountView } from './views/account.view';
/**
* Default number of posts to return in a profile
*/
const DEFAULT_POSTS_LIMIT = 20;
/**
* Maximum number of posts that can be returned in a profile
*/
const MAX_POSTS_LIMIT = 100;
/**
* Keyword to indicate a request is for the current user
*/
const CURRENT_USER_KEYWORD = 'me';
/**
* Create a handler to handle a request for an account
*/
export function createGetAccountHandler(
accountView: AccountView,
accountRepository: KnexAccountRepository,
) {
/**
* Handle a request for an account
*
* @param ctx App context
*/
return async function handleGetAccount(ctx: AppContext) {
const handle = ctx.req.param('handle');
if (handle !== CURRENT_USER_KEYWORD && !isHandle(handle)) {
return new Response(null, { status: 404 });
}
const siteDefaultAccount = await accountRepository.getBySite(
ctx.get('site'),
);
let accountDto: AccountDTO | null = null;
const viewContext = {
requestUserAccount: siteDefaultAccount,
};
if (handle === CURRENT_USER_KEYWORD) {
accountDto = await accountView.viewById(
siteDefaultAccount.id!,
viewContext,
);
} else {
accountDto = await accountView.viewByHandle(handle, viewContext);
}
if (accountDto === null) {
return new Response(null, { status: 404 });
}
return new Response(JSON.stringify(accountDto), {
headers: {
'Content-Type': 'application/json',
},
status: 200,
});
};
}
/**
* Create a handler to handle a request for a list of account follows
*
* @param accountService Account service instance
*/
export function createGetAccountFollowsHandler(
accountRepository: KnexAccountRepository,
accountFollowsView: AccountFollowsView,
fedifyContextFactory: FedifyContextFactory,
) {
/**
* Handle a request for a list of account follows
*
* @param ctx App context
*/
return async function handleGetAccountFollows(ctx: AppContext) {
const site = ctx.get('site');
const handle = ctx.req.param('handle') || '';
if (handle === '') {
return new Response(null, { status: 400 });
}
const type = ctx.req.param('type');
if (!['following', 'followers'].includes(type)) {
return new Response(null, { status: 400 });
}
const siteDefaultAccount = await accountRepository.getBySite(site);
const queryNext = ctx.req.query('next');
const next = queryNext ? decodeURIComponent(queryNext) : null;
let accountFollows: AccountFollows;
if (handle === 'me') {
accountFollows = await accountFollowsView.getFollowsByAccount(
siteDefaultAccount,
type,
Number.parseInt(next || '0'),
siteDefaultAccount,
);
} else {
const ctx = fedifyContextFactory.getFedifyContext();
const apId = await lookupAPIdByHandle(ctx, handle);
if (!apId) {
return new Response(null, { status: 400 });
}
const account = await accountRepository.getByApId(new URL(apId));
if (!account) {
return new Response(null, { status: 400 });
}
accountFollows = await accountFollowsView.getFollowsByHandle(
handle,
account,
type,
next,
siteDefaultAccount,
);
}
// Return response
return new Response(
JSON.stringify({
accounts: accountFollows.accounts,
total: accountFollows.total,
next: accountFollows.next,
}),
{
headers: {
'Content-Type': 'application/json',
},
status: 200,
},
);
};
}
/**
* Validates and extracts pagination parameters from the request
*
* @param ctx App context
* @returns Object containing cursor and limit, or null if invalid
*/
function validateRequestParams(ctx: AppContext) {
const queryCursor = ctx.req.query('next');
const cursor = queryCursor ? decodeURIComponent(queryCursor) : null;
const queryLimit = ctx.req.query('limit');
const limit = queryLimit ? Number(queryLimit) : DEFAULT_POSTS_LIMIT;
if (limit > MAX_POSTS_LIMIT) {
return null;
}
return { cursor, limit };
}
/**
* Create a handler to handle a request for a list of posts by an account
*
* @param accountService Account service instance
* @param profileService Profile service instance
*/
export function createGetAccountPostsHandler(
postService: PostService,
accountRepository: KnexAccountRepository,
fedify: Federation<ContextData>,
) {
/**
* Handle a request for a list of posts by an account
*
* @param ctx App context
*/
return async function handleGetPosts(ctx: AppContext) {
const params = validateRequestParams(ctx);
if (!params) {
return new Response(null, { status: 400 });
}
const logger = ctx.get('logger');
let account: Account | null = null;
const db = ctx.get('db');
const apCtx = fedify.createContext(ctx.req.raw as Request, {
db,
globaldb: ctx.get('globaldb'),
logger,
});
const handle = ctx.req.param('handle');
if (!handle) {
return new Response(null, { status: 400 });
}
const defaultAccount = await accountRepository.getBySite(
ctx.get('site'),
);
if (!defaultAccount || !defaultAccount.id) {
return new Response(null, { status: 400 });
}
// We are using the keyword 'me', if we want to get the posts of the current user
if (handle === 'me') {
account = defaultAccount;
} else {
if (!isHandle(handle)) {
return new Response(null, { status: 400 });
}
const apId = await lookupAPIdByHandle(apCtx, handle);
if (apId) {
account = await accountRepository.getByApId(new URL(apId));
}
}
const result: GetProfileDataResult = {
results: [],
nextCursor: null,
};
try {
//If we found the account in our db and it's an internal account, do an internal lookup
if (account?.isInternal && account.id) {
const postResult = await postService.getPostsByAccount(
account.id,
defaultAccount.id,
params.limit,
params.cursor,
);
result.results = postResult.results;
result.nextCursor = postResult.nextCursor;
} else {
//Otherwise, do a remote lookup to fetch the posts
const postResult = await postService.getPostsByRemoteLookUp(
defaultAccount,
handle,
params.cursor || '',
);
if (postResult instanceof Error) {
throw postResult;
}
result.results = postResult.results;
result.nextCursor = postResult.nextCursor;
}
} catch (error) {
logger.error(`Error getting posts for ${handle}: {error}`, {
error,
});
return new Response(null, { status: 500 });
}
return new Response(
JSON.stringify({
posts: result.results,
next: result.nextCursor,
}),
{ status: 200 },
);
};
}
/**
* Create a handler to handle a request for a list of posts liked by an account
*
* @param accountService Account service instance
* @param profileService Profile service instance
*/
export function createGetAccountLikedPostsHandler(
accountService: AccountService,
postService: PostService,
) {
/**
* Handle a request for a list of posts liked by an account
*
* @param ctx App context
*/
return async function handleGetLikedPosts(ctx: AppContext) {
const params = validateRequestParams(ctx);
if (!params) {
return new Response(null, { status: 400 });
}
const account = await accountService.getDefaultAccountForSite(
ctx.get('site'),
);
if (!account) {
return new Response(null, { status: 404 });
}
const { results, nextCursor } =
await postService.getPostsLikedByAccount(
account.id,
params.limit,
params.cursor,
);
return new Response(
JSON.stringify({
posts: results,
next: nextCursor,
}),
{ status: 200 },
);
};
}