Skip to content

Commit

Permalink
fix(chat): fix decoding url (Issue epam#165, epam#680) (epam#699)
Browse files Browse the repository at this point in the history
  • Loading branch information
IlyaBondar authored Feb 14, 2024
1 parent 2294685 commit aed6f37
Show file tree
Hide file tree
Showing 9 changed files with 83 additions and 84 deletions.
14 changes: 3 additions & 11 deletions apps/chat/src/components/Chatbar/ChatFolders.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,6 @@ export function ChatFolders() {
const isFilterEmpty = useAppSelector(
ConversationsSelectors.selectIsEmptySearchFilter,
);
const searchTerm = useAppSelector(ConversationsSelectors.selectSearchTerm);
const commonItemFilter = useAppSelector(
ConversationsSelectors.selectMyItemsFilters,
);
Expand All @@ -351,15 +350,15 @@ export function ChatFolders() {
filters: PublishedWithMeFilter,
displayRootFiles: true,
dataQa: 'published-with-me',
openByDefault: !!searchTerm.length,
openByDefault: true,
},
{
hidden: !isSharingEnabled || !isFilterEmpty,
name: t('Shared with me'),
filters: SharedWithMeFilter,
displayRootFiles: true,
dataQa: 'shared-with-me',
openByDefault: !!searchTerm.length,
openByDefault: true,
},
{
name: t('Pinned chats'),
Expand All @@ -369,14 +368,7 @@ export function ChatFolders() {
dataQa: 'pinned-chats',
},
].filter(({ hidden }) => !hidden),
[
commonItemFilter,
isFilterEmpty,
isPublishingEnabled,
isSharingEnabled,
searchTerm.length,
t,
],
[commonItemFilter, isFilterEmpty, isPublishingEnabled, isSharingEnabled, t],
);

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,6 @@ export function PromptFolders() {
const isFilterEmpty = useAppSelector(
PromptsSelectors.selectIsEmptySearchFilter,
);
const searchTerm = useAppSelector(PromptsSelectors.selectSearchTerm);
const commonSearchFilter = useAppSelector(
PromptsSelectors.selectMyItemsFilters,
);
Expand All @@ -335,15 +334,15 @@ export function PromptFolders() {
filters: PublishedWithMeFilter,
displayRootFiles: true,
dataQa: 'published-with-me',
openByDefault: !!searchTerm.length,
openByDefault: true,
},
{
hidden: !isSharingEnabled || !isFilterEmpty,
name: t('Shared with me'),
filters: SharedWithMeFilter,
displayRootFiles: true,
dataQa: 'shared-with-me',
openByDefault: !!searchTerm.length,
openByDefault: true,
},
{
name: t('Pinned prompts'),
Expand All @@ -358,7 +357,6 @@ export function PromptFolders() {
isFilterEmpty,
isPublishingEnabled,
isSharingEnabled,
searchTerm.length,
t,
],
);
Expand Down
3 changes: 2 additions & 1 deletion apps/chat/src/pages/api/[entitytype]/listing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { validateServerSession } from '@/src/utils/auth/session';
import { OpenAIError } from '@/src/utils/server';
import {
ApiKeys,
encodeApiUrl,
getEntityTypeFromPath,
isValidEntityApiType,
} from '@/src/utils/server/api';
Expand Down Expand Up @@ -54,7 +55,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {

const url = `${
process.env.DIAL_API_HOST
}/v1/metadata/${path ? `${encodeURI(path)}` : `${entityType}/${bucket}`}/?limit=1000${recursive ? '&recursive=true' : ''}`;
}/v1/metadata/${path ? `${encodeApiUrl(path)}` : `${entityType}/${bucket}`}/?limit=1000${recursive ? '&recursive=true' : ''}`;

const response = await fetch(url, {
headers: getApiHeaders({ jwt: token?.access_token as string }),
Expand Down
88 changes: 37 additions & 51 deletions apps/chat/src/store/conversations/conversations.epics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,9 @@ import { combineEpics } from 'redux-observable';
import { clearStateForMessages } from '@/src/utils/app/clear-messages-state';
import {
combineEntities,
updateEntitiesFoldersAndIds,
} from '@/src/utils/app/common';
import {
filterMigratedEntities,
filterOnlyMyEntities,
updateEntitiesFoldersAndIds,
} from '@/src/utils/app/common';
import {
compareConversationsByDate,
Expand Down Expand Up @@ -161,6 +159,7 @@ const initSelectedConversationsEpic: AppEpic = (action$) =>
}),
switchMap(({ conversations, selectedConversationsIds }) => {
const actions: Observable<AnyAction>[] = [];

if (conversations.length) {
actions.push(
of(
Expand All @@ -170,6 +169,17 @@ const initSelectedConversationsEpic: AppEpic = (action$) =>
}),
),
);
const paths = selectedConversationsIds.flatMap((id) =>
getParentFolderIdsFromEntityId(id),
);
actions.push(
of(
UIActions.setOpenedFoldersIds({
openedFolderIds: paths,
featureType: FeatureType.Chat,
}),
),
);
}
actions.push(
of(
Expand All @@ -178,18 +188,16 @@ const initSelectedConversationsEpic: AppEpic = (action$) =>
}),
),
);
if (!conversations.length || !selectedConversationsIds.length) {
if (!conversations.length) {
actions.push(
of(
ConversationsActions.createNewConversations({
names: [translate(DEFAULT_CONVERSATION_NAME)],
shouldUploadConversationsForCompare: true,
}),
),
);
}
actions.push(
of(ConversationsActions.uploadConversationsWithFoldersRecursive()),
);

return concat(...actions);
}),
Expand All @@ -200,41 +208,9 @@ const initFoldersAndConversationsEpic: AppEpic = (action$) =>
filter((action) =>
ConversationsActions.initFoldersAndConversations.match(action),
),
switchMap(() => ConversationService.getSelectedConversationsIds()),
switchMap((selectedIds) => {
const paths = selectedIds.flatMap((id) =>
getParentFolderIdsFromEntityId(id),
);
const uploadPaths = [undefined, ...paths];
return zip(
uploadPaths.map((path) =>
ConversationService.getConversationsAndFolders(path),
),
).pipe(
switchMap((foldersAndEntities) => {
const folders = foldersAndEntities.flatMap((f) => f.folders);
const conversations = foldersAndEntities.flatMap((f) => f.entities);
return concat(
of(
ConversationsActions.setFolders({
folders,
}),
),
of(
ConversationsActions.setConversations({
conversations,
}),
),
of(
UIActions.setOpenedFoldersIds({
openedFolderIds: paths,
featureType: FeatureType.Chat,
}),
),
);
}),
);
}),
switchMap(() =>
of(ConversationsActions.uploadConversationsWithFoldersRecursive()),
),
);

const createNewConversationsEpic: AppEpic = (action$, state$) =>
Expand All @@ -246,16 +222,26 @@ const createNewConversationsEpic: AppEpic = (action$, state$) =>
state$.value,
),
conversations: ConversationsSelectors.selectConversations(state$.value),
shouldUploadConversationsForCompare:
payload.shouldUploadConversationsForCompare,
})),
switchMap(({ names, lastConversation, conversations }) =>
forkJoin({
names: of(names),
lastConversation:
lastConversation && lastConversation.status !== UploadStatus.LOADED
? ConversationService.getConversation(lastConversation)
: (of(lastConversation) as Observable<Conversation>),
conversations: of(conversations),
}),
switchMap(
({
names,
lastConversation,
conversations,
shouldUploadConversationsForCompare,
}) =>
forkJoin({
names: of(names),
lastConversation:
lastConversation && lastConversation.status !== UploadStatus.LOADED
? ConversationService.getConversation(lastConversation)
: (of(lastConversation) as Observable<Conversation>),
conversations: shouldUploadConversationsForCompare
? ConversationService.getConversations()
: of(conversations),
}),
),
switchMap(({ names, lastConversation, conversations }) => {
return state$.pipe(
Expand Down
9 changes: 8 additions & 1 deletion apps/chat/src/store/conversations/conversations.reducers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,10 @@ export const conversationsSlice = createSlice({
},
createNewConversations: (
state,
_action: PayloadAction<{ names: string[] }>,
_action: PayloadAction<{
names: string[];
shouldUploadConversationsForCompare?: boolean;
}>,
) => state,
publishConversation: (
state,
Expand Down Expand Up @@ -265,6 +268,7 @@ export const conversationsSlice = createSlice({
) => {
state.conversations = state.conversations.concat(newConversation);
state.selectedConversationsIds = [newConversation.id];
state.areSelectedConversationsLoaded = true;
},
createNewPlaybackConversation: (
state,
Expand Down Expand Up @@ -621,6 +625,9 @@ export const conversationsSlice = createSlice({
}
: f,
);
if (payload.allLoaded) {
state.conversationsLoaded = true;
}
state.foldersStatus = payload.allLoaded
? UploadStatus.ALL_LOADED
: UploadStatus.LOADED;
Expand Down
25 changes: 18 additions & 7 deletions apps/chat/src/utils/app/data/file-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ import {
} from '@/src/types/files';
import { FolderType } from '@/src/types/folder';

import { ApiKeys, ApiUtils } from '../../server/api';
import {
ApiKeys,
ApiUtils,
decodeApiUrl,
encodeApiUrl,
} from '../../server/api';
import { constructPath } from '../file';
import { getRootId } from '../id';
import { BucketService } from './bucket-service';
Expand All @@ -20,7 +25,7 @@ export class FileService {
relativePath: string | undefined,
fileName: string,
): Observable<{ percent?: number; result?: DialFile }> {
const resultPath = encodeURI(
const resultPath = encodeApiUrl(
constructPath(BucketService.getBucket(), relativePath, fileName),
);

Expand All @@ -47,11 +52,13 @@ export class FileService {
}

const typedResult = result as BackendFile;
const relativePath = typedResult.parentPath || undefined;
const relativePath = typedResult.parentPath
? decodeApiUrl(typedResult.parentPath)
: undefined;

return {
result: {
id: decodeURI(typedResult.url),
id: decodeApiUrl(typedResult.url),
name: typedResult.name,
absolutePath: constructPath(
ApiKeys.Files,
Expand Down Expand Up @@ -91,7 +98,9 @@ export class FileService {
return ApiUtils.request(`api/${ApiKeys.Files}/listing?${resultQuery}`).pipe(
map((folders: BackendFileFolder[]) => {
return folders.map((folder): FileFolderInterface => {
const relativePath = folder.parentPath || undefined;
const relativePath = folder.parentPath
? decodeApiUrl(folder.parentPath)
: undefined;

return {
id: constructPath(
Expand Down Expand Up @@ -120,7 +129,7 @@ export class FileService {
}

public static removeFile(filePath: string): Observable<void> {
const resultPath = encodeURI(
const resultPath = encodeApiUrl(
constructPath(BucketService.getBucket(), filePath),
);

Expand All @@ -147,7 +156,9 @@ export class FileService {
return ApiUtils.request(`api/${ApiKeys.Files}/listing?${resultQuery}`).pipe(
map((files: BackendFile[]) => {
return files.map((file): DialFile => {
const relativePath = file.parentPath || undefined;
const relativePath = file.parentPath
? decodeApiUrl(file.parentPath)
: undefined;

return {
id: constructPath(
Expand Down
13 changes: 6 additions & 7 deletions apps/chat/src/utils/app/data/storages/api/api-entity-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { EMPTY, Observable, catchError, map, of } from 'rxjs';
import {
ApiKeys,
ApiUtils,
decodeApiUrl,
encodeApiUrl,
getFolderTypeByApiKey,
} from '@/src/utils/server/api';

Expand All @@ -26,7 +28,7 @@ export abstract class ApiEntityStorage<
> implements EntityStorage<TEntityInfo, TEntity>
{
private mapFolder(folder: BackendChatFolder): FolderInterface {
const id = decodeURI(folder.url.slice(0, folder.url.length - 1));
const id = decodeApiUrl(folder.url.slice(0, folder.url.length - 1));
const { apiKey, bucket, parentPath } = splitEntityId(id);

return {
Expand All @@ -39,7 +41,7 @@ export abstract class ApiEntityStorage<

private mapEntity(entity: BackendChatEntity): TEntityInfo {
const info = this.parseEntityKey(entity.name);
const id = decodeURI(entity.url);
const id = decodeApiUrl(entity.url);
const { apiKey, bucket, parentPath } = splitEntityId(id);

return {
Expand All @@ -50,14 +52,11 @@ export abstract class ApiEntityStorage<
} as unknown as TEntityInfo;
}

private encodePath = (path: string): string =>
constructPath(...path.split('/').map((part) => encodeURIComponent(part)));

private getEntityUrl = (entity: TEntityInfo): string =>
this.encodePath(constructPath('api', entity.id));
encodeApiUrl(constructPath('api', entity.id));

private getListingUrl = (resultQuery: string): string => {
const listingUrl = this.encodePath(
const listingUrl = encodeApiUrl(
constructPath('api', this.getStorageKey(), 'listing'),
);
return `${listingUrl}?${resultQuery}`;
Expand Down
3 changes: 1 addition & 2 deletions apps/chat/src/utils/app/folders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,8 +418,7 @@ export const getParentFolderIdsFromFolderId = (path?: string): string[] => {
};

export const getParentFolderIdsFromEntityId = (id: string): string[] => {
const { parentPath } = splitEntityId(id);
return getParentFolderIdsFromFolderId(parentPath);
return getParentFolderIdsFromFolderId(id);
};

export const getFolderFromId = (
Expand Down
Loading

0 comments on commit aed6f37

Please sign in to comment.