Skip to content

Commit

Permalink
Android Tor Requests
Browse files Browse the repository at this point in the history
  • Loading branch information
KoalaSat committed Sep 19, 2022
1 parent ce2ef1f commit 914dc05
Show file tree
Hide file tree
Showing 25 changed files with 675 additions and 30,771 deletions.
15,030 changes: 167 additions & 14,863 deletions frontend/package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@typescript-eslint/eslint-plugin": "^5.35.1",
"@typescript-eslint/parser": "^5.35.1",
"babel-loader": "^8.2.5",
"copy-webpack-plugin": "^11.0.0",
"eslint": "^8.23.0",
"eslint-config-prettier": "^8.5.0",
"eslint-config-standard-with-typescript": "^22.0.0",
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export default class App extends Component {
>
<SchoolIcon />
</IconButton>
<UnsafeAlert className='unsafeAlert' />
{/* <UnsafeAlert className='unsafeAlert' /> */}
<HomePage {...this.state} />
</ThemeProvider>
</I18nextProvider>
Expand Down
13 changes: 6 additions & 7 deletions frontend/src/components/BottomBar.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,10 @@ class BottomBar extends Component {

showProfileButton = () => {
return (
this.props.avatarLoaded &&
(this.props.token ? getCookie('robot_token') == this.props.token : true) &&
getCookie('sessionid')
this.props.avatarLoaded
// FIXME: Cookies not available on local dev
// (this.props.token ? getCookie('robot_token') == this.props.token : true) &&
// getCookie('sessionid')
);
};

Expand Down Expand Up @@ -201,14 +202,12 @@ class BottomBar extends Component {
sx={{ margin: 0, top: -13 }}
alt={this.props.nickname}
imgProps={{
// FIXME: Avatar src not working
onLoad: () => this.props.setAppState({ avatarLoaded: true }),
}}
src={
this.props.nickname
? window.location.origin +
'/static/assets/avatars/' +
this.props.nickname +
'.png'
? 'https://robosats.onion.moe/static/assets/avatars/' + this.props.nickname + '.png'
: null
}
/>
Expand Down
25 changes: 18 additions & 7 deletions frontend/src/components/HomePage.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { HashRouter, BrowserRouter , Switch, Route } from 'react-router-dom';

import UserGenPage from './UserGenPage';
import MakerPage from './MakerPage';
Expand Down Expand Up @@ -39,16 +39,27 @@ export default class HomePage extends Component {
this.props.history.push(location);
}

getBasename() {
if (window.NativeRobosats) {
// Only for Android
return window.location.pathname
}

return ""
}

render() {
const fontSize = this.props.theme.typography.fontSize;
const fontSizeFactor = fontSize / 14; // default fontSize is 14
const Router = window.NativeRobosats ? HashRouter : BrowserRouter

return (
<Router>
<Router basename={this.getBasename()}>
<div className='appCenter'>
<Switch>
<Route
exact
path='/'
path="/"
render={(props) => (
<UserGenPage
{...props}
Expand All @@ -59,7 +70,7 @@ export default class HomePage extends Component {
)}
/>
<Route
path='/ref/:refCode'
path="/ref/:refCode"
render={(props) => (
<UserGenPage
{...props}
Expand All @@ -70,7 +81,7 @@ export default class HomePage extends Component {
)}
/>
<Route
path='/make'
path="/make"
render={(props) => (
<MakerPage
{...props}
Expand All @@ -81,7 +92,7 @@ export default class HomePage extends Component {
)}
/>
<Route
path='/book'
path="/book"
render={(props) => (
<BookPage
{...props}
Expand All @@ -92,7 +103,7 @@ export default class HomePage extends Component {
)}
/>
<Route
path='/order/:orderId'
path="/order/:orderId"
render={(props) => (
<OrderPage
{...props}
Expand Down
30 changes: 19 additions & 11 deletions frontend/src/components/UserGenPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class UserGenPage extends Component {
this.setState({
nickname: this.props.nickname,
token: this.props.token ? this.props.token : '',
avatarUrl: '/static/assets/avatars/' + this.props.nickname + '.png',
avatarUrl: 'https://robosats.onion.moe/static/assets/avatars/' + this.props.nickname + '.png',
loadingRobot: false,
});
} else {
Expand All @@ -75,13 +75,12 @@ class UserGenPage extends Component {
ref_code: refCode,
};
});

requestBody.then((body) =>
apiClient.post('/api/user/', body).then((data) => {
this.setState({
nickname: data.nickname,
bit_entropy: data.token_bits_entropy,
avatarUrl: '/static/assets/avatars/' + data.nickname + '.png',
avatarUrl: 'https://robosats.onion.moe/static/assets/avatars/' + data.nickname + '.png',
shannon_entropy: data.token_shannon_entropy,
bad_request: data.bad_request,
found: data.found,
Expand All @@ -102,7 +101,8 @@ class UserGenPage extends Component {
: this.props.setAppState({
nickname: data.nickname,
token,
avatarLoaded: false,
// FIXME: Avatar src not working
avatarLoaded: true,
activeOrderId: data.active_order_id ? data.active_order_id : null,
lastOrderId: data.last_order_id ? data.last_order_id : null,
referralCode: data.referral_code,
Expand Down Expand Up @@ -299,7 +299,9 @@ class UserGenPage extends Component {
<IconButton
color='primary'
disabled={
!(getCookie('robot_token') == this.state.token) ||
// FIXME: Cookies not available on local dev
// https://github.com/react-native-webview/react-native-webview/issues/2643
// !(getCookie('robot_token') == this.state.token) ||
!this.props.avatarLoaded
}
onClick={() =>
Expand All @@ -318,7 +320,9 @@ class UserGenPage extends Component {
<IconButton
color={this.props.copiedToken ? 'inherit' : 'primary'}
disabled={
!(getCookie('robot_token') == this.state.token) ||
// FIXME: Cookies not available on local dev
// https://github.com/react-native-webview/react-native-webview/issues/2643
// !(getCookie('robot_token') == this.state.token) ||
!this.props.avatarLoaded
}
onClick={() =>
Expand Down Expand Up @@ -374,11 +378,13 @@ class UserGenPage extends Component {
<ButtonGroup variant='contained' aria-label='outlined primary button group'>
<Button
disabled={
this.state.loadingRobot ||
!(this.props.token ? getCookie('robot_token') == this.props.token : true)
this.state.loadingRobot !== false
// FIXME: Cookies not available on local dev
// https://github.com/react-native-webview/react-native-webview/issues/2643
// !(this.props.token ? getCookie('robot_token') == this.props.token : true)
}
color='primary'
to='/make/'
to='/make'
component={Link}
>
{t('Make Order')}
Expand All @@ -393,8 +399,10 @@ class UserGenPage extends Component {
/>
<Button
disabled={
this.state.loadingRobot ||
!(this.props.token ? getCookie('robot_token') == this.props.token : true)
this.state.loadingRobot !== false
// FIXME: Cookies not available on local dev
// https://github.com/react-native-webview/react-native-webview/issues/2643
// !(this.props.token ? getCookie('robot_token') == this.props.token : true)
}
color='secondary'
to='/book/'
Expand Down
41 changes: 41 additions & 0 deletions frontend/src/components/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,25 @@ import HttpApi from 'i18next-http-backend';
// import translationPT from "../../static/locales/pt.json";
// import translationEU from "../../static/locales/th.json";

const loadJsonFile = async (path) => {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', path, true);
request.responseType = 'blob';

request.onload = () => {
const reader = new FileReader();

reader.onload = (e) => resolve(e.target.result);
reader.onerror = err => reject(err);
reader.readAsDataURL(request.response);
};

request.send();
});
}


i18n
.use(HttpApi)
.use(LanguageDetector)
Expand Down Expand Up @@ -44,6 +63,28 @@ i18n
withCredentials: false,
overrideMimeType: false,
reloadInterval: false, // can be used to reload resources in a specific interval (useful in server environments)
request: (
_options,
url,
_payload,
callback
) => {
if (window.ReactNativeWebView) {
loadJsonFile(window.location.pathname.slice(0, -1) + url)
.then((response) => {
console.log(response)
const data = JSON.stringify(response)
callback(null, { status: 200, data })
})
} else {
fetch(url)
.then(async (response) => await response.json())
.then((response) => {
const data = JSON.stringify(response)
callback(null, { status: 200, data })
})
}
}
},

fallbackLng: 'en',
Expand Down
28 changes: 28 additions & 0 deletions frontend/src/services/Native/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import NativeRobosats from './index'

declare global {
interface Window {
ReactNativeWebView?: ReactNativeWebView
NativeRobosats?: NativeRobosats
}
}

export interface ReactNativeWebView {
postMessage(message: string): void
}

export interface NativeWebViewMessageHttp {
id?: number
category: 'http'
type: 'post' | 'get' | 'put' | 'delete'
path: string
headers?: object
body?: object
}

export declare type NativeWebViewMessage = NativeWebViewMessageHttp

export interface NativeRobosatsPromise {
resolve: (value: object | PromiseLike<object>) => void,
reject: (reason?: any) => void
}
43 changes: 43 additions & 0 deletions frontend/src/services/Native/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { NativeRobosatsPromise, NativeWebViewMessage } from './index.d'

class NativeRobosats {
constructor() {
this.messageCounter = 0
}

public messageCounter: number

public pendingMessages: {[id:number]: NativeRobosatsPromise} = []

public onMessageResolve: (messageId: number, response?: object) => void = (messageId, response = {}) =>{
if (this.pendingMessages[messageId]) {
this.pendingMessages[messageId].resolve(response)
delete this.pendingMessages[messageId]
}
}

public onMessageReject: (messageId: number, response?: object) => void = (messageId, response = {}) =>{
if (this.pendingMessages[messageId]) {
this.pendingMessages[messageId].reject(response)
delete this.pendingMessages[messageId]
}
}

public postMessage: (message: NativeWebViewMessage) => Promise<object> = (message) => {
this.messageCounter += 1
message.id = this.messageCounter
const json = JSON.stringify(message)
window.ReactNativeWebView?.postMessage(json)

return new Promise<object>(async (resolve, reject) => {
if (message.id) {
this.pendingMessages[message.id] = {
resolve: resolve,
reject: reject
}
}
})
}
}

export default NativeRobosats
50 changes: 50 additions & 0 deletions frontend/src/services/api/ApiNativeClient/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { ApiClient } from '../api';
import { getCookie } from '../../../utils/cookies';
import NativeRobosats from '../../Native';

class ApiNativeClient implements ApiClient {
constructor() {
window.NativeRobosats = new NativeRobosats()
}

private readonly getHeaders: () => HeadersInit = () => {
return { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') || '' };
};

public put: (path: string, body: object) => Promise<object | undefined> = async (path, body) => {
const requestOptions = {
method: 'PUT',
headers: this.getHeaders(),
body: JSON.stringify(body),
};
return await fetch('https://unsafe.robosats.com' + path, requestOptions).then(async (response) => await response.json());
};

public delete: (path: string) => Promise<object | undefined> = async (path) => {
const requestOptions = {
method: 'DELETE',
headers: this.getHeaders(),
};
return await fetch('https://unsafe.robosats.com' + path, requestOptions).then(async (response) => await response.json());
};

public post: (path: string, body: object) => Promise<object | undefined> = async (path, body) => {
return window.NativeRobosats?.postMessage({
category: 'http',
type: 'post',
path,
body,
headers: this.getHeaders()
})
};

public get: (path: string) => Promise<object | undefined> = async (path) => {
return window.NativeRobosats?.postMessage({
category: 'http',
type: 'get',
path
})
};
}

export default ApiNativeClient;
Loading

0 comments on commit 914dc05

Please sign in to comment.