Spaces:
Running

File size: 3,227 Bytes
6f5f15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8bfbc2
 
 
6f5f15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8bfbc2
6f5f15e
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useCallback, useEffect, useState } from 'react';

const USER_STORAGE_KEY = 'mcp-webcam-user-id';
const VALID_USER_RE = /^[a-zA-Z0-9._-]{1,48}$/;

/**
 * Extract and sanitize `?user=` from a query string.
 */
export function getUserFromSearch(search: string): string | null {
  const params = new URLSearchParams(search);
  const raw = params.get('user')?.trim();
  if (!raw || !VALID_USER_RE.test(raw)) return null;
  return raw;
}

/**
 * Sanitize an arbitrary user/room input string.
 */
export function sanitizeUserId(input: string): string {
  const cleaned = input.trim().replace(/[^a-zA-Z0-9._-]/g, '-').slice(0, 48);
  return cleaned || 'default';
}

/**
 * Generate a short memorable room/user slug (e.g. "room-k4m9ab").
 */
export function generateUserId(randomFn: () => number = Math.random): string {
  const alphabet = 'abcdefghjkmnpqrstuvwxyz23456789';
  let suffix = '';
  for (let i = 0; i < 6; i++) {
    suffix += alphabet[Math.floor(randomFn() * alphabet.length)];
  }
  return `room-${suffix}`;
}

/**
 * Resolve the active user ID given URL search, stored value, and whether multi-user mode is active.
 */
export function resolveUserId(opts: {
  search: string;
  stored?: string | null;
  multiUser: boolean;
  randomFn?: () => number;
}): string {
  const fromUrl = getUserFromSearch(opts.search);
  if (fromUrl) return fromUrl;
  if (!opts.multiUser) return 'default';
  if (opts.stored && VALID_USER_RE.test(opts.stored) && opts.stored !== 'default') {
    return opts.stored;
  }
  return generateUserId(opts.randomFn);
}

/**
 * Build a URL string with `?user=` set (or removed when `user === 'default'`).
 */
export function buildUserUrl(currentHref: string, user: string): string {
  const url = new URL(currentHref);
  if (url.pathname === '/') {
    url.pathname = '/mcp';
  }
  if (!user || user === 'default') {
    url.searchParams.delete('user');
  } else {
    url.searchParams.set('user', user);
  }
  return url.toString();
}

export function useUserId(multiUser: boolean) {
  const [explicitUser, setExplicitUser] = useState<string | null>(() => {
    if (typeof window === 'undefined') return null;
    return getUserFromSearch(window.location.search);
  });

  const [fallbackMultiUser] = useState<string>(() => {
    if (typeof window === 'undefined') return generateUserId();
    const stored = window.sessionStorage.getItem(USER_STORAGE_KEY);
    if (stored && VALID_USER_RE.test(stored) && stored !== 'default') {
      return stored;
    }
    return generateUserId();
  });

  const user = explicitUser ?? (multiUser ? fallbackMultiUser : 'default');

  useEffect(() => {
    if (typeof window === 'undefined') return;
    try {
      window.sessionStorage.setItem(USER_STORAGE_KEY, user);
    } catch {
      // ignore storage quota errors
    }
    if (multiUser || user !== 'default' || window.location.pathname === '/') {
      const nextUrl = buildUserUrl(window.location.href, user);
      if (nextUrl !== window.location.href) {
        window.history.replaceState(null, '', nextUrl);
      }
    }
  }, [user, multiUser]);

  const setUser = useCallback((nextRaw: string) => {
    setExplicitUser(sanitizeUserId(nextRaw));
  }, []);

  return { user, setUser };
}