robosats/mobile/App.tsx

234 lines
7.8 KiB
TypeScript
Raw Permalink Normal View History

import React, { useEffect, useRef } from 'react';
import { WebView, WebViewMessageEvent } from 'react-native-webview';
import { SafeAreaView, Text, Platform, Appearance, DeviceEventEmitter } from 'react-native';
import TorClient from './services/Tor';
import Clipboard from '@react-native-clipboard/clipboard';
import EncryptedStorage from 'react-native-encrypted-storage';
import { name as app_name, version as app_version } from './package.json';
2024-03-29 19:05:50 +00:00
import TorModule from './native/TorModule';
2024-04-27 21:33:52 +00:00
import RoboIdentitiesModule from './native/RoboIdentitiesModule';
2024-07-09 19:38:25 +00:00
import NotificationsModule from './native/NotificationsModule';
2024-07-12 10:57:09 +00:00
import SystemModule from './native/SystemModule';
const backgroundColors = {
light: 'white',
dark: 'black',
};
export type TorStatus = 'ON' | 'STARTING' | 'STOPPING' | 'OFF';
const App = () => {
const colorScheme = Appearance.getColorScheme() ?? 'light';
const torClient = new TorClient();
const webViewRef = useRef<WebView>();
const uri = (Platform.OS === 'android' ? 'file:///android_asset/' : '') + 'Web.bundle/index.html';
useEffect(() => {
TorModule.start();
2024-07-12 10:57:09 +00:00
DeviceEventEmitter.addListener('navigateToPage', (payload) => {
2024-07-12 19:43:23 +00:00
window.navigateToPage = payload;
2024-07-12 10:57:09 +00:00
injectMessage({
category: 'system',
type: 'navigateToPage',
detail: payload,
});
});
DeviceEventEmitter.addListener('TorStatus', (payload) => {
if (payload.torStatus === 'OFF') TorModule.restart();
injectMessage({
category: 'system',
type: 'torStatus',
detail: payload.torStatus,
});
});
}, []);
useEffect(() => {
const interval = setInterval(() => {
TorModule.getTorStatus();
}, 2000);
return () => clearInterval(interval);
}, []);
const injectMessageResolve = (id: string, data?: object) => {
2022-10-16 17:04:10 +00:00
const json = JSON.stringify(data || {});
webViewRef.current?.injectJavaScript(
`(function() {window.NativeRobosats.onMessageResolve(${id}, ${json});})();`,
);
};
const injectMessage = (message: object) => {
const json = JSON.stringify(message);
webViewRef.current?.injectJavaScript(
`(function() {window.NativeRobosats?.onMessage(${json});})();`,
);
};
2024-07-12 19:43:23 +00:00
const onLoadEnd = () => {
if (window.navigateToPage) {
injectMessage({
category: 'system',
type: 'navigateToPage',
detail: window.navigateToPage,
});
window.navigateToPage = undefined;
}
};
2023-05-01 19:11:08 +00:00
const init = (responseId: string) => {
const loadCookie = async (key: string) => {
return await EncryptedStorage.getItem(key).then((value) => {
if (value) {
const json = JSON.stringify({ key, value });
webViewRef.current?.injectJavaScript(
`(function() {window.NativeRobosats?.loadCookie(${json});})();`,
);
2024-07-09 19:38:25 +00:00
return value;
}
});
};
loadCookie('settings_fontsize_basic');
loadCookie('settings_language');
loadCookie('settings_mode');
2023-05-05 17:19:45 +00:00
loadCookie('settings_light_qr');
loadCookie('settings_network');
2024-07-12 10:57:09 +00:00
loadCookie('settings_use_proxy').then((useProxy) => {
SystemModule.useProxy(useProxy ?? 'true');
});
2024-09-18 13:34:31 +00:00
loadCookie('settings_stop_notifications').then((stopNotifications) => {
SystemModule.stopNotifications(stopNotifications ?? 'true');
});
2024-07-09 19:38:25 +00:00
loadCookie('garage_slots').then((slots) => {
NotificationsModule.monitorOrders(slots ?? '{}');
injectMessageResolve(responseId);
});
};
const onCatch = (dataId: string, event: any) => {
let json = '{}';
let code = 500;
if (event.message) {
const reponse = /Request Response Code \((?<code>\d*)\)\: (?<json>\{.*\})/.exec(
event.message,
);
json = reponse?.groups?.json ?? '{}';
2023-03-10 23:47:25 +00:00
code = reponse?.groups?.code ? parseInt(reponse?.groups?.code) : 500;
}
injectMessageResolve(dataId, {
headers: {},
respCode: code,
json: JSON.parse(json),
});
};
const onMessage = async (event: WebViewMessageEvent) => {
const data = JSON.parse(event.nativeEvent.data);
if (data.category === 'http') {
TorModule.getTorStatus();
if (data.type === 'get') {
torClient
.get(data.baseUrl, data.path, data.headers)
.then((response: object) => {
injectMessageResolve(data.id, response);
})
.catch((e) => onCatch(data.id, e))
.finally(TorModule.getTorStatus);
} else if (data.type === 'post') {
torClient
.post(data.baseUrl, data.path, data.body, data.headers)
.then((response: object) => {
injectMessageResolve(data.id, response);
})
.catch((e) => onCatch(data.id, e))
.finally(TorModule.getTorStatus);
} else if (data.type === 'delete') {
torClient
.delete(data.baseUrl, data.path, data.headers)
.then((response: object) => {
injectMessageResolve(data.id, response);
})
.catch((e) => onCatch(data.id, e))
.finally(TorModule.getTorStatus);
}
} else if (data.category === 'system') {
if (data.type === 'init') {
init(data.id);
} else if (data.type === 'copyToClipboardString') {
Clipboard.setString(data.detail);
} else if (data.type === 'setCookie') {
setCookie(data.key, data.detail);
2024-07-12 10:57:09 +00:00
if (data.key === 'federation') {
SystemModule.setFederation(data.detail ?? '{}');
} else if (data.key === 'garage_slots') {
NotificationsModule.monitorOrders(data.detail ?? '{}');
} else if (data.key === 'settings_use_proxy') {
SystemModule.useProxy(data.detail ?? 'true');
2024-09-18 13:34:31 +00:00
} else if (data.key === 'settings_stop_notifications') {
SystemModule.stopNotifications(data.detail ?? 'false');
2024-07-12 10:57:09 +00:00
}
} else if (data.type === 'deleteCookie') {
EncryptedStorage.removeItem(data.key);
}
2024-04-27 21:33:52 +00:00
} else if (data.category === 'roboidentities') {
if (data.type === 'roboname') {
2024-04-28 12:34:32 +00:00
const roboname = await RoboIdentitiesModule.generateRoboname(data.detail);
injectMessageResolve(data.id, { roboname });
} else if (data.type === 'robohash') {
const robohash = await RoboIdentitiesModule.generateRobohash(data.detail);
injectMessageResolve(data.id, { robohash });
2024-04-27 21:33:52 +00:00
}
}
};
const setCookie = async (key: string, value: string) => {
try {
await EncryptedStorage.setItem(key, value);
const storedValue = await EncryptedStorage.getItem(key);
injectMessage({
category: 'system',
type: 'setCookie',
key,
detail: storedValue,
});
} catch (error) {}
};
return (
<SafeAreaView style={{ flex: 1, backgroundColor: backgroundColors[colorScheme] }}>
<WebView
source={{
uri,
}}
onMessage={onMessage}
// @ts-expect-error
userAgent={`${app_name} v${app_version} Android`}
style={{ backgroundColor: backgroundColors[colorScheme] }}
ref={(ref) => (webViewRef.current = ref)}
overScrollMode='never'
javaScriptEnabled={true}
domStorageEnabled={true}
sharedCookiesEnabled={true}
thirdPartyCookiesEnabled={true}
originWhitelist={[uri]}
scalesPageToFit={true}
startInLoadingState={true}
mixedContentMode={'always'}
allowsInlineMediaPlayback={true}
allowsFullscreenVideo={false}
setBuiltInZoomControls={false}
allowingReadAccessToURL={uri}
allowFileAccess={true}
allowsBackForwardNavigationGestures={true}
2023-05-27 09:08:00 +00:00
mediaPlaybackRequiresUserAction={false} // Allow autoplay
allowsLinkPreview={false}
renderLoading={() => <Text></Text>}
onError={(syntheticEvent) => <Text>{syntheticEvent.type}</Text>}
2024-07-12 19:43:23 +00:00
onLoadEnd={() => setTimeout(onLoadEnd, 3000)}
/>
</SafeAreaView>
);
};
export default App;