Spaces:
Build error
Build error
File size: 19,816 Bytes
0bfe2e3 |
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 |
'use client';
import { PageWrapper } from '../shared/page-wrapper';
import * as constants from '../../../../core/src/utils/constants';
import { ParsedStream } from '../../../../core/src/db/schemas';
import React, { useState, useEffect, useCallback } from 'react';
import { useUserData } from '@/context/userData';
import { SettingsCard } from '../shared/settings-card';
import { Textarea } from '../ui/textarea';
import { Select } from '../ui/select';
import { Switch } from '../ui/switch';
import { TextInput } from '../ui/text-input';
import FileParser from '@aiostreams/core/src/parser/file';
import { UserConfigAPI } from '@/services/api';
import { SNIPPETS } from '../../../../core/src/utils/constants';
import { Modal } from '@/components/ui/modal';
import { useDisclosure } from '@/hooks/disclosure';
import { Button } from '../ui/button';
import { CopyIcon } from 'lucide-react';
import { toast } from 'sonner';
import { NumberInput } from '../ui/number-input';
import { PageControls } from '../shared/page-controls';
const formatterChoices = Object.values(constants.FORMATTER_DETAILS);
// Remove the throttle utility and replace with FormatQueue
class FormatQueue {
private queue: (() => Promise<void>)[] = [];
private processing = false;
private readonly delay: number;
constructor(delay: number) {
this.delay = delay;
}
enqueue(formatFn: () => Promise<void>) {
// Replace any existing queued format request with the new one
this.queue = [formatFn];
this.process();
}
private async process() {
if (this.processing) return;
this.processing = true;
while (this.queue.length > 0) {
const formatFn = this.queue.shift();
if (formatFn) {
try {
await formatFn();
} catch (error) {
console.error('Error in format queue:', error);
}
// Wait for the specified delay before processing the next request
await new Promise((resolve) => setTimeout(resolve, this.delay));
}
}
this.processing = false;
}
}
export function FormatterMenu() {
return (
<>
<PageWrapper className="space-y-4 p-4 sm:p-8">
<Content />
</PageWrapper>
</>
);
}
function FormatterPreviewBox({
name,
description,
}: {
name?: string;
description?: string;
}) {
return (
<div className="bg-gray-900 rounded-md p-4 border border-gray-800">
<div
className="text-xl font-bold mb-1 overflow-x-auto"
style={{ whiteSpace: 'pre' }}
>
{name}
</div>
<div
className="text-base text-muted-foreground overflow-x-auto"
style={{ whiteSpace: 'pre' }}
>
{description}
</div>
</div>
);
}
function Content() {
const { userData, setUserData } = useUserData();
const [selectedFormatter, setSelectedFormatter] =
useState<constants.FormatterType>(
(userData.formatter?.id as constants.FormatterType) ||
formatterChoices[0].id
);
const [formattedStream, setFormattedStream] = useState<{
name: string;
description: string;
} | null>(null);
const [isFormatting, setIsFormatting] = useState(false);
// Create format queue ref to persist between renders
const formatQueueRef = React.useRef<FormatQueue>(new FormatQueue(200));
// Stream preview state
const [filename, setFilename] = useState(
'Movie.Title.2023.2160p.BluRay.HEVC.DV.TrueHD.Atmos.7.1.iTA.ENG-GROUP.mkv'
);
const [folder, setFolder] = useState(
'Movie.Title.2023.2160p.BluRay.HEVC.DV.TrueHD.Atmos.7.1.iTA.ENG-GROUP'
);
const [indexer, setIndexer] = useState('RARBG');
const [seeders, setSeeders] = useState<number | undefined>(125);
const [age, setAge] = useState<string>('10d');
const [addonName, setAddonName] = useState('Torrentio');
const [providerId, setProviderId] = useState<constants.ServiceId | 'none'>(
'none'
);
const [isCached, setIsCached] = useState(true);
const [type, setType] =
useState<(typeof constants.STREAM_TYPES)[number]>('debrid');
const [library, setLibrary] = useState(false);
const [duration, setDuration] = useState<number | undefined>(9120000); // 2h 32m in milliseconds
const [fileSize, setFileSize] = useState<number | undefined>(62500000000); // 58.2 GB in bytes
const [folderSize, setFolderSize] = useState<number | undefined>(
125000000000
); // 116.4 GB in bytes
const [proxied, setProxied] = useState(false);
const [regexMatched, setRegexMatched] = useState<string | undefined>(
undefined
);
const [message, setMessage] = useState('This is a message');
// Custom formatter state (to avoid losing one field when editing the other)
const [customName, setCustomName] = useState(
userData.formatter?.definition?.name || ''
);
const [customDescription, setCustomDescription] = useState(
userData.formatter?.definition?.description || ''
);
// Keep userData in sync with custom formatter fields
useEffect(() => {
if (selectedFormatter === constants.CUSTOM_FORMATTER) {
setUserData((prev) => ({
...prev,
formatter: {
id: constants.CUSTOM_FORMATTER,
definition: { name: customName, description: customDescription },
},
}));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [customName, customDescription, selectedFormatter]);
const handleFormatterChange = (value: string) => {
setSelectedFormatter(value as constants.FormatterType);
if (value === constants.CUSTOM_FORMATTER) {
setCustomName(userData.formatter?.definition?.name || '');
setCustomDescription(userData.formatter?.definition?.description || '');
}
setUserData((prev) => ({
...prev,
formatter: {
id: value as constants.FormatterType,
definition:
value === constants.CUSTOM_FORMATTER
? {
name: userData.formatter?.definition?.name || '',
description: userData.formatter?.definition?.description || '',
}
: // keep definitions even when switching to a non-custom formatter
prev.formatter?.definition,
},
}));
};
const formatStream = useCallback(async () => {
if (isFormatting) return;
try {
setIsFormatting(true);
const parsedFile = FileParser.parse(filename);
const stream: ParsedStream = {
id: 'preview',
type,
addon: {
name: addonName,
presetType: 'custom',
presetInstanceId: 'custom',
enabled: true,
manifestUrl: 'http://localhost:2000/manifest.json',
timeout: 10000,
},
library,
parsedFile,
filename,
folderName: folder,
folderSize,
indexer,
regexMatched: {
name: regexMatched,
index: 0,
},
torrent: {
infoHash: type === 'p2p' ? '1234567890' : undefined,
seeders,
},
service:
providerId === 'none'
? undefined
: {
id: providerId,
cached: isCached,
},
age,
duration,
size: fileSize,
proxied,
message,
};
let data;
if (selectedFormatter === constants.CUSTOM_FORMATTER) {
const res = await UserConfigAPI.formatStream(
stream,
selectedFormatter,
{
name: customName,
description: customDescription,
},
userData.addonName
);
if (!res.success) {
toast.error(res.error?.message || 'Failed to format stream');
return;
}
data = res.data;
} else {
const res = await UserConfigAPI.formatStream(
stream,
selectedFormatter,
undefined,
userData.addonName
);
if (!res.success) {
toast.error(res.error?.message || 'Failed to format stream');
return;
}
data = res.data;
}
setFormattedStream(data ?? null);
} catch (error) {
console.error('Error formatting stream:', error);
toast.error('Failed to format stream');
} finally {
setIsFormatting(false);
}
}, [
filename || undefined,
folder || undefined,
indexer,
seeders,
age,
addonName,
providerId,
isCached,
type,
library,
duration,
fileSize,
folderSize,
proxied,
selectedFormatter,
isFormatting,
customName,
customDescription,
regexMatched,
message,
]);
useEffect(() => {
formatQueueRef.current.enqueue(formatStream);
}, [
filename,
folder,
indexer,
seeders,
age,
addonName,
providerId,
isCached,
type,
library,
duration,
fileSize,
folderSize,
proxied,
selectedFormatter,
customName,
regexMatched,
customDescription,
message,
]);
return (
<>
<div className="flex items-center w-full">
<div>
<h2>Formatter</h2>
<p className="text-[--muted]">Format your streams to your liking.</p>
</div>
<div className="hidden lg:block lg:ml-auto">
<PageControls />
</div>
</div>
{/* Formatter Selection in its own SettingsCard */}
<SettingsCard
title="Formatter Selection"
description="Choose how your streams should be formatted"
>
<Select
value={selectedFormatter}
onValueChange={handleFormatterChange}
options={formatterChoices.map((f) => ({
label: f.name,
value: f.id,
}))}
/>
<p className="text-sm text-muted-foreground mt-2">
{selectedFormatter !== constants.CUSTOM_FORMATTER &&
formatterChoices.find((f) => f.id === selectedFormatter)
?.description}
</p>
</SettingsCard>
{/* Custom Formatter Definition in its own SettingsCard, only if custom is selected */}
{selectedFormatter === constants.CUSTOM_FORMATTER && (
<SettingsCard
title="Custom Formatter"
description="Define your own formatter"
>
<div className="text-sm text-gray-400">
Type <span className="font-mono">{'{debug.jsonf}'}</span> to see the
available variables. For a more detailed explanation, check the{' '}
<a
href="https://github.com/Viren070/AIOStreams/wiki/Custom-Formatter"
target="_blank"
rel="noopener noreferrer"
className="text-[--brand] hover:text-[--brand]/80 hover:underline"
>
wiki
</a>
. You can also check the definitions of the predefined formatters{' '}
<a
href="https://github.com/Viren070/AIOStreams/blob/main/packages/core/src/formatters/predefined.ts"
target="_blank"
rel="noopener noreferrer"
className="text-[--brand] hover:text-[--brand]/80 hover:underline"
>
here
</a>
.
</div>
<div className="space-y-4">
<div>
<label className="text-sm font-medium mb-2 block">
Name Template
</label>
<Textarea
value={customName}
onChange={(e) => setCustomName(e.target.value)}
placeholder="Enter a template for the stream name"
/>
</div>
<div>
<label className="text-sm font-medium mb-2 block">
Description Template
</label>
<Textarea
value={customDescription}
onChange={(e) => setCustomDescription(e.target.value)}
placeholder="Enter a template for the stream description"
/>
</div>
<SnippetsButton />
</div>
</SettingsCard>
)}
{/* Preview in its own SettingsCard */}
<SettingsCard
title="Preview"
description="See how your streams would be formatted based on controllable variables"
>
<div className="space-y-4">
<div className="flex flex-col space-y-2">
<FormatterPreviewBox
name={formattedStream?.name}
description={formattedStream?.description}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<TextInput
label={<span className="truncate block">Filename</span>}
value={filename}
onValueChange={(value) => setFilename(value || '')}
className="w-full"
/>
<TextInput
label={<span className="truncate block">Folder Name</span>}
value={folder}
onValueChange={(value) => setFolder(value || '')}
className="w-full"
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-6 gap-4">
<TextInput
label={<span className="truncate block">Indexer</span>}
value={indexer}
onValueChange={(value) => setIndexer(value || '')}
className="w-full"
/>
<NumberInput
label={<span className="truncate block">Seeders</span>}
value={seeders}
onValueChange={(value) => setSeeders(value || undefined)}
className="w-full"
min={0}
defaultValue={0}
/>
<TextInput
label={<span className="truncate block">Age</span>}
value={age}
onValueChange={(value) => setAge(value || '')}
className="w-full"
/>
<NumberInput
label={<span className="truncate block">Duration (s)</span>}
value={duration ? duration / 1000 : undefined}
onValueChange={(value) =>
setDuration(value ? value * 1000 : undefined)
}
className="w-full"
min={0}
step={1000}
defaultValue={0}
/>
<NumberInput
label={<span className="truncate block">File Size (bytes)</span>}
value={fileSize}
onValueChange={(value) => setFileSize(value || undefined)}
className="w-full"
step={1000000000}
defaultValue={0}
min={0}
/>
<NumberInput
label={
<span className="truncate block">Folder Size (bytes)</span>
}
value={folderSize}
onValueChange={(value) => setFolderSize(value || undefined)}
className="w-full"
step={1000000000}
defaultValue={0}
min={0}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
<Select
label={<span className="truncate block">Service</span>}
value={providerId}
options={[
{ label: 'None', value: 'none' },
...Object.values(constants.SERVICE_DETAILS).map((service) => ({
label: service.name,
value: service.id,
})),
]}
onValueChange={(value: string) =>
setProviderId(value as constants.ServiceId)
}
className="w-full"
/>
<TextInput
label={<span className="truncate block">Addon Name</span>}
value={addonName}
onChange={(e) => setAddonName(e.target.value)}
className="w-full"
/>
<Select
label={<span className="truncate block">Stream Type</span>}
value={type}
onValueChange={(value: string) =>
setType(value as (typeof constants.STREAM_TYPES)[number])
}
options={constants.STREAM_TYPES.map((type) => ({
label: type.charAt(0).toUpperCase() + type.slice(1),
value: type,
}))}
className="w-full"
/>
<TextInput
label={<span className="truncate block">Regex Matched</span>}
value={regexMatched}
onValueChange={(value) => setRegexMatched(value || undefined)}
className="w-full"
/>
</div>
<TextInput
label={<span className="truncate block">Message</span>}
value={message}
onValueChange={(value) => setMessage(value || '')}
className="w-full"
placeholder="This is a message"
/>
{/* Centralized Switches Container - flex row, wraps on small width, centered */}
<div className="flex justify-center flex-wrap gap-4 pt-2">
<Switch
label={<span className="truncate block">Cached</span>}
value={isCached}
onValueChange={setIsCached}
/>
<Switch
label={<span className="truncate block">Library</span>}
value={library}
onValueChange={setLibrary}
/>
<Switch
label={<span className="truncate block">Proxied</span>}
value={proxied}
onValueChange={setProxied}
/>
</div>
</div>
</SettingsCard>
</>
);
}
function SnippetsButton() {
const disclosure = useDisclosure(false);
return (
<>
<Button intent="white" size="sm" onClick={disclosure.open}>
Snippets
</Button>
<Modal
open={disclosure.isOpen}
onOpenChange={disclosure.close}
title="Formatter Snippets"
>
<div className="space-y-4">
{SNIPPETS.map((snippet, idx) => (
<div
key={idx}
className="flex flex-col sm:flex-row sm:items-center sm:justify-between border rounded-md p-3 bg-gray-900 border-gray-800 gap-3"
>
<div>
<div className="font-semibold text-base mb-1">
{snippet.name}
</div>
<div className="text-sm text-muted-foreground mb-1 break-words">
{snippet.description}
</div>
<div className="font-mono text-xs bg-gray-800 rounded px-2 py-1 inline-block break-all">
{snippet.value}
</div>
</div>
<Button
size="sm"
intent="primary-outline"
className="sm:ml-4 flex-shrink-0"
onClick={async () => {
if (!navigator.clipboard) {
toast.error(
'The clipboard API is not available in this browser or context.'
);
return;
}
try {
await navigator.clipboard.writeText(snippet.value);
toast.success('Snippet copied to clipboard');
} catch (error) {
console.error(
'Failed to copy snippet to clipboard:',
error
);
toast.error('Failed to copy snippet to clipboard');
}
}}
title="Copy snippet"
>
<CopyIcon className="w-5 h-5" />
</Button>
</div>
))}
</div>
</Modal>
</>
);
}
|