File size: 2,138 Bytes
2e28042
 
 
f249cfc
e943a05
5da61b4
 
 
fc15a4c
 
 
 
2e28042
fc15a4c
 
 
5da61b4
fc15a4c
 
1eff97d
fc15a4c
76d4779
fc15a4c
 
 
 
17a481a
fc15a4c
5da61b4
fc15a4c
 
 
76d4779
 
 
 
 
 
5da61b4
06e879d
3a01622
af58e08
fc15a4c
 
76d4779
fc15a4c
0e5c445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc15a4c
 
17a481a
fc15a4c
5da61b4
fc15a4c
 
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
import { authCondition } from "$lib/server/auth";
import { collections } from "$lib/server/database";
import type { SharedConversation } from "$lib/types/SharedConversation";
import { getShareUrl } from "$lib/utils/getShareUrl";
import { hashConv } from "$lib/utils/hashConv";
import { error } from "@sveltejs/kit";
import { ObjectId } from "mongodb";
import { nanoid } from "nanoid";

export async function POST({ params, url, locals }) {
	const conversation = await collections.conversations.findOne({
		_id: new ObjectId(params.id),
		...authCondition(locals),
	});

	if (!conversation) {
		throw error(404, "Conversation not found");
	}

	const hash = await hashConv(conversation);

	const existingShare = await collections.sharedConversations.findOne({ hash });

	if (existingShare) {
		return new Response(
			JSON.stringify({
				url: getShareUrl(url, existingShare._id),
			}),
			{ headers: { "Content-Type": "application/json" } }
		);
	}

	const shared: SharedConversation = {
		_id: nanoid(7),
		createdAt: new Date(),
		messages: conversation.messages,
		hash,
		updatedAt: new Date(),
		title: conversation.title,
		model: conversation.model,
		embeddingModel: conversation.embeddingModel,
		preprompt: conversation.preprompt,
	};

	await collections.sharedConversations.insertOne(shared);

	// copy files from `${conversation._id}-` to `${shared._id}-`
	const files = await collections.bucket
		.find({ filename: { $regex: `${conversation._id}-` } })
		.toArray();

	await Promise.all(
		files.map(async (file) => {
			const newFilename = file.filename.replace(`${conversation._id}-`, `${shared._id}-`);
			// copy files from `${conversation._id}-` to `${shared._id}-` by downloading and reuploaidng
			const downloadStream = collections.bucket.openDownloadStream(file._id);
			const uploadStream = collections.bucket.openUploadStream(newFilename, {
				metadata: { ...file.metadata, conversation: shared._id.toString() },
			});
			downloadStream.pipe(uploadStream);
		})
	);

	return new Response(
		JSON.stringify({
			url: getShareUrl(url, shared._id),
		}),
		{ headers: { "Content-Type": "application/json" } }
	);
}