LibreChat/packages/data-provider/src/data-service.ts
Danny Avila f0e8cca5df
🚀 feat: Shared Links (#2772)
*  feat(types): add necessary types for shared link feature

*  feat: add shared links functions to data service

Added functions for retrieving, creating, updating, and deleting shared links and shared messages.

*  feat: Add useGetSharedMessages hook to fetch shared messages by shareId

Adds a new hook `useGetSharedMessages` which fetches shared messages based on the provided shareId.

*  feat: Add share schema and data access functions to API models

*  feat: Add share endpoint to API

The GET /api/share/${shareId} is exposed to the public, so authentication is not required. Other paths require authentication.

* ♻️ refactor(utils): generalize react-query cache manipulation functions

Introduces generic functions for manipulating react-query cache entries, marking a refinement in how query cache data is managed. It aims to enhance the flexibility and reusability of the cache interaction patterns within our application.

- Replaced specific index names with more generic terms in queries.ts, enhancing consistency across data handling functions.
- Introduced new utility functions in collection.ts for adding, updating, and deleting data entries in an InfiniteData<TCollection>. These utility functions (`addData`, `updateData`, `deleteData`, `findPage`) are designed to be re-usable across different data types and collections.
- Adapted existing conversation utility functions in convos.ts to leverage these new generic utilities.

*  feat(shared-link): add functions to manipulate shared link cache list

implemented new utility functions to handle additions, updates, and deletions in the shared link cache list.

*  feat: Add mutations and queries for shared links

*  feat(shared-link): add `Share` button to conversation list

- Added a share button in each conversation in the conversation list.
- Implemented functionality where clicking the share button triggers a POST request to the API.
- The API checks if a share link was already created for the conversation today; if so, it returns the existing link.
- If no link was created for today, the API will create a new share link and return it.
- Each click on the share button results in a new API request, following the specification similar to ChatGPT's share link feature.

* ♻️ refactor(hooks): generalize useNavScrolling for broader use

- Modified `useNavScrolling` to accept a generic type parameter `TData`, allowing it to be used with different data structures besides `ConversationListResponse`.
- Updated instances in `Nav.tsx` and `ArchivedChatsTable.tsx` to explicitly specify `ConversationListResponse` as the type argument when invoking `useNavScrolling`.

*  feat(settings): add shared links listing table with delete functionality in settings

- Integrated a delete button for each shared link in the table, allowing users to remove links as needed.

* ♻️ refactor(components): separate `EndpointIcon` from `Icon` component for standalone use

* ♻️ refactor: update useGetSharedMessages to return TSharedLink

- Modified the useGetSharedMessages hook to return not only a list of TMessage but also the TSharedLink itself.
- This change was necessary to support displaying the title and date in the Shared Message UI, which requires data from TSharedLink.

*  feat(shared link): add UI for displaying shared conversations without authentication

- Implemented a new UI component to display shared conversations, designed to be accessible without requiring authentication.
- Reused components from the authenticated Messages module where possible. Copied and adapted components that could not be directly reused to fit the non-authenticated context.

* 🔧 chore: Add translations

Translate labels only. Messages remain in English as they are possibly subject to change.

* ♻️ refactor: add icon and tooltip props to EditMenuButton component

* moved icon and popover to arguments so that EditMenuButton can be reused.
* modified so that when a ShareButton is closed, the parent DropdownMenu is also closed.

* ♻️irefactor: added DropdownMenu for Export and Share

* ♻️ refactor: renamed component names more intuitive

* More accurate naming of the dropdown menu.
* When the export button is closed, the parent dropdown menu is also closed.

* 🌍 chore: updated translations

* 🐞 Fix: OpenID Profile Image Download (#2757)

* Add fetch requirement

Fixes - error: [openidStrategy] downloadImage: Error downloading image at URL "https://graph.microsoft.com/v1.0/me/photo/$value": TypeError: response.buffer is not a function

* Update openidStrategy.js

---------

Co-authored-by: Danny Avila <danacordially@gmail.com>

* 🚑 fix(export): Issue exporting Conversation with Assistants (#2769)

* 🚑 fix(export): use content as text if content is present in the message

If the endpoint is assistants, the text of the message goes into content, not message.text.

* refactor(ExportModel): TypeScript, remove unused code

---------

Co-authored-by: Yuichi Ohneda <ohneda@gmail.com>

* 📤style: export button icon (#2752)

* refactor(ShareDialog): logic and styling

* refactor(ExportAndShareMenu): imports order and icon update

* chore: imports

* chore: imports/render logic

* feat: message branching

* refactor: add optional config to useGetStartupConfig

* refactor: disable endpoints query

* chore: fix search view styling gradient in light mode

* style: ShareView gradient styling

* refactor(Share): use select queries

* style: shared link table buttons

* localization and dark text styling

* style: fix clipboard button layout shift app-wide and add localization for copy code

* support assistants message content in shared links, add useCopyToClipboard, add copy buttons to Search Messages and Shared Link Messages

* add localizations

* comparisons

---------

Co-authored-by: Yuichi Ohneda <ohneda@gmail.com>
Co-authored-by: bsu3338 <bsu3338@users.noreply.github.com>
Co-authored-by: Fuegovic <32828263+fuegovic@users.noreply.github.com>
2024-05-17 18:13:32 -04:00

356 lines
11 KiB
TypeScript

import * as f from './types/files';
import * as q from './types/queries';
import * as m from './types/mutations';
import * as a from './types/assistants';
import * as t from './types';
import * as s from './schemas';
import request from './request';
import * as endpoints from './api-endpoints';
import type { AxiosResponse } from 'axios';
export function abortRequestWithMessage(
endpoint: string,
abortKey: string,
message: string,
): Promise<void> {
return request.post(endpoints.abortRequest(endpoint), { arg: { abortKey, message } });
}
export function revokeUserKey(name: string): Promise<unknown> {
return request.delete(endpoints.revokeUserKey(name));
}
export function revokeAllUserKeys(): Promise<unknown> {
return request.delete(endpoints.revokeAllUserKeys());
}
export function getMessagesByConvoId(conversationId: string): Promise<s.TMessage[]> {
if (conversationId === 'new') {
return Promise.resolve([]);
}
return request.get(endpoints.messages(conversationId));
}
export function getSharedMessages(shareId: string): Promise<t.TSharedMessagesResponse> {
return request.get(endpoints.shareMessages(shareId));
}
export const listSharedLinks = (
params?: q.SharedLinkListParams,
): Promise<q.SharedLinksResponse> => {
const pageNumber = params?.pageNumber || '1'; // Default to page 1 if not provided
const isPublic = params?.isPublic || true; // Default to true if not provided
return request.get(endpoints.getSharedLinks(pageNumber, isPublic));
};
export function getSharedLink(shareId: string): Promise<t.TSharedLinkResponse> {
return request.get(endpoints.shareMessages(shareId));
}
export function createSharedLink(payload: t.TSharedLinkRequest): Promise<t.TSharedLinkResponse> {
return request.post(endpoints.createSharedLink, payload);
}
export function updateSharedLink(payload: t.TSharedLinkRequest): Promise<t.TSharedLinkResponse> {
return request.patch(endpoints.updateSharedLink, payload);
}
export function deleteSharedLink(shareId: string): Promise<t.TDeleteSharedLinkResponse> {
return request.delete(endpoints.shareMessages(shareId));
}
export function updateMessage(payload: t.TUpdateMessageRequest): Promise<unknown> {
const { conversationId, messageId, text } = payload;
if (!conversationId) {
throw new Error('conversationId is required');
}
return request.put(endpoints.messages(conversationId, messageId), { text });
}
export function updateUserKey(payload: t.TUpdateUserKeyRequest) {
const { value } = payload;
if (!value) {
throw new Error('value is required');
}
return request.put(endpoints.keys(), payload);
}
export function getPresets(): Promise<s.TPreset[]> {
return request.get(endpoints.presets());
}
export function createPreset(payload: s.TPreset): Promise<s.TPreset> {
return request.post(endpoints.presets(), payload);
}
export function updatePreset(payload: s.TPreset): Promise<s.TPreset> {
return request.post(endpoints.presets(), payload);
}
export function deletePreset(arg: s.TPreset | undefined): Promise<m.PresetDeleteResponse> {
return request.post(endpoints.deletePreset(), arg);
}
export function getSearchEnabled(): Promise<boolean> {
return request.get(endpoints.searchEnabled());
}
export function getUser(): Promise<t.TUser> {
return request.get(endpoints.user());
}
export function getUserBalance(): Promise<string> {
return request.get(endpoints.balance());
}
export const updateTokenCount = (text: string) => {
return request.post(endpoints.tokenizer(), { arg: text });
};
export const login = (payload: t.TLoginUser) => {
return request.post(endpoints.login(), payload);
};
export const logout = () => {
return request.post(endpoints.logout());
};
export const register = (payload: t.TRegisterUser) => {
return request.post(endpoints.register(), payload);
};
export const userKeyQuery = (name: string): Promise<t.TCheckUserKeyResponse> =>
request.get(endpoints.userKeyQuery(name));
export const getLoginGoogle = () => {
return request.get(endpoints.loginGoogle());
};
export const requestPasswordReset = (
payload: t.TRequestPasswordReset,
): Promise<t.TRequestPasswordResetResponse> => {
return request.post(endpoints.requestPasswordReset(), payload);
};
export const resetPassword = (payload: t.TResetPassword) => {
return request.post(endpoints.resetPassword(), payload);
};
export const getAvailablePlugins = (): Promise<s.TPlugin[]> => {
return request.get(endpoints.plugins());
};
export const updateUserPlugins = (payload: t.TUpdateUserPlugins) => {
return request.post(endpoints.userPlugins(), payload);
};
/* Config */
export const getStartupConfig = (): Promise<t.TStartupConfig> => {
return request.get(endpoints.config());
};
export const getAIEndpoints = (): Promise<t.TEndpointsConfig> => {
return request.get(endpoints.aiEndpoints());
};
export const getModels = async (): Promise<t.TModelsConfig> => {
return request.get(endpoints.models());
};
export const getEndpointsConfigOverride = (): Promise<unknown | boolean> => {
return request.get(endpoints.endpointsConfigOverride());
};
/* Assistants */
export const createAssistant = (data: a.AssistantCreateParams): Promise<a.Assistant> => {
return request.post(endpoints.assistants(), data);
};
export const getAssistantById = (assistant_id: string): Promise<a.Assistant> => {
return request.get(endpoints.assistants(assistant_id));
};
export const updateAssistant = (
assistant_id: string,
data: a.AssistantUpdateParams,
): Promise<a.Assistant> => {
return request.patch(endpoints.assistants(assistant_id), data);
};
export const deleteAssistant = (assistant_id: string, model: string): Promise<void> => {
return request.delete(endpoints.assistants(assistant_id, { model }));
};
export const listAssistants = (
params?: a.AssistantListParams,
): Promise<a.AssistantListResponse> => {
return request.get(endpoints.assistants(), { params });
};
export function getAssistantDocs(): Promise<a.AssistantDocument[]> {
return request.get(endpoints.assistants('documents'));
}
/* Tools */
export const getAvailableTools = (): Promise<s.TPlugin[]> => {
return request.get(`${endpoints.assistants()}/tools`);
};
/* Files */
export const getFiles = (): Promise<f.TFile[]> => {
return request.get(endpoints.files());
};
export const getFileConfig = (): Promise<f.FileConfig> => {
return request.get(`${endpoints.files()}/config`);
};
export const uploadImage = (data: FormData): Promise<f.TFileUpload> => {
return request.postMultiPart(endpoints.images(), data);
};
export const uploadFile = (data: FormData): Promise<f.TFileUpload> => {
return request.postMultiPart(endpoints.files(), data);
};
/**
* Imports a conversations file.
*
* @param data - The FormData containing the file to import.
* @returns A Promise that resolves to the import start response.
*/
export const importConversationsFile = (data: FormData): Promise<t.TImportStartResponse> => {
return request.postMultiPart(endpoints.importConversation(), data);
};
/**
* Retrieves the status of an import conversation job.
*
* @param jobId - The ID of the import conversation job.
* @returns A promise that resolves to the import job status.
*/
export const queryImportConversationJobStatus = async (
jobId: string,
): Promise<t.TImportJobStatus> => {
return request.get(endpoints.importConversationJobStatus(jobId));
};
export const uploadAvatar = (data: FormData): Promise<f.AvatarUploadResponse> => {
return request.postMultiPart(endpoints.avatar(), data);
};
export const uploadAssistantAvatar = (data: m.AssistantAvatarVariables): Promise<a.Assistant> => {
return request.postMultiPart(
endpoints.assistants(`avatar/${data.assistant_id}`, { model: data.model }),
data.formData,
);
};
export const getFileDownload = async (userId: string, file_id: string): Promise<AxiosResponse> => {
return request.getResponse(`${endpoints.files()}/download/${userId}/${file_id}`, {
responseType: 'blob',
headers: {
Accept: 'application/octet-stream',
},
});
};
export const deleteFiles = async (
files: f.BatchFile[],
assistant_id?: string,
): Promise<f.DeleteFilesResponse> =>
request.deleteWithOptions(endpoints.files(), {
data: { files, assistant_id },
});
/* actions */
export const updateAction = (data: m.UpdateActionVariables): Promise<m.UpdateActionResponse> => {
const { assistant_id, ...body } = data;
return request.post(endpoints.assistants(`actions/${assistant_id}`), body);
};
export function getActions(): Promise<a.Action[]> {
return request.get(endpoints.assistants('actions'));
}
export const deleteAction = async (
assistant_id: string,
action_id: string,
model: string,
): Promise<void> =>
request.delete(endpoints.assistants(`actions/${assistant_id}/${action_id}/${model}`));
/* conversations */
export function forkConversation(payload: t.TForkConvoRequest): Promise<t.TForkConvoResponse> {
return request.post(endpoints.forkConversation(), payload);
}
export function deleteConversation(payload: t.TDeleteConversationRequest) {
//todo: this should be a DELETE request
return request.post(endpoints.deleteConversation(), { arg: payload });
}
export function clearAllConversations(): Promise<unknown> {
return request.post(endpoints.deleteConversation(), { arg: {} });
}
export const listConversations = (
params?: q.ConversationListParams,
): Promise<q.ConversationListResponse> => {
// Assuming params has a pageNumber property
const pageNumber = params?.pageNumber || '1'; // Default to page 1 if not provided
const isArchived = params?.isArchived || false; // Default to false if not provided
return request.get(endpoints.conversations(pageNumber, isArchived));
};
export const listConversationsByQuery = (
params?: q.ConversationListParams & { searchQuery?: string },
): Promise<q.ConversationListResponse> => {
const pageNumber = params?.pageNumber || '1'; // Default to page 1 if not provided
const searchQuery = params?.searchQuery || ''; // If no search query is provided, default to an empty string
// Update the endpoint to handle a search query
if (searchQuery !== '') {
return request.get(endpoints.search(searchQuery, pageNumber));
} else {
return request.get(endpoints.conversations(pageNumber));
}
};
export const searchConversations = async (
q: string,
pageNumber: string,
): Promise<t.TSearchResults> => {
return request.get(endpoints.search(q, pageNumber));
};
export function getConversations(pageNumber: string): Promise<t.TGetConversationsResponse> {
return request.get(endpoints.conversations(pageNumber));
}
export function getConversationById(id: string): Promise<s.TConversation> {
return request.get(endpoints.conversationById(id));
}
export function updateConversation(
payload: t.TUpdateConversationRequest,
): Promise<t.TUpdateConversationResponse> {
return request.post(endpoints.updateConversation(), { arg: payload });
}
export function archiveConversation(
payload: t.TArchiveConversationRequest,
): Promise<t.TArchiveConversationResponse> {
return request.post(endpoints.updateConversation(), { arg: payload });
}
export function genTitle(payload: m.TGenTitleRequest): Promise<m.TGenTitleResponse> {
return request.post(endpoints.genTitle(), payload);
}