Skip to content

Commit

Permalink
add support for deleting chats
Browse files Browse the repository at this point in the history
  • Loading branch information
cogentapps committed Mar 17, 2023
1 parent 6415e30 commit 1be33f5
Show file tree
Hide file tree
Showing 10 changed files with 193 additions and 29 deletions.
14 changes: 14 additions & 0 deletions app/src/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ export class Backend extends EventEmitter {
id: chatID,
messages: new MessageTree(),
} as Chat;

if (response[chatID].deleted) {
chatManager.deleteChat(chatID);
continue;
}

chat.title = response[chatID].title || chat.title;
chat.messages.addMessages(response[chatID].messages);
chatManager.loadChat(chat);
Expand Down Expand Up @@ -131,6 +137,14 @@ export class Backend extends EventEmitter {
return null;
}

async deleteChat(id: string) {
if (!this.isAuthenticated) {
return;
}

return this.post(endpoint + '/delete', { id });
}

async get(url: string) {
const response = await fetch(url);
if (!response.ok) {
Expand Down
58 changes: 45 additions & 13 deletions app/src/chat-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,20 @@ export class ChatManager extends EventEmitter {
});

channel.onmessage = (message: {
type: 'chat-update',
type: 'chat-update' | 'chat-delete',
data: string,
}) => {
const chat = deserializeChat(message.data);
const id = chat.id;
this.chats.set(id, chat);
this.emit(id);
switch (message.type) {
case 'chat-update':
const chat = deserializeChat(message.data);
const id = chat.id;
this.chats.set(id, chat);
this.emit(id);
break;
case 'chat-delete':
this.deleteChat(message.data, false);
break;
}
};

(async () => {
Expand Down Expand Up @@ -69,7 +76,7 @@ export class ChatManager extends EventEmitter {
public async sendMessage(message: UserSubmittedMessage) {
const chat = this.chats.get(message.chatID);

if (!chat) {
if (!chat || chat.deleted) {
throw new Error('Chat not found');
}

Expand Down Expand Up @@ -101,7 +108,7 @@ export class ChatManager extends EventEmitter {
public async regenerate(message: Message, requestedParameters: Parameters) {
const chat = this.chats.get(message.chatID);

if (!chat) {
if (!chat || chat.deleted) {
throw new Error('Chat not found');
}

Expand All @@ -116,7 +123,7 @@ export class ChatManager extends EventEmitter {
const latestMessage = messages[messages.length - 1];
const chat = this.chats.get(latestMessage.chatID);

if (!chat) {
if (!chat || chat.deleted) {
throw new Error('Chat not found');
}

Expand Down Expand Up @@ -250,12 +257,19 @@ export class ChatManager extends EventEmitter {
const serialized = await idb.get('chats');
if (serialized) {
for (const chat of serialized) {
const messages = new MessageTree();
for (const m of chat.messages) {
messages.addMessage(m);
try {
if (chat.deleted) {
continue;
}
const messages = new MessageTree();
for (const m of chat.messages) {
messages.addMessage(m);
}
chat.messages = messages;
this.loadChat(chat);
} catch (e) {
console.error(e);
}
chat.messages = messages;
this.loadChat(chat);
}
this.emit('update');
}
Expand All @@ -268,6 +282,11 @@ export class ChatManager extends EventEmitter {
}

const existing = this.chats.get(chat.id);

if (existing && existing.deleted) {
return;
}

if (existing && existing.title && !chat.title) {
chat.title = existing.title;
}
Expand All @@ -283,6 +302,15 @@ export class ChatManager extends EventEmitter {
public get(id: string): Chat | undefined {
return this.chats.get(id);
}

public deleteChat(id: string, broadcast = true) {
this.chats.delete(id);
this.search.delete(id);
this.emit(id);
if (broadcast) {
channel.postMessage({ type: 'chat-delete', data: id });
}
}
}

export class Search {
Expand All @@ -309,6 +337,10 @@ export class Search {
}
}

public delete(id: string) {
this.index.remove({ id });
}

public query(query: string) {
if (!query?.trim().length) {
const searchResults = Array.from(this.chats.values())
Expand Down
5 changes: 3 additions & 2 deletions app/src/components/sidebar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export default function Sidebar(props: {
className?: string;
}) {
const intl = useIntl();
const context = useAppContext();
const dispatch = useAppDispatch();
const sidebarOpen = useAppSelector(selectSidebarOpen);
const onBurgerClick = useCallback(() => dispatch(toggleSidebar()), [dispatch]);
Expand Down Expand Up @@ -147,13 +148,13 @@ export default function Sidebar(props: {
<Menu.Divider />
<Menu.Item color="red" onClick={() => backend.current?.logout()} icon={<i className="fas fa-sign-out-alt" />}>
<FormattedMessage defaultMessage={"Sign out"} />
</Menu.Item>
</Menu.Item>
*/}
</Menu.Dropdown>
</Menu>
)}
</Container>
), [sidebarOpen, width, ref, burgerLabel, onBurgerClick, dispatch]);
), [sidebarOpen, width, ref, burgerLabel, onBurgerClick, dispatch, context.chat.chats.size]);

return elem;
}
91 changes: 78 additions & 13 deletions app/src/components/sidebar/recent-chats.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import styled from '@emotion/styled';
import { useCallback, useEffect } from 'react';
import { FormattedMessage } from 'react-intl';
import { Link } from 'react-router-dom';
import { Link, useNavigate } from 'react-router-dom';
import { useAppContext } from '../../context';
import { useAppDispatch } from '../../store';
import { toggleSidebar } from '../../store/sidebar';
import { ActionIcon, Menu } from '@mantine/core';
import { useModals } from '@mantine/modals';
import { backend } from '../../backend';

const Container = styled.div`
margin: calc(1.618rem - 1rem);
Expand All @@ -19,8 +22,9 @@ const Empty = styled.p`

const ChatList = styled.div``;

const ChatListItem = styled(Link)`
const ChatListItemLink = styled(Link)`
display: block;
position: relative;
padding: 0.4rem 1rem;
margin: 0.218rem 0;
line-height: 1.7;
Expand All @@ -35,24 +39,91 @@ const ChatListItem = styled(Link)`
background: #2b3d54;
}
&, * {
color: white;
}
strong {
display: block;
font-weight: 400;
font-size: 1rem;
line-height: 1.6;
padding-right: 1rem;
color: white;
}
p {
font-size: 0.8rem;
font-weight: 200;
opacity: 0.8;
}
.mantine-ActionIcon-root {
position: absolute;
right: 0.5rem;
top: 50%;
margin-top: -14px;
}
`;

function ChatListItem(props: { chat: any, onClick: any, selected: boolean }) {
const c = props.chat;
const context = useAppContext();
const modals = useModals();
const navigate = useNavigate();

const onDelete = useCallback(() => {
modals.openConfirmModal({
title: "Are you sure you want to delete this chat?",
children: <p style={{ lineHeight: 1.7 }}>The chat "{c.title}" will be permanently deleted. This cannot be undone.</p>,
labels: {
confirm: "Delete permanently",
cancel: "Cancel",
},
confirmProps: {
color: 'red',
},
onConfirm: async () => {
try {
await backend.current?.deleteChat(c.chatID);
context.chat.deleteChat(c.chatID);
navigate('/');
} catch (e) {
console.error(e);
modals.openConfirmModal({
title: "Something went wrong",
children: <p style={{ lineHeight: 1.7 }}>The chat "{c.title}" could not be deleted.</p>,
labels: {
confirm: "Try again",
cancel: "Cancel",
},
onConfirm: onDelete,
});
}
},
});
}, [c.chatID, c.title]);

return (
<ChatListItemLink to={'/chat/' + c.chatID}
onClick={props.onClick}
data-chat-id={c.chatID}
className={props.selected ? 'selected' : ''}>
<strong>{c.title || <FormattedMessage defaultMessage={"Untitled"} description="default title for untitled chat sessions" />}</strong>
{props.selected && (
<Menu>
<Menu.Target>
<ActionIcon>
<i className="fas fa-ellipsis" />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item onClick={onDelete} color="red" icon={<i className="fa fa-trash" />}>
<FormattedMessage defaultMessage={"Delete this chat"} />
</Menu.Item>
</Menu.Dropdown>
</Menu>
)}
</ChatListItemLink>
);
}

export default function RecentChats(props: any) {
const context = useAppContext();
const dispatch = useAppDispatch();
Expand All @@ -79,13 +150,7 @@ export default function RecentChats(props: any) {
<Container>
{recentChats.length > 0 && <ChatList>
{recentChats.map(c => (
<ChatListItem key={c.chatID}
to={'/chat/' + c.chatID}
onClick={onClick}
data-chat-id={c.chatID}
className={c.chatID === currentChatID ? 'selected' : ''}>
<strong>{c.title || <FormattedMessage defaultMessage={"Untitled"} description="default title for untitled chat sessions" />}</strong>
</ChatListItem>
<ChatListItem key={c.chatID} chat={c} onClick={onClick} selected={c.chatID === currentChatID} />
))}
</ChatList>}
{recentChats.length === 0 && <Empty>
Expand Down
1 change: 1 addition & 0 deletions app/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export interface Chat {
title?: string | null;
created: number;
updated: number;
deleted?: boolean;
}

export function serializeChat(chat: Chat): string {
Expand Down
2 changes: 2 additions & 0 deletions server/src/database/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ export default abstract class Database {
public abstract insertMessages(userID: string, messages: any[]): Promise<void>;
public abstract createShare(userID: string|null, id: string): Promise<boolean>;
public abstract setTitle(userID: string, chatID: string, title: string): Promise<void>;
public abstract deleteChat(userID: string, chatID: string): Promise<any>;
public abstract getDeletedChatIDs(userID: string): Promise<string[]>;
}
27 changes: 27 additions & 0 deletions server/src/database/sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ export class SQLiteAdapter extends Database {
title TEXT
)`);

db.run(`CREATE TABLE IF NOT EXISTS deleted_chats (
id TEXT PRIMARY KEY,
user_id TEXT,
deleted_at DATETIME
)`);

db.run(`CREATE TABLE IF NOT EXISTS messages (
id TEXT PRIMARY KEY,
user_id TEXT,
Expand Down Expand Up @@ -170,4 +176,25 @@ export class SQLiteAdapter extends Database {
});
});
}

public async deleteChat(userID: string, chatID: string): Promise<any> {
db.serialize(() => {
db.run(`DELETE FROM chats WHERE id = ? AND user_id = ?`, [chatID, userID]);
db.run(`DELETE FROM messages WHERE chat_id = ? AND user_id = ?`, [chatID, userID]);
db.run(`INSERT INTO deleted_chats (id, user_id, deleted_at) VALUES (?, ?, ?)`, [chatID, userID, new Date()]);
console.log(`[database:sqlite] deleted chat ${chatID}`);
});
}

public async getDeletedChatIDs(userID: string): Promise<string[]> {
return new Promise((resolve, reject) => {
db.all(`SELECT * FROM deleted_chats WHERE user_id = ?`, [userID], (err: any, rows: any) => {
if (err) {
reject(err);
} else {
resolve(rows.map((row: any) => row.id));
}
});
});
}
}
13 changes: 13 additions & 0 deletions server/src/endpoints/delete-chat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import express from 'express';
import RequestHandler from "./base";

export default class DeleteChatRequestHandler extends RequestHandler {
async handler(req: express.Request, res: express.Response) {
await this.context.database.deleteChat(this.userID!, req.body.id);
res.json({ status: 'ok' });
}

public isProtected() {
return true;
}
}
Loading

0 comments on commit 1be33f5

Please sign in to comment.