Skip to content

Commit

Permalink
Fix order autoupdate and chat (#1047)
Browse files Browse the repository at this point in the history
* Fix Order autoupdate and chat

* Remove console.log
  • Loading branch information
KoalaSat authored Jan 6, 2024
1 parent 399671d commit 94af0b2
Show file tree
Hide file tree
Showing 14 changed files with 110 additions and 82 deletions.
2 changes: 1 addition & 1 deletion frontend/src/basic/OrderPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ const OrderPage = (): JSX.Element => {
if (robot != null && slot?.token != null) {
void federation.fetchRobot(garage, slot.token);
coordinator
.fetchOrder(currentOrderId, robot)
.fetchOrder(currentOrderId, robot, slot.token)
.then((order) => {
if (order?.bad_request !== undefined) {
setBadOrder(order.bad_request);
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/basic/RobotPage/RobotProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ const RobotProfile = ({

const handleChangeSlot = (e: SelectChangeEvent<number | 'loading'>): void => {
garage.currentSlot = e.target.value;
setInputToken(garage.getSlot()?.getRobot()?.token ?? '');
setInputToken(garage.getSlot()?.token ?? '');
setLoading(true);
};

Expand Down
9 changes: 8 additions & 1 deletion frontend/src/components/MakerForm/MakerForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,13 @@ const MakerForm = ({

useEffect(() => {
setCurrencyCode(currencyDict[fav.currency === 0 ? 1 : fav.currency]);
}, [coordinatorUpdatedAt]);

useEffect(() => {
updateCoordinatorInfo();
}, [maker.coordinator]);

const updateCoordinatorInfo = () => {
if (maker.coordinator != null) {
const newLimits = federation.getCoordinator(maker.coordinator).limits;
if (Object.keys(newLimits).length !== 0) {
Expand All @@ -107,7 +114,7 @@ const MakerForm = ({
setLimits(newLimits);
}
}
}, [coordinatorUpdatedAt]);
};

const updateAmountLimits = function (
limitList: LimitList,
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/RobotInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ const RobotInfo: React.FC<Props> = ({ coordinator, onClose }: Props) => {
const slot = garage.getSlot();
const robot = slot?.getRobot(coordinator.shortAlias);

if (robot != null && slot?.token != null && robot.encPrivKey != null && robot.token != null) {
void signCleartextMessage(rewardInvoice, robot.encPrivKey, robot.token).then(
if (robot != null && slot?.token != null && robot.encPrivKey != null) {
void signCleartextMessage(rewardInvoice, robot.encPrivKey, slot?.token).then(
(signedInvoice) => {
void coordinator.fetchReward(signedInvoice, garage, slot?.token).then((data) => {
setBadInvoice(data.bad_invoice ?? '');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,17 @@ import ChatHeader from '../ChatHeader';
import { type EncryptedChatMessage, type ServerMessage } from '..';
import ChatBottom from '../ChatBottom';
import { sha256 } from 'js-sha256';
import { Order } from '../../../../models';
import { UseFederationStoreType, FederationContext } from '../../../../contexts/FederationContext';
import { UseAppStoreType, AppContext } from '../../../../contexts/AppContext';

const audioPath =
window.NativeRobosats === undefined
? '/static/assets/sounds'
: 'file:///android_asset/Web.bundle/assets/sounds';

interface Props {
orderId: number;
order: Order;
status: number;
userNick: string;
takerNick: string;
Expand All @@ -34,7 +37,7 @@ interface Props {
}

const EncryptedSocketChat: React.FC<Props> = ({
orderId,
order,
status,
userNick,
takerNick,
Expand All @@ -46,7 +49,9 @@ const EncryptedSocketChat: React.FC<Props> = ({
}: Props): JSX.Element => {
const { t } = useTranslation();
const theme = useTheme();
const { origin, hostUrl, settings } = useContext<UseAppStoreType>(AppContext);
const { garage, robotUpdatedAt } = useContext<UseGarageStoreType>(GarageContext);
const { federation } = useContext<UseFederationStoreType>(FederationContext);

const [audio] = useState(() => new Audio(`${audioPath}/chat-open.mp3`));
const [connected, setConnected] = useState<boolean>(false);
Expand Down Expand Up @@ -98,13 +103,20 @@ const EncryptedSocketChat: React.FC<Props> = ({
}, [serverMessages]);

const connectWebsocket = (): void => {
const robot = garage.getSlot()?.getRobot();
const slot = garage.getSlot();
const robot = slot?.getRobot();

if (!robot) return;
if (!slot?.token) return;

const { url, basePath } = federation
.getCoordinator(order.shortAlias)
.getEndpoint(settings.network, origin, settings.selfhostedClient, hostUrl);

websocketClient
.open(
`ws://${window.location.host}/ws/chat/${orderId}/?token_sha256_hex=${sha256(robot?.token)}`,
`${url.replace(/^https?:\/\//, 'ws://') + basePath}/ws/chat/${
order.id
}/?token_sha256_hex=${sha256(slot?.token)}`,
)
.then((connection) => {
setConnection(connection);
Expand Down Expand Up @@ -144,7 +156,8 @@ const EncryptedSocketChat: React.FC<Props> = ({

const onMessage: (message: any) => void = (message) => {
const dataFromServer = JSON.parse(message.data);
const robot = garage.getSlot()?.getRobot();
const slot = garage.getSlot();
const robot = slot?.getRobot();
if (dataFromServer != null && !receivedIndexes.includes(dataFromServer.index)) {
setReceivedIndexes((prev) => [...prev, dataFromServer.index]);
setPeerConnected(dataFromServer.peer_connected);
Expand All @@ -166,7 +179,7 @@ const EncryptedSocketChat: React.FC<Props> = ({
dataFromServer.message.split('\\').join('\n'),
dataFromServer.user_nick === userNick ? robot.pubKey : peerPubKey,
robot.encPrivKey,
robot.token,
slot.token,
).then((decryptedData) => {
setWaitingEcho(waitingEcho ? decryptedData.decryptedMessage !== lastSent : false);
setLastSent(decryptedData.decryptedMessage === lastSent ? '----BLANK----' : lastSent);
Expand Down Expand Up @@ -214,8 +227,9 @@ const EncryptedSocketChat: React.FC<Props> = ({
};

const onButtonClicked = (e: React.FormEvent<HTMLFormElement>): void => {
const robot = garage.getSlot()?.getRobot();
if (robot?.token !== undefined && value.includes(robot.token)) {
const slot = garage.getSlot();
const robot = slot?.getRobot();
if (slot?.token !== undefined && value.includes(slot.token)) {
alert(
`Aye! You just sent your own robot robot.token to your peer in chat, that's a catastrophic idea! So bad your message was blocked.`,
);
Expand All @@ -235,7 +249,7 @@ const EncryptedSocketChat: React.FC<Props> = ({
setValue('');
setWaitingEcho(true);
setLastSent(value);
encryptMessage(value, robot.pubKey, peerPubKey, robot.encPrivKey, robot.token)
encryptMessage(value, robot.pubKey, peerPubKey, robot.encPrivKey, slot.token)
.then((encryptedMessage) => {
if (connection != null) {
connection.send({
Expand Down Expand Up @@ -264,12 +278,12 @@ const EncryptedSocketChat: React.FC<Props> = ({
onClose={() => {
setAudit(false);
}}
orderId={Number(orderId)}
orderId={Number(order.id)}
messages={messages}
ownPubKey={garage.getSlot()?.getRobot()?.pubKey ?? ''}
ownEncPrivKey={garage.getSlot()?.getRobot()?.encPrivKey ?? ''}
peerPubKey={peerPubKey ?? 'Not received yet'}
passphrase={garage.getSlot()?.getRobot()?.token ?? ''}
passphrase={garage.getSlot()?.token ?? ''}
onClickBack={() => {
setAudit(false);
}}
Expand Down Expand Up @@ -381,7 +395,7 @@ const EncryptedSocketChat: React.FC<Props> = ({
</Grid>
<Grid item>
<ChatBottom
orderId={orderId}
orderId={order.id}
audit={audit}
setAudit={setAudit}
createJsonFile={createJsonFile}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ import {
FederationContext,
} from '../../../../contexts/FederationContext';
import { type UseGarageStoreType, GarageContext } from '../../../../contexts/GarageContext';
import { Order } from '../../../../models';

interface Props {
orderId: number;
order: Order;
userNick: string;
takerNick: string;
chatOffset: number;
Expand All @@ -38,7 +39,7 @@ const audioPath =
: 'file:///android_asset/Web.bundle/assets/sounds';

const EncryptedTurtleChat: React.FC<Props> = ({
orderId,
order,
userNick,
takerNick,
chatOffset,
Expand Down Expand Up @@ -94,7 +95,7 @@ const EncryptedTurtleChat: React.FC<Props> = ({
.getCoordinator(shortAlias)
.getEndpoint(settings.network, origin, settings.selfhostedClient, hostUrl);
apiClient
.get(url + basePath, `/api/chat/?order_id=${orderId}&offset=${lastIndex}`, {
.get(url + basePath, `/api/chat/?order_id=${order.id}&offset=${lastIndex}`, {
tokenSHA256: garage.getSlot()?.getRobot()?.tokenSHA256 ?? '',
})
.then((results: any) => {
Expand Down Expand Up @@ -122,15 +123,16 @@ const EncryptedTurtleChat: React.FC<Props> = ({
};

const onMessage = (dataFromServer: ServerMessage): void => {
const robot = garage.getSlot();
const slot = garage.getSlot();
const robot = slot?.getRobot();
if (robot && dataFromServer != null) {
// If we receive an encrypted message
if (dataFromServer.message.substring(0, 27) === `-----BEGIN PGP MESSAGE-----`) {
void decryptMessage(
dataFromServer.message.split('\\').join('\n'),
dataFromServer.nick === userNick ? robot.pubKey : peerPubKey,
robot.encPrivKey,
robot.token,
slot.token,
).then((decryptedData) => {
setLastSent(decryptedData.decryptedMessage === lastSent ? '----BLANK----' : lastSent);
setLastIndex(lastIndex < dataFromServer.index ? dataFromServer.index : lastIndex);
Expand Down Expand Up @@ -178,11 +180,12 @@ const EncryptedTurtleChat: React.FC<Props> = ({
};

const onButtonClicked = (e: React.FormEvent<HTMLFormElement>): void => {
const robot = garage.getSlot()?.getRobot();
const slot = garage.getSlot();
const robot = slot?.getRobot();

if (!robot) return;

if (robot?.token && value.includes(robot.token)) {
if (slot?.token && value.includes(slot.token)) {
alert(
`Aye! You just sent your own robot robot.token to your peer in chat, that's a catastrophic idea! So bad your message was blocked.`,
);
Expand All @@ -199,7 +202,7 @@ const EncryptedTurtleChat: React.FC<Props> = ({
`/api/chat/`,
{
PGP_message: value,
order_id: orderId,
order_id: order.id,
offset: lastIndex,
},
{ tokenSHA256: robot?.tokenSHA256 ?? '' },
Expand All @@ -221,7 +224,7 @@ const EncryptedTurtleChat: React.FC<Props> = ({
else if (value !== '' && Boolean(robot?.pubKey)) {
setWaitingEcho(true);
setLastSent(value);
encryptMessage(value, robot?.pubKey, peerPubKey ?? '', robot?.encPrivKey, robot?.token)
encryptMessage(value, robot?.pubKey, peerPubKey ?? '', robot?.encPrivKey, slot?.token)
.then((encryptedMessage) => {
const { url, basePath } = federation
.getCoordinator(garage.getSlot()?.activeShortAlias ?? '')
Expand All @@ -232,7 +235,7 @@ const EncryptedTurtleChat: React.FC<Props> = ({
`/api/chat/`,
{
PGP_message: String(encryptedMessage).split('\n').join('\\'),
order_id: orderId,
order_id: order.id,
offset: lastIndex,
},
{ tokenSHA256: robot?.tokenSHA256 },
Expand Down Expand Up @@ -270,7 +273,7 @@ const EncryptedTurtleChat: React.FC<Props> = ({
onClose={() => {
setAudit(false);
}}
orderId={Number(orderId)}
orderId={Number(order.id)}
messages={messages}
ownPubKey={garage.getSlot()?.getRobot()?.pubKey ?? ''}
ownEncPrivKey={garage.getSlot()?.getRobot()?.encPrivKey ?? ''}
Expand Down Expand Up @@ -382,7 +385,7 @@ const EncryptedTurtleChat: React.FC<Props> = ({

<Grid item>
<ChatBottom
orderId={orderId}
orderId={order.id}
audit={audit}
setAudit={setAudit}
createJsonFile={createJsonFile}
Expand Down
10 changes: 5 additions & 5 deletions frontend/src/components/TradeBox/EncryptedChat/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import React, { useState } from 'react';
import { type Robot } from '../../../models';
import { Order, type Robot } from '../../../models';
import EncryptedSocketChat from './EncryptedSocketChat';
import EncryptedTurtleChat from './EncryptedTurtleChat';

interface Props {
orderId: number;
order: Order;
status: number;
takerNick: string;
makerNick: string;
Expand Down Expand Up @@ -33,7 +33,7 @@ export interface ServerMessage {
}

const EncryptedChat: React.FC<Props> = ({
orderId,
order,
takerNick,
userNick,
chatOffset,
Expand All @@ -48,7 +48,7 @@ const EncryptedChat: React.FC<Props> = ({
<EncryptedTurtleChat
messages={messages}
setMessages={setMessages}
orderId={orderId}
order={order}
takerNick={takerNick}
userNick={userNick}
chatOffset={chatOffset}
Expand All @@ -61,7 +61,7 @@ const EncryptedChat: React.FC<Props> = ({
status={status}
messages={messages}
setMessages={setMessages}
orderId={orderId}
order={order}
takerNick={takerNick}
userNick={userNick}
baseUrl={baseUrl}
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/TradeBox/Prompts/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export const ChatPrompt = ({
<EncryptedChat
status={order.status}
chatOffset={order.chat_last_index}
orderId={order.id}
order={order}
takerNick={order.taker_nick}
makerNick={order.maker_nick}
userNick={order.ur_nick}
Expand Down
18 changes: 10 additions & 8 deletions frontend/src/components/TradeBox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -269,11 +269,12 @@ const TradeBox = ({ baseUrl, onStartAgain }: TradeBoxProps): JSX.Element => {
};

const updateInvoice = function (invoice: string): void {
const robot = garage.getSlot()?.getRobot();
const slot = garage.getSlot();
const robot = slot?.getRobot();

if (robot?.encPrivKey != null && robot?.token != null) {
if (robot?.encPrivKey != null && slot?.token != null) {
setLoadingButtons({ ...noLoadingButtons, submitInvoice: true });
void signCleartextMessage(invoice, robot.encPrivKey, robot.token).then((signedInvoice) => {
void signCleartextMessage(invoice, robot.encPrivKey, slot.token).then((signedInvoice) => {
submitAction({
action: 'update_invoice',
invoice: signedInvoice,
Expand All @@ -284,11 +285,12 @@ const TradeBox = ({ baseUrl, onStartAgain }: TradeBoxProps): JSX.Element => {
};

const updateAddress = function (): void {
const robot = garage.getSlot()?.getRobot();
const slot = garage.getSlot();
const robot = slot?.getRobot();

if (robot?.encPrivKey != null && robot?.token != null) {
if (robot?.encPrivKey != null && slot?.token != null) {
setLoadingButtons({ ...noLoadingButtons, submitAddress: true });
void signCleartextMessage(onchain.address, robot.encPrivKey, robot.token).then(
void signCleartextMessage(onchain.address, robot.encPrivKey, slot.token).then(
(signedAddress) => {
submitAction({
action: 'update_address',
Expand All @@ -306,10 +308,10 @@ const TradeBox = ({ baseUrl, onStartAgain }: TradeBoxProps): JSX.Element => {
};

const submitStatement = function (): void {
const robot = garage.getSlot()?.getRobot();
const slot = garage.getSlot();
let statement = dispute.statement;
if (dispute.attachLogs) {
const payload = { statement, messages, token: robot?.token };
const payload = { statement, messages, token: slot?.token };
statement = JSON.stringify(payload, null, 2);
}
setLoadingButtons({ ...noLoadingButtons, submitStatement: true });
Expand Down
Loading

0 comments on commit 94af0b2

Please sign in to comment.