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
 
 
 
 
 
 
 
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
// Blomp integration — OpenStack Swift (Keystone v2).
//
// Blomp is an object-storage provider with a documented OpenStack Swift API.
// Unlike S3, objects are private by default, so this server authenticates with
// the account email/password, lists containers/objects, and proxies downloads
// with the Swift `X-Auth-Token` header.
//
// Auth:    POST https://authenticate.blomp.com/v2.0/tokens
// Tenant:  "storage" (the only tenant on Blomp)
// API:     OpenStack Swift object store
// Docs:    https://docs.openstack.org/api-ref/object-store/
//
// Blomp containers are typically named after the account email. The configured
// container is optional: when omitted we auto-detect the email-named container
// (or the only container on the account).
//
// Note: Blomp has a ~5 GiB object limit for uploads via Swift — irrelevant
// here: the only writes this server performs are small thumbnail images
// (found on the public web by video title) pushed by the auto thumbnail
// uploader (src/lib/thumb-uploader.ts). Videos are never uploaded,
// overwritten or deleted; large files may be stored as Static Large Objects,
// which Swift serves transparently.

import { createHash } from "node:crypto";
import { db } from "./db";
import type { CustomThumbImage } from "./custom-thumbs";
import type { SourceFile } from "./types";

const DEFAULT_AUTH_URL = "https://authenticate.blomp.com";
/**

 * Default object-name prefix for Blomp. The scanner starts here, then (when no

 * root is configured) auto-detects every other folder that actually contains

 * videos, so users normally never have to set a root at all. Users can still

 * point it anywhere else (or at "/" for the whole container).

 */
export const DEFAULT_BLOMP_ROOT = "/deovr";
const TENANT_NAME = "storage";
const MAX_FILES = 5000;
/** Hard cap on raw objects read from one container listing (videos + images). */
const MAX_OBJECTS = 20000;
const PAGE_SIZE = 1000;
// Blomp deliberately refuses Swift account-level container listings with 403.
// The account's container is deterministic (the login email), so callers must
// fall back to that instead of treating the 403 as a connection failure.
const ACCOUNT_LISTING_HINT =
  "Blomp blocks account-level container listing; using the configured or email-named container.";

class BlompHttpError extends Error {
  readonly status: number;

  constructor(message: string, status: number) {
    super(message);
    this.name = "BlompHttpError";
    this.status = status;
  }
}

/** True for the expected 403 on `GET <storageUrl>?format=json`. */
function isAccountListingForbidden(err: unknown): err is BlompHttpError {
  return err instanceof BlompHttpError && err.status === 403;
}
const BLOMP_UA =
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
  "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";

/** Settings that must never be returned to the browser in clear text. */
export const BLOMP_SECRET_KEYS = ["blomp_password"] as const;

export interface BlompConfig {
  email: string | null;
  password: string | null;
  /** Optional container override. Empty = auto-detect. */
  container: string | null;
  /** Object-name prefix to scan, displayed with a leading slash. */
  root: string;
  /** True when no root was configured: scans auto-detect folders with videos. */
  autoRoot: boolean;
  authUrl: string;
  configured: boolean;
}

export interface BlompConnectionResult {
  connected: boolean;
  configured: boolean;
  email: string | null;
  container: string | null;
  root: string;
  /** True when no root is configured and scans auto-detect video folders. */
  autoRoot: boolean;
  containers?: string[];
  error?: string;
}

export interface BlompScanResult {
  files: SourceFile[];
  /** Image objects found anywhere in the container (custom thumbnails). */
  images: CustomThumbImage[];
  /** Every folder that exists in the container, display form ("/gta"). */
  folders: string[];
  container: string | null;
  /** Display form of the scanned root(s), e.g. "/deovr" or "/deovr, /Movies". */
  root: string;
  /** Every folder the scan actually read, in display form. Empty in auto mode = none found. */
  roots: string[];
  error?: string;
}

export interface BlompAuthState {
  token: string;
  storageUrl: string;
  expiresAt: number;
}

export interface BlompContainer {
  name: string;
  count: number;
  bytes: number;
}

interface BlompObject {
  name: string;
  bytes: number;
  lastModified: string | null;
  contentType: string | null;
}

// ---------------------------------------------------------------------------
// Settings helpers
// ---------------------------------------------------------------------------

async function readBlompSettings(): Promise<Record<string, string>> {
  try {
    const rows = await db.setting.findMany();
    const out: Record<string, string> = {};
    for (const row of rows) {
      if (row.key.startsWith("blomp_")) out[row.key] = row.value;
    }
    return out;
  } catch {
    // DB may not be initialized yet.
    return {};
  }
}

function envOr(value: string | undefined, fallback: string | null | undefined): string | null {
  const v = value?.trim() || fallback?.trim() || "";
  return v || null;
}

/** Display form: always starts with "/", no trailing slash except root. */
function normalizeRoot(root: string | null | undefined): string {
  let out = (root ?? "").trim();
  if (!out || out === "/") return "/";
  out = out.replace(/^\/+/, "").replace(/\/+$/, "");
  return out ? `/${out}` : "/";
}

/** Swift prefix form: no leading/trailing slash. */
function rootPrefix(root: string): string {
  return root.replace(/^\/+/, "").replace(/\/+$/, "");
}

function normalizeContainer(container: string | null | undefined): string | null {
  const out = (container ?? "").trim().replace(/^\/+|\/+$/g, "");
  return out || null;
}

export async function getBlompConfig(): Promise<BlompConfig> {
  const settings = await readBlompSettings();
  const env = process.env;

  const email = envOr(env.BLOMP_EMAIL, settings.blomp_email);
  const password = envOr(env.BLOMP_PASSWORD, settings.blomp_password);
  const container = normalizeContainer(envOr(env.BLOMP_CONTAINER, settings.blomp_container));
  // No configured root = auto-detect: start at the /deovr default, then scan
  // every folder that actually holds videos. An explicit "/" still means the
  // whole container, so keep the raw value to distinguish the two cases.
  const explicitRoot = envOr(env.BLOMP_ROOT, settings.blomp_root);
  const root = normalizeRoot(explicitRoot ?? DEFAULT_BLOMP_ROOT);
  const authUrl = envOr(env.BLOMP_AUTH_URL, null) ?? DEFAULT_AUTH_URL;

  return {
    email,
    password,
    container,
    root,
    autoRoot: !explicitRoot,
    authUrl: authUrl.replace(/\/+$/, ""),
    configured: !!(email && password),
  };
}

/** True when an account email + password are available. */
export async function isBlompConfigured(): Promise<boolean> {
  const cfg = await getBlompConfig();
  return cfg.configured;
}

// ---------------------------------------------------------------------------
// Authentication (Keystone v2)
// ---------------------------------------------------------------------------

let authCache: (BlompAuthState & { key: string }) | null = null;

function credentialsKey(cfg: BlompConfig): string {
  return createHash("sha256")
    .update(`${cfg.email ?? ""}\u0000${cfg.password ?? ""}\u0000${cfg.authUrl}`)
    .digest("hex");
}

function tokenEndpoint(authUrl: string): string {
  const base = authUrl.replace(/\/+$/, "");
  if (base.endsWith("/tokens")) return base;
  if (base.endsWith("/v2.0")) return `${base}/tokens`;
  return `${base}/v2.0/tokens`;
}

function authErrorMessage(data: unknown, status: number): string {
  const obj = data as Record<string, any> | null;
  const message =
    obj?.unauthorized?.message ||
    obj?.error?.message ||
    obj?.error_description ||
    obj?.message ||
    obj?.error;
  return typeof message === "string" && message
    ? message
    : `Blomp authentication failed (HTTP ${status})`;
}

function pickStorageUrl(catalog: any[], authUrl: string): string {
  const objectStore = catalog?.find((entry) => entry?.type === "object-store");
  const endpoints: any[] = Array.isArray(objectStore?.endpoints) ? objectStore.endpoints : [];
  const endpoint =
    endpoints.find((entry) => entry?.interface === "public") ??
    endpoints.find((entry) => entry?.publicURL || entry?.url) ??
    endpoints[0];

  const storageUrl = endpoint?.publicURL || endpoint?.url;
  if (typeof storageUrl !== "string" || !storageUrl) {
    throw new Error(`Blomp returned no object-store endpoint from ${authUrl}`);
  }
  return storageUrl.replace(/\/+$/, "");
}

async function authenticate(cfg: BlompConfig, force = false): Promise<BlompAuthState> {
  if (!cfg.email || !cfg.password) {
    throw new Error("Blomp is not configured — enter your account email and password.");
  }

  const key = credentialsKey(cfg);
  const now = Date.now();
  if (
    !force &&
    authCache &&
    authCache.key === key &&
    authCache.expiresAt - now > 5 * 60 * 1000
  ) {
    return authCache;
  }

  const endpoint = tokenEndpoint(cfg.authUrl);
  const body = JSON.stringify({
    auth: {
      tenantName: TENANT_NAME,
      passwordCredentials: {
        username: cfg.email,
        password: cfg.password,
      },
    },
  });

  let res: Response;
  try {
    res = await fetch(endpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
        "User-Agent": BLOMP_UA,
      },
      body,
      signal: AbortSignal.timeout(20000),
    });
  } catch (err) {
    throw new Error(
      `Blomp authentication request failed: ${err instanceof Error ? err.message : "network error"}`
    );
  }

  const text = await res.text();
  let data: any = null;
  try {
    data = text ? JSON.parse(text) : null;
  } catch {
    // Keystone errors are normally JSON, but a proxy may return HTML.
  }

  if (!res.ok) {
    throw new Error(authErrorMessage(data, res.status));
  }

  const token = data?.access?.token?.id;
  if (!token) {
    throw new Error("Blomp did not return an auth token. Check your email and password.");
  }

  const expiresRaw = data?.access?.token?.expires;
  const parsedExpires = expiresRaw ? Date.parse(String(expiresRaw)) : NaN;
  const expiresAt = Number.isFinite(parsedExpires) && parsedExpires > now
    ? parsedExpires
    : now + 60 * 60 * 1000;

  const storageUrl = pickStorageUrl(data?.access?.serviceCatalog, endpoint);
  authCache = { token: String(token), storageUrl, expiresAt, key };
  return authCache;
}

/** Current auth token + storage URL. Used by the stream proxy headers. */
export async function getBlompAuth(): Promise<BlompAuthState> {
  const cfg = await getBlompConfig();
  return authenticate(cfg);
}

/** Drop cached auth/status after settings change or 401. */
export function clearBlompCache(): void {
  authCache = null;
  statusCache = null;
}

// ---------------------------------------------------------------------------
// Swift request helpers
// ---------------------------------------------------------------------------

function objectPath(container: string, objectName: string): string {
  const safeContainer = encodeURIComponent(container);
  const safeObject = objectName
    .split("/")
    .map((segment) => encodeURIComponent(segment))
    .join("/");
  return `${safeContainer}/${safeObject}`;
}

/** Canonical, token-free URL for a Swift object. */
export function blompObjectUrl(storageUrl: string, container: string, objectName: string): string {
  return `${storageUrl.replace(/\/+$/, "")}/${objectPath(container, objectName)}`;
}

async function swiftFetch(

  url: string,

  init: RequestInit = {},

  retryOn401 = true

): Promise<Response> {
  const auth = await getBlompAuth();
  const headers = new Headers(init.headers);
  headers.set("X-Auth-Token", auth.token);
  headers.set("User-Agent", BLOMP_UA);
  headers.set("Accept", "application/json, text/plain, */*");

  const res = await fetch(url, { ...init, headers, signal: init.signal ?? AbortSignal.timeout(25000) });
  if (res.status === 401 && retryOn401) {
    try {
      await res.body?.cancel();
    } catch {
      // Ignore.
    }
    clearBlompCache();
    return swiftFetch(url, init, false);
  }
  return res;
}

async function readJson(res: Response): Promise<any> {
  const text = await res.text();
  if (!text) return null;
  try {
    return JSON.parse(text);
  } catch {
    throw new Error("Blomp returned a non-JSON response");
  }
}

/** List all containers on the account. */
export async function listBlompContainers(): Promise<BlompContainer[]> {
  const auth = await getBlompAuth();
  const url = `${auth.storageUrl}?format=json`;
  const res = await swiftFetch(url);
  if (!res.ok) {
    const body = await res.text().catch(() => "");
    throw new BlompHttpError(
      `Blomp container list failed (HTTP ${res.status})${body ? `: ${body.slice(0, 160)}` : ""}`,
      res.status
    );
  }
  const data = await readJson(res);
  if (!Array.isArray(data)) {
    throw new Error("Blomp returned an unexpected container list");
  }
  return data.map((entry: any) => ({
    name: String(entry?.name ?? ""),
    count: Number(entry?.count ?? 0) || 0,
    bytes: Number(entry?.bytes ?? 0) || 0,
  })).filter((entry) => entry.name);
}

/**

 * Resolve the container to scan.

 *

 * Blomp returns 403 for Swift account-level container listings, so we must not

 * depend on that call. The account container is the login email; an explicit

 * container setting always wins. When a listing happens to be available we use

 * it to recover the exact casing/name, otherwise `verifyBlompContainer` below

 * confirms the chosen container directly.

 */
export async function resolveBlompContainer(

  cfg?: BlompConfig,

  containers?: BlompContainer[]

): Promise<string> {
  const config = cfg ?? (await getBlompConfig());
  if (!config.configured) throw new Error("Blomp is not configured.");

  if (config.container) return config.container;

  if (containers?.length) {
    const emailMatch = config.email
      ? containers.find((entry) => entry.name.toLowerCase() === config.email!.toLowerCase())
      : undefined;
    if (emailMatch) return emailMatch.name;
    if (containers.length === 1) return containers[0].name;

    const available = containers.map((entry) => entry.name).join(", ");
    throw new Error(`Multiple Blomp containers found — set one explicitly. Available: ${available}`);
  }

  if (config.email) return config.email;

  const list = containers ?? (await listBlompContainers());
  if (list.length === 1) return list[0].name;
  if (list.length === 0) {
    throw new Error("No Blomp containers found. Upload some files to Blomp first.");
  }

  const available = list.map((entry) => entry.name).join(", ");
  throw new Error(`Multiple Blomp containers found — set one explicitly. Available: ${available}`);
}

/**

 * Confirm a container is reachable without using the forbidden account-level

 * listing. The account listing is blocked, but listing one object inside the

 * container is exactly what the dashboard and the scanner do.

 */
async function verifyBlompContainer(container: string): Promise<void> {
  const auth = await getBlompAuth();
  const url = new URL(`${auth.storageUrl.replace(/\/+$/, "")}/${encodeURIComponent(container)}`);
  url.searchParams.set("format", "json");
  url.searchParams.set("limit", "1");
  const res = await swiftFetch(url.toString());

  if (res.status === 404) {
    throw new Error(
      `Blomp container "${container}" was not found. Use the email address of your Blomp account, or set the container explicitly.`
    );
  }
  if (!res.ok) {
    const body = await res.text().catch(() => "");
    throw new BlompHttpError(
      `Blomp container check failed (HTTP ${res.status})${body ? `: ${body.slice(0, 160)}` : ""}`,
      res.status
    );
  }

  // A 204/empty response is valid for an empty container. A 200 must be a
  // Swift JSON listing.
  const data = await readJson(res);
  if (data !== null && !Array.isArray(data)) {
    throw new Error("Blomp returned an unexpected container listing");
  }
}

async function listObjectPage(

  container: string,

  prefix: string,

  marker: string | null

): Promise<{
  objects: BlompObject[];
  /** Pseudo-directory entries ("folder exists" proofs), raw Swift form. */
  subdirs: string[];
  rawCount: number;
  lastRawName: string | null;
}> {
  const auth = await getBlompAuth();
  // Container listing endpoint (no trailing slash — a trailing slash would be
  // parsed as an empty object name by some Swift deployments).
  const url = new URL(`${auth.storageUrl.replace(/\/+$/, "")}/${encodeURIComponent(container)}`);
  url.searchParams.set("format", "json");
  url.searchParams.set("limit", String(PAGE_SIZE));
  if (prefix) url.searchParams.set("prefix", prefix);
  if (marker) url.searchParams.set("marker", marker);

  const res = await swiftFetch(url.toString());
  if (res.status === 404) {
    throw new Error(`Blomp container "${container}" was not found`);
  }
  if (!res.ok) {
    const body = await res.text().catch(() => "");
    throw new Error(`Blomp object list failed (HTTP ${res.status})${body ? `: ${body.slice(0, 160)}` : ""}`);
  }

  const data = await readJson(res);
  if (!Array.isArray(data)) {
    throw new Error("Blomp returned an unexpected object list");
  }

  const objects: BlompObject[] = [];
  // Pseudo-directory entries (Swift `subdir` items) prove a folder exists on
  // the drive — even while empty — so the auto thumbnail uploader can target
  // it without ever creating anything.
  const subdirs: string[] = [];
  // Swift pagination markers must be the LAST name in the raw listing, which
  // includes those pseudo-directory entries that we skip for scanning.
  let lastRawName: string | null = null;
  for (const entry of data as any[]) {
    const name = String(entry?.name ?? entry?.subdir ?? "");
    if (name) lastRawName = name;
    if (entry?.subdir) {
      subdirs.push(String(entry.subdir));
      continue;
    }
    if (!name || name.endsWith("/")) continue;
    objects.push({
      name,
      bytes: Number(entry?.bytes ?? 0) || 0,
      lastModified: entry?.last_modified ? String(entry.last_modified) : null,
      contentType: entry?.content_type ? String(entry.content_type) : null,
    });
  }
  return { objects, subdirs, rawCount: data.length, lastRawName };
}

/**

 * List every object under a prefix, plus every folder that exists there:

 * all ancestor folders of real objects and Swift pseudo-directory entries

 * (folders that exist even while empty). Display form, e.g. "/gta".

 */
async function listAllObjects(

  container: string,

  prefix: string

): Promise<{ objects: BlompObject[]; folders: string[] }> {
  const out: BlompObject[] = [];
  const folders = new Set<string>();
  const seen = new Set<string>();
  let marker: string | null = null;

  /** Remember a folder and every ancestor of it ("/a/b" also remembers "/a"). */
  const rememberFolder = (displayPath: string): void => {
    const segments = displayPath.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
    for (let i = 1; i <= segments.length; i++) {
      folders.add(`/${segments.slice(0, i).join("/")}`);
    }
  };

  for (let page = 0; page < 100; page++) {
    const { objects, subdirs, rawCount, lastRawName } = await listObjectPage(container, prefix, marker);

    for (const object of objects) {
      rememberFolder(dirName(object.name));
      if (seen.has(object.name)) continue;
      seen.add(object.name);
      out.push(object);
      if (out.length >= MAX_OBJECTS) break;
    }
    for (const subdir of subdirs) rememberFolder(subdir);

    if (out.length >= MAX_OBJECTS) break;
    if (rawCount < PAGE_SIZE) break;

    // Advance using the raw listing entry (may be a pseudo-directory).
    if (!lastRawName || lastRawName === marker) break;
    marker = lastRawName;
  }

  return { objects: out, folders: [...folders].sort() };
}

// ---------------------------------------------------------------------------
// Scanning
// ---------------------------------------------------------------------------

function isVideoName(name: string): boolean {
  return /\.(mp4|mkv|webm|mov|m4v|avi|ts|m2ts|mts|wmv|flv|mpg|mpeg|3gp)$/i.test(name);
}

/** Image objects usable as user-supplied custom thumbnails. */
function isImageName(name: string): boolean {
  return /\.(jpe?g|png|webp|gif|bmp|avif)$/i.test(name);
}

function baseName(objectName: string): string {
  const parts = objectName.split("/");
  return parts[parts.length - 1] || objectName;
}

function dirName(objectName: string): string {
  const idx = objectName.lastIndexOf("/");
  if (idx <= 0) return "/";
  return `/${objectName.slice(0, idx)}`;
}

function formatSize(bytes: number): string {
  if (!Number.isFinite(bytes) || bytes <= 0) return "—";
  const units = ["B", "KB", "MB", "GB", "TB"];
  let i = 0;
  let size = bytes;
  while (size >= 1024 && i < units.length - 1) {
    size /= 1024;
    i++;
  }
  return `${size.toFixed(1)} ${units[i]}`;
}

function parseObjectPath(sourceId: string | null | undefined): { container: string; object: string } | null {
  const value = (sourceId ?? "").trim();
  if (!value) return null;
  const idx = value.indexOf("/");
  if (idx <= 0 || idx >= value.length - 1) return null;
  return { container: value.slice(0, idx), object: value.slice(idx + 1) };
}

/**

 * Top-level folder a folderPath belongs to: "/deovr/sub" -> "/deovr".

 * Auto-detection reports top-level roots so the DEOVR tab stays short.

 */
function topLevelRoot(folderPath: string | null | undefined): string {
  const seg = (folderPath ?? "").replace(/^\/+/, "").split("/")[0];
  return seg ? `/${seg}` : "/";
}

/** Dedupe detected roots, keeping the /deovr default first. */
function orderRoots(roots: string[]): string[] {
  const unique = [...new Set(roots.filter(Boolean))];
  const preferred = DEFAULT_BLOMP_ROOT.toLowerCase();
  return unique.sort((a, b) => {
    const ap = a.toLowerCase() === preferred ? 0 : 1;
    const bp = b.toLowerCase() === preferred ? 0 : 1;
    return ap - bp || a.localeCompare(b);
  });
}

/** Display form for one or more detected roots. */
function formatRoots(roots: string[]): string {
  if (roots.length === 0) return DEFAULT_BLOMP_ROOT;
  if (roots.length <= 3) return roots.join(", ");
  return `${roots.slice(0, 3).join(", ")} +${roots.length - 3} more`;
}

/**

 * Walk a Blomp container and return video objects, thumbnail images and the

 * folders that exist on the drive.

 *

 * With an explicit root, only that prefix is read for videos. With no

 * configured root the whole container is read once and the folders that

 * actually contain videos are reported as the roots - so /deovr is the

 * starting default, but a library kept in /VR, /Movies or anywhere else is

 * still discovered automatically.

 *

 * Images (custom thumbnails) are ALWAYS collected from the whole container,

 * regardless of the configured root, so a thumbnail uploaded anywhere in the

 * drive still matches its video by name. Folder paths are collected the same

 * way — they are the destinations the auto thumbnail uploader may use, and it

 * must never create a folder that is not in this list.

 */
export async function scanBlompLibrary(): Promise<BlompScanResult> {
  const cfg = await getBlompConfig();
  if (!cfg.configured) {
    return {
      files: [],
      images: [],
      folders: [],
      container: cfg.container,
      root: cfg.root,
      roots: [],
      error: "Blomp is not configured.",
    };
  }

  try {
    const auth = await getBlompAuth();
    // Do not list account containers here: Blomp always answers that call
    // with 403. The container is the login email unless explicitly configured.
    const container = await resolveBlompContainer(cfg);
    // Videos honour the configured root, but images must be discoverable from
    // any folder, so the listing always covers the whole container and the
    // root filter is applied afterwards.
    const videoPrefix = cfg.autoRoot ? "" : rootPrefix(cfg.root);
    const { objects, folders: rawFolders } = await listAllObjects(container, "");

    const files: SourceFile[] = [];   // videos
    const images: CustomThumbImage[] = []; // custom thumbnails, any folder
    const seen = new Set<string>();

    for (const object of objects) {
      if (object.name.startsWith(".file-segments/") || object.name.includes("/.file-segments/")) continue;

      const key = `${container}/${object.name}`;
      if (seen.has(key)) continue;

      // Custom thumbnails: images live anywhere in the drive.
      if (isImageName(object.name)) {
        if (images.length >= MAX_FILES) continue;
        seen.add(key);
        images.push({
          container,
          objectName: object.name,
          baseName: baseName(object.name),
          folderPath: dirName(object.name),
          bytes: object.bytes,
          lastModified: object.lastModified,
          contentType: object.contentType,
        });
        continue;
      }

      // Videos: respect the configured root (auto mode = whole container).
      if (!isVideoName(object.name)) continue;
      if (videoPrefix && object.name !== videoPrefix && !object.name.startsWith(`${videoPrefix}/`)) continue;

      seen.add(key);
      files.push({
        source: "blomp",
        sourceId: key,
        sourcePath: key,
        name: baseName(object.name),
        folderPath: dirName(object.name),
        streamUrl: blompObjectUrl(auth.storageUrl, container, object.name),
        size: formatSize(object.bytes),
        addedAt: object.lastModified && Number.isFinite(Date.parse(object.lastModified))
          ? new Date(object.lastModified)
          : undefined,
      });
      if (files.length >= MAX_FILES) break;
    }

    const roots = cfg.autoRoot
      ? orderRoots(files.map((file) => topLevelRoot(file.folderPath)))
      : [cfg.root];

    // Folders the auto thumbnail uploader may target: every folder that
    // exists on the drive (from real objects + pseudo-dirs), minus
    // hidden/system ones.
    const folders = rawFolders.filter(
      (path) => !path.split("/").some((seg) => seg && seg.startsWith("."))
    );

    return { files, images, folders, container, root: formatRoots(roots), roots };
  } catch (err) {
    return {
      files: [],
      images: [],
      folders: [],
      container: cfg.container,
      root: cfg.root,
      roots: [],
      error: err instanceof Error ? err.message : "Unknown Blomp scan error",
    };
  }
}

/**

 * Refresh a playable Blomp object URL. Blomp object URLs are stable; the auth

 * token is sent separately by the stream proxy. This still authenticates first

 * so a stale/expired account is reported early.

 *

 * `sourceId` / `sourcePath` are stored as `<container>/<objectName>`.

 */
export async function refreshBlompStreamUrl(file: {

  sourceId?: string | null;

  sourcePath?: string | null;

}): Promise<string | null> {
  try {
    const cfg = await getBlompConfig();
    if (!cfg.configured) return null;

    const parsed = parseObjectPath(file.sourcePath) ?? parseObjectPath(file.sourceId);
    if (!parsed) return null;

    const auth = await getBlompAuth();
    return blompObjectUrl(auth.storageUrl, parsed.container, parsed.object);
  } catch (err) {
    console.warn("[blomp] failed to refresh object URL:", err);
    return null;
  }
}

/** Auth headers for the streaming proxy. */
export async function blompUpstreamHeaders(): Promise<Record<string, string>> {
  const auth = await getBlompAuth();
  return {
    "X-Auth-Token": auth.token,
    "User-Agent": BLOMP_UA,
    Accept: "*/*",
  };
}

// ---------------------------------------------------------------------------
// Uploads — generated poster thumbnails only
// ---------------------------------------------------------------------------

/** Result of a Swift object PUT. */
export interface BlompPutResult {
  ok: boolean;
  status: number;
  /** True when the object already existed (HTTP 412 from If-None-Match). */
  exists: boolean;
  error?: string;
}

/**

 * Upload a small object into the configured container.

 *

 * Used exclusively by the auto thumbnail uploader to push a thumbnail image

 * found on the web; nothing else in this server writes to Blomp.

 * `If-None-Match: *` makes

 * the PUT fail with 412 instead of overwriting an object that already exists

 * (e.g. a poster the user uploaded manually between listings) — a 412 is

 * reported as `{ ok: false, exists: true }`, never as an error.

 */
export async function putBlompObject(opts: {

  /** Object name inside the container, e.g. "gta/Trip to Mars.jpg". */

  objectName: string;

  bytes: Buffer;

  contentType: string;

  /** Send If-None-Match: * (default). Disable only for the 400-fallback retry. */

  ifNoneMatch?: boolean;

}): Promise<BlompPutResult> {
  const attemptPut = async (withGuard: boolean): Promise<Response> => {
    const cfg = await getBlompConfig();
    if (!cfg.configured) throw new Error("Blomp is not configured.");
    const container = await resolveBlompContainer(cfg);
    const auth = await getBlompAuth();
    const url = `${auth.storageUrl.replace(/\/+$/, "")}/${objectPath(container, opts.objectName)}`;
    const headers: Record<string, string> = { "Content-Type": opts.contentType };
    if (withGuard) headers["If-None-Match"] = "*";
    return swiftFetch(url, {
      method: "PUT",
      headers,
      body: new Uint8Array(opts.bytes),
    });
  };

  try {
    let res = await attemptPut(opts.ifNoneMatch !== false);

    // Some Swift builds reject the conditional header outright; retry once
    // without it (the uploader's HEAD pre-check already made an overwrite
    // very unlikely).
    if (res.status === 400 && opts.ifNoneMatch !== false) {
      try {
        await res.body?.cancel();
      } catch {
        // Ignore.
      }
      res = await attemptPut(false);
    }

    if (res.status === 201 || res.status === 200) {
      return { ok: true, status: res.status, exists: false };
    }
    if (res.status === 412) {
      return { ok: false, status: 412, exists: true };
    }

    const body = await res.text().catch(() => "");
    return {
      ok: false,
      status: res.status,
      exists: false,
      error: `Blomp upload failed (HTTP ${res.status})${body ? `: ${body.slice(0, 160)}` : ""}`,
    };
  } catch (err) {
    return {
      ok: false,
      status: 0,
      exists: false,
      error: err instanceof Error ? err.message : "Blomp upload failed",
    };
  }
}

/**

 * Does an object already exist in the configured container?

 * Returns null when the answer is unknown (auth or network problem) — callers

 * then proceed to the guarded PUT, which cannot overwrite either.

 */
export async function blompObjectExists(objectName: string): Promise<boolean | null> {
  try {
    const cfg = await getBlompConfig();
    if (!cfg.configured) return null;
    const container = await resolveBlompContainer(cfg);
    const auth = await getBlompAuth();
    const url = `${auth.storageUrl.replace(/\/+$/, "")}/${objectPath(container, objectName)}`;
    const res = await swiftFetch(url, { method: "HEAD" });
    if (res.status === 200) return true;
    if (res.status === 404) return false;
    return null;
  } catch {
    return null;
  }
}

// ---------------------------------------------------------------------------
// Connection status
// ---------------------------------------------------------------------------

let statusCache: { at: number; result: BlompConnectionResult } | null = null;

export async function testBlompConnection(opts: { force?: boolean } = {}): Promise<BlompConnectionResult> {
  if (!opts.force && statusCache && Date.now() - statusCache.at < 30_000) {
    return statusCache.result;
  }

  const cfg = await getBlompConfig();
  const base: Omit<BlompConnectionResult, "connected"> = {
    configured: cfg.configured,
    email: cfg.email,
    container: cfg.container,
    root: cfg.root,
    autoRoot: cfg.autoRoot,
  };

  let result: BlompConnectionResult;
  if (!cfg.configured) {
    result = { ...base, connected: false };
  } else {
    try {
      // Blomp's account-level container listing is intentionally 403, so
      // resolve the deterministic container and probe it directly instead.
      const container = await resolveBlompContainer(cfg);
      await verifyBlompContainer(container);
      result = {
        ...base,
        connected: true,
        container,
        containers: [container],
      };
    } catch (err) {
      result = {
        ...base,
        connected: false,
        error: err instanceof Error ? err.message : "Unknown Blomp error",
      };
    }
  }

  statusCache = { at: Date.now(), result };
  return result;
}

// ---------------------------------------------------------------------------
// Diagnostics / disconnect
// ---------------------------------------------------------------------------

export async function debugBlomp(): Promise<Record<string, unknown>> {
  const cfg = await getBlompConfig();
  const redacted = {
    email: cfg.email,
    configured: cfg.configured,
    hasPassword: !!cfg.password,
    container: cfg.container,
    root: cfg.root,
    autoRoot: cfg.autoRoot,
    authUrl: cfg.authUrl,
  };

  let containers: string[] | undefined;
  let entries: { name: string; bytes: number; contentType: string | null }[] | undefined;
  const notes: string[] = [];
  let error: string | undefined;

  try {
    let list: BlompContainer[] | undefined;
    try {
      list = await listBlompContainers();
      containers = list.map((entry) => entry.name);
    } catch (err) {
      if (!isAccountListingForbidden(err)) throw err;
      notes.push(ACCOUNT_LISTING_HINT);
    }

    const container = await resolveBlompContainer(cfg, list);
    await verifyBlompContainer(container);
    if (!containers) containers = [container];

    if (cfg.autoRoot) {
      notes.push(
        `No root configured: starting at ${DEFAULT_BLOMP_ROOT} and auto-detecting every folder that contains videos.`
      );
    }

    const { objects } = await listAllObjects(container, cfg.autoRoot ? "" : rootPrefix(cfg.root));
    entries = objects.slice(0, 25).map((object) => ({
      name: object.name,
      bytes: object.bytes,
      contentType: object.contentType,
    }));
  } catch (err) {
    error = err instanceof Error ? err.message : "Unknown Blomp error";
  }

  return {
    config: redacted,
    containers,
    entries,
    notes,
    error,
    timestamp: new Date().toISOString(),
  };
}

/** Remove the saved Blomp password but keep email/container/root preferences. */
export async function disconnectBlomp(): Promise<void> {
  await db.setting.deleteMany({ where: { key: { in: ["blomp_password"] } } });
  clearBlompCache();
}