-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
483 lines (442 loc) · 16.2 KB
/
App.js
File metadata and controls
483 lines (442 loc) · 16.2 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
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
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { StatusBar } from 'expo-status-bar';
import { Alert, Linking, PermissionsAndroid, Platform, Animated, Easing, Modal, TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { LinearGradient } from 'expo-linear-gradient';
import {
Button,
H1,
H2,
Paragraph,
ScrollView,
SizableText,
TamaguiProvider,
Theme,
XStack,
YStack,
Input,
Switch,
Spacer,
Stack,
} from 'tamagui';
import { useFonts, Syne_700Bold, Syne_500Medium } from '@expo-google-fonts/syne';
import { Manrope_400Regular, Manrope_600SemiBold } from '@expo-google-fonts/manrope';
import { Ionicons } from '@expo/vector-icons';
import { tamaguiConfig } from './tamagui.config';
import {
startWolServer,
stopWolServer,
getLogs,
clearLogs,
isIgnoringBatteryOptimizations,
requestIgnoreBatteryOptimizations,
getAutoStartConfig,
} from "./native/WolServerModule";
const statusSubscribers = new Set();
const logStatus = (message) => {
const timestamped = `[${new Date().toISOString().split('T')[1].slice(0, 8)}] ${message}`;
console.log(timestamped);
statusSubscribers.forEach((handler) => handler(timestamped));
};
const subscribeToStatus = (handler) => {
statusSubscribers.add(handler);
return () => {
statusSubscribers.delete(handler);
};
};
const DEFAULT_PORT = '8080';
const StatusOrb = ({ isRunning, onPress }) => {
const pulseAnim = useRef(new Animated.Value(1)).current;
const rotateAnim = useRef(new Animated.Value(0)).current;
useEffect(() => {
if (isRunning) {
Animated.loop(
Animated.sequence([
Animated.timing(pulseAnim, {
toValue: 1.2,
duration: 2000,
useNativeDriver: true,
easing: Easing.inOut(Easing.ease),
}),
Animated.timing(pulseAnim, {
toValue: 1,
duration: 2000,
useNativeDriver: true,
easing: Easing.inOut(Easing.ease),
}),
])
).start();
Animated.loop(
Animated.timing(rotateAnim, {
toValue: 1,
duration: 10000,
useNativeDriver: true,
easing: Easing.linear,
})
).start();
} else {
pulseAnim.setValue(1);
rotateAnim.setValue(0);
}
}, [isRunning]);
const spin = rotateAnim.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg'],
});
return (
<TouchableOpacity onPress={onPress} activeOpacity={0.8}>
<Stack alignItems="center" justifyContent="center" width={240} height={240}>
{/* Outer Glow */}
<Animated.View
style={{
position: 'absolute',
width: 240,
height: 240,
borderRadius: 120,
backgroundColor: isRunning ? 'rgba(34, 211, 238, 0.1)' : 'rgba(239, 68, 68, 0.05)',
transform: [{ scale: pulseAnim }],
}}
/>
{/* Inner Ring */}
<Animated.View
style={{
position: 'absolute',
width: 200,
height: 200,
borderRadius: 100,
borderWidth: 2,
borderColor: isRunning ? 'rgba(34, 211, 238, 0.3)' : 'rgba(239, 68, 68, 0.2)',
borderStyle: 'dashed',
transform: [{ rotate: spin }],
}}
/>
{/* Core */}
<LinearGradient
colors={isRunning ? ['#22d3ee', '#0891b2'] : ['#ef4444', '#991b1b']}
style={{
width: 160,
height: 160,
borderRadius: 80,
alignItems: 'center',
justifyContent: 'center',
shadowColor: isRunning ? '#22d3ee' : '#ef4444',
shadowOffset: { width: 0, height: 0 },
shadowOpacity: 0.5,
shadowRadius: 20,
elevation: 10,
}}
>
<Ionicons name="power" size={64} color="white" />
<SizableText color="white" fontFamily="Syne_700Bold" fontSize={18} marginTop={8}>
{isRunning ? 'ONLINE' : 'OFFLINE'}
</SizableText>
</LinearGradient>
</Stack>
</TouchableOpacity>
);
};
const GlassCard = ({ children, style }) => (
<Stack
backgroundColor="rgba(255, 255, 255, 0.05)"
borderColor="rgba(255, 255, 255, 0.1)"
borderWidth={1}
borderRadius={24}
padding={20}
{...style}
>
{children}
</Stack>
);
const AppContent = () => {
const [listenPort, setListenPort] = useState(DEFAULT_PORT);
const [sharedSecret, setSharedSecret] = useState('');
const [isRunning, setIsRunning] = useState(false);
const [statusLog, setStatusLog] = useState([]);
const [activePort, setActivePort] = useState(null);
const [showSettings, setShowSettings] = useState(false);
const [showLogs, setShowLogs] = useState(false);
const logScrollRef = useRef(null);
useEffect(() => {
return subscribeToStatus((entry) => {
setStatusLog((current) => {
const next = [entry, ...current];
return next.slice(0, 50);
});
});
}, []);
const fetchLogs = async () => {
try {
const logs = await getLogs();
// Parse logs or just split by newline
const logLines = logs.split('\n').filter(Boolean).reverse();
setStatusLog(logLines);
} catch (e) {
Alert.alert('Error', 'Failed to fetch logs');
}
};
const handleClearLogs = async () => {
try {
await clearLogs();
setStatusLog([]);
} catch (e) {
Alert.alert('Error', 'Failed to clear logs');
}
};
useEffect(() => {
if (showLogs) {
fetchLogs();
}
}, [showLogs]);
useEffect(() => {
setIsRunning(false);
// Only auto-start if previously running. This avoids requesting POST_NOTIFICATIONS
// on first install before the user interacts with the app.
getAutoStartConfig().then((config) => {
if (config && config.autostart) {
if (config.port) setListenPort(config.port.toString());
if (config.token) setSharedSecret(config.token);
// The useCallback of startRelay depends on state, so we call startRelay directly
// with the config to ensure it uses the latest values from SharedPreferences
startRelayWithConfig(config.port, config.token);
}
});
}, []);
const ensureForegroundServiceReady = useCallback(async () => {
if (Platform.OS !== 'android') return true;
const sdkInt = Number(Platform.Version);
if (!Number.isNaN(sdkInt) && sdkInt >= 33) {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
);
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
Alert.alert('Notifications required', 'Grant notification permission to run the foreground service.');
return false;
}
} catch (e) {
return false;
}
}
return true;
}, []);
const startRelayWithConfig = useCallback(
async (customPort, customToken) => {
const portNumber = Number(customPort ?? listenPort);
const token = customToken ?? sharedSecret;
if (Number.isNaN(portNumber) || portNumber <= 0 || portNumber > 65535) {
Alert.alert(
"Invalid port",
"Please enter a TCP port between 1 and 65535.",
);
return;
}
if (isRunning) return;
const ok = await ensureForegroundServiceReady();
if (!ok) return;
try {
await startWolServer({ port: portNumber, token: token || null });
logStatus(`Wake relay listening on port ${portNumber}`);
setIsRunning(true);
setActivePort(portNumber);
} catch (error) {
Alert.alert("Failed to start relay", error.message);
}
},
[listenPort, sharedSecret, ensureForegroundServiceReady, isRunning],
);
const startRelay = useCallback(() => {
return startRelayWithConfig();
}, [startRelayWithConfig]);
const stopRelay = useCallback(async () => {
if (!isRunning) return;
try {
await stopWolServer();
setIsRunning(false);
setActivePort(null);
logStatus('Wake relay stopped');
} catch (error) {
Alert.alert('Failed to stop relay', error.message);
}
}, [isRunning]);
const toggleRelay = () => {
if (isRunning) stopRelay();
else startRelay();
};
const handleOpenWebUi = useCallback(() => {
const portNumber = Number(activePort ?? listenPort);
const url = `http://127.0.0.1:${portNumber}/`;
Linking.openURL(url).catch(() => Alert.alert('Error', 'Could not open browser'));
}, [activePort, listenPort]);
return (
<LinearGradient
colors={['#0f172a', '#1e293b', '#0f172a']}
style={{ flex: 1 }}
>
<SafeAreaView style={{ flex: 1 }}>
<StatusBar style="light" />
{/* Header */}
<XStack paddingHorizontal={24} paddingTop={12} justifyContent="space-between" alignItems="center">
<YStack>
<SizableText fontFamily="Syne_700Bold" fontSize={32} color="white">WOLE</SizableText>
<SizableText fontFamily="Manrope_400Regular" fontSize={14} color="rgba(255,255,255,0.5)">Relay Station</SizableText>
</YStack>
<TouchableOpacity onPress={() => setShowSettings(true)}>
<Stack backgroundColor="rgba(255,255,255,0.1)" padding={10} borderRadius={20}>
<Ionicons name="settings-outline" size={24} color="white" />
</Stack>
</TouchableOpacity>
</XStack>
{/* Main Content */}
<YStack flex={1} alignItems="center" justifyContent="center" gap={40}>
<StatusOrb isRunning={isRunning} onPress={toggleRelay} />
<YStack alignItems="center" gap={8}>
<SizableText fontFamily="Manrope_600SemiBold" fontSize={18} color="white">
{isRunning ? `Listening on Port ${activePort}` : 'Service Stopped'}
</SizableText>
<SizableText fontFamily="Manrope_400Regular" fontSize={14} color="rgba(255,255,255,0.5)" textAlign="center" maxWidth={280}>
{isRunning
? 'Ready to forward Wake-on-LAN packets from authorized web clients.'
: 'Tap the orb to start the relay service.'}
</SizableText>
</YStack>
{isRunning && (
<Button
backgroundColor="rgba(34, 211, 238, 0.15)"
borderColor="rgba(34, 211, 238, 0.3)"
borderWidth={1}
color="#22d3ee"
icon={<Ionicons name="globe-outline" size={18} color="#22d3ee" />}
onPress={handleOpenWebUi}
pressStyle={{ backgroundColor: 'rgba(34, 211, 238, 0.25)' }}
borderRadius={100}
paddingHorizontal={24}
>
Open Web Dashboard
</Button>
)}
</YStack>
{/* Footer Actions */}
<XStack padding={24} justifyContent="center">
<TouchableOpacity onPress={() => setShowLogs(true)}>
<XStack alignItems="center" gap={8}>
<Ionicons name="terminal-outline" size={16} color="rgba(255,255,255,0.5)" />
<SizableText fontFamily="Manrope_600SemiBold" fontSize={14} color="rgba(255,255,255,0.5)">
View System Logs
</SizableText>
</XStack>
</TouchableOpacity>
</XStack>
{/* Settings Modal */}
<Modal visible={showSettings} animationType="slide" transparent>
<Stack flex={1} backgroundColor="rgba(0,0,0,0.8)">
<Stack flex={1} onPress={() => setShowSettings(false)} />
<GlassCard style={{ borderBottomLeftRadius: 0, borderBottomRightRadius: 0, paddingBottom: 40 }}>
<XStack justifyContent="space-between" alignItems="center" marginBottom={24}>
<SizableText fontFamily="Syne_700Bold" fontSize={24} color="white">Configuration</SizableText>
<TouchableOpacity onPress={() => setShowSettings(false)}>
<Ionicons name="close-circle" size={32} color="rgba(255,255,255,0.5)" />
</TouchableOpacity>
</XStack>
<YStack gap={20}>
<YStack gap={8}>
<SizableText color="rgba(255,255,255,0.7)" fontFamily="Manrope_600SemiBold">Listen Port</SizableText>
<Input
value={listenPort}
onChangeText={setListenPort}
keyboardType="numeric"
backgroundColor="rgba(0,0,0,0.3)"
borderColor="rgba(255,255,255,0.1)"
color="white"
editable={!isRunning}
/>
</YStack>
<YStack gap={8}>
<SizableText color="rgba(255,255,255,0.7)" fontFamily="Manrope_600SemiBold">Auth Token (Optional)</SizableText>
<Input
value={sharedSecret}
onChangeText={setSharedSecret}
secureTextEntry
backgroundColor="rgba(0,0,0,0.3)"
borderColor="rgba(255,255,255,0.1)"
color="white"
editable={!isRunning}
placeholder="Leave empty for no auth"
placeholderTextColor="rgba(255,255,255,0.2)"
/>
</YStack>
<Button
onPress={async () => {
try {
const isIgnoring = await isIgnoringBatteryOptimizations();
if (isIgnoring) {
Alert.alert('Already Optimized', 'Battery optimization is already disabled for WOLE. The service will run reliably in the background.');
} else {
await requestIgnoreBatteryOptimizations();
}
} catch (e) {
Linking.openSettings();
}
}}
backgroundColor="rgba(255,255,255,0.1)"
color="white"
icon={<Ionicons name="battery-charging-outline" size={18} color="white" />}
>
Disable Battery Optimization
</Button>
</YStack>
</GlassCard>
</Stack>
</Modal>
{/* Logs Modal */}
<Modal visible={showLogs} animationType="slide" transparent>
<Stack flex={1} backgroundColor="rgba(0,0,0,0.8)">
<Stack flex={1} onPress={() => setShowLogs(false)} />
<GlassCard style={{ height: '60%', borderBottomLeftRadius: 0, borderBottomRightRadius: 0 }}>
<XStack justifyContent="space-between" alignItems="center" marginBottom={16}>
<SizableText fontFamily="Syne_700Bold" fontSize={20} color="white">System Logs</SizableText>
<TouchableOpacity onPress={handleClearLogs}>
<SizableText color="#ef4444" fontFamily="Manrope_600SemiBold">Clear</SizableText>
</TouchableOpacity>
</XStack>
<ScrollView
ref={logScrollRef}
showsVerticalScrollIndicator={false}
contentContainerStyle={{ paddingBottom: 20 }}
>
{statusLog.map((log, i) => (
<SizableText key={i} fontFamily="monospace" fontSize={12} color="rgba(255,255,255,0.7)" marginBottom={8}>
{log}
</SizableText>
))}
{statusLog.length === 0 && (
<SizableText color="rgba(255,255,255,0.3)" textAlign="center" marginTop={20}>No logs yet.</SizableText>
)}
</ScrollView>
<Button onPress={() => setShowLogs(false)} marginTop={16} backgroundColor="rgba(255,255,255,0.1)" color="white">
Close
</Button>
</GlassCard>
</Stack>
</Modal>
</SafeAreaView>
</LinearGradient>
);
};
export default function App() {
const [fontsLoaded] = useFonts({
Syne_700Bold,
Syne_500Medium,
Manrope_400Regular,
Manrope_600SemiBold,
});
if (!fontsLoaded) {
return null;
}
return (
<TamaguiProvider config={tamaguiConfig}>
<Theme name="dark">
<AppContent />
</Theme>
</TamaguiProvider>
);
}