-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
358 lines (315 loc) · 14.1 KB
/
App.tsx
File metadata and controls
358 lines (315 loc) · 14.1 KB
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
import React, { useState, useEffect, useRef } from 'react';
import JSZip from 'jszip';
import { Settings, Download, Calendar, Activity, AlertCircle, FileAudio, CheckCircle } from 'lucide-react';
import Background from './components/Background';
import SettingsModal from './components/SettingsModal';
import StatsCard from './components/StatsCard';
import { AppConfig, ExtractionMode, ProcessingLog, LimitlessRecording } from './types';
import { LimitlessService } from './services/limitlessService';
import { getDaysInRange, getMonthDays, getDayBoundaries, formatDateInTimezone, getDayChunks } from './utils/dateUtils';
const App: React.FC = () => {
// Config State
// Config State
const [config, setConfig] = useState<AppConfig>(() => {
const saved = localStorage.getItem('limitless_config');
if (saved) {
try {
return JSON.parse(saved);
} catch (e) {
console.error("Failed to parse saved config", e);
}
}
return {
apiKey: '',
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
};
});
// Persist config
useEffect(() => {
localStorage.setItem('limitless_config', JSON.stringify(config));
}, [config]);
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
// Selection State
const [mode, setMode] = useState<ExtractionMode>(ExtractionMode.SINGLE_DAY);
const [selectedDate, setSelectedDate] = useState<string>(new Date().toISOString().split('T')[0]);
const [endDate, setEndDate] = useState<string>(new Date().toISOString().split('T')[0]);
const [selectedMonth, setSelectedMonth] = useState<string>(new Date().toISOString().slice(0, 7));
// Processing State
const [isProcessing, setIsProcessing] = useState(false);
const [progress, setProgress] = useState(0); // 0-100
const [statusText, setStatusText] = useState('');
const [logs, setLogs] = useState<ProcessingLog[]>([]);
const logContainerRef = useRef<HTMLDivElement>(null);
// Auto-scroll logs
useEffect(() => {
if (logContainerRef.current) {
logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
}
}, [logs]);
const addLog = (message: string, type: ProcessingLog['type'] = 'info') => {
setLogs(prev => [...prev, { timestamp: Date.now(), message, type }]);
};
const handleExtract = async () => {
if (!config.apiKey) {
setIsSettingsOpen(true);
addLog("Please configure your API Key first.", "warning");
return;
}
setIsProcessing(true);
setProgress(0);
setLogs([]);
addLog("Initializing extraction sequence...", "info");
const service = new LimitlessService(config.apiKey);
// const zip = new JSZip(); // Removed to avoid memory issues
let daysToProcess: Date[] = [];
// 1. Determine Date Range
try {
if (mode === ExtractionMode.SINGLE_DAY) {
daysToProcess = [new Date(selectedDate)];
} else if (mode === ExtractionMode.RANGE) {
daysToProcess = getDaysInRange(new Date(selectedDate), new Date(endDate));
} else if (mode === ExtractionMode.MONTH) {
const [y, m] = selectedMonth.split('-').map(Number);
daysToProcess = getMonthDays(y, m - 1); // JS Month is 0-indexed
}
addLog(`Selected ${daysToProcess.length} days to process.`, "info");
let totalRecordingsFound = 0;
const totalDays = daysToProcess.length;
// 2. Iterate Days
for (let i = 0; i < totalDays; i++) {
const day = daysToProcess[i];
const dayStr = day.toISOString().split('T')[0];
setStatusText(`Processing ${dayStr}...`);
// Update progress
setProgress(Math.floor((i / totalDays) * 100));
const chunks = getDayChunks(day, config.timezone);
const dayBlobs: Blob[] = [];
// Process chunks sequentially to respect rate limits and order
for (const chunk of chunks) {
try {
// Construct URL for this chunk (using Express proxy on port 3001)
const chunkUrl = `http://localhost:3001/api/v1/download-audio?audioSource=pendant&startMs=${chunk.startMs}&endMs=${chunk.endMs}`;
// Download
const blob = await service.downloadAudioFile(chunkUrl);
// Only add if it has content (size > 0)
if (blob.size > 0) {
dayBlobs.push(blob);
}
} catch (e) {
// console.warn(`No audio for chunk ${chunk.startMs}`, e);
}
}
if (dayBlobs.length > 0) {
addLog(`Downloaded ${dayBlobs.length} parts for ${dayStr}`, "success");
// Merge blobs into one file for the day
const mergedBlob = new Blob(dayBlobs, { type: 'audio/ogg' });
// Create descriptive filename: YYYY-MM-DD_DayOfWeek.ogg
const dateObj = new Date(dayStr);
const localDate = new Date(dayStr + 'T00:00:00');
const dayName = localDate.toLocaleDateString('en-US', { weekday: 'long' });
const fileName = `${dayStr}_${dayName}.ogg`;
// SAVE TO DISK VIA PROXY
addLog(`Saving ${fileName} to disk...`, "info");
try {
const saveResponse = await fetch(`http://localhost:3001/save-file?filename=${fileName}`, {
method: 'POST',
body: mergedBlob
});
if (saveResponse.ok) {
addLog(`Saved: ${fileName}`, "success");
totalRecordingsFound++;
} else {
const errText = await saveResponse.text();
addLog(`Failed to save ${fileName}: ${errText}`, "error");
}
} catch (saveError: any) {
addLog(`Save error: ${saveError.message}`, "error");
}
// Clear memory explicitly (though GC handles it eventually)
dayBlobs.length = 0;
} else {
addLog(`No audio found for ${dayStr}`, "info");
}
}
if (totalRecordingsFound === 0) {
addLog("Extraction complete. No recordings found in range.", "warning");
} else {
addLog(`Extraction complete. ${totalRecordingsFound} files saved to 'downloads' folder.`, "success");
}
setStatusText("Complete");
setProgress(100);
} catch (e: any) {
addLog(`Critical Error: ${e.message}`, "error");
} finally {
setIsProcessing(false);
}
};
return (
<div className="min-h-screen text-white font-sans selection:bg-purple-500/30">
<Background />
<SettingsModal
isOpen={isSettingsOpen}
onClose={() => setIsSettingsOpen(false)}
config={config}
onSave={setConfig}
/>
<main className="container mx-auto px-4 py-12 max-w-5xl">
{/* Header */}
<header className="flex justify-between items-center mb-12">
<div>
<h1 className="text-4xl font-light tracking-tighter mb-2 bg-clip-text text-transparent bg-gradient-to-r from-white to-white/60">
Limitless Aether
</h1>
<p className="text-white/40 font-light">Audio Archive Extractor</p>
</div>
<button
onClick={() => setIsSettingsOpen(true)}
className="glass-button w-12 h-12 rounded-full flex items-center justify-center text-white/80"
>
<Settings size={20} />
</button>
</header>
<div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
{/* Left Column: Controls */}
<div className="lg:col-span-7 space-y-6">
{/* Mode Selection */}
<div className="glass-panel p-6 rounded-2xl space-y-6">
<div className="flex gap-2 p-1 bg-white/5 rounded-xl">
{Object.values(ExtractionMode).map((m) => (
<button
key={m}
onClick={() => setMode(m)}
className={`flex-1 py-2 px-4 rounded-lg text-sm font-medium transition-all ${mode === m
? 'bg-white text-black shadow-lg'
: 'text-white/40 hover:text-white/80'
}`}
>
{m === ExtractionMode.SINGLE_DAY && 'Single Day'}
{m === ExtractionMode.RANGE && 'Range'}
{m === ExtractionMode.MONTH && 'Whole Month'}
</button>
))}
</div>
{/* Date Inputs */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 animate-fade-in">
{mode === ExtractionMode.MONTH ? (
<div className="space-y-2 col-span-2">
<label className="text-xs font-medium text-white/40 uppercase tracking-wider ml-1">Select Month</label>
<div className="relative">
<Calendar className="absolute left-4 top-1/2 -translate-y-1/2 text-white/30" size={16} />
<input
type="month"
value={selectedMonth}
onChange={(e) => setSelectedMonth(e.target.value)}
className="w-full pl-12 pr-4 py-4 rounded-xl glass-input appearance-none"
/>
</div>
</div>
) : (
<>
<div className="space-y-2">
<label className="text-xs font-medium text-white/40 uppercase tracking-wider ml-1">Start Date</label>
<div className="relative">
<Calendar className="absolute left-4 top-1/2 -translate-y-1/2 text-white/30" size={16} />
<input
type="date"
value={selectedDate}
onChange={(e) => setSelectedDate(e.target.value)}
className="w-full pl-12 pr-4 py-4 rounded-xl glass-input appearance-none"
/>
</div>
</div>
{mode === ExtractionMode.RANGE && (
<div className="space-y-2 animate-fade-in">
<label className="text-xs font-medium text-white/40 uppercase tracking-wider ml-1">End Date</label>
<div className="relative">
<Calendar className="absolute left-4 top-1/2 -translate-y-1/2 text-white/30" size={16} />
<input
type="date"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
className="w-full pl-12 pr-4 py-4 rounded-xl glass-input appearance-none"
/>
</div>
</div>
)}
</>
)}
</div>
{/* Action Button */}
<button
onClick={handleExtract}
disabled={isProcessing}
className="w-full glass-button group relative overflow-hidden rounded-xl py-4 mt-4 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="relative z-10 flex items-center justify-center gap-3">
{isProcessing ? (
<>
<Activity className="animate-spin" size={20} />
<span className="font-medium">Processing...</span>
</>
) : (
<>
<Download size={20} />
<span className="font-medium">Extract & Download Zip</span>
</>
)}
</div>
{/* Progress Bar Background */}
{isProcessing && (
<div
className="absolute inset-0 bg-white/10 transition-all duration-300 ease-out"
style={{ width: `${progress}%` }}
/>
)}
</button>
</div>
{/* Quick Stats (Placeholder/Mock) */}
<div className="grid grid-cols-2 gap-4">
<StatsCard
label="Configured Zone"
value={config.timezone.split('/')[1] || config.timezone}
icon={<Settings size={18} />}
/>
<StatsCard
label="Status"
value={config.apiKey ? "Ready" : "No Token"}
icon={config.apiKey ? <CheckCircle size={18} className="text-green-400" /> : <AlertCircle size={18} className="text-orange-400" />}
/>
</div>
</div>
{/* Right Column: Logs/Output */}
<div className="lg:col-span-5 h-[500px] flex flex-col glass-panel rounded-2xl overflow-hidden">
<div className="p-4 border-b border-white/10 bg-white/5 flex justify-between items-center">
<span className="text-sm font-medium text-white/70">System Logs</span>
{statusText && <span className="text-xs text-white/40 animate-pulse">{statusText}</span>}
</div>
<div ref={logContainerRef} className="flex-1 overflow-y-auto p-4 space-y-3 font-mono text-sm">
{logs.length === 0 && (
<div className="h-full flex flex-col items-center justify-center text-white/20 gap-4">
<FileAudio size={48} strokeWidth={1} />
<p>Ready to extract</p>
</div>
)}
{logs.map((log, i) => (
<div key={i} className="flex gap-3 items-start animate-fade-in">
<span className="text-white/20 text-xs mt-1">
{new Date(log.timestamp).toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' })}
</span>
<p className={`flex-1 break-words ${log.type === 'error' ? 'text-red-400' :
log.type === 'success' ? 'text-green-400' :
log.type === 'warning' ? 'text-orange-300' :
'text-white/70'
}`}>
{log.message}
</p>
</div>
))}
</div>
</div>
</div>
</main>
</div>
);
};
export default App;