-
Notifications
You must be signed in to change notification settings - Fork 354
/
index.ts
414 lines (360 loc) · 10.3 KB
/
index.ts
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import { uniq } from "lodash";
import { Db } from "mongodb";
import isNonNullArray from "coral-common/helpers/isNonNullArray";
import { Config } from "coral-server/config";
import { StoryURLInvalidError, UserNotFoundError } from "coral-server/errors";
import { StoryCreatedCoralEvent } from "coral-server/events";
import { CoralEventPublisherBroker } from "coral-server/events/publisher";
import logger from "coral-server/logger";
import {
mergeCommentActionCounts,
mergeManyStoryActions,
removeStoryActions,
} from "coral-server/models/action/comment";
import {
calculateTotalCommentCount,
mergeCommentModerationQueueCount,
mergeCommentStatusCount,
mergeManyCommentStories,
removeStoryComments,
} from "coral-server/models/comment";
import {
addExpert,
closeStory,
createStory,
CreateStoryInput,
findOrCreateStory,
FindOrCreateStoryInput,
findStory,
FindStoryInput,
openStory,
removeExpert,
removeStories,
removeStory,
retrieveManyStories,
retrieveStory,
setStoryMode,
Story,
updateStory,
updateStoryCounts,
UpdateStoryInput,
updateStorySettings,
UpdateStorySettingsInput,
} from "coral-server/models/story";
import { Tenant } from "coral-server/models/tenant";
import { retrieveUser } from "coral-server/models/user";
import { ScraperQueue } from "coral-server/queue/tasks/scraper";
import { findSiteByURL } from "coral-server/services/sites";
import { scrape } from "coral-server/services/stories/scraper";
import { GQLSTORY_MODE } from "coral-server/graph/schema/__generated__/types";
export type FindStory = FindStoryInput;
export async function find(mongo: Db, tenant: Tenant, input: FindStory) {
return findStory(mongo, tenant.id, input);
}
export type FindOrCreateStory = FindOrCreateStoryInput;
export async function findOrCreate(
mongo: Db,
tenant: Tenant,
broker: CoralEventPublisherBroker,
input: FindOrCreateStory,
scraper: ScraperQueue,
now = new Date()
) {
let siteID = null;
if (input.url) {
const site = await findSiteByURL(mongo, tenant.id, input.url);
// If the URL is provided, and the url is not associated with a site, then refuse
// to create the Asset.
if (!site) {
throw new StoryURLInvalidError({
storyURL: input.url,
});
}
siteID = site.id;
}
const { story, wasUpserted } = await findOrCreateStory(
mongo,
tenant.id,
input,
siteID,
now
);
if (!story) {
return null;
}
if (wasUpserted) {
StoryCreatedCoralEvent.publish(broker, {
storyID: story.id,
storyURL: story.url,
siteID: story.siteID,
});
}
if (tenant.stories.scraping.enabled && !story.metadata && !story.scrapedAt) {
// If the scraper has not scraped this story, and we have no metadata, we
// need to scrape it now!
await scraper.add({
storyID: story.id,
storyURL: story.url,
tenantID: tenant.id,
});
}
return story;
}
export async function remove(
mongo: Db,
tenant: Tenant,
storyID: string,
includeComments = false
) {
// Create a logger for this function.
const log = logger.child(
{
storyID,
includeComments,
},
true
);
log.debug("starting to remove story");
// Get the story so we can see if there are associated comments.
const story = await retrieveStory(mongo, tenant.id, storyID);
if (!story) {
// No story was found!
log.warn("attempted to remove story that wasn't found");
return null;
}
if (includeComments) {
// Remove the actions associated with the comments we just removed.
const { deletedCount: removedActions } = await removeStoryActions(
mongo,
tenant.id,
story.id
);
log.debug({ removedActions }, "removed actions while deleting story");
// Remove the comments for the story.
const { deletedCount: removedComments } = await removeStoryComments(
mongo,
tenant.id,
story.id
);
log.debug({ removedComments }, "removed comments while deleting story");
} else if (calculateTotalCommentCount(story.commentCounts.status) > 0) {
log.warn(
"attempted to remove story that has linked comments without consent for deleting comments"
);
// TODO: (wyattjoh) improve error
throw new Error("asset has comments, cannot remove");
}
const removedStory = await removeStory(mongo, tenant.id, story.id);
if (!removedStory) {
// Story was already removed.
// TODO: evaluate use of transaction here.
return null;
}
log.debug("removed story");
return removedStory;
}
// export type CreateStory = CreateStoryInput;
export type CreateStory = Partial<
Pick<Story, "metadata" | "scrapedAt" | "closedAt" | "siteID">
>;
export async function create(
mongo: Db,
tenant: Tenant,
broker: CoralEventPublisherBroker,
config: Config,
storyID: string,
storyURL: string,
{ metadata, closedAt }: CreateStory,
now = new Date()
) {
const site = await findSiteByURL(mongo, tenant.id, storyURL);
// // If the URL is provided, and the url is not associated with a site, then refuse
// // to create the Asset.
if (!site) {
throw new StoryURLInvalidError({
storyURL,
});
}
// Construct the input payload.
const input: CreateStoryInput = { metadata, closedAt, siteID: site.id };
if (metadata) {
input.scrapedAt = now;
}
// Create the story in the database.
let story = await createStory(
mongo,
tenant.id,
storyID,
storyURL,
input,
now
);
if (!metadata && tenant.stories.scraping.enabled) {
// If the scraper has not scraped this story and story metadata was not
// provided, we need to scrape it now!
story = await scrape(mongo, config, tenant.id, story.id, storyURL);
}
StoryCreatedCoralEvent.publish(broker, {
storyID: story.id,
storyURL: story.url,
siteID: site.id,
});
return story;
}
export type UpdateStory = UpdateStoryInput;
export async function update(
mongo: Db,
tenant: Tenant,
storyID: string,
input: UpdateStory,
now = new Date()
) {
if (input.url) {
const site = await findSiteByURL(mongo, tenant.id, input.url);
// // If the URL is provided, and the url is not associated with a site, then refuse
// // to update the Asset.
if (!site) {
throw new StoryURLInvalidError({
storyURL: input.url,
});
}
}
return updateStory(mongo, tenant.id, storyID, input, now);
}
export type UpdateStorySettings = UpdateStorySettingsInput;
export async function updateSettings(
mongo: Db,
tenant: Tenant,
storyID: string,
input: UpdateStorySettings,
now = new Date()
) {
return updateStorySettings(mongo, tenant.id, storyID, input, now);
}
export async function open(
mongo: Db,
tenant: Tenant,
storyID: string,
now = new Date()
) {
return openStory(mongo, tenant.id, storyID, now);
}
export async function close(
mongo: Db,
tenant: Tenant,
storyID: string,
now = new Date()
) {
return closeStory(mongo, tenant.id, storyID, now);
}
export async function merge(
mongo: Db,
tenant: Tenant,
destinationID: string,
sourceIDs: string[]
) {
// Create a logger for this operation.
const log = logger.child({ destinationID, sourceIDs }, true);
if (sourceIDs.length === 0) {
log.warn("cannot merge from 0 stories");
return null;
}
// Collect the story id's and check for duplicates.
const storyIDs = [destinationID, ...sourceIDs];
if (uniq(storyIDs).length !== storyIDs.length) {
throw new Error("cannot merge from/to the same story ID");
}
// Get the stories referenced.
const stories = await retrieveManyStories(mongo, tenant.id, storyIDs);
if (!isNonNullArray(stories)) {
throw new Error("cannot find all the stories");
}
// We can only merge stories if they are all on the same site.
if (uniq(stories.map(({ siteID }) => siteID)).length > 1) {
throw new Error("cannot merge stories on different sites");
}
// Move all the comment's from the source stories over to the destination
// story.
const { modifiedCount: updatedComments } = await mergeManyCommentStories(
mongo,
tenant.id,
destinationID,
sourceIDs
);
log.debug({ updatedComments }, "updated comments while merging stories");
// Update all the action's that referenced the old story to reference the new
// story.
const { modifiedCount: updatedActions } = await mergeManyStoryActions(
mongo,
tenant.id,
destinationID,
sourceIDs
);
log.debug({ updatedActions }, "updated actions while merging stories");
// Merge the comment and action counts for all the source stories.
const [, ...sourceStories] = stories;
// Compute the new comment counts from the old stories.
const commentCounts = {
status: mergeCommentStatusCount(
...sourceStories.map(s => s.commentCounts.status)
),
moderationQueue: mergeCommentModerationQueueCount(
...sourceStories.map(s => s.commentCounts.moderationQueue)
),
action: mergeCommentActionCounts(
...sourceStories.map(s => s.commentCounts.action)
),
};
// Update the story that was the destination of the merge.
const destinationStory = await updateStoryCounts(
mongo,
tenant.id,
destinationID,
commentCounts
);
if (!destinationStory) {
log.warn("destination story cannot be updated with new comment counts");
return null;
}
log.debug(
{ commentCounts: destinationStory.commentCounts },
"updated destination story with new comment counts"
);
// Remove the stories from MongoDB.
const { deletedCount } = await removeStories(mongo, tenant.id, sourceIDs);
log.debug({ deletedStories: deletedCount }, "deleted source stories");
// Return the story that had the other stories merged into.
return destinationStory;
}
export async function addStoryExpert(
mongo: Db,
tenant: Tenant,
storyID: string,
userID: string
) {
const user = await retrieveUser(mongo, tenant.id, userID);
if (!user) {
throw new UserNotFoundError(userID);
}
return addExpert(mongo, tenant.id, storyID, userID);
}
export async function removeStoryExpert(
mongo: Db,
tenant: Tenant,
storyID: string,
userID: string
) {
const user = await retrieveUser(mongo, tenant.id, userID);
if (!user) {
throw new UserNotFoundError(userID);
}
return removeExpert(mongo, tenant.id, storyID, userID);
}
export async function updateStoryMode(
mongo: Db,
tenant: Tenant,
storyID: string,
mode: GQLSTORY_MODE
) {
return setStoryMode(mongo, tenant.id, storyID, mode);
}