potree_build/src/api/pocketbase.ts
2025-07-30 14:09:58 +07:00

463 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Модуль для работы с PocketBase API
interface PocketBaseAuthResponse {
token: string;
record: {
collectionId: string;
collectionName: string;
id: string;
email: string;
emailVisibility: boolean;
verified: boolean;
name: string;
avatar?: string;
created: string;
updated: string;
};
}
interface PocketBaseErrorResponse {
status: number;
message: string;
data?: {
[key: string]: {
code: string;
message: string;
};
};
}
interface PocketBaseCreateUserRequest {
email: string;
password: string;
passwordConfirm: string;
name?: string;
emailVisibility?: boolean;
}
interface PocketBaseCreateUserResponse {
collectionId: string;
collectionName: string;
id: string;
email: string;
emailVisibility: boolean;
verified: boolean;
name: string;
avatar?: string;
created: string;
updated: string;
}
interface ModelViewerSettings {
pointSize: number;
pointBudget: number;
fov: number;
edlEnabled: boolean;
edlRadius: number;
edlStrength: number;
pointSizeType: string;
pointShape: string;
pointColorType: string;
showBoundingBox: boolean;
classifications: Record<string, any>;
returnNumberRange: number[];
numberOfReturnsRange: number[];
gpsTimeRange: number[];
clipTask: number;
clipMethod: number;
}
interface UserModelSettings {
id?: string;
userId: string;
modelId: string;
settings: ModelViewerSettings;
created?: string;
updated?: string;
}
interface UserModelSettingsCreateRequest {
userId: string;
modelId: string;
settings: ModelViewerSettings;
}
interface UserModelSettingsUpdateRequest {
settings: ModelViewerSettings;
}
class PocketBaseClient {
private baseUrl: string;
private authStore: {
token: string | null;
record: any;
isValid: boolean;
} = {
token: null,
record: null,
isValid: false
};
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
/**
* Авторизация пользователя по email и паролю
*/
async authWithPassword(email: string, password: string): Promise<PocketBaseAuthResponse> {
try {
const url = `${this.baseUrl}/api/collections/users/auth-with-password`;
const requestBody = {
identity: email,
password: password
};
console.log('PocketBase авторизация:', {
url,
body: requestBody
});
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody)
});
console.log('PocketBase ответ:', {
status: response.status,
statusText: response.statusText,
url: response.url
});
const data = await response.json();
console.log('PocketBase данные:', data);
if (!response.ok) {
const errorData = data as PocketBaseErrorResponse;
throw new Error(errorData.message || 'Ошибка авторизации');
}
const authData = data as PocketBaseAuthResponse;
// Сохраняем данные авторизации в authStore
this.authStore.token = authData.token;
this.authStore.record = authData.record;
this.authStore.isValid = true;
console.log('PocketBase авторизация успешна:', {
userId: authData.record.id,
email: authData.record.email
});
return authData;
} catch (error) {
console.error('Ошибка авторизации PocketBase:', error);
// Очищаем authStore при ошибке
this.authStore.token = null;
this.authStore.record = null;
this.authStore.isValid = false;
throw error;
}
}
/**
* Проверка валидности токена
*/
async verifyToken(token: string): Promise<boolean> {
try {
const response = await fetch(`${this.baseUrl}/api/collections/users/auth-refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
const data = await response.json();
this.authStore.token = data.token;
this.authStore.record = data.record;
this.authStore.isValid = true;
return true;
}
return false;
} catch (error) {
console.error('Ошибка проверки токена:', error);
return false;
}
}
/**
* Получение информации о пользователе по токену
*/
async getUserInfo(token: string): Promise<any> {
try {
const response = await fetch(`${this.baseUrl}/api/collections/users/auth-refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
const data = await response.json();
return data.record;
}
return null;
} catch (error) {
console.error('Ошибка получения информации о пользователе:', error);
return null;
}
}
/**
* Очистка данных авторизации
*/
clearAuth(): void {
this.authStore.token = null;
this.authStore.record = null;
this.authStore.isValid = false;
}
/**
* Регистрация нового пользователя
*/
async createUser(userData: PocketBaseCreateUserRequest): Promise<PocketBaseCreateUserResponse> {
try {
const url = `${this.baseUrl}/api/collections/users/records`;
console.log('PocketBase регистрация пользователя:', {
url,
userData: { ...userData, password: '[HIDDEN]', passwordConfirm: '[HIDDEN]' }
});
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
console.log('PocketBase ответ на регистрацию:', {
status: response.status,
statusText: response.statusText,
url: response.url
});
const data = await response.json();
console.log('PocketBase данные регистрации:', data);
if (!response.ok) {
const errorData = data as PocketBaseErrorResponse;
throw new Error(errorData.message || 'Ошибка регистрации');
}
const userData_created = data as PocketBaseCreateUserResponse;
console.log('PocketBase регистрация успешна:', {
userId: userData_created.id,
email: userData_created.email,
name: userData_created.name
});
return userData_created;
} catch (error) {
console.error('Ошибка регистрации в PocketBase:', error);
throw error;
}
}
/**
* Получение текущего токена
*/
getToken(): string | null {
return this.authStore.token;
}
/**
* Получение текущего пользователя
*/
getCurrentUser(): any {
return this.authStore.record;
}
/**
* Проверка валидности авторизации
*/
isAuthenticated(): boolean {
return this.authStore.isValid && this.authStore.token !== null;
}
/**
* Получение настроек просмотра модели для пользователя
*/
async getUserModelSettings(userId: string, modelId: string): Promise<UserModelSettings | null> {
try {
console.log('Получение настроек модели:', { userId, modelId });
const filter = `userId="${userId}" && modelId="${modelId}"`;
const response = await fetch(`${this.baseUrl}/api/collections/user_model_settings/records?filter=${encodeURIComponent(filter)}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.authStore.token}`,
'Content-Type': 'application/json'
}
});
console.log('Response настроек модели:', {
status: response.status,
statusText: response.statusText,
url: response.url
});
if (!response.ok) {
console.warn('Настройки модели не найдены:', response.status);
return null;
}
const data = await response.json();
console.log('Данные настроек модели:', data);
if (data.items && data.items.length > 0) {
return data.items[0] as UserModelSettings;
}
return null;
} catch (error) {
console.error('Ошибка получения настроек модели:', error);
return null;
}
}
/**
* Сохранение настроек просмотра модели для пользователя
*/
async saveUserModelSettings(userId: string, modelId: string, settings: ModelViewerSettings): Promise<UserModelSettings> {
try {
console.log('Сохранение настроек модели:', { userId, modelId, settings });
// Сначала проверяем, есть ли уже настройки для этой модели
const existingSettings = await this.getUserModelSettings(userId, modelId);
if (existingSettings) {
// Обновляем существующие настройки
const updateData: UserModelSettingsUpdateRequest = { settings };
const response = await fetch(`${this.baseUrl}/api/collections/user_model_settings/records/${existingSettings.id}`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${this.authStore.token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(updateData)
});
if (!response.ok) {
const errorData = await response.json() as PocketBaseErrorResponse;
throw new Error(errorData.message || 'Ошибка обновления настроек');
}
const updatedSettings = await response.json() as UserModelSettings;
console.log('Настройки модели обновлены:', updatedSettings);
return updatedSettings;
} else {
// Создаем новые настройки
const createData: UserModelSettingsCreateRequest = { userId, modelId, settings };
const response = await fetch(`${this.baseUrl}/api/collections/user_model_settings/records`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.authStore.token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(createData)
});
if (!response.ok) {
const errorData = await response.json() as PocketBaseErrorResponse;
throw new Error(errorData.message || 'Ошибка сохранения настроек');
}
const newSettings = await response.json() as UserModelSettings;
console.log('Настройки модели созданы:', newSettings);
return newSettings;
}
} catch (error) {
console.error('Ошибка сохранения настроек модели:', error);
throw error;
}
}
/**
* Удаление настроек просмотра модели для пользователя (сброс к умолчанию)
*/
async deleteUserModelSettings(userId: string, modelId: string): Promise<boolean> {
try {
console.log('Удаление настроек модели:', { userId, modelId });
const existingSettings = await this.getUserModelSettings(userId, modelId);
if (!existingSettings) {
console.log('Настройки модели не найдены для удаления');
return true;
}
const response = await fetch(`${this.baseUrl}/api/collections/user_model_settings/records/${existingSettings.id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${this.authStore.token}`
}
});
if (!response.ok) {
const errorData = await response.json() as PocketBaseErrorResponse;
throw new Error(errorData.message || 'Ошибка удаления настроек');
}
console.log('Настройки модели удалены');
return true;
} catch (error) {
console.error('Ошибка удаления настроек модели:', error);
return false;
}
}
}
// Создаем экземпляр клиента PocketBase
const getPocketBaseUrl = (): string => {
const isClient = typeof window !== 'undefined';
let url: string;
if (isClient) {
// На клиенте (браузер) используем localhost для разработки
url = 'http://localhost:5174';
} else {
// На сервере используем URL из переменной окружения (внутри контейнера)
url = process.env.POCKETBASE_URL || 'http://pocketbase:8080';
}
console.log('PocketBase URL определен:', {
isClient,
url,
processEnv: process.env.POCKETBASE_URL
});
return url;
};
export const pocketBaseClient = new PocketBaseClient(getPocketBaseUrl());
export type {
PocketBaseAuthResponse,
PocketBaseErrorResponse,
ModelViewerSettings,
UserModelSettings,
UserModelSettingsCreateRequest,
UserModelSettingsUpdateRequest
};