Apply prettier on client

This commit is contained in:
Jeremie Pardou-Piquemal 2020-06-13 16:21:35 +02:00 committed by Jérémie Pardou-Piquemal
parent 3f17ca707b
commit e06b0e384c
58 changed files with 1217 additions and 966 deletions

View File

@ -2,7 +2,7 @@
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@/*":["src/*"]
"@/*": ["src/*"]
}
}
}

View File

@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="en" class='h-100'>
<html lang="en" class="h-100">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
@ -20,12 +20,12 @@
Learn how to configure a non-root public URL by running `npm run build`.
-->
<meta name="robots" content="index,nofollow">
<meta name="googlebot" content="index,nofollow">
<meta name="description" content="darkwire.io is the simplest way to chat with encryption online.">
<meta name="robots" content="index,nofollow" />
<meta name="googlebot" content="index,nofollow" />
<meta name="description" content="darkwire.io is the simplest way to chat with encryption online." />
<title>darkwire.io - instant encrypted web chat</title>
</head>
<body class='h-100'>
<body class="h-100">
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root" class="h-100"></div>
<!--

View File

@ -1,40 +1,40 @@
export const openModal = payload => ({ type: 'OPEN_MODAL', payload })
export const closeModal = () => ({ type: 'CLOSE_MODAL' })
export const openModal = payload => ({ type: 'OPEN_MODAL', payload });
export const closeModal = () => ({ type: 'CLOSE_MODAL' });
export const setScrolledToBottom = payload => ({ type: 'SET_SCROLLED_TO_BOTTOM', payload })
export const setScrolledToBottom = payload => ({ type: 'SET_SCROLLED_TO_BOTTOM', payload });
export const showNotice = payload => async (dispatch) => {
dispatch({ type: 'SHOW_NOTICE', payload })
}
export const showNotice = payload => async dispatch => {
dispatch({ type: 'SHOW_NOTICE', payload });
};
export const toggleWindowFocus = payload => async (dispatch) => {
dispatch({ type: 'TOGGLE_WINDOW_FOCUS', payload })
}
export const toggleWindowFocus = payload => async dispatch => {
dispatch({ type: 'TOGGLE_WINDOW_FOCUS', payload });
};
export const toggleSoundEnabled = payload => async (dispatch) => {
dispatch({ type: 'TOGGLE_SOUND_ENABLED', payload })
}
export const toggleSoundEnabled = payload => async dispatch => {
dispatch({ type: 'TOGGLE_SOUND_ENABLED', payload });
};
export const toggleNotificationEnabled = payload => async (dispatch) => {
dispatch({ type: 'TOGGLE_NOTIFICATION_ENABLED', payload })
}
export const toggleNotificationEnabled = payload => async dispatch => {
dispatch({ type: 'TOGGLE_NOTIFICATION_ENABLED', payload });
};
export const toggleNotificationAllowed = payload => async (dispatch) => {
dispatch({ type: 'TOGGLE_NOTIFICATION_ALLOWED', payload })
}
export const toggleNotificationAllowed = payload => async dispatch => {
dispatch({ type: 'TOGGLE_NOTIFICATION_ALLOWED', payload });
};
export const toggleSocketConnected = payload => async (dispatch) => {
dispatch({ type: 'TOGGLE_SOCKET_CONNECTED', payload })
}
export const toggleSocketConnected = payload => async dispatch => {
dispatch({ type: 'TOGGLE_SOCKET_CONNECTED', payload });
};
export const createUser = payload => async (dispatch) => {
dispatch({ type: 'CREATE_USER', payload })
}
export const createUser = payload => async dispatch => {
dispatch({ type: 'CREATE_USER', payload });
};
export const clearActivities = () => async (dispatch) => {
dispatch({ type: 'CLEAR_ACTIVITIES' })
}
export const clearActivities = () => async dispatch => {
dispatch({ type: 'CLEAR_ACTIVITIES' });
};
export const setLanguage = payload => async (dispatch) => {
dispatch({type: 'CHANGE_LANGUAGE', payload});
}
export const setLanguage = payload => async dispatch => {
dispatch({ type: 'CHANGE_LANGUAGE', payload });
};

View File

@ -1,19 +1,16 @@
import { getSocket } from 'utils/socket'
import {
prepare as prepareMessage,
process as processMessage,
} from 'utils/message'
import { getSocket } from 'utils/socket';
import { prepare as prepareMessage, process as processMessage } from 'utils/message';
export const sendEncryptedMessage = payload => async (dispatch, getState) => {
const state = getState()
const msg = await prepareMessage(payload, state)
dispatch({ type: `SEND_ENCRYPTED_MESSAGE_${msg.original.type}`, payload: msg.original.payload })
getSocket().emit('ENCRYPTED_MESSAGE', msg.toSend)
}
const state = getState();
const msg = await prepareMessage(payload, state);
dispatch({ type: `SEND_ENCRYPTED_MESSAGE_${msg.original.type}`, payload: msg.original.payload });
getSocket().emit('ENCRYPTED_MESSAGE', msg.toSend);
};
export const receiveEncryptedMessage = payload => async (dispatch, getState) => {
const state = getState()
const message = await processMessage(payload, state)
const state = getState();
const message = await processMessage(payload, state);
// Pass current state to all RECEIVE_ENCRYPTED_MESSAGE reducers for convenience, since each may have different needs
dispatch({ type: `RECEIVE_ENCRYPTED_MESSAGE_${message.type}`, payload: { payload: message.payload, state } })
}
dispatch({ type: `RECEIVE_ENCRYPTED_MESSAGE_${message.type}`, payload: { payload: message.payload, state } });
};

View File

@ -1,6 +1,5 @@
/* istanbul ignore file */
export * from './app'
export * from './unencrypted_messages'
export * from './encrypted_messages'
export * from './app';
export * from './unencrypted_messages';
export * from './encrypted_messages';

View File

@ -1,15 +1,15 @@
import { getSocket } from 'utils/socket'
import { getSocket } from 'utils/socket';
const receiveUserEnter = (payload, dispatch) => {
dispatch({ type: 'USER_ENTER', payload })
}
dispatch({ type: 'USER_ENTER', payload });
};
const receiveToggleLockRoom = (payload, dispatch, getState) => {
const state = getState()
const state = getState();
const lockedByUser = state.room.members.find(m => m.publicKey.n === payload.publicKey.n)
const lockedByUsername = lockedByUser.username
const lockedByUserId = lockedByUser.id
const lockedByUser = state.room.members.find(m => m.publicKey.n === payload.publicKey.n);
const lockedByUsername = lockedByUser.username;
const lockedByUserId = lockedByUser.id;
dispatch({
type: 'RECEIVE_TOGGLE_LOCK_ROOM',
@ -18,20 +18,20 @@ const receiveToggleLockRoom = (payload, dispatch, getState) => {
locked: payload.locked,
id: lockedByUserId,
},
})
}
});
};
const receiveUserExit = (payload, dispatch, getState) => {
const state = getState()
const state = getState();
const payloadPublicKeys = payload.map(member => member.publicKey.n);
const exitingUser = state.room.members.find(m => !payloadPublicKeys.includes(m.publicKey.n))
const exitingUser = state.room.members.find(m => !payloadPublicKeys.includes(m.publicKey.n));
if (!exitingUser) {
return;
}
const exitingUserId = exitingUser.id
const exitingUsername = exitingUser.username
const exitingUserId = exitingUser.id;
const exitingUsername = exitingUser.username;
dispatch({
type: 'USER_EXIT',
@ -40,11 +40,11 @@ const receiveUserExit = (payload, dispatch, getState) => {
id: exitingUserId,
username: exitingUsername,
},
})
}
});
};
export const receiveUnencryptedMessage = (type, payload) => async (dispatch, getState) => {
switch(type) {
switch (type) {
case 'USER_ENTER':
return receiveUserEnter(payload, dispatch);
case 'USER_EXIT':
@ -54,11 +54,11 @@ export const receiveUnencryptedMessage = (type, payload) => async (dispatch, get
default:
return;
}
}
};
const sendToggleLockRoom = (dispatch, getState) => {
const state = getState()
getSocket().emit('TOGGLE_LOCK_ROOM', null, (res) => {
const state = getState();
getSocket().emit('TOGGLE_LOCK_ROOM', null, res => {
dispatch({
type: 'TOGGLE_LOCK_ROOM',
payload: {
@ -66,15 +66,15 @@ const sendToggleLockRoom = (dispatch, getState) => {
username: state.user.username,
sender: state.user.id,
},
})
})
}
});
});
};
export const sendUnencryptedMessage = (type, payload) => async (dispatch, getState) => {
switch(type) {
switch (type) {
case 'TOGGLE_LOCK_ROOM':
return sendToggleLockRoom(dispatch, getState);
default:
return;
}
}
};

View File

@ -1,27 +1,27 @@
/* istanbul ignore file */
let host
let protocol
let port
let host;
let protocol;
let port;
switch (process.env.NODE_ENV) {
case 'staging':
host = process.env.REACT_APP_API_HOST
protocol = process.env.REACT_APP_API_PROTOCOL || 'https'
port = process.env.REACT_APP_API_PORT || 443
break
host = process.env.REACT_APP_API_HOST;
protocol = process.env.REACT_APP_API_PROTOCOL || 'https';
port = process.env.REACT_APP_API_PORT || 443;
break;
case 'production':
host = process.env.REACT_APP_API_HOST
protocol = process.env.REACT_APP_API_PROTOCOL || 'https'
port = process.env.REACT_APP_API_PORT || 443
break
host = process.env.REACT_APP_API_HOST;
protocol = process.env.REACT_APP_API_PROTOCOL || 'https';
port = process.env.REACT_APP_API_PORT || 443;
break;
default:
host = process.env.REACT_APP_API_HOST || 'localhost'
protocol = process.env.REACT_APP_API_PROTOCOL || 'http'
port = process.env.REACT_APP_API_PORT || 3001
host = process.env.REACT_APP_API_HOST || 'localhost';
protocol = process.env.REACT_APP_API_PROTOCOL || 'http';
port = process.env.REACT_APP_API_PORT || 3001;
}
export default {
host,
port,
protocol,
}
};

View File

@ -1,14 +1,14 @@
/* istanbul ignore file */
import config from './config'
import config from './config';
export default (resourceName = '') => {
const { port, protocol, host } = config
const { port, protocol, host } = config;
const resourcePath = resourceName
const resourcePath = resourceName;
if (!host) {
return `/${resourcePath}`;
}
return `${protocol}://${host}:${port}/${resourcePath}`
}
return `${protocol}://${host}:${port}/${resourcePath}`;
};

View File

@ -1,78 +1,125 @@
/* eslint-disable */
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import apiUrlGenerator from '../../api/generator';
import styles from './styles.module.scss'
import styles from './styles.module.scss';
class About extends Component {
constructor(props) {
super(props);
this.state = {
roomId: props.roomId,
abuseReported: false
}
abuseReported: false,
};
}
handleUpdateRoomId(evt) {
this.setState({
roomId: evt.target.value,
})
});
}
handleReportAbuse(evt) {
evt.preventDefault();
fetch(`${apiUrlGenerator('abuse')}/${this.state.roomId}`, {
method: 'POST'
method: 'POST',
});
this.setState({
abuseReported: true,
})
});
}
render() {
return (
<div className={styles.base}>
<div className={styles.links}>
<div><a href="#version">Version</a></div>
<div><a href="#software">Software</a></div>
<div><a href="#report-abuse">Report Abuse</a></div>
<div><a href="#acceptable-use">Acceptable Use Policy</a></div>
<div><a href="#disclaimer">Disclaimer</a></div>
<div><a href="#terms">Terms of Service</a></div>
<div><a href="#contact">Contact</a></div>
<div><a href="#donate">Donate</a></div>
<div>
<a href="#version">Version</a>
</div>
<div>
<a href="#software">Software</a>
</div>
<div>
<a href="#report-abuse">Report Abuse</a>
</div>
<div>
<a href="#acceptable-use">Acceptable Use Policy</a>
</div>
<div>
<a href="#disclaimer">Disclaimer</a>
</div>
<div>
<a href="#terms">Terms of Service</a>
</div>
<div>
<a href="#contact">Contact</a>
</div>
<div>
<a href="#donate">Donate</a>
</div>
</div>
<section id='version'>
<section id="version">
<h4>Version</h4>
<p>
Commit SHA: <a target="_blank" href={`https://github.com/darkwire/darkwire.io/commit/${process.env.REACT_APP_COMMIT_SHA}`}>{process.env.REACT_APP_COMMIT_SHA}</a></p>
Commit SHA:{' '}
<a
target="_blank"
href={`https://github.com/darkwire/darkwire.io/commit/${process.env.REACT_APP_COMMIT_SHA}`}
>
{process.env.REACT_APP_COMMIT_SHA}
</a>
</p>
</section>
<section id='software'>
<section id="software">
<h4>Software</h4>
<p>This software uses the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Crypto" target="_blank" rel="noopener noreferrer">Web Cryptography API</a> to
encrypt data which is transferred using <a href="https://en.wikipedia.org/wiki/WebSocket" target="_blank" rel="noopener noreferrer">secure WebSockets</a>.
Messages are never stored on a server or sent over the wire in plain-text.</p>
<p>We believe in privacy and transparency.
&nbsp;<a href="https://github.com/darkwire/darkwire.io" target="_blank" rel="noopener noreferrer">View the source code and documentation on GitHub.</a></p>
<p>
This software uses the{' '}
<a href="https://developer.mozilla.org/en-US/docs/Web/API/Crypto" target="_blank" rel="noopener noreferrer">
Web Cryptography API
</a>{' '}
to encrypt data which is transferred using{' '}
<a href="https://en.wikipedia.org/wiki/WebSocket" target="_blank" rel="noopener noreferrer">
secure WebSockets
</a>
. Messages are never stored on a server or sent over the wire in plain-text.
</p>
<p>
We believe in privacy and transparency. &nbsp;
<a href="https://github.com/darkwire/darkwire.io" target="_blank" rel="noopener noreferrer">
View the source code and documentation on GitHub.
</a>
</p>
</section>
<section id='report-abuse'>
<section id="report-abuse">
<h4>Report Abuse</h4>
<p>We encourage you to report problematic content to us. Please keep in mind that to help ensure the safety, confidentiality and security of your messages, we do not have the contents of messages available to us, which limits our ability to verify the report and take action.</p>
<p>When needed, you can take a screenshot of the content and share it, along with any available contact info, with appropriate law enforcement authorities.</p>
<p>To report any content, email us at abuse[at]darkwire.io or submit the room ID below to report anonymously.</p>
<p>
We encourage you to report problematic content to us. Please keep in mind that to help ensure the safety,
confidentiality and security of your messages, we do not have the contents of messages available to us,
which limits our ability to verify the report and take action.
</p>
<p>
When needed, you can take a screenshot of the content and share it, along with any available contact info,
with appropriate law enforcement authorities.
</p>
<p>
To report any content, email us at abuse[at]darkwire.io or submit the room ID below to report anonymously.
</p>
<form onSubmit={this.handleReportAbuse.bind(this)}>
{this.state.abuseReported && <div>Thank you!</div>}
<div>
<div className="input-group">
<input className='form-control' placeholder='Room ID' onChange={this.handleUpdateRoomId.bind(this)} value={this.state.roomId} type="text"/>
<input
className="form-control"
placeholder="Room ID"
onChange={this.handleUpdateRoomId.bind(this)}
value={this.state.roomId}
type="text"
/>
<div className="input-group-append">
<button
className="btn btn-secondary"
type="submit"
>
<button className="btn btn-secondary" type="submit">
Submit
</button>
</div>
@ -81,128 +128,296 @@ class About extends Component {
</form>
<br />
<p>If you feel you or anyone else is in immediate danger, please contact your local emergency services.</p>
<p>If you receive content from someone who wishes to hurt themselves, and you're concerned for their safety, please contact your local emergency services or a <a href="https://faq.whatsapp.com/en/general/28030010">suicide prevention hotline</a>.</p>
<p>If you receive or encounter content indicating abuse or exploitation of a child, please contact the <a href="http://www.missingkids.com">National Center for Missing and Exploited Children (NCMEC)</a>.</p>
<p>
If you receive content from someone who wishes to hurt themselves, and you're concerned for their safety,
please contact your local emergency services or a{' '}
<a href="https://faq.whatsapp.com/en/general/28030010">suicide prevention hotline</a>.
</p>
<p>
If you receive or encounter content indicating abuse or exploitation of a child, please contact the{' '}
<a href="http://www.missingkids.com">National Center for Missing and Exploited Children (NCMEC)</a>.
</p>
</section>
<section id='acceptable-use'>
<section id="acceptable-use">
<h4>Acceptable Use Policy</h4>
<p>This Acceptable Use Policy (this Policy) describes prohibited uses of the web services offered by Darkwire and its affiliates (the Services) and the website located at https://darkwire.io (the “Darkwire Site”). The examples described in this Policy are not exhaustive. We may modify this Policy at any time by posting a revised version on the Darkwire Site. By using the Services or accessing the Darkwire Site, you agree to the latest version of this Policy. If you violate the Policy or authorize or help others to do so, we may suspend or terminate your use of the Services.</p>
<p>
This Acceptable Use Policy (this Policy) describes prohibited uses of the web services offered by Darkwire
and its affiliates (the Services) and the website located at https://darkwire.io (the “Darkwire Site”).
The examples described in this Policy are not exhaustive. We may modify this Policy at any time by posting a
revised version on the Darkwire Site. By using the Services or accessing the Darkwire Site, you agree to the
latest version of this Policy. If you violate the Policy or authorize or help others to do so, we may
suspend or terminate your use of the Services.
</p>
<strong>No Illegal, Harmful, or Offensive Use or Content</strong>
<p>You may not use, or encourage, promote, facilitate or instruct others to use, the Services or Darkwire Site for any illegal, harmful, fraudulent, infringing or offensive use, or to transmit, store, display, distribute or otherwise make available content that is illegal, harmful, fraudulent, infringing or offensive. Prohibited activities or content include:</p>
<p>
You may not use, or encourage, promote, facilitate or instruct others to use, the Services or Darkwire Site
for any illegal, harmful, fraudulent, infringing or offensive use, or to transmit, store, display,
distribute or otherwise make available content that is illegal, harmful, fraudulent, infringing or
offensive. Prohibited activities or content include:
</p>
<ul>
<li><strong>Illegal, Harmful or Fraudulent Activities.</strong> Any activities that are illegal, that violate the rights of others, or that may be harmful to others, our operations or reputation, including disseminating, promoting or facilitating child pornography, offering or disseminating fraudulent goods, services, schemes, or promotions, make-money-fast schemes, ponzi and pyramid schemes, phishing, or pharming.</li>
<li>
<strong>Illegal, Harmful or Fraudulent Activities.</strong> Any activities that are illegal, that violate
the rights of others, or that may be harmful to others, our operations or reputation, including
disseminating, promoting or facilitating child pornography, offering or disseminating fraudulent goods,
services, schemes, or promotions, make-money-fast schemes, ponzi and pyramid schemes, phishing, or
pharming.
</li>
<li><strong>Infringing Content.</strong> Content that infringes or misappropriates the intellectual property or proprietary rights of others.</li>
<li>
<strong>Infringing Content.</strong> Content that infringes or misappropriates the intellectual property
or proprietary rights of others.
</li>
<li><strong>Offensive Content.</strong> Content that is defamatory, obscene, abusive, invasive of privacy, or otherwise objectionable, including content that constitutes child pornography, relates to bestiality, or depicts non-consensual sex acts.</li>
<li>
<strong>Offensive Content.</strong> Content that is defamatory, obscene, abusive, invasive of privacy, or
otherwise objectionable, including content that constitutes child pornography, relates to bestiality, or
depicts non-consensual sex acts.
</li>
<li><strong>Harmful Content.</strong> Content or other computer technology that may damage, interfere with, surreptitiously intercept, or expropriate any system, program, or data, including viruses, Trojan horses, worms, time bombs, or cancelbots.</li>
<li>
<strong>Harmful Content.</strong> Content or other computer technology that may damage, interfere with,
surreptitiously intercept, or expropriate any system, program, or data, including viruses, Trojan horses,
worms, time bombs, or cancelbots.
</li>
</ul>
<strong>No Security Violations</strong>
<br/>You may not use the Services to violate the security or integrity of any network, computer or communications system, software application, or network or computing device (each, a System). Prohibited activities include:
<br />
You may not use the Services to violate the security or integrity of any network, computer or communications
system, software application, or network or computing device (each, a System). Prohibited activities
include:
<ul>
<li><strong>Unauthorized Access.</strong> Accessing or using any System without permission, including attempting to probe, scan, or test the vulnerability of a System or to breach any security or authentication measures used by a System.</li>
<li>
<strong>Unauthorized Access.</strong> Accessing or using any System without permission, including
attempting to probe, scan, or test the vulnerability of a System or to breach any security or
authentication measures used by a System.
</li>
<li><strong>Interception.</strong> Monitoring of data or traffic on a System without permission.</li>
<li>
<strong>Interception.</strong> Monitoring of data or traffic on a System without permission.
</li>
<li><strong>Falsification of Origin.</strong> Forging TCP-IP packet headers, e-mail headers, or any part of a message describing its origin or route. The legitimate use of aliases and anonymous remailers is not prohibited by this provision.</li>
<li>
<strong>Falsification of Origin.</strong> Forging TCP-IP packet headers, e-mail headers, or any part of a
message describing its origin or route. The legitimate use of aliases and anonymous remailers is not
prohibited by this provision.
</li>
</ul>
<strong>No Network Abuse</strong>
<br/>You may not make network connections to any users, hosts, or networks unless you have permission to communicate with them. Prohibited activities include:
<br />
You may not make network connections to any users, hosts, or networks unless you have permission to
communicate with them. Prohibited activities include:
<ul>
<li><strong>Monitoring or Crawling.</strong> Monitoring or crawling of a System that impairs or disrupts the System being monitored or crawled.</li>
<li>
<strong>Monitoring or Crawling.</strong> Monitoring or crawling of a System that impairs or disrupts the
System being monitored or crawled.
</li>
<li><strong>Denial of Service (DoS).</strong> Inundating a target with communications requests so the target either cannot respond to legitimate traffic or responds so slowly that it becomes ineffective.</li>
<li>
<strong>Denial of Service (DoS).</strong> Inundating a target with communications requests so the target
either cannot respond to legitimate traffic or responds so slowly that it becomes ineffective.
</li>
<li><strong>Intentional Interference.</strong> Interfering with the proper functioning of any System, including any deliberate attempt to overload a system by mail bombing, news bombing, broadcast attacks, or flooding techniques.</li>
<li>
<strong>Intentional Interference.</strong> Interfering with the proper functioning of any System,
including any deliberate attempt to overload a system by mail bombing, news bombing, broadcast attacks, or
flooding techniques.
</li>
<li><strong>Operation of Certain Network Services.</strong> Operating network services like open proxies, open mail relays, or open recursive domain name servers.</li>
<li>
<strong>Operation of Certain Network Services.</strong> Operating network services like open proxies, open
mail relays, or open recursive domain name servers.
</li>
<li><strong>Avoiding System Restrictions.</strong> Using manual or electronic means to avoid any use limitations placed on a System, such as access and storage restrictions.</li>
<li>
<strong>Avoiding System Restrictions.</strong> Using manual or electronic means to avoid any use
limitations placed on a System, such as access and storage restrictions.
</li>
</ul>
<strong>No E-Mail or Other Message Abuse</strong>
<br/>You will not distribute, publish, send, or facilitate the sending of unsolicited mass e-mail or other messages, promotions, advertising, or solicitations (like spam), including commercial advertising and informational announcements. You will not alter or obscure mail headers or assume a senders identity without the senders explicit permission. You will not collect replies to messages sent from another internet service provider if those messages violate this Policy or the acceptable use policy of that provider.
<br />
You will not distribute, publish, send, or facilitate the sending of unsolicited mass e-mail or other
messages, promotions, advertising, or solicitations (like spam), including commercial advertising and
informational announcements. You will not alter or obscure mail headers or assume a senders identity without
the senders explicit permission. You will not collect replies to messages sent from another internet service
provider if those messages violate this Policy or the acceptable use policy of that provider.
<strong>Our Monitoring and Enforcement</strong>
<br/>We reserve the right, but do not assume the obligation, to investigate any violation of this Policy or misuse of the Services or Darkwire Site. We may:
<br />
We reserve the right, but do not assume the obligation, to investigate any violation of this Policy or misuse
of the Services or Darkwire Site. We may:
<ul>
<li>investigate violations of this Policy or misuse of the Services or Darkwire Site; or</li>
<li>remove, disable access to, or modify any content or resource that violates this Policy or any other agreement we have with you for use of the Services or the Darkwire Site.</li>
<li>We may report any activity that we suspect violates any law or regulation to appropriate law enforcement officials, regulators, or other appropriate third parties. Our reporting may include disclosing appropriate customer information. We also may cooperate with appropriate law enforcement agencies, regulators, or other appropriate third parties to help with the investigation and prosecution of illegal conduct by providing network and systems information related to alleged violations of this Policy.</li>
<li>
remove, disable access to, or modify any content or resource that violates this Policy or any other
agreement we have with you for use of the Services or the Darkwire Site.
</li>
<li>
We may report any activity that we suspect violates any law or regulation to appropriate law enforcement
officials, regulators, or other appropriate third parties. Our reporting may include disclosing
appropriate customer information. We also may cooperate with appropriate law enforcement agencies,
regulators, or other appropriate third parties to help with the investigation and prosecution of illegal
conduct by providing network and systems information related to alleged violations of this Policy.
</li>
</ul>
Reporting of Violations of this Policy
<br/>If you become aware of any violation of this Policy, you will immediately notify us and provide us with assistance, as requested, to stop or remedy the violation. To report any violation of this Policy, please follow our abuse reporting process.
<br />
If you become aware of any violation of this Policy, you will immediately notify us and provide us with
assistance, as requested, to stop or remedy the violation. To report any violation of this Policy, please
follow our abuse reporting process.
</section>
<section id='terms'>
<section id="terms">
<h4>Terms of Service ("Terms")</h4>
<p>Last updated: December 11, 2017</p>
<p>Please read these Terms of Service ("Terms", "Terms of Service") carefully before using the https://darkwire.io website (the "Service") operated by Darkwire ("us", "we", or "our").</p>
<p>Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms. These Terms apply to all visitors, users and others who access or use the Service.</p>
<p>By accessing or using the Service you agree to be bound by these Terms. If you disagree with any part of the terms then you may not access the Service.</p>
<p>
Please read these Terms of Service ("Terms", "Terms of Service") carefully before using the
https://darkwire.io website (the "Service") operated by Darkwire ("us", "we", or "our").
</p>
<p>
Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms.
These Terms apply to all visitors, users and others who access or use the Service.
</p>
<p>
By accessing or using the Service you agree to be bound by these Terms. If you disagree with any part of the
terms then you may not access the Service.
</p>
<strong>Links To Other Web Sites</strong>
<p>Our Service may contain links to third-party web sites or services that are not owned or controlled by Darkwire.</p>
<p>Darkwire has no control over, and assumes no responsibility for, the content, privacy policies, or practices of any third party web sites or services. You further acknowledge and agree that Darkwire shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods or services available on or through any such web sites or services.</p>
<p>We strongly advise you to read the terms and conditions and privacy policies of any third-party web sites or services that you visit.</p>
<p>
Our Service may contain links to third-party web sites or services that are not owned or controlled by
Darkwire.
</p>
<p>
Darkwire has no control over, and assumes no responsibility for, the content, privacy policies, or practices
of any third party web sites or services. You further acknowledge and agree that Darkwire shall not be
responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or
in connection with use of or reliance on any such content, goods or services available on or through any
such web sites or services.
</p>
<p>
We strongly advise you to read the terms and conditions and privacy policies of any third-party web sites or
services that you visit.
</p>
<strong>Termination</strong>
<p>We may terminate or suspend access to our Service immediately, without prior notice or liability, for any reason whatsoever, including without limitation if you breach the Terms.</p>
<p>All provisions of the Terms which by their nature should survive termination shall survive termination, including, without limitation, ownership provisions,
warranty disclaimers, indemnity and limitations of liability.</p>
<p>
We may terminate or suspend access to our Service immediately, without prior notice or liability, for any
reason whatsoever, including without limitation if you breach the Terms.
</p>
<p>
All provisions of the Terms which by their nature should survive termination shall survive termination,
including, without limitation, ownership provisions, warranty disclaimers, indemnity and limitations of
liability.
</p>
<strong>Governing Law</strong>
<p>These Terms shall be governed and construed in accordance with the laws of New York, United States, without regard to its conflict of law provisions.</p>
<p>Our failure to enforce any right or provision of these Terms will not be considered a waiver of those rights. If any provision of these Terms is held to be
invalid or unenforceable by a court, the remaining provisions of these Terms will remain in effect. These Terms constitute the entire agreement between us
regarding our Service, and supersede and replace any prior agreements we might have between us regarding the Service.</p>
<p>
These Terms shall be governed and construed in accordance with the laws of New York, United States, without
regard to its conflict of law provisions.
</p>
<p>
Our failure to enforce any right or provision of these Terms will not be considered a waiver of those
rights. If any provision of these Terms is held to be invalid or unenforceable by a court, the remaining
provisions of these Terms will remain in effect. These Terms constitute the entire agreement between us
regarding our Service, and supersede and replace any prior agreements we might have between us regarding the
Service.
</p>
</section>
<section id='disclaimer'>
<section id="disclaimer">
<h4>Disclaimer</h4>
<p className="bold">WARNING: Darkwire does not mask IP addresses nor can verify the integrity of parties recieving messages.
&nbsp;Proceed with caution and always confirm recipients beforre starting a chat session.</p>
<p>Please also note that <strong>ALL CHATROOMS</strong> are public.
&nbsp;Anyone can guess your room URL. If you need a more-private room, use the lock feature or set the URL manually by entering a room ID after &quot;darkwire.io/&quot;.
<p className="bold">
WARNING: Darkwire does not mask IP addresses nor can verify the integrity of parties recieving messages.
&nbsp;Proceed with caution and always confirm recipients beforre starting a chat session.
</p>
<p>
Please also note that <strong>ALL CHATROOMS</strong> are public. &nbsp;Anyone can guess your room URL. If
you need a more-private room, use the lock feature or set the URL manually by entering a room ID after
&quot;darkwire.io/&quot;.
</p>
<br />
<strong>No Warranties; Exclusion of Liability; Indemnification</strong>
<p><strong>OUR WEBSITE IS OPERATED BY Darkwire ON AN "AS IS," "AS AVAILABLE" BASIS, WITHOUT REPRESENTATIONS OR WARRANTIES OF ANY KIND. TO THE FULLEST EXTENT PERMITTED BY LAW, Darkwire SPECIFICALLY DISCLAIMS ALL WARRANTIES AND CONDITIONS OF ANY KIND, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NONINFRINGEMENT FOR OUR WEBSITE AND ANY CONTRACTS AND SERVICES YOU PURCHASE THROUGH IT. Darkwire SHALL NOT HAVE ANY LIABILITY OR RESPONSIBILITY FOR ANY ERRORS OR OMISSIONS IN THE CONTENT OF OUR WEBSITE, FOR CONTRACTS OR SERVICES SOLD THROUGH OUR WEBSITE, FOR YOUR ACTION OR INACTION IN CONNECTION WITH OUR WEBSITE OR FOR ANY DAMAGE TO YOUR COMPUTER OR DATA OR ANY OTHER DAMAGE YOU MAY INCUR IN CONNECTION WITH OUR WEBSITE. YOUR USE OF OUR WEBSITE AND ANY CONTRACTS OR SERVICES ARE AT YOUR OWN RISK. IN NO EVENT SHALL EITHER Darkwire OR THEIR AGENTS BE LIABLE FOR ANY DIRECT, INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR IN ANY WAY CONNECTED WITH THE USE OF OUR WEBSITE, CONTRACTS AND SERVICES PURCHASED THROUGH OUR WEBSITE, THE DELAY OR INABILITY TO USE OUR WEBSITE OR OTHERWISE ARISING IN CONNECTION WITH OUR WEBSITE, CONTRACTS OR RELATED SERVICES, WHETHER BASED ON CONTRACT,
TORT, STRICT LIABILITY OR OTHERWISE, EVEN IF ADVISED OF THE POSSIBILITY OF ANY SUCH DAMAGES. IN NO EVENT SHALL Darkwires LIABILITY FOR ANY DAMAGE CLAIM EXCEED THE AMOUNT PAID BY YOU TO Darkwire FOR THE TRANSACTION GIVING RISE TO SUCH DAMAGE CLAIM.</strong></p>
<p><strong>SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE ABOVE EXCLUSION MAY NOT APPLY TO YOU.</strong></p>
<p><strong>WITHOUT LIMITING THE FOREGOING, Darkwire DO NOT REPRESENT OR WARRANT THAT THE INFORMATION ON THE WEBITE IS ACCURATE, COMPLETE, RELIABLE, USEFUL, TIMELY OR CURRENT OR THAT OUR WEBSITE WILL OPERATE WITHOUT INTERRUPTION OR ERROR.</strong></p>
<p><strong>YOU AGREE THAT ALL TIMES, YOU WILL LOOK TO ATTORNEYS FROM WHOM YOU PURCHASE SERVICES FOR ANY CLAIMS OF ANY NATURE, INCLUDING LOSS, DAMAGE, OR WARRANTY. Darkwire AND THEIR RESPECTIVE AFFILIATES MAKE NO REPRESENTATION OR GUARANTEES ABOUT ANY CONTRACTS AND SERVICES OFFERED THROUGH OUR WEBSITE.</strong></p>
<p><strong>Darkwire MAKES NO REPRESENTATION THAT CONTENT PROVIDED ON OUR WEBSITE, CONTRACTS, OR RELATED SERVICES ARE APPLICABLE OR APPROPRIATE FOR USE IN ALL
JURISDICTIONS.</strong></p>
<p>
<strong>
OUR WEBSITE IS OPERATED BY Darkwire ON AN "AS IS," "AS AVAILABLE" BASIS, WITHOUT REPRESENTATIONS OR
WARRANTIES OF ANY KIND. TO THE FULLEST EXTENT PERMITTED BY LAW, Darkwire SPECIFICALLY DISCLAIMS ALL
WARRANTIES AND CONDITIONS OF ANY KIND, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NONINFRINGEMENT FOR OUR WEBSITE AND ANY CONTRACTS AND SERVICES
YOU PURCHASE THROUGH IT. Darkwire SHALL NOT HAVE ANY LIABILITY OR RESPONSIBILITY FOR ANY ERRORS OR
OMISSIONS IN THE CONTENT OF OUR WEBSITE, FOR CONTRACTS OR SERVICES SOLD THROUGH OUR WEBSITE, FOR YOUR
ACTION OR INACTION IN CONNECTION WITH OUR WEBSITE OR FOR ANY DAMAGE TO YOUR COMPUTER OR DATA OR ANY OTHER
DAMAGE YOU MAY INCUR IN CONNECTION WITH OUR WEBSITE. YOUR USE OF OUR WEBSITE AND ANY CONTRACTS OR SERVICES
ARE AT YOUR OWN RISK. IN NO EVENT SHALL EITHER Darkwire OR THEIR AGENTS BE LIABLE FOR ANY DIRECT,
INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR IN ANY WAY CONNECTED
WITH THE USE OF OUR WEBSITE, CONTRACTS AND SERVICES PURCHASED THROUGH OUR WEBSITE, THE DELAY OR INABILITY
TO USE OUR WEBSITE OR OTHERWISE ARISING IN CONNECTION WITH OUR WEBSITE, CONTRACTS OR RELATED SERVICES,
WHETHER BASED ON CONTRACT, TORT, STRICT LIABILITY OR OTHERWISE, EVEN IF ADVISED OF THE POSSIBILITY OF ANY
SUCH DAMAGES. IN NO EVENT SHALL Darkwires LIABILITY FOR ANY DAMAGE CLAIM EXCEED THE AMOUNT PAID BY YOU TO
Darkwire FOR THE TRANSACTION GIVING RISE TO SUCH DAMAGE CLAIM.
</strong>
</p>
<p>
<strong>
SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE
ABOVE EXCLUSION MAY NOT APPLY TO YOU.
</strong>
</p>
<p>
<strong>
WITHOUT LIMITING THE FOREGOING, Darkwire DO NOT REPRESENT OR WARRANT THAT THE INFORMATION ON THE WEBITE IS
ACCURATE, COMPLETE, RELIABLE, USEFUL, TIMELY OR CURRENT OR THAT OUR WEBSITE WILL OPERATE WITHOUT
INTERRUPTION OR ERROR.
</strong>
</p>
<p>
<strong>
YOU AGREE THAT ALL TIMES, YOU WILL LOOK TO ATTORNEYS FROM WHOM YOU PURCHASE SERVICES FOR ANY CLAIMS OF ANY
NATURE, INCLUDING LOSS, DAMAGE, OR WARRANTY. Darkwire AND THEIR RESPECTIVE AFFILIATES MAKE NO
REPRESENTATION OR GUARANTEES ABOUT ANY CONTRACTS AND SERVICES OFFERED THROUGH OUR WEBSITE.
</strong>
</p>
<p>
<strong>
Darkwire MAKES NO REPRESENTATION THAT CONTENT PROVIDED ON OUR WEBSITE, CONTRACTS, OR RELATED SERVICES ARE
APPLICABLE OR APPROPRIATE FOR USE IN ALL JURISDICTIONS.
</strong>
</p>
<strong>Indemnification</strong>
<p>You agree to defend, indemnify and hold Darkwire harmless from and against any and all claims, damages, costs and expenses, including attorneys' fees, arising
from or related to your use of our Website or any Contracts or Services you purchase through it.</p>
<p>
You agree to defend, indemnify and hold Darkwire harmless from and against any and all claims, damages,
costs and expenses, including attorneys' fees, arising from or related to your use of our Website or any
Contracts or Services you purchase through it.
</p>
<strong>Changes</strong>
<p>We reserve the right, at our sole discretion, to modify or replace these Terms at any time. If a revision is material we will try to provide at least 30 days notice prior to any new terms taking effect. What constitutes a material change will be determined at our sole discretion.</p>
<p>By continuing to access or use our Service after those revisions become effective, you agree to be bound by the revised terms. If you do not agree to the new
terms, please stop using the Service.</p>
<p>
We reserve the right, at our sole discretion, to modify or replace these Terms at any time. If a revision is
material we will try to provide at least 30 days notice prior to any new terms taking effect. What
constitutes a material change will be determined at our sole discretion.
</p>
<p>
By continuing to access or use our Service after those revisions become effective, you agree to be bound by
the revised terms. If you do not agree to the new terms, please stop using the Service.
</p>
<strong>Contact Us</strong>
<p>If you have any questions about these Terms, please contact us at hello[at]darkwire.io.</p>
</section>
<section id='contact'>
<section id="contact">
<h4>Contact</h4>
<p>Questions/comments? Email us at hello[at]darkwire.io</p>
<p>Found a bug or want a new feature? <a href="https://github.com/darkwire/darkwire.io/issues" target="_blank" rel="noopener noreferrer">Open a ticket on Github</a>.</p>
<p>
Found a bug or want a new feature?{' '}
<a href="https://github.com/darkwire/darkwire.io/issues" target="_blank" rel="noopener noreferrer">
Open a ticket on Github
</a>
.
</p>
</section>
<section id='donate'>
<section id="donate">
<h4>Donate</h4>
<p>Darkwire is maintained and hosted by two developers with full-time jobs. If you get some value
from this service we would appreciate any donation you can afford. We use these funds for
server and DNS costs. Thank you!
<p>
Darkwire is maintained and hosted by two developers with full-time jobs. If you get some value from this
service we would appreciate any donation you can afford. We use these funds for server and DNS costs. Thank
you!
</p>
<strong>Bitcoin</strong>
<p>189sPnHGcjP5uteg2UuNgcJ5eoaRAP4Bw4</p>
@ -215,17 +430,23 @@ class About extends Component {
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="cmd" value="_s-xclick" />
<input type="hidden" name="hosted_button_id" value="UAH5BCLA9Y8VW" />
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" />
<input
type="image"
src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif"
border="0"
name="submit"
alt="PayPal - The safer, easier way to pay online!"
/>
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1" />
</form>
</section>
</div>
)
);
}
}
About.propTypes = {
roomId: PropTypes.string.isRequired,
}
};
export default About
export default About;

View File

@ -1,21 +1,17 @@
import Chat from './Chat'
import { connect } from 'react-redux'
import { clearActivities, showNotice, sendEncryptedMessage } from '../../actions'
import Chat from './Chat';
import { connect } from 'react-redux';
import { clearActivities, showNotice, sendEncryptedMessage } from '../../actions';
const mapStateToProps = state => ({
username: state.user.username,
userId: state.user.id,
translations: state.app.translations,
})
});
const mapDispatchToProps = {
clearActivities,
showNotice,
sendEncryptedMessage
}
sendEncryptedMessage,
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Chat)
export default connect(mapStateToProps, mapDispatchToProps)(Chat);

View File

@ -1,9 +1,9 @@
import React from 'react'
import { render } from '@testing-library/react'
import Connecting from '.'
import React from 'react';
import { render } from '@testing-library/react';
import Connecting from '.';
test('Connecting component is displaying', async () => {
const {asFragment} = render(<Connecting />)
const { asFragment } = render(<Connecting />);
expect(asFragment()).toMatchSnapshot()
})
expect(asFragment()).toMatchSnapshot();
});

View File

@ -1,11 +1,7 @@
import React, { Component } from 'react'
import React, { Component } from 'react';
export default class Connecting extends Component {
render() {
return (
<div>
Please wait while we secure a connection to Darkwire...
</div>
)
return <div>Please wait while we secure a connection to Darkwire...</div>;
}
}

View File

@ -1,84 +1,106 @@
import React from 'react'
import PropTypes from 'prop-types'
import uuid from 'uuid'
import { File } from 'react-feather'
import { sanitize } from 'utils'
import { styles } from './styles.module.scss'
import React from 'react';
import PropTypes from 'prop-types';
import uuid from 'uuid';
import { File } from 'react-feather';
import { sanitize } from 'utils';
import { styles } from './styles.module.scss';
const VALID_FILE_TYPES = ['png', 'jpg', 'jpeg', 'gif', 'zip', 'rar', 'gzip', 'pdf', 'txt', 'json', 'doc', 'docx', 'csv', 'js', 'html', 'css']
const VALID_FILE_TYPES = [
'png',
'jpg',
'jpeg',
'gif',
'zip',
'rar',
'gzip',
'pdf',
'txt',
'json',
'doc',
'docx',
'csv',
'js',
'html',
'css',
];
const MAX_FILE_SIZE = process.env.REACT_APP_MAX_FILE_SIZE || 4
const MAX_FILE_SIZE = process.env.REACT_APP_MAX_FILE_SIZE || 4;
/**
* Encode the given file to binary string
* @param {File} file
*/
const encodeFile = (file) => {
const encodeFile = file => {
return new Promise((resolve, reject) => {
const reader = new window.FileReader()
const reader = new window.FileReader();
if (!file) {
reject()
return
reject();
return;
}
reader.onload = (readerEvent) => {
resolve(window.btoa(readerEvent.target.result))
}
reader.onload = readerEvent => {
resolve(window.btoa(readerEvent.target.result));
};
reader.readAsBinaryString(file)
})
}
reader.readAsBinaryString(file);
});
};
export const FileTransfer = ({ sendEncryptedMessage }) => {
const fileInput = React.useRef(null);
const supported = React.useMemo(() =>
Boolean(window.File) && Boolean(window.FileReader) && Boolean(window.FileList) && Boolean(window.Blob) &&
Boolean(window.btoa) && Boolean(window.atob) && Boolean(window.URL),
[]
)
const supported = React.useMemo(
() =>
Boolean(window.File) &&
Boolean(window.FileReader) &&
Boolean(window.FileList) &&
Boolean(window.Blob) &&
Boolean(window.btoa) &&
Boolean(window.atob) &&
Boolean(window.URL),
[],
);
React.useEffect(() => {
const currentFileInput = fileInput.current
const currentFileInput = fileInput.current;
let isMounted = true;
const handleFileTransfer = async (event) => {
const file = event.target.files && event.target.files[0]
const handleFileTransfer = async event => {
const file = event.target.files && event.target.files[0];
if (file) {
const fileType = file.type || 'file'
const fileName = sanitize(file.name)
const fileExtension = file.name.split('.').pop().toLowerCase()
const fileType = file.type || 'file';
const fileName = sanitize(file.name);
const fileExtension = file.name.split('.').pop().toLowerCase();
if (VALID_FILE_TYPES.indexOf(fileExtension) <= -1) {
// eslint-disable-next-line no-alert
alert('File type not supported')
return false
alert('File type not supported');
return false;
}
if (file.size > MAX_FILE_SIZE * 1000000) {
// eslint-disable-next-line no-alert
alert(`Max filesize is ${MAX_FILE_SIZE}MB`)
return false
alert(`Max filesize is ${MAX_FILE_SIZE}MB`);
return false;
}
const fileId = uuid.v4()
const fileId = uuid.v4();
const fileData = {
id: fileId,
file,
fileName,
fileType,
encodedFile: await encodeFile(file),
}
};
// Mounted component guard
if (!isMounted) {
return
return;
}
fileInput.current.value = ''
fileInput.current.value = '';
sendEncryptedMessage({
type: 'SEND_FILE',
@ -88,22 +110,22 @@ export const FileTransfer = ({ sendEncryptedMessage }) => {
fileType: fileData.fileType,
timestamp: Date.now(),
},
})
});
}
return false
}
return false;
};
currentFileInput.addEventListener('change', handleFileTransfer)
currentFileInput.addEventListener('change', handleFileTransfer);
return () => {
isMounted = false
currentFileInput.removeEventListener('change', handleFileTransfer)
}
}, [sendEncryptedMessage])
isMounted = false;
currentFileInput.removeEventListener('change', handleFileTransfer);
};
}, [sendEncryptedMessage]);
if (!supported) {
return null
return null;
}
return (
@ -114,10 +136,10 @@ export const FileTransfer = ({ sendEncryptedMessage }) => {
</label>
</div>
);
}
};
FileTransfer.propTypes = {
sendEncryptedMessage: PropTypes.func.isRequired,
}
};
export default FileTransfer
export default FileTransfer;

View File

@ -1,20 +1,20 @@
import React from 'react'
import PropTypes from 'prop-types'
import Message from 'components/Message'
import Username from 'components/Username'
import Notice from 'components/Notice'
import Zoom from 'utils/ImageZoom'
import { getObjectUrl } from 'utils/file'
import React from 'react';
import PropTypes from 'prop-types';
import Message from 'components/Message';
import Username from 'components/Username';
import Notice from 'components/Notice';
import Zoom from 'utils/ImageZoom';
import { getObjectUrl } from 'utils/file';
import T from 'components/T'
import T from 'components/T';
const FileDisplay = ({ activity: { fileType, encodedFile, fileName, username }, scrollToBottom }) => {
const zoomableImage = React.useRef(null)
const zoomableImage = React.useRef(null);
const handleImageDisplay = () => {
Zoom(zoomableImage.current)
scrollToBottom()
}
Zoom(zoomableImage.current);
scrollToBottom();
};
if (fileType.match('image.*')) {
return (
@ -25,117 +25,147 @@ const FileDisplay = ({ activity: { fileType, encodedFile, fileName, username },
alt={`${fileName} from ${username}`}
onLoad={handleImageDisplay}
/>
)
);
}
return null
}
return null;
};
const Activity = ({ activity, scrollToBottom }) => {
switch (activity.type) {
case 'TEXT_MESSAGE':
return (
<Message
sender={activity.username}
message={activity.text}
timestamp={activity.timestamp}
/>
)
return <Message sender={activity.username} message={activity.text} timestamp={activity.timestamp} />;
case 'USER_ENTER':
return (
<Notice>
<div>
<T data={{
username: <Username key={0} username={activity.username} />
}} path='userJoined'/>
<T
data={{
username: <Username key={0} username={activity.username} />,
}}
path="userJoined"
/>
</div>
</Notice>
)
);
case 'USER_EXIT':
return (
<Notice>
<div>
<T data={{
username: <Username key={0} username={activity.username} />
}} path='userLeft'/>
<T
data={{
username: <Username key={0} username={activity.username} />,
}}
path="userLeft"
/>
</div>
</Notice>
)
);
case 'TOGGLE_LOCK_ROOM':
if (activity.locked) {
return (
<Notice>
<div><T data={{
username: <Username key={0} username={activity.username} />
}} path='lockedRoom'/></div>
<div>
<T
data={{
username: <Username key={0} username={activity.username} />,
}}
path="lockedRoom"
/>
</div>
</Notice>
)
);
} else {
return (
<Notice>
<div><T data={{
username: <Username key={0} username={activity.username} />
}} path='unlockedRoom'/></div>
<div>
<T
data={{
username: <Username key={0} username={activity.username} />,
}}
path="unlockedRoom"
/>
</div>
</Notice>
)
);
}
case 'NOTICE':
return (
<Notice>
<div>{activity.message}</div>
</Notice>
)
);
case 'CHANGE_USERNAME':
return (
<Notice>
<div><T data={{
<div>
<T
data={{
oldUsername: <Username key={0} username={activity.currentUsername} />,
newUsername: <Username key={1} username={activity.newUsername} />
}} path='nameChange'/>
newUsername: <Username key={1} username={activity.newUsername} />,
}}
path="nameChange"
/>
</div>
</Notice>
)
);
case 'USER_ACTION':
return (
<Notice>
<div>&#42; <Username username={activity.username} /> {activity.action}</div>
<div>
&#42; <Username username={activity.username} /> {activity.action}
</div>
</Notice>
)
);
case 'RECEIVE_FILE':
const downloadUrl = getObjectUrl(activity.encodedFile, activity.fileType)
const downloadUrl = getObjectUrl(activity.encodedFile, activity.fileType);
return (
<div>
<T data={{
<T
data={{
username: <Username key={0} username={activity.username} />,
}} path='userSentFile'/>&nbsp;
<a target="_blank" href={downloadUrl} rel="noopener noreferrer" download={activity.fileName} >
<T data={{
}}
path="userSentFile"
/>
&nbsp;
<a target="_blank" href={downloadUrl} rel="noopener noreferrer" download={activity.fileName}>
<T
data={{
filename: activity.fileName,
}} path='downloadFile'/>
}}
path="downloadFile"
/>
</a>
<FileDisplay activity={activity} scrollToBottom={scrollToBottom} />
</div>
)
);
case 'SEND_FILE':
const url = getObjectUrl(activity.encodedFile, activity.fileType)
const url = getObjectUrl(activity.encodedFile, activity.fileType);
return (
<Notice>
<div>
<T data={{
filename: <a key={0} target="_blank" href={url} rel="noopener noreferrer" download={activity.fileName}>{activity.fileName}</a>,
}} path='sentFile'/>&nbsp;
<T
data={{
filename: (
<a key={0} target="_blank" href={url} rel="noopener noreferrer" download={activity.fileName}>
{activity.fileName}
</a>
),
}}
path="sentFile"
/>
&nbsp;
</div>
<FileDisplay activity={activity} scrollToBottom={scrollToBottom} />
</Notice>
)
);
default:
return false
return false;
}
}
};
Activity.propTypes = {
activity: PropTypes.object.isRequired,
scrollToBottom: PropTypes.func.isRequired,
}
};
export default Activity
export default Activity;

View File

@ -1,11 +1,11 @@
import React from 'react'
import PropTypes from 'prop-types'
import ChatInput from 'components/Chat'
import Activity from './Activity'
import T from 'components/T'
import { defer } from 'lodash'
import React from 'react';
import PropTypes from 'prop-types';
import ChatInput from 'components/Chat';
import Activity from './Activity';
import T from 'components/T';
import { defer } from 'lodash';
import styles from './styles.module.scss'
import styles from './styles.module.scss';
const ActivityList = ({ activities, openModal }) => {
const [focusChat, setFocusChat] = React.useState(false);
@ -18,56 +18,63 @@ const ActivityList = ({ activities, openModal }) => {
// Update scrolledToBottom state if we scroll the activity stream
const onScroll = () => {
const messageStreamHeight = messageStream.current.clientHeight
const activitiesListHeight = activitiesList.current.clientHeight
const messageStreamHeight = messageStream.current.clientHeight;
const activitiesListHeight = activitiesList.current.clientHeight;
const bodyRect = document.body.getBoundingClientRect()
const elemRect = activitiesList.current.getBoundingClientRect()
const offset = elemRect.top - bodyRect.top
const activitiesListYPos = offset
const bodyRect = document.body.getBoundingClientRect();
const elemRect = activitiesList.current.getBoundingClientRect();
const offset = elemRect.top - bodyRect.top;
const activitiesListYPos = offset;
const newScrolledToBottom = (activitiesListHeight + (activitiesListYPos - 60)) <= messageStreamHeight
const newScrolledToBottom = activitiesListHeight + (activitiesListYPos - 60) <= messageStreamHeight;
if (newScrolledToBottom) {
if (!scrolledToBottom) {
setScrolledToBottom(true)
setScrolledToBottom(true);
}
} else if (scrolledToBottom) {
setScrolledToBottom(false)
}
setScrolledToBottom(false);
}
};
currentMessageStream.addEventListener('scroll', onScroll)
currentMessageStream.addEventListener('scroll', onScroll);
return () => {
// Unbind event if component unmounted
currentMessageStream.removeEventListener('scroll', onScroll)
}
}, [scrolledToBottom])
currentMessageStream.removeEventListener('scroll', onScroll);
};
}, [scrolledToBottom]);
const scrollToBottomIfShould = React.useCallback(() => {
if (scrolledToBottom) {
messageStream.current.scrollTop = messageStream.current.scrollHeight
messageStream.current.scrollTop = messageStream.current.scrollHeight;
}
}, [scrolledToBottom])
}, [scrolledToBottom]);
React.useEffect(() => {
scrollToBottomIfShould(); // Only if activities.length bigger
}, [scrollToBottomIfShould, activities]);
const scrollToBottom = React.useCallback(() => {
messageStream.current.scrollTop = messageStream.current.scrollHeight
setScrolledToBottom(true)
}, [])
messageStream.current.scrollTop = messageStream.current.scrollHeight;
setScrolledToBottom(true);
}, []);
const handleChatClick = () => {
setFocusChat(true);
defer(() => setFocusChat(false))
}
defer(() => setFocusChat(false));
};
return (
<div className="main-chat">
<div onClick={handleChatClick} className="message-stream h-100" ref={messageStream} data-testid="main-div">
<ul className="plain" ref={activitiesList}>
<li><p className={styles.tos}><button className='btn btn-link' onClick={() => openModal('About')}> <T path='agreement'/></button></p></li>
<li>
<p className={styles.tos}>
<button className="btn btn-link" onClick={() => openModal('About')}>
{' '}
<T path="agreement" />
</button>
</p>
</li>
{activities.map((activity, index) => (
<li key={index} className={`activity-item ${activity.type}`}>
<Activity activity={activity} scrollToBottom={scrollToBottomIfShould} />
@ -79,12 +86,12 @@ const ActivityList = ({ activities, openModal }) => {
<ChatInput scrollToBottom={scrollToBottom} focusChat={focusChat} />
</div>
</div>
)
}
);
};
ActivityList.propTypes = {
activities: PropTypes.array.isRequired,
openModal: PropTypes.func.isRequired,
}
};
export default ActivityList
export default ActivityList;

View File

@ -36,7 +36,6 @@ jest.mock('utils/crypto', () => {
});
});
test('Home component is displaying', async () => {
const { asFragment } = render(
<Provider store={store}>

View File

@ -18,7 +18,7 @@ const mapStateToProps = state => {
const mapDispatchToProps = {
toggleNotificationAllowed,
toggleNotificationEnabled
toggleNotificationEnabled,
};
const WithNewMessageNotification = WrappedComponent => {

View File

@ -1,5 +1,5 @@
import Home from './Home'
import { connect } from 'react-redux'
import Home from './Home';
import { connect } from 'react-redux';
import {
receiveEncryptedMessage,
createUser,
@ -13,12 +13,12 @@ import {
receiveUnencryptedMessage,
sendUnencryptedMessage,
sendEncryptedMessage,
setLanguage
} from 'actions'
import WithNewMessageNotification from './WithNewMessageNotification'
setLanguage,
} from 'actions';
import WithNewMessageNotification from './WithNewMessageNotification';
const mapStateToProps = (state) => {
const me = state.room.members.find(m => m.id === state.user.id)
const mapStateToProps = state => {
const me = state.room.members.find(m => m.id === state.user.id);
return {
activities: state.activities.items,
@ -38,8 +38,8 @@ const mapStateToProps = (state) => {
socketConnected: state.app.socketConnected,
language: state.app.language,
translations: state.app.translations,
}
}
};
};
const mapDispatchToProps = {
receiveEncryptedMessage,
@ -54,10 +54,7 @@ const mapDispatchToProps = {
receiveUnencryptedMessage,
sendUnencryptedMessage,
sendEncryptedMessage,
setLanguage
}
setLanguage,
};
export default WithNewMessageNotification(connect(
mapStateToProps,
mapDispatchToProps
)(Home))
export default WithNewMessageNotification(connect(mapStateToProps, mapDispatchToProps)(Home));

View File

@ -87,15 +87,15 @@ jest.mock('tinycon', () => {
});
describe('Connected Home component', () => {
beforeEach(()=>{
beforeEach(() => {
global.Notification = {
permission: 'granted'
}
})
permission: 'granted',
};
});
afterEach(()=>{
delete global.Notification
})
afterEach(() => {
delete global.Notification;
});
it('should display', () => {
const { asFragment } = render(
@ -118,8 +118,8 @@ describe('Connected Home component', () => {
expect(store.getState().app.notificationIsEnabled).toBe(true);
global.Notification = {
permission: 'denied'
}
permission: 'denied',
};
render(
<Provider store={store}>
@ -130,8 +130,8 @@ describe('Connected Home component', () => {
expect(store.getState().app.notificationIsAllowed).toBe(false);
global.Notification = {
permission: 'default'
}
permission: 'default',
};
render(
<Provider store={store}>
@ -140,8 +140,6 @@ describe('Connected Home component', () => {
);
expect(store.getState().app.notificationIsAllowed).toBe(null);
});
it('should send notifications', async () => {

View File

@ -3,13 +3,7 @@ import { render } from '@testing-library/react';
import Message from '.';
test('Message component is displaying', async () => {
const { asFragment } = render(
<Message
sender={'linus'}
timestamp={1588794269074}
message={'we come in peace'}
/>
);
const { asFragment } = render(<Message sender={'linus'} timestamp={1588794269074} message={'we come in peace'} />);
expect(asFragment()).toMatchSnapshot();
});

View File

@ -1,29 +1,31 @@
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Username from 'components/Username'
import moment from 'moment'
import Linkify from 'react-linkify'
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Username from 'components/Username';
import moment from 'moment';
import Linkify from 'react-linkify';
class Message extends Component {
render() {
const msg = decodeURI(this.props.message)
const msg = decodeURI(this.props.message);
return (
<div>
<div className="chat-meta">
<Username username={this.props.sender} />
<span className="muted timestamp">
{moment(this.props.timestamp).format('LT')}
</span>
<span className="muted timestamp">{moment(this.props.timestamp).format('LT')}</span>
</div>
<div className="chat">
<Linkify properties={{
<Linkify
properties={{
target: '_blank',
rel: 'noopener noreferrer',
}}>{msg}</Linkify>
}}
>
{msg}
</Linkify>
</div>
</div>
)
);
}
}
@ -31,6 +33,6 @@ Message.propTypes = {
sender: PropTypes.string.isRequired,
timestamp: PropTypes.number.isRequired,
message: PropTypes.string.isRequired,
}
};
export default Message
export default Message;

View File

@ -6,7 +6,7 @@ test('Notice component is displaying', async () => {
const { asFragment } = render(
<Notice level={'warning'}>
<div>Hello world</div>
</Notice>
</Notice>,
);
expect(asFragment()).toMatchSnapshot();

View File

@ -1,26 +1,28 @@
import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
const Notice = props => (
<div>
<div className={classNames({
<div
className={classNames({
info: props.level === 'info',
warning: props.level === 'warning',
danger: props.level === 'danger',
})}>
})}
>
{props.children}
</div>
</div>
)
);
Notice.defaultProps = {
level: 'info',
}
};
Notice.propTypes = {
children: PropTypes.node.isRequired,
level: PropTypes.string,
}
};
export default Notice
export default Notice;

View File

@ -1,10 +1,10 @@
.info {
color: white
color: white;
}
.warning {
color: yellow
color: yellow;
}
.danger {
color: gold
color: gold;
}

View File

@ -36,21 +36,15 @@ class RoomLink extends Component {
render() {
return (
<form>
<div className='form-group'>
<div className='input-group'>
<input
id='room-url'
className='form-control'
type='text'
readOnly
value={this.state.roomUrl}
/>
<div className='input-group-append'>
<div className="form-group">
<div className="input-group">
<input id="room-url" className="form-control" type="text" readOnly value={this.state.roomUrl} />
<div className="input-group-append">
<button
className='copy-room btn btn-secondary'
type='button'
data-toggle='tooltip'
data-placement='bottom'
className="copy-room btn btn-secondary"
type="button"
data-toggle="tooltip"
data-placement="bottom"
data-clipboard-text={this.state.roomUrl}
title={this.props.translations.copyButtonTooltip}
>

View File

@ -1,11 +1,7 @@
import React, { Component } from 'react'
import React, { Component } from 'react';
export default class RoomLocked extends Component {
render() {
return (
<div>
{this.props.modalContent}
</div>
)
return <div>{this.props.modalContent}</div>;
}
}

View File

@ -51,7 +51,6 @@ describe('Settings component', () => {
);
expect(asFragment()).toMatchSnapshot();
});
it('should toggle sound', async () => {
@ -106,8 +105,7 @@ describe('Settings component', () => {
delete global.Notification;
waitFor(() =>expect(toggleNotifications).toHaveBeenCalledWith(false));
waitFor(() => expect(toggleNotifications).toHaveBeenCalledWith(false));
});
it('should not toggle notifications', async () => {
@ -139,11 +137,10 @@ describe('Settings component', () => {
delete global.Notification;
waitFor(() =>expect(toggleAllowed).toHaveBeenCalledWith(false));
waitFor(() =>expect(toggleNotifications).not.toHaveBeenCalled());
waitFor(() => expect(toggleAllowed).toHaveBeenCalledWith(false));
waitFor(() => expect(toggleNotifications).not.toHaveBeenCalled());
});
it('should change lang', async () => {
const changeLang = jest.fn();

View File

@ -50,7 +50,7 @@ class Settings extends Component {
</div>
<div className="form-check">
<label className="form-check-label" htmlFor="notif-control">
{this.props.notificationIsAllowed !== false &&
{this.props.notificationIsAllowed !== false && (
<>
<input
id="notif-control"
@ -62,7 +62,7 @@ class Settings extends Component {
/>
<T path="desktopNotification" />
</>
}
)}
{this.props.notificationIsAllowed === false && <T path="desktopNotificationBlocked" />}
</label>
</div>

View File

@ -9,11 +9,10 @@ class T extends Component {
render() {
const t = getTranslations(this.props.language);
const englishT = getTranslations('en');
const str =
_.get(t, this.props.path, '') || _.get(englishT, this.props.path, '');
const str = _.get(t, this.props.path, '') || _.get(englishT, this.props.path, '');
let string = str.split(regex);
if (this.props.data) {
string = string.map((word) => {
string = string.map(word => {
if (this.props.data[word]) {
return this.props.data[word];
}

View File

@ -4,7 +4,7 @@ import { render } from '@testing-library/react';
import Username from '.';
test('Username component is displaying', async () => {
const { asFragment } = render(<Username username='paul' />);
const { asFragment } = render(<Username username="paul" />);
expect(asFragment()).toMatchSnapshot();
});

View File

@ -1,6 +1,6 @@
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import randomColor from 'randomcolor'
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import randomColor from 'randomcolor';
class Username extends Component {
render() {
@ -8,12 +8,12 @@ class Username extends Component {
<span className="username" style={{ color: randomColor({ seed: this.props.username, luminosity: 'light' }) }}>
{this.props.username}
</span>
)
);
}
}
Username.propTypes = {
username: PropTypes.string.isRequired,
}
};
export default Username
export default Username;

View File

@ -4,9 +4,7 @@ import { render } from '@testing-library/react';
import Welcome from '.';
test('Welcome component is displaying', async () => {
const { asFragment } = render(
<Welcome roomId='roomtest' close={() => {}} translations={{}} />
);
const { asFragment } = render(<Welcome roomId="roomtest" close={() => {}} translations={{}} />);
expect(asFragment()).toMatchSnapshot();
});

View File

@ -1,13 +1,13 @@
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import RoomLink from 'components/RoomLink'
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import RoomLink from 'components/RoomLink';
class Welcome extends Component {
constructor(props) {
super(props)
super(props);
this.state = {
roomUrl: `https://darkwire.io/${props.roomId}`,
}
};
}
render() {
@ -23,17 +23,23 @@ class Welcome extends Component {
<li>Send files up to 4 MB</li>
</ul>
<div>
You can learn more <a href="https://github.com/darkwire/darkwire.io" target="_blank" rel="noopener noreferrer">here</a>.
You can learn more{' '}
<a href="https://github.com/darkwire/darkwire.io" target="_blank" rel="noopener noreferrer">
here
</a>
.
</div>
</div>
<br />
<p className='mb-2'>Others can join this room using the following URL:</p>
<p className="mb-2">Others can join this room using the following URL:</p>
<RoomLink roomId={this.props.roomId} translations={this.props.translations} />
<div className="react-modal-footer">
<button className="btn btn-primary btn-lg" onClick={this.props.close}>{this.props.translations.welcomeModalCTA}</button>
<button className="btn btn-primary btn-lg" onClick={this.props.close}>
{this.props.translations.welcomeModalCTA}
</button>
</div>
</div>
)
);
}
}
@ -41,6 +47,6 @@ Welcome.propTypes = {
roomId: PropTypes.string.isRequired,
close: PropTypes.func.isRequired,
translations: PropTypes.object.isRequired,
}
};
export default Welcome
export default Welcome;

View File

@ -1,2 +1,2 @@
/* istanbul ignore file */
export default process.env.NODE_ENV
export default process.env.NODE_ENV;

View File

@ -18,7 +18,12 @@
"settings": "die Einstellungen",
"settingsButton": "die Einstellungen",
"settingsHeader": "Einstellungen & Hilfe",
"slashCommandsBullets": ["Ändert den Benutzernamen", "führt eine Aktion aus", "löscht den Nachrichtenverlauf", "listet alle Befehle auf"],
"slashCommandsBullets": [
"Ändert den Benutzernamen",
"führt eine Aktion aus",
"löscht den Nachrichtenverlauf",
"listet alle Befehle auf"
],
"slashCommandsHeader": "Slash-Befehle",
"slashCommandsText": "Die folgenden Schrägstrichbefehle sind verfügbar:",
"sound": "Klingen",

View File

@ -25,7 +25,12 @@
"lockRoomText": "If you are the room owner, you can lock and unlock the room by clicking the lock icon in the nav bar. When a room is locked, no other participants will be able to join.",
"slashCommandsHeader": "Slash Commands",
"slashCommandsText": "The following slash commands are available:",
"slashCommandsBullets": ["changes username", "performs an action", "clears your message history", "lists all commands"],
"slashCommandsBullets": [
"changes username",
"performs an action",
"clears your message history",
"lists all commands"
],
"sound": "Sound",
"newMessageNotification": "New message notification",
"desktopNotification": "Desktop Notification",

View File

@ -25,7 +25,12 @@
"lockRoomText": "Si vous êtes le propriétaire du salon, vous pouvez le verrouiller et le déverrouiller en cliquant sur l'icône de cadenas située dans la barre de navigation. Quand un salon est verrouillé, aucun autre participant ne peut rejoindre.",
"slashCommandsHeader": "Commandes",
"slashCommandsText": "Les commandes suivantes sont disponibles :",
"slashCommandsBullets": ["changer de pseudo", "effectuer une action", "effacer votre historique de messages", "lister toutes les commandes"],
"slashCommandsBullets": [
"changer de pseudo",
"effectuer une action",
"effacer votre historique de messages",
"lister toutes les commandes"
],
"sound": "Son",
"newMessageNotification": "Notification lors d'un nouveau message",
"desktopNotification": "Notification Système",

View File

@ -13,15 +13,15 @@ const languagesMap = {
de,
it,
zhCN,
nl
}
nl,
};
/**
* Return best match for lang and variant.
* @param {string} language string from navigator configuration or cookie.
* @returns the translation dict
*/
export function getTranslations(language = "") {
export function getTranslations(language = '') {
const [lang, variant] = language.split('-');
if (languagesMap.hasOwnProperty(`${lang}${variant}`)) {

View File

@ -18,7 +18,12 @@
"settings": "impostazioni",
"settingsButton": "impostazioni",
"settingsHeader": "Impostazioni e aiuto",
"slashCommandsBullets": ["cambia nome utente", "esegue un'azione", "cancella la cronologia dei messaggi", "elenca tutti i comandi"],
"slashCommandsBullets": [
"cambia nome utente",
"esegue un'azione",
"cancella la cronologia dei messaggi",
"elenca tutti i comandi"
],
"slashCommandsHeader": "Comandi",
"slashCommandsText": "Sono disponibili i seguenti comandi:",
"sound": "Suono",

View File

@ -18,7 +18,12 @@
"settings": "instellingen",
"settingsButton": "instellingen",
"settingsHeader": "Instellingen & Help",
"slashCommandsBullets": ["wijzigt gebruikersnaam", "voert een actie uit", "wist uw berichtgeschiedenis", "geeft alle opdrachten weer"],
"slashCommandsBullets": [
"wijzigt gebruikersnaam",
"voert een actie uit",
"wist uw berichtgeschiedenis",
"geeft alle opdrachten weer"
],
"slashCommandsHeader": "Slash-opdrachten",
"slashCommandsText": "De volgende slash-opdrachten zijn beschikbaar:",
"sound": "Geluid",

View File

@ -25,7 +25,12 @@
"lockRoomText": "Se sètz lo proprietari de la sala, podètz clavar e desclavar en clicar licòna del cadenat de la barra de navigacion. Quand una sala es clavada, cap de participant pòt pas la rejónher .",
"slashCommandsHeader": "Comandas",
"slashCommandsText": "Las comandas seguentas son disponiblas:",
"slashCommandsBullets": ["càmbia descais-nom", "realiza una accion", "escafa listoric de conversacion", "lista totas las comandas"],
"slashCommandsBullets": [
"càmbia descais-nom",
"realiza una accion",
"escafa listoric de conversacion",
"lista totas las comandas"
],
"sound": "Son",
"newMessageNotification": "New message notification",
"desktopNotification": "Desktop Notification",

View File

@ -1,14 +1,12 @@
body {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans',
'Droid Sans', 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
}

View File

@ -1,6 +1,6 @@
const initialState = {
items: [],
}
};
const activities = (state = initialState, action) => {
switch (action.type) {
@ -8,7 +8,7 @@ const activities = (state = initialState, action) => {
return {
...state,
items: [],
}
};
case 'SEND_ENCRYPTED_MESSAGE_SLASH_COMMAND':
return {
...state,
@ -19,7 +19,7 @@ const activities = (state = initialState, action) => {
type: 'SLASH_COMMAND',
},
],
}
};
case 'SEND_ENCRYPTED_MESSAGE_FILE_TRANSFER':
return {
...state,
@ -30,7 +30,7 @@ const activities = (state = initialState, action) => {
type: 'FILE',
},
],
}
};
case 'SEND_ENCRYPTED_MESSAGE_TEXT_MESSAGE':
return {
...state,
@ -41,7 +41,7 @@ const activities = (state = initialState, action) => {
type: 'TEXT_MESSAGE',
},
],
}
};
case 'RECEIVE_ENCRYPTED_MESSAGE_TEXT_MESSAGE':
return {
...state,
@ -52,7 +52,7 @@ const activities = (state = initialState, action) => {
type: 'TEXT_MESSAGE',
},
],
}
};
case 'SEND_ENCRYPTED_MESSAGE_SEND_FILE':
return {
...state,
@ -63,7 +63,7 @@ const activities = (state = initialState, action) => {
type: 'SEND_FILE',
},
],
}
};
case 'RECEIVE_ENCRYPTED_MESSAGE_SEND_FILE':
return {
...state,
@ -74,13 +74,13 @@ const activities = (state = initialState, action) => {
type: 'RECEIVE_FILE',
},
],
}
};
case 'RECEIVE_ENCRYPTED_MESSAGE_ADD_USER':
const newUserId = action.payload.payload.id
const newUserId = action.payload.payload.id;
const haveUser = action.payload.state.room.members.find(m => m.id === newUserId)
const haveUser = action.payload.state.room.members.find(m => m.id === newUserId);
if (haveUser) {
return state
return state;
}
return {
@ -93,10 +93,10 @@ const activities = (state = initialState, action) => {
username: action.payload.payload.username,
},
],
}
};
case 'USER_EXIT':
if (!action.payload.id) {
return state
return state;
}
return {
...state,
@ -108,7 +108,7 @@ const activities = (state = initialState, action) => {
username: action.payload.username,
},
],
}
};
case 'TOGGLE_LOCK_ROOM':
return {
...state,
@ -122,7 +122,7 @@ const activities = (state = initialState, action) => {
sender: action.payload.sender,
},
],
}
};
case 'RECEIVE_TOGGLE_LOCK_ROOM':
return {
...state,
@ -136,7 +136,7 @@ const activities = (state = initialState, action) => {
sender: action.payload.sender,
},
],
}
};
case 'SHOW_NOTICE':
return {
...state,
@ -147,7 +147,7 @@ const activities = (state = initialState, action) => {
message: action.payload.message,
},
],
}
};
case 'SEND_ENCRYPTED_MESSAGE_CHANGE_USERNAME':
return {
...state,
@ -158,16 +158,16 @@ const activities = (state = initialState, action) => {
currentUsername: action.payload.currentUsername,
newUsername: action.payload.newUsername,
},
].map((item) => {
].map(item => {
if (item.sender === action.payload.sender && item.type !== 'CHANGE_USERNAME') {
return {
...item,
username: action.payload.newUsername,
};
}
}
return item
return item;
}),
}
};
case 'RECEIVE_ENCRYPTED_MESSAGE_CHANGE_USERNAME':
return {
...state,
@ -178,16 +178,16 @@ const activities = (state = initialState, action) => {
currentUsername: action.payload.payload.currentUsername,
newUsername: action.payload.payload.newUsername,
},
].map((item) => {
].map(item => {
if (['TEXT_MESSAGE', 'USER_ACTION'].includes(item.type) && item.sender === action.payload.payload.sender) {
return {
...item,
username: action.payload.payload.newUsername,
};
}
}
return item
return item;
}),
}
};
case 'SEND_ENCRYPTED_MESSAGE_USER_ACTION':
return {
...state,
@ -198,7 +198,7 @@ const activities = (state = initialState, action) => {
...action.payload,
},
],
}
};
case 'RECEIVE_ENCRYPTED_MESSAGE_USER_ACTION':
return {
...state,
@ -209,10 +209,10 @@ const activities = (state = initialState, action) => {
...action.payload.payload,
},
],
}
};
default:
return state
return state;
}
}
};
export default activities
export default activities;

View File

@ -1,17 +1,17 @@
/* istanbul ignore file */
import { combineReducers } from 'redux'
import app from './app'
import activities from './activities'
import user from './user'
import room from './room'
import { combineReducers } from 'redux';
import app from './app';
import activities from './activities';
import user from './user';
import room from './room';
const appReducer = combineReducers({
app,
user,
room,
activities,
})
});
const rootReducer = (state, action) => appReducer(state, action)
const rootReducer = (state, action) => appReducer(state, action);
export default rootReducer
export default rootReducer;

View File

@ -1,4 +1,4 @@
import _ from 'lodash'
import _ from 'lodash';
const initialState = {
members: [
@ -9,42 +9,42 @@ const initialState = {
],
id: '',
isLocked: false,
}
};
const room = (state = initialState, action) => {
switch (action.type) {
case 'USER_EXIT':
const memberPubKeys = action.payload.members.map(m => m.publicKey.n)
const memberPubKeys = action.payload.members.map(m => m.publicKey.n);
return {
...state,
members: state.members
.filter(member => memberPubKeys.includes(member.publicKey.n))
.map(member => {
const thisMember = action.payload.members.find(mem => mem.publicKey.n === member.id)
if (thisMember){
const thisMember = action.payload.members.find(mem => mem.publicKey.n === member.id);
if (thisMember) {
return {
...member,
isOwner: thisMember.isOwner
}
}
return {...member}
})
isOwner: thisMember.isOwner,
};
}
return { ...member };
}),
};
case 'RECEIVE_ENCRYPTED_MESSAGE_ADD_USER':
return {
...state,
members: state.members.map((member) => {
members: state.members.map(member => {
if (member.publicKey.n === action.payload.payload.publicKey.n) {
return {
...member,
username: action.payload.payload.username,
isOwner: action.payload.payload.isOwner,
id: action.payload.payload.publicKey.n,
};
}
}
return member
return member;
}),
}
};
case 'CREATE_USER':
return {
...state,
@ -56,7 +56,7 @@ const room = (state = initialState, action) => {
id: action.payload.publicKey.n,
},
],
}
};
case 'USER_ENTER':
const members = _.uniqBy(action.payload.users, member => member.publicKey.n);
@ -65,15 +65,15 @@ const room = (state = initialState, action) => {
id: action.payload.id,
isLocked: Boolean(action.payload.isLocked),
members: members.reduce((acc, user) => {
const exists = state.members.find(m => m.publicKey.n === user.publicKey.n)
const exists = state.members.find(m => m.publicKey.n === user.publicKey.n);
if (exists) {
return [
...acc,
{
...user,
...exists,
}
]
},
];
}
return [
...acc,
@ -81,49 +81,51 @@ const room = (state = initialState, action) => {
publicKey: user.publicKey,
isOwner: user.isOwner,
id: user.id,
}
]
},
];
}, []),
}
};
case 'TOGGLE_LOCK_ROOM':
return {
...state,
isLocked: !state.isLocked,
}
};
case 'RECEIVE_TOGGLE_LOCK_ROOM':
return {
...state,
isLocked: action.payload.locked,
}
};
case 'SEND_ENCRYPTED_MESSAGE_CHANGE_USERNAME':
const newUsername = action.payload.newUsername
const userId = action.payload.id
const newUsername = action.payload.newUsername;
const userId = action.payload.id;
return {
...state,
members: state.members.map(member => (
member.id === userId ?
{
members: state.members.map(member =>
member.id === userId
? {
...member,
username: newUsername,
} : member
)),
}
: member,
),
};
case 'RECEIVE_ENCRYPTED_MESSAGE_CHANGE_USERNAME':
const newUsername2 = action.payload.payload.newUsername
const userId2 = action.payload.payload.id
const newUsername2 = action.payload.payload.newUsername;
const userId2 = action.payload.payload.id;
return {
...state,
members: state.members.map(member => (
member.id === userId2 ?
{
members: state.members.map(member =>
member.id === userId2
? {
...member,
username: newUsername2,
} : member
)),
}
: member,
),
};
default:
return state
return state;
}
}
};
export default room
export default room;

View File

@ -3,7 +3,7 @@ const initialState = {
publicKey: {},
username: '',
id: '',
}
};
const user = (state = initialState, action) => {
switch (action.type) {
@ -11,15 +11,15 @@ const user = (state = initialState, action) => {
return {
...action.payload,
id: action.payload.publicKey.n,
}
};
case 'SEND_ENCRYPTED_MESSAGE_CHANGE_USERNAME':
return {
...state,
username: action.payload.newUsername,
}
};
default:
return state
return state;
}
}
};
export default user
export default user;

View File

@ -1,22 +1,22 @@
import 'bootstrap/dist/css/bootstrap.min.css'
import 'react-simple-dropdown/styles/Dropdown.css'
import 'stylesheets/app.sass'
import 'bootstrap/dist/css/bootstrap.min.css';
import 'react-simple-dropdown/styles/Dropdown.css';
import 'stylesheets/app.sass';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import React, { Component } from 'react'
import { Redirect } from 'react-router'
import { Provider } from 'react-redux'
import configureStore from 'store'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import shortId from 'shortid'
import Home from 'components/Home'
import { hasTouchSupport } from './utils/dom'
import React, { Component } from 'react';
import { Redirect } from 'react-router';
import { Provider } from 'react-redux';
import configureStore from 'store';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import shortId from 'shortid';
import Home from 'components/Home';
import { hasTouchSupport } from './utils/dom';
const store = configureStore()
const store = configureStore();
export default class Root extends Component {
componentWillMount() {
if (hasTouchSupport) {
document.body.classList.add('touch')
document.body.classList.add('touch');
}
}
@ -32,6 +32,6 @@ export default class Root extends Component {
</div>
</BrowserRouter>
</Provider>
)
);
}
}

View File

@ -16,9 +16,7 @@ const isLocalhost = Boolean(
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/),
);
export function register(config) {
@ -44,7 +42,7 @@ export function register(config) {
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
'worker. To learn more, visit https://bit.ly/CRA-PWA',
);
});
} else {
@ -72,7 +70,7 @@ function registerValidSW(swUrl, config) {
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
'tabs for this page are closed. See https://bit.ly/CRA-PWA.',
);
// Execute callback
@ -105,10 +103,7 @@ function checkValidServiceWorker(swUrl, config) {
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
if (response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1)) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
@ -121,9 +116,7 @@ function checkValidServiceWorker(swUrl, config) {
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
console.log('No internet connection found. App is running in offline mode.');
});
}

View File

@ -1,28 +1,25 @@
/* istanbul ignore file */
import { createStore, applyMiddleware, compose } from 'redux'
import reducers from 'reducers'
import thunk from 'redux-thunk'
import { createStore, applyMiddleware, compose } from 'redux';
import reducers from 'reducers';
import thunk from 'redux-thunk';
const composeEnhancers = process.env.NODE_ENV === 'production' ? compose : (window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose)
const composeEnhancers =
process.env.NODE_ENV === 'production' ? compose : window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const enabledMiddlewares = [thunk]
const enabledMiddlewares = [thunk];
const middlewares = applyMiddleware(...enabledMiddlewares)
const middlewares = applyMiddleware(...enabledMiddlewares);
export default function configureStore(preloadedState) {
const store = createStore(
reducers,
preloadedState,
composeEnhancers(middlewares)
)
const store = createStore(reducers, preloadedState, composeEnhancers(middlewares));
if (module.hot) {
module.hot.accept('../reducers', () => {
// eslint-disable-next-line global-require
const nextRootReducer = require('../reducers/index')
store.replaceReducer(nextRootReducer)
})
const nextRootReducer = require('../reducers/index');
store.replaceReducer(nextRootReducer);
});
}
return store
return store;
}

View File

@ -4,4 +4,4 @@ module.exports = {
plugins: [
require('autoprefixer')({}), // eslint-disable-line
],
}
};

View File

@ -1,250 +1,246 @@
/* eslint-disable */
function Zoom(domContent) {
const OFFSET = 80
const OFFSET = 80;
// From http://youmightnotneedjquery.com/#offset
function offset(element) {
const rect = element.getBoundingClientRect()
const rect = element.getBoundingClientRect();
return {
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft,
}
};
}
function zoomListener() {
let activeZoom = null
let initialScrollPosition = null
let initialTouchPosition = null
let activeZoom = null;
let initialScrollPosition = null;
let initialTouchPosition = null;
function listen() {
domContent.addEventListener('click', (event) => {
if (event.target.tagName !== 'IMG') return
domContent.addEventListener('click', event => {
if (event.target.tagName !== 'IMG') return;
zoom(event)
})
zoom(event);
});
}
function zoom(event) {
event.stopPropagation()
event.stopPropagation();
if (document.body.classList.contains('zoom-overlay-open')) return
if (event.target.width >= (window.innerWidth - OFFSET)) return
if (document.body.classList.contains('zoom-overlay-open')) return;
if (event.target.width >= window.innerWidth - OFFSET) return;
if (event.metaKey || event.ctrlKey) return openInNewWindow()
if (event.metaKey || event.ctrlKey) return openInNewWindow();
closeActiveZoom({ forceDispose: true })
closeActiveZoom({ forceDispose: true });
activeZoom = vanillaZoom(event.target)
activeZoom.zoomImage()
activeZoom = vanillaZoom(event.target);
activeZoom.zoomImage();
addCloseActiveZoomListeners()
addCloseActiveZoomListeners();
}
function openInNewWindow() {
window.open(event.target.getAttribute('data-original') ||
event.target.currentSrc ||
event.target.src,
'_blank')
window.open(event.target.getAttribute('data-original') || event.target.currentSrc || event.target.src, '_blank');
}
function closeActiveZoom(options) {
options = options || { forceDispose: false }
if (!activeZoom) return
options = options || { forceDispose: false };
if (!activeZoom) return;
activeZoom[options.forceDispose ? 'dispose' : 'close']()
removeCloseActiveZoomListeners()
activeZoom = null
activeZoom[options.forceDispose ? 'dispose' : 'close']();
removeCloseActiveZoomListeners();
activeZoom = null;
}
function addCloseActiveZoomListeners() {
// todo(fat): probably worth throttling this
window.addEventListener('scroll', handleScroll)
document.addEventListener('click', handleClick)
document.addEventListener('keyup', handleEscPressed)
document.addEventListener('touchstart', handleTouchStart)
window.addEventListener('scroll', handleScroll);
document.addEventListener('click', handleClick);
document.addEventListener('keyup', handleEscPressed);
document.addEventListener('touchstart', handleTouchStart);
}
function removeCloseActiveZoomListeners() {
window.removeEventListener('scroll', handleScroll)
document.removeEventListener('keyup', handleEscPressed)
document.removeEventListener('click', handleClick)
document.removeEventListener('touchstart', handleTouchStart)
window.removeEventListener('scroll', handleScroll);
document.removeEventListener('keyup', handleEscPressed);
document.removeEventListener('click', handleClick);
document.removeEventListener('touchstart', handleTouchStart);
}
function handleScroll(event) {
if (initialScrollPosition === null) initialScrollPosition = window.scrollY
const deltaY = initialScrollPosition - window.scrollY
if (Math.abs(deltaY) >= 40) closeActiveZoom()
if (initialScrollPosition === null) initialScrollPosition = window.scrollY;
const deltaY = initialScrollPosition - window.scrollY;
if (Math.abs(deltaY) >= 40) closeActiveZoom();
}
function handleEscPressed(event) {
if (event.keyCode == 27) closeActiveZoom()
if (event.keyCode == 27) closeActiveZoom();
}
function handleClick(event) {
event.stopPropagation()
event.preventDefault()
closeActiveZoom()
event.stopPropagation();
event.preventDefault();
closeActiveZoom();
}
function handleTouchStart(event) {
initialTouchPosition = event.touches[0].pageY
event.target.addEventListener('touchmove', handleTouchMove)
initialTouchPosition = event.touches[0].pageY;
event.target.addEventListener('touchmove', handleTouchMove);
}
function handleTouchMove(event) {
if (Math.abs(event.touches[0].pageY - initialTouchPosition) <= 10) return
closeActiveZoom()
event.target.removeEventListener('touchmove', handleTouchMove)
if (Math.abs(event.touches[0].pageY - initialTouchPosition) <= 10) return;
closeActiveZoom();
event.target.removeEventListener('touchmove', handleTouchMove);
}
return { listen }
return { listen };
}
var vanillaZoom = (function () {
let fullHeight = null
let fullWidth = null
let overlay = null
let imgScaleFactor = null
let fullHeight = null;
let fullWidth = null;
let overlay = null;
let imgScaleFactor = null;
let targetImage = null
let targetImageWrap = null
let targetImageClone = null
let targetImage = null;
let targetImageWrap = null;
let targetImageClone = null;
function zoomImage() {
const img = document.createElement('img')
const img = document.createElement('img');
img.onload = function () {
fullHeight = Number(img.height)
fullWidth = Number(img.width)
zoomOriginal()
}
img.src = targetImage.currentSrc || targetImage.src
fullHeight = Number(img.height);
fullWidth = Number(img.width);
zoomOriginal();
};
img.src = targetImage.currentSrc || targetImage.src;
}
function zoomOriginal() {
targetImageWrap = document.createElement('div')
targetImageWrap.className = 'zoom-img-wrap'
targetImageWrap.style.position = 'absolute'
targetImageWrap.style.top = `${offset(targetImage).top}px`
targetImageWrap.style.left = `${offset(targetImage).left}px`
targetImageWrap = document.createElement('div');
targetImageWrap.className = 'zoom-img-wrap';
targetImageWrap.style.position = 'absolute';
targetImageWrap.style.top = `${offset(targetImage).top}px`;
targetImageWrap.style.left = `${offset(targetImage).left}px`;
targetImageClone = targetImage.cloneNode()
targetImageClone.style.visibility = 'hidden'
targetImageClone = targetImage.cloneNode();
targetImageClone.style.visibility = 'hidden';
targetImage.style.width = `${targetImage.offsetWidth}px`
targetImage.parentNode.replaceChild(targetImageClone, targetImage)
targetImage.style.width = `${targetImage.offsetWidth}px`;
targetImage.parentNode.replaceChild(targetImageClone, targetImage);
document.body.appendChild(targetImageWrap)
targetImageWrap.appendChild(targetImage)
document.body.appendChild(targetImageWrap);
targetImageWrap.appendChild(targetImage);
targetImage.classList.add('zoom-img')
targetImage.setAttribute('data-action', 'zoom-out')
targetImage.classList.add('zoom-img');
targetImage.setAttribute('data-action', 'zoom-out');
overlay = document.createElement('div')
overlay.className = 'zoom-overlay'
overlay = document.createElement('div');
overlay.className = 'zoom-overlay';
document.body.appendChild(overlay)
document.body.appendChild(overlay);
calculateZoom()
triggerAnimation()
calculateZoom();
triggerAnimation();
}
function calculateZoom() {
targetImage.offsetWidth // repaint before animating
targetImage.offsetWidth; // repaint before animating
const originalFullImageWidth = fullWidth
const originalFullImageHeight = fullHeight
const originalFullImageWidth = fullWidth;
const originalFullImageHeight = fullHeight;
const maxScaleFactor = originalFullImageWidth / targetImage.width
const maxScaleFactor = originalFullImageWidth / targetImage.width;
const viewportHeight = window.innerHeight - OFFSET
const viewportWidth = window.innerWidth - OFFSET
const viewportHeight = window.innerHeight - OFFSET;
const viewportWidth = window.innerWidth - OFFSET;
const imageAspectRatio = originalFullImageWidth / originalFullImageHeight
const viewportAspectRatio = viewportWidth / viewportHeight
const imageAspectRatio = originalFullImageWidth / originalFullImageHeight;
const viewportAspectRatio = viewportWidth / viewportHeight;
if (originalFullImageWidth < viewportWidth && originalFullImageHeight < viewportHeight) {
imgScaleFactor = maxScaleFactor
imgScaleFactor = maxScaleFactor;
} else if (imageAspectRatio < viewportAspectRatio) {
imgScaleFactor = (viewportHeight / originalFullImageHeight) * maxScaleFactor
imgScaleFactor = (viewportHeight / originalFullImageHeight) * maxScaleFactor;
} else {
imgScaleFactor = (viewportWidth / originalFullImageWidth) * maxScaleFactor
imgScaleFactor = (viewportWidth / originalFullImageWidth) * maxScaleFactor;
}
}
function triggerAnimation() {
targetImage.offsetWidth // repaint before animating
targetImage.offsetWidth; // repaint before animating
const imageOffset = offset(targetImage)
const scrollTop = window.scrollY
const imageOffset = offset(targetImage);
const scrollTop = window.scrollY;
const viewportY = scrollTop + (window.innerHeight / 2)
const viewportX = (window.innerWidth / 2)
const viewportY = scrollTop + window.innerHeight / 2;
const viewportX = window.innerWidth / 2;
const imageCenterY = imageOffset.top + (targetImage.height / 2)
const imageCenterX = imageOffset.left + (targetImage.width / 2)
const imageCenterY = imageOffset.top + targetImage.height / 2;
const imageCenterX = imageOffset.left + targetImage.width / 2;
const translateY = viewportY - imageCenterY
const translateX = viewportX - imageCenterX
const translateY = viewportY - imageCenterY;
const translateX = viewportX - imageCenterX;
const targetImageTransform = `scale(${imgScaleFactor})`
const targetImageWrapTransform =
`translate(${translateX}px, ${translateY}px) translateZ(0)`
const targetImageTransform = `scale(${imgScaleFactor})`;
const targetImageWrapTransform = `translate(${translateX}px, ${translateY}px) translateZ(0)`;
targetImage.style.webkitTransform = targetImageTransform
targetImage.style.msTransform = targetImageTransform
targetImage.style.transform = targetImageTransform
targetImage.style.webkitTransform = targetImageTransform;
targetImage.style.msTransform = targetImageTransform;
targetImage.style.transform = targetImageTransform;
targetImageWrap.style.webkitTransform = targetImageWrapTransform
targetImageWrap.style.msTransform = targetImageWrapTransform
targetImageWrap.style.transform = targetImageWrapTransform
targetImageWrap.style.webkitTransform = targetImageWrapTransform;
targetImageWrap.style.msTransform = targetImageWrapTransform;
targetImageWrap.style.transform = targetImageWrapTransform;
document.body.classList.add('zoom-overlay-open')
document.body.classList.add('zoom-overlay-open');
}
function close() {
document.body.classList.remove('zoom-overlay-open')
document.body.classList.add('zoom-overlay-transitioning')
document.body.classList.remove('zoom-overlay-open');
document.body.classList.add('zoom-overlay-transitioning');
targetImage.style.webkitTransform = ''
targetImage.style.msTransform = ''
targetImage.style.transform = ''
targetImage.style.webkitTransform = '';
targetImage.style.msTransform = '';
targetImage.style.transform = '';
targetImageWrap.style.webkitTransform = ''
targetImageWrap.style.msTransform = ''
targetImageWrap.style.transform = ''
targetImageWrap.style.webkitTransform = '';
targetImageWrap.style.msTransform = '';
targetImageWrap.style.transform = '';
if (!('transition' in document.body.style)) return dispose()
if (!('transition' in document.body.style)) return dispose();
targetImage.addEventListener('transitionend', dispose)
targetImage.addEventListener('webkitTransitionEnd', dispose)
targetImage.addEventListener('transitionend', dispose);
targetImage.addEventListener('webkitTransitionEnd', dispose);
}
function dispose() {
targetImage.removeEventListener('transitionend', dispose)
targetImage.removeEventListener('webkitTransitionEnd', dispose)
targetImage.removeEventListener('transitionend', dispose);
targetImage.removeEventListener('webkitTransitionEnd', dispose);
if (!targetImageWrap || !targetImageWrap.parentNode) return
if (!targetImageWrap || !targetImageWrap.parentNode) return;
targetImage.classList.remove('zoom-img')
targetImage.style.width = ''
targetImage.setAttribute('data-action', 'zoom')
targetImage.classList.remove('zoom-img');
targetImage.style.width = '';
targetImage.setAttribute('data-action', 'zoom');
targetImageClone.parentNode.replaceChild(targetImage, targetImageClone)
targetImageWrap.parentNode.removeChild(targetImageWrap)
overlay.parentNode.removeChild(overlay)
targetImageClone.parentNode.replaceChild(targetImage, targetImageClone);
targetImageWrap.parentNode.removeChild(targetImageWrap);
overlay.parentNode.removeChild(overlay);
document.body.classList.remove('zoom-overlay-transitioning')
document.body.classList.remove('zoom-overlay-transitioning');
}
return function (target) {
targetImage = target
return { zoomImage, close, dispose }
}
}())
targetImage = target;
return { zoomImage, close, dispose };
};
})();
zoomListener().listen()
zoomListener().listen();
}
export default Zoom
export default Zoom;

View File

@ -1,32 +1,32 @@
export default class Crypto {
constructor() {
this._crypto = window.crypto || false
this._crypto = window.crypto || false;
if (!this._crypto || (!this._crypto.subtle && !this._crypto.webkitSubtle)) {
return false
return false;
}
}
get crypto() {
return this._crypto
return this._crypto;
}
convertStringToArrayBufferView(str) {
const bytes = new Uint8Array(str.length)
const bytes = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++) {
bytes[i] = str.charCodeAt(i)
bytes[i] = str.charCodeAt(i);
}
return bytes
return bytes;
}
convertArrayBufferViewToString(buffer) {
let str = ''
let str = '';
for (let i = 0; i < buffer.byteLength; i++) {
str += String.fromCharCode(buffer[i])
str += String.fromCharCode(buffer[i]);
}
return str
return str;
}
createEncryptDecryptKeys() {
@ -38,8 +38,8 @@ export default class Crypto {
hash: { name: 'SHA-1' },
},
true, // whether the key is extractable (i.e. can be used in exportKey)
['encrypt', 'decrypt', 'wrapKey', 'unwrapKey'] // must be ['encrypt', 'decrypt'] or ['wrapKey', 'unwrapKey']
)
['encrypt', 'decrypt', 'wrapKey', 'unwrapKey'], // must be ['encrypt', 'decrypt'] or ['wrapKey', 'unwrapKey']
);
}
createSecretKey() {
@ -49,8 +49,8 @@ export default class Crypto {
length: 256, // can be 128, 192, or 256
},
true, // whether the key is extractable (i.e. can be used in exportKey)
['encrypt', 'decrypt'] // can be 'encrypt', 'decrypt', 'wrapKey', or 'unwrapKey'
)
['encrypt', 'decrypt'], // can be 'encrypt', 'decrypt', 'wrapKey', or 'unwrapKey'
);
}
createSigningKey() {
@ -60,8 +60,8 @@ export default class Crypto {
hash: { name: 'SHA-256' },
},
true, // whether the key is extractable (i.e. can be used in exportKey)
['sign', 'verify'] // can be 'encrypt', 'decrypt', 'wrapKey', or 'unwrapKey'
)
['sign', 'verify'], // can be 'encrypt', 'decrypt', 'wrapKey', or 'unwrapKey'
);
}
encryptMessage(data, secretKey, iv) {
@ -73,8 +73,8 @@ export default class Crypto {
iv,
},
secretKey, // from generateKey or importKey above
data // ArrayBuffer of data you want to encrypt
)
data, // ArrayBuffer of data you want to encrypt
);
}
decryptMessage(data, secretKey, iv) {
@ -84,31 +84,31 @@ export default class Crypto {
iv, // The initialization vector you used to encrypt
},
secretKey, // from generateKey or importKey above
data // ArrayBuffer of the data
)
data, // ArrayBuffer of the data
);
}
importEncryptDecryptKey(jwkData, format = 'jwk', ops) {
const hashObj = {
name: 'RSA-OAEP',
hash: { name: 'SHA-1' },
}
};
return this.crypto.subtle.importKey(
format, // can be 'jwk' (public or private), 'spki' (public only), or 'pkcs8' (private only)
jwkData,
hashObj,
true, // whether the key is extractable (i.e. can be used in exportKey)
ops || ['encrypt', 'wrapKey'] // 'encrypt' or 'wrapKey' for public key import or
ops || ['encrypt', 'wrapKey'], // 'encrypt' or 'wrapKey' for public key import or
// 'decrypt' or 'unwrapKey' for private key imports
)
);
}
exportKey(key, format) {
return this.crypto.subtle.exportKey(
format || 'jwk', // can be 'jwk' (public or private), 'spki' (public only), or 'pkcs8' (private only)
key // can be a publicKey or privateKey, as long as extractable was true
)
key, // can be a publicKey or privateKey, as long as extractable was true
);
}
signMessage(data, keyToSignWith) {
@ -118,8 +118,8 @@ export default class Crypto {
hash: { name: 'SHA-256' },
},
keyToSignWith, // from generateKey or importKey above
data // ArrayBuffer of data you want to sign
)
data, // ArrayBuffer of data you want to sign
);
}
verifyPayload(signature, data, keyToVerifyWith) {
@ -131,20 +131,15 @@ export default class Crypto {
},
keyToVerifyWith, // from generateKey or importKey above
signature, // ArrayBuffer of the signature
data // ArrayBuffer of the data
)
data, // ArrayBuffer of the data
);
}
wrapKey(keyToWrap, keyToWrapWith, format = 'jwk') {
return this.crypto.subtle.wrapKey(
format,
keyToWrap,
keyToWrapWith,
{
return this.crypto.subtle.wrapKey(format, keyToWrap, keyToWrapWith, {
name: 'RSA-OAEP',
hash: { name: 'SHA-1' },
}
)
});
}
unwrapKey(
@ -154,7 +149,7 @@ export default class Crypto {
unwrapAlgo,
unwrappedKeyAlgo, // AES-CBC for session, HMAC for signing
extractable = true,
keyUsages// verify for signing // decrypt for session
keyUsages, // verify for signing // decrypt for session
) {
return this.crypto.subtle.unwrapKey(
format,
@ -163,7 +158,7 @@ export default class Crypto {
unwrapAlgo,
unwrappedKeyAlgo,
extractable,
keyUsages
)
keyUsages,
);
}
}

View File

@ -1,14 +1,13 @@
/* eslint-disable import/prefer-default-export */
export const getSelectedText = () => {
let text = ''
let text = '';
if (typeof window.getSelection !== 'undefined') {
text = window.getSelection().toString()
text = window.getSelection().toString();
} else if (typeof document.selection !== 'undefined' && document.selection.type === 'Text') {
text = document.selection.createRange().text
text = document.selection.createRange().text;
}
return text
}
return text;
};
export const hasTouchSupport =
('ontouchstart' in window)
|| (window.DocumentTouch && document instanceof window.DocumentTouch)
'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);

View File

@ -1,29 +1,29 @@
/* eslint-disable import/prefer-default-export */
export const getObjectUrl = (encodedFile, fileType) => {
const b64 = unescape(encodedFile)
const sliceSize = 1024
const byteCharacters = window.atob(b64)
const byteArrays = []
const b64 = unescape(encodedFile);
const sliceSize = 1024;
const byteCharacters = window.atob(b64);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize)
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length)
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i)
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers)
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray)
byteArrays.push(byteArray);
}
if (byteArrays.length <= 0) {
return ''
return '';
}
const blob = new window.Blob(byteArrays, { type: fileType })
const blob = new window.Blob(byteArrays, { type: fileType });
const url = window.URL.createObjectURL(blob)
return url
}
const url = window.URL.createObjectURL(blob);
return url;
};

View File

@ -1,4 +1,4 @@
/* eslint-disable import/prefer-default-export */
export function sanitize(str) {
return str.replace(/[^A-Za-z0-9._]/g, '-').replace(/[<>]/ig, '')
return str.replace(/[^A-Za-z0-9._]/g, '-').replace(/[<>]/gi, '');
}

View File

@ -1,20 +1,21 @@
import Crypto from './crypto'
import Crypto from './crypto';
const crypto = new Crypto()
const crypto = new Crypto();
export const process = (payload, state) => new Promise(async (resolve, reject) => {
const privateKeyJson = state.user.privateKey
const privateKey = await crypto.importEncryptDecryptKey(privateKeyJson, 'jwk', ['decrypt', 'unwrapKey'])
export const process = (payload, state) =>
new Promise(async (resolve, reject) => {
const privateKeyJson = state.user.privateKey;
const privateKey = await crypto.importEncryptDecryptKey(privateKeyJson, 'jwk', ['decrypt', 'unwrapKey']);
let sessionKey
let signingKey
let sessionKey;
let signingKey;
const iv = await crypto.convertStringToArrayBufferView(payload.iv)
const signature = await crypto.convertStringToArrayBufferView(payload.signature)
const payloadBuffer = await crypto.convertStringToArrayBufferView(payload.payload)
const iv = await crypto.convertStringToArrayBufferView(payload.iv);
const signature = await crypto.convertStringToArrayBufferView(payload.signature);
const payloadBuffer = await crypto.convertStringToArrayBufferView(payload.payload);
await new Promise((resolvePayload) => {
payload.keys.forEach(async (key) => {
await new Promise(resolvePayload => {
payload.keys.forEach(async key => {
try {
sessionKey = await crypto.unwrapKey(
'jwk',
@ -26,8 +27,8 @@ export const process = (payload, state) => new Promise(async (resolve, reject) =
},
{ name: 'AES-CBC' },
true,
['decrypt']
)
['decrypt'],
);
signingKey = await crypto.unwrapKey(
'jwk',
@ -39,42 +40,35 @@ export const process = (payload, state) => new Promise(async (resolve, reject) =
},
{ name: 'HMAC', hash: { name: 'SHA-256' } },
true,
['verify']
)
resolvePayload()
} catch (e) { } // eslint-disable-line
})
})
['verify'],
);
resolvePayload();
} catch (e) {} // eslint-disable-line
});
});
const verified = await crypto.verifyPayload(
signature,
payloadBuffer,
signingKey
)
const verified = await crypto.verifyPayload(signature, payloadBuffer, signingKey);
if (!verified) {
reject()
return
reject();
return;
}
const decryptedPayload = await crypto.decryptMessage(
payloadBuffer,
sessionKey,
iv
)
const decryptedPayload = await crypto.decryptMessage(payloadBuffer, sessionKey, iv);
const payloadJson = JSON.parse(crypto.convertArrayBufferViewToString(new Uint8Array(decryptedPayload)))
const payloadJson = JSON.parse(crypto.convertArrayBufferViewToString(new Uint8Array(decryptedPayload)));
resolve(payloadJson)
})
resolve(payloadJson);
});
export const prepare = (payload, state) => new Promise(async (resolve) => {
const myUsername = state.user.username
const myId = state.user.id
export const prepare = (payload, state) =>
new Promise(async resolve => {
const myUsername = state.user.username;
const myId = state.user.id;
const sessionKey = await crypto.createSecretKey()
const signingKey = await crypto.createSigningKey()
const iv = await crypto.crypto.getRandomValues(new Uint8Array(16))
const sessionKey = await crypto.createSecretKey();
const signingKey = await crypto.createSigningKey();
const iv = await crypto.crypto.getRandomValues(new Uint8Array(16));
const jsonToSend = {
...payload,
@ -84,31 +78,28 @@ export const prepare = (payload, state) => new Promise(async (resolve) => {
username: myUsername,
text: encodeURI(payload.payload.text),
},
}
};
const payloadBuffer = crypto.convertStringToArrayBufferView(JSON.stringify(jsonToSend))
const payloadBuffer = crypto.convertStringToArrayBufferView(JSON.stringify(jsonToSend));
const encryptedPayload = await crypto.encryptMessage(payloadBuffer, sessionKey, iv)
const payloadString = await crypto.convertArrayBufferViewToString(new Uint8Array(encryptedPayload))
const encryptedPayload = await crypto.encryptMessage(payloadBuffer, sessionKey, iv);
const payloadString = await crypto.convertArrayBufferViewToString(new Uint8Array(encryptedPayload));
const signature = await crypto.signMessage(encryptedPayload, signingKey)
const signature = await crypto.signMessage(encryptedPayload, signingKey);
const encryptedKeys = await Promise.all(state.room.members
.map(async (member) => {
const key = await crypto.importEncryptDecryptKey(member.publicKey)
const enc = await Promise.all([
crypto.wrapKey(sessionKey, key),
crypto.wrapKey(signingKey, key),
])
const encryptedKeys = await Promise.all(
state.room.members.map(async member => {
const key = await crypto.importEncryptDecryptKey(member.publicKey);
const enc = await Promise.all([crypto.wrapKey(sessionKey, key), crypto.wrapKey(signingKey, key)]);
return {
sessionKey: enc[0],
signingKey: enc[1],
}
})
)
};
}),
);
const ivString = await crypto.convertArrayBufferViewToString(new Uint8Array(iv))
const signatureString = await crypto.convertArrayBufferViewToString(new Uint8Array(signature))
const ivString = await crypto.convertArrayBufferViewToString(new Uint8Array(iv));
const signatureString = await crypto.convertArrayBufferViewToString(new Uint8Array(signature));
resolve({
toSend: {
@ -118,5 +109,5 @@ export const prepare = (payload, state) => new Promise(async (resolve) => {
keys: encryptedKeys,
},
original: jsonToSend,
})
})
});
});

View File

@ -1,16 +1,16 @@
import socketIO from 'socket.io-client'
import socketIO from 'socket.io-client';
import generateUrl from '../api/generator';
let socket
let socket;
export const connect = (roomId) => {
export const connect = roomId => {
socket = socketIO(generateUrl(), {
query: {
roomId,
},
forceNew: true,
})
return socket
}
});
return socket;
};
export const getSocket = () => socket
export const getSocket = () => socket;