All files / src/services eventService.ts

68.91% Statements 153/222
69.91% Branches 79/113
46.42% Functions 26/56
68.06% Lines 130/191

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 64016x 16x                                                                     16x                                     8x               8x 8x 8x 40x 40x 18x 18x 16x 16x   8x                                         16x             16x         1x     16x                             16x             16x                     16x                     16x                     16x                 16x             16x               16x             16x                       16x                       16x             16x       1x             16x             16x               16x                         16x     13x   11x             11x 11x   1x     10x   9x 9x   7x   9x 9x 7x 7x   6x 6x   5x           9x     16x       9x   7x             7x 7x   1x     6x   5x 5x   2x 2x     2x 2x 2x 2x   1x             16x                                 16x     13x 23x 1x     21x   10x       10x 10x   2x   8x   7x 7x 5x 5x   3x 3x 9x 9x 9x 8x   3x     16x                         16x                     16x                     16x                       16x           3x 3x         1x     2x           2x 1x       16x                                                                                                                     5x           5x             5x   5x 5x     5x 1x     4x             5x 5x   5x                             16x 2x 8x     8x           2x             2x 2x 2x   2x   2x           2x 4x 3x 3x   2x           16x               16x                    
import { apiGet, apiGetAuth, apiPostAuth, apiPatchAuth, apiPutAuth, apiDeleteAuth } from '@/services/api';
import * as FileSystem from 'expo-file-system/legacy';
import {
  PrivacyLevel,
  CreateEventRequest,
  CreateEventResponse,
  UpdateEventRequest,
  UpdateEventResponse,
  EventDetail,
  EventHostContextSummary,
  JoinEventResponse,
  LeaveEventResponse,
  LocationSuggestion,
  ListEventsQuery,
  ListCategoriesResponse,
  MyEventRelation,
  MyEventStatus,
  type MyEventSummary,
  type MyEventsResponse,
  PaginatedEventsResponse,
  RequestJoinRequest,
  RequestJoinResponse,
  ReconfirmParticipationResponse,
  ImageUploadInitResponse,
  EventApprovedParticipantsResponse,
  EventPendingJoinRequestsResponse,
  EventInvitationsResponse,
  RatingWriteRequest,
  RatingResponse,
  EventReportCategory,
  RequestReportEvent,
  ReportEventResponse,
} from '@/models/event';
import { shouldShowProfileEvent } from '@/utils/eventStatus';
 
 
const PHOTON_BASE = 'https://photon.komoot.io';
type SupportedUploadMethod = 'POST' | 'PUT' | 'PATCH';
 
interface PhotonProperties {
  name?: string;
  street?: string;
  housenumber?: string;
  district?: string;
  city?: string;
  state?: string;
  country?: string;
}
 
interface PhotonFeature {
  geometry?: { coordinates?: [number, number] };
  properties?: PhotonProperties;
}
 
function buildPhotonDisplayName(props: PhotonProperties): string {
  const parts = [
    [props.name, props.street && props.housenumber ? `${props.street} ${props.housenumber}` : props.street].filter(Boolean).join(' '),
    props.district,
    props.city,
    props.state,
    props.country,
  ];
 
  const seen = new Set<string>();
  const deduped: string[] = [];
  for (const part of parts) {
    const value = (part ?? '').trim();
    if (!value) continue;
    const key = value.toLowerCase();
    if (seen.has(key)) continue;
    seen.add(key);
    deduped.push(value);
  }
  return deduped.join(', ');
}
 
interface BackendEventSummary {
  id: string;
  title: string;
  start_time: string;
  end_time?: string | null;
  status: string;
  category?: string | null;
  image_url?: string | null;
  participants_count?: number | null;
  location_address?: string | null;
  privacy_level: PrivacyLevel;
}
 
interface BackendEventsListResponse {
  events: BackendEventSummary[];
}
 
 
export async function createEvent(
  request: CreateEventRequest,
  token: string,
): Promise<CreateEventResponse> {
  return apiPostAuth<CreateEventResponse>('/events', request, token);
}
 
export async function updateEvent(
  id: string,
  request: UpdateEventRequest,
  token: string,
): Promise<UpdateEventResponse> {
  return apiPatchAuth<UpdateEventResponse>(`/events/${id}`, request, token);
}
 
export async function getEventDetail(
  id: string,
  token: string,
): Promise<EventDetail> {
  return apiGetAuth<EventDetail>(`/events/${id}`, token);
}
 
function buildCollectionPath(id: string, resource: string, limit?: number, cursor?: string | null) {
  const params = new URLSearchParams();
  Iif (limit != null) params.set('limit', String(limit));
  Iif (cursor) params.set('cursor', cursor);
  const query = params.toString();
  return query === '' ? `/events/${id}/${resource}` : `/events/${id}/${resource}?${query}`;
}
 
export async function getEventHostContextSummary(
  id: string,
  token: string,
): Promise<EventHostContextSummary> {
  return apiGetAuth<EventHostContextSummary>(`/events/${id}/host-context`, token);
}
 
export async function listEventApprovedParticipants(
  id: string,
  token: string,
  options: { limit?: number; cursor?: string | null } = {},
): Promise<EventApprovedParticipantsResponse> {
  return apiGetAuth<EventApprovedParticipantsResponse>(
    buildCollectionPath(id, 'participants', options.limit, options.cursor),
    token,
  );
}
 
export async function listEventPendingJoinRequests(
  id: string,
  token: string,
  options: { limit?: number; cursor?: string | null } = {},
): Promise<EventPendingJoinRequestsResponse> {
  return apiGetAuth<EventPendingJoinRequestsResponse>(
    buildCollectionPath(id, 'join-requests', options.limit, options.cursor),
    token,
  );
}
 
export async function listEventInvitations(
  id: string,
  token: string,
  options: { limit?: number; cursor?: string | null } = {},
): Promise<EventInvitationsResponse> {
  return apiGetAuth<EventInvitationsResponse>(
    buildCollectionPath(id, 'invitations', options.limit, options.cursor),
    token,
  );
}
 
export async function createEventInvitations(
  id: string,
  usernames: string[],
  token: string,
  message?: string,
): Promise<any> {
  return apiPostAuth<any>(`/events/${id}/invitations`, { usernames, message }, token);
}
 
export async function joinEvent(
  id: string,
  token: string,
): Promise<JoinEventResponse> {
  return apiPostAuth<JoinEventResponse>(`/events/${id}/join`, {}, token);
}
 
export async function requestJoinEvent(
  id: string,
  body: RequestJoinRequest,
  token: string,
): Promise<RequestJoinResponse> {
  return apiPostAuth<RequestJoinResponse>(`/events/${id}/join-request`, body, token);
}
 
export async function withdrawJoinRequest(
  eventId: string,
  token: string,
): Promise<void> {
  return apiDeleteAuth<void>(`/events/${eventId}/join-requests/me`, token);
}
 
export async function approveJoinRequest(
  eventId: string,
  joinRequestId: string,
  token: string,
): Promise<any> {
  return apiPostAuth<any>(
    `/events/${eventId}/join-requests/${joinRequestId}/approve`,
    {},
    token,
  );
}
 
export async function rejectJoinRequest(
  eventId: string,
  joinRequestId: string,
  token: string,
): Promise<any> {
  return apiPostAuth<any>(
    `/events/${eventId}/join-requests/${joinRequestId}/reject`,
    {},
    token,
  );
}
 
export async function leaveEvent(
  eventId: string,
  token: string,
): Promise<LeaveEventResponse> {
  return apiPatchAuth<LeaveEventResponse>(`/events/${eventId}/leave`, {}, token);
}
 
export async function reconfirmEventParticipation(
  eventId: string,
  token: string,
): Promise<ReconfirmParticipationResponse> {
  return apiPostAuth<ReconfirmParticipationResponse>(
    `/events/${eventId}/participation/reconfirm`,
    {},
    token,
  );
}
 
export async function cancelEvent(
  eventId: string,
  token: string,
): Promise<any> {
  return apiPatchAuth<any>(`/events/${eventId}/cancel`, {}, token);
}
 
export async function upsertEventRating(
  eventId: string,
  request: RatingWriteRequest,
  token: string,
): Promise<RatingResponse> {
  return apiPutAuth<RatingResponse>(`/events/${eventId}/rating`, request, token);
}
 
export async function upsertParticipantRating(
  eventId: string,
  participantUserId: string,
  request: RatingWriteRequest,
  token: string,
): Promise<RatingResponse> {
  return apiPutAuth<RatingResponse>(
    `/events/${eventId}/participants/${participantUserId}/rating`,
    request,
    token,
  );
}
 
export async function searchLocation(
  query: string,
): Promise<LocationSuggestion[]> {
  if (query.trim().length < 2) return [];
 
  const params = new URLSearchParams({
    q: query,
    limit: '5',
    lang: 'en',
  });
 
  let response: Response;
  try {
    response = await fetch(`${PHOTON_BASE}/api?${params}`);
  } catch {
    return [];
  }
 
  if (!response.ok) return [];
 
  const data = await response.json().catch(() => null);
  if (!data || !Array.isArray(data.features)) return [];
 
  return (data.features as PhotonFeature[])
    .map((feature): LocationSuggestion | null => {
      const coords = feature.geometry?.coordinates;
      if (!Array.isArray(coords) || coords.length < 2) return null;
      const [lon, lat] = coords;
      if (typeof lon !== 'number' || typeof lat !== 'number') return null;
 
      const displayName = buildPhotonDisplayName(feature.properties ?? {});
      if (!displayName) return null;
 
      return {
        display_name: displayName,
        lat: String(lat),
        lon: String(lon),
      };
    })
    .filter((s): s is LocationSuggestion => s !== null);
}
 
export async function reverseGeocode(
  lat: number,
  lon: number,
): Promise<LocationSuggestion | null> {
  if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
 
  const params = new URLSearchParams({
    lat: String(lat),
    lon: String(lon),
    lang: 'en',
  });
 
  let response: Response;
  try {
    response = await fetch(`${PHOTON_BASE}/reverse?${params}`);
  } catch {
    return null;
  }
 
  if (!response.ok) return null;
 
  const data = await response.json().catch(() => null);
  if (!data || !Array.isArray(data.features) || data.features.length === 0) return null;
 
  const feature = data.features[0] as PhotonFeature;
  const coords = feature.geometry?.coordinates;
  // Prefer the original tap coordinates so the marker stays where the user tapped,
  // even if Photon snaps the result to a nearby road or POI.
  const resolvedLat = Array.isArray(coords) && typeof coords[1] === 'number' ? coords[1] : lat;
  const resolvedLon = Array.isArray(coords) && typeof coords[0] === 'number' ? coords[0] : lon;
  const displayName = buildPhotonDisplayName(feature.properties ?? {});
  if (!displayName) return null;
 
  return {
    display_name: displayName,
    lat: String(resolvedLat),
    lon: String(resolvedLon),
  };
}
 
const OSRM_BASE = 'https://router.project-osrm.org';
 
interface OSRMRoute {
  geometry?: { coordinates?: Array<[number, number]> };
}
 
interface OSRMResponse {
  code?: string;
  routes?: OSRMRoute[];
}
 
/**
 * Fetches a routed geometry that follows the road network between the given
 * waypoints (in order). Uses OSRM's public driving profile — keyless and free,
 * but rate-limited and not for production-grade traffic. Returns null on any
 * failure so callers can fall back to a straight polyline.
 */
export async function fetchRoutedGeometry(
  waypoints: Array<{ lat: number; lon: number }>,
): Promise<Array<{ lat: number; lon: number }> | null> {
  if (waypoints.length < 2) return null;
  if (waypoints.some((p) => !Number.isFinite(p.lat) || !Number.isFinite(p.lon))) {
    return null;
  }
 
  const coords = waypoints.map((p) => `${p.lon},${p.lat}`).join(';');
  const url =
    `${OSRM_BASE}/route/v1/driving/${coords}` +
    `?overview=full&geometries=geojson`;
 
  let response: Response;
  try {
    response = await fetch(url);
  } catch {
    return null;
  }
  if (!response.ok) return null;
 
  const data = (await response.json().catch(() => null)) as OSRMResponse | null;
  if (!data || data.code !== 'Ok') return null;
  const geom = data.routes?.[0]?.geometry?.coordinates;
  if (!Array.isArray(geom) || geom.length < 2) return null;
 
  const points: Array<{ lat: number; lon: number }> = [];
  for (const pair of geom) {
    Iif (!Array.isArray(pair) || pair.length < 2) continue;
    const [lon, lat] = pair;
    if (typeof lat !== 'number' || typeof lon !== 'number') continue;
    points.push({ lat, lon });
  }
  return points.length >= 2 ? points : null;
}
 
export async function listCategories(): Promise<ListCategoriesResponse> {
  return apiGet<ListCategoriesResponse>('/categories');
}
 
function appendArrayParam(
  params: URLSearchParams,
  key: string,
  values?: Array<string | number>,
) {
  Iif (!values || values.length === 0) return;
  params.set(key, values.join(','));
}
 
export async function getJoinRequestImageUploadUrl(
  eventId: string,
  token: string,
): Promise<ImageUploadInitResponse> {
  return apiPostAuth<ImageUploadInitResponse>(
    `/events/${eventId}/join-request/image/upload-url`,
    {},
    token,
  );
}
 
export async function getEventImageUploadUrl(
  eventId: string,
  token: string,
): Promise<ImageUploadInitResponse> {
  return apiPostAuth<ImageUploadInitResponse>(
    `/events/${eventId}/image/upload-url`,
    {},
    token,
  );
}
 
export async function confirmEventImageUpload(
  eventId: string,
  confirmToken: string,
  token: string,
): Promise<void> {
  return apiPostAuth<void>(
    `/events/${eventId}/image/confirm`,
    { confirm_token: confirmToken },
    token,
  );
}
 
export async function uploadFileToPresignedUrl(
  method: string,
  url: string,
  headers: Record<string, string>,
  fileUri: string,
): Promise<void> {
  const normalizedMethod = method.toUpperCase();
  if (
    normalizedMethod !== 'POST'
    && normalizedMethod !== 'PUT'
    && normalizedMethod !== 'PATCH'
  ) {
    throw new Error(`Unsupported upload method: ${method}`);
  }
 
  const uploadResponse = await FileSystem.uploadAsync(url, fileUri, {
    httpMethod: normalizedMethod as SupportedUploadMethod,
    headers,
    uploadType: FileSystem.FileSystemUploadType.BINARY_CONTENT,
  });
 
  if (uploadResponse.status < 200 || uploadResponse.status >= 300) {
    throw new Error(`Upload failed with status ${uploadResponse.status}`);
  }
}
 
export async function listEvents(
  query: ListEventsQuery,
  token: string,
): Promise<PaginatedEventsResponse> {
  const params = new URLSearchParams();
 
  params.set('lat', String(query.lat));
  params.set('lon', String(query.lon));
 
  Iif (query.radius_meters != null) {
    params.set('radius_meters', String(query.radius_meters));
  }
 
  Iif (query.q?.trim()) {
    params.set('q', query.q.trim());
  }
 
 
  appendArrayParam(params, 'privacy_levels', query.privacy_levels);
  appendArrayParam(params, 'category_ids', query.category_ids);
  appendArrayParam(params, 'tag_names', query.tag_names);
 
 
  Iif (query.start_from) {
    params.set('start_from', query.start_from);
  }
 
  Iif (query.start_to) {
    params.set('start_to', query.start_to);
  }
 
  Iif (query.only_favorited != null) {
    params.set('only_favorited', String(query.only_favorited));
  }
 
  Iif (query.sort_by) {
    params.set('sort_by', query.sort_by);
  }
 
  Iif (query.child_friendly != null) {
    params.set('child_friendly', String(query.child_friendly));
  }
 
  Iif (query.family_oriented != null) {
    params.set('family_oriented', String(query.family_oriented));
  }
 
  Iif (query.limit != null) {
    params.set('limit', String(query.limit));
  }
 
  Iif (query.cursor) {
    params.set('cursor', query.cursor);
  }
 
  return apiGetAuth<PaginatedEventsResponse>(`/events?${params.toString()}`, token);
}
 
function normalizeMyEventStatus(value: string): MyEventStatus | null {
  if (
    value === 'ACTIVE'
    || value === 'IN_PROGRESS'
    || value === 'COMPLETED'
    || value === 'CANCELED'
  ) {
    return value;
  }
 
  return null;
}
 
function normalizeOptionalDateTime(value?: string | null): string | null {
  Iif (!value) return null;
 
  const parsed = new Date(value);
  Iif (Number.isNaN(parsed.getTime())) return null;
 
  // Backend profile event summaries currently serialize a zero time when end_time is absent.
  if (parsed.getUTCFullYear() <= 1) {
    return null;
  }
 
  return value;
}
 
function mapToMyEventSummary(
  summary: BackendEventSummary,
  relation: MyEventRelation,
): MyEventSummary | null {
  const status = normalizeMyEventStatus(summary.status);
  Iif (!status) return null;
 
  return {
    id: summary.id,
    title: summary.title,
    image_url: summary.image_url ?? null,
    start_time: summary.start_time,
    end_time: normalizeOptionalDateTime(summary.end_time),
    location_address: summary.location_address ?? null,
    approved_participant_count: summary.participants_count ?? null,
    status,
    relation,
    privacy_level: summary.privacy_level,
    badges: relation === 'HOSTING' ? [{ type: 'HOST', label: 'Host' }] : [],
  };
}
 
export async function listMyEvents(token: string): Promise<MyEventsResponse> {
  const withTimeout = <T>(promise: Promise<T>, timeoutMs = 10000): Promise<T> => {
    return Promise.race([
      promise,
      new Promise<T>((_, reject) =>
        setTimeout(() => reject(new Error('Request timed out')), timeoutMs)
      ),
    ]);
  };
 
  const [hostedResponse, upcomingResponse, completedResponse, canceledResponse] =
    await Promise.all([
      withTimeout(apiGetAuth<BackendEventsListResponse>('/me/events/hosted', token)).catch(() => ({ events: [] })),
      withTimeout(apiGetAuth<BackendEventsListResponse>('/me/events/upcoming', token)).catch(() => ({ events: [] })),
      withTimeout(apiGetAuth<BackendEventsListResponse>('/me/events/completed', token)).catch(() => ({ events: [] })),
      withTimeout(apiGetAuth<BackendEventsListResponse>('/me/events/canceled', token)).catch(() => ({ events: [] })),
    ]);
 
  const hostedEvents = (hostedResponse?.events ?? [])
    .map((event) => mapToMyEventSummary(event, 'HOSTING'))
    .filter((event): event is MyEventSummary => event != null);
 
  const hostedEventIds = new Set(hostedEvents.map((event) => event.id));
 
  const attendedSources = [
    ...(upcomingResponse?.events ?? []),
    ...(completedResponse?.events ?? []),
    ...(canceledResponse?.events ?? []),
  ];
 
  const attendedEvents = attendedSources
    .filter((event) => !hostedEventIds.has(event.id))
    .map((event) => mapToMyEventSummary(event, 'ATTENDING'))
    .filter((event): event is MyEventSummary => event != null);
 
  return {
    hosted_events: hostedEvents,
    attended_events: attendedEvents,
  };
}
 
export async function reportEvent(
  id: string,
  body: RequestReportEvent,
  token: string,
): Promise<ReportEventResponse> {
  return apiPostAuth<ReportEventResponse>(`/events/${id}/reports`, body, token);
}
 
export async function getEventReportImageUploadUrl(
  eventId: string,
  token: string,
): Promise<ImageUploadInitResponse> {
  return apiPostAuth<ImageUploadInitResponse>(
    `/events/${eventId}/reports/image/upload-url`,
    {},
    token,
  );
}