diff --git a/net/web/index.html b/net/web/index.html index 95957f5e..20a58ddf 100644 --- a/net/web/index.html +++ b/net/web/index.html @@ -1,39 +1,21 @@ - + - - - + + + - - + + Databag
- + diff --git a/net/web/mock/fileMock.js b/net/web/mock/fileMock.js index 9dc5fc1e..6952308a 100644 --- a/net/web/mock/fileMock.js +++ b/net/web/mock/fileMock.js @@ -1 +1,2 @@ -module.exports = ''; +module.exports = ''; + diff --git a/net/web/src/App.tsx b/net/web/src/App.tsx index 04237758..62b82c39 100644 --- a/net/web/src/App.tsx +++ b/net/web/src/App.tsx @@ -1,6 +1,7 @@ + import 'antd/dist/reset.css'; import { Colors } from 'constants/Colors'; -import { HashRouter as Router, Routes, Route } from 'react-router-dom'; +import { HashRouter as Router, Routes, Route } from "react-router-dom"; import { AppContextProvider } from 'context/AppContext'; import { AccountContextProvider } from 'context/AccountContext'; @@ -22,6 +23,7 @@ import { Dashboard } from './dashboard/Dashboard'; import { ConfigProvider } from 'antd'; function App() { + return ( @@ -33,46 +35,25 @@ function App() { - + - } - /> - } - /> - } - /> - } - /> - } - /> - - - - } - > + } /> + } /> + } /> + } /> + } /> + + + + }> + diff --git a/net/web/src/access/Access.styled.ts b/net/web/src/access/Access.styled.ts index 9e84aaf9..3afbce03 100644 --- a/net/web/src/access/Access.styled.ts +++ b/net/web/src/access/Access.styled.ts @@ -2,7 +2,7 @@ import styled from 'styled-components'; export const AccessWrapper = styled.div` height: 100%; - color: ${(props) => props.theme.hintText}; + color: ${props => props.theme.hintText}; .footer { display: flex; @@ -22,12 +22,12 @@ export const AccessWrapper = styled.div` width: 100%; height: 100%; padding: 8px; - + .center { width: 100%; height: 100%; border-radius: 4px; - background: ${(props) => props.theme.frameArea}; + background: ${props => props.theme.frameArea}; display: flex; flex-direction: column; align-items: center; @@ -44,7 +44,7 @@ export const AccessWrapper = styled.div` width: 50%; height: 100%; padding: 32px; - background-color: ${(props) => props.theme.splashArea}; + background-color: ${props => props.theme.splashArea}; .splash { width: 100%; @@ -56,7 +56,7 @@ export const AccessWrapper = styled.div` .right { width: 50%; height: 100%; - background: ${(props) => props.theme.frameArea}; + background: ${props => props.theme.frameArea}; display: flex; flex-direction: column; align-items: center; diff --git a/net/web/src/access/Access.tsx b/net/web/src/access/Access.tsx index 3628e05a..774cbd6c 100644 --- a/net/web/src/access/Access.tsx +++ b/net/web/src/access/Access.tsx @@ -3,98 +3,104 @@ import { AccessWrapper } from './Access.styled'; import { Login } from './login/Login'; import { Admin } from './admin/Admin'; import { CreateAccount } from './createAccount/CreateAccount'; -import { ThemeProvider } from 'styled-components'; +import { ThemeProvider } from "styled-components"; import { Select } from 'antd'; import dogin from 'images/dogin.png'; import bogin from 'images/bogin.png'; export function Access({ mode }) { + const { state, actions } = useAccess(); return ( - {(state.display === 'large' || state.display === 'xlarge') && ( + { (state.display === 'large' || state.display === 'xlarge') && (
- {state.scheme === 'dark' && ( - Databag Splash + { state.scheme === 'dark' && ( + Databag Splash )} - {state.scheme === 'light' && ( - Databag Splash + { state.scheme === 'light' && ( + Databag Splash )}
- {mode === 'login' && } - {mode === 'create' && } - {mode === 'admin' && } + { mode === 'login' && ( + + )} + { mode === 'create' && ( + + )} + { mode === 'admin' && ( + + )}
{state.strings.theme}
+ defaultValue={null} + size="small" + style={{ width: 128 }} + value={state.language} + onChange={actions.setLanguage} + options={[{value: null, label: state.strings.default}, ...state.languages]} + />
)} - {(state.display === 'medium' || state.display === 'small') && ( + { (state.display === 'medium' || state.display === 'small') && (
- {mode === 'login' && } - {mode === 'create' && } - {mode === 'admin' && } + { mode === 'login' && ( + + )} + { mode === 'create' && ( + + )} + { mode === 'admin' && ( + + )}
{state.strings.theme}
+ defaultValue={null} + size="small" + style={{ width: 128 }} + value={state.language} + onChange={actions.setLanguage} + options={[{value: null, label: state.strings.default}, ...state.languages]} + />
+
)} @@ -102,3 +108,4 @@ export function Access({ mode }) {
); } + diff --git a/net/web/src/access/admin/Admin.styled.ts b/net/web/src/access/admin/Admin.styled.ts index c4200849..97a42676 100644 --- a/net/web/src/access/admin/Admin.styled.ts +++ b/net/web/src/access/admin/Admin.styled.ts @@ -7,20 +7,20 @@ export const AdminWrapper = styled.div` height: 90%; display: flex; flex-direction: column; - + .disabled { - background-color: ${(props) => props.theme.disabledArea}; + background-color: ${props => props.theme.disabledArea}; button { - color: ${(props) => props.theme.idleText}; + color: ${props => props.theme.idleText}; } } .enabled { - background-color: ${(props) => props.theme.enabledArea}; + background-color: ${props => props.theme.enabledArea}; button { - color: ${(props) => props.theme.activeText}; + color: ${props => props.theme.activeText}; } } @@ -54,7 +54,7 @@ export const AdminWrapper = styled.div` .form-form { flex: 2; - + .form-button { display: flex; align-items: center; @@ -70,3 +70,5 @@ export const AdminWrapper = styled.div` background-color: #444444; } `; + + diff --git a/net/web/src/access/admin/Admin.tsx b/net/web/src/access/admin/Admin.tsx index 7ff697dc..9e59c467 100644 --- a/net/web/src/access/admin/Admin.tsx +++ b/net/web/src/access/admin/Admin.tsx @@ -3,75 +3,59 @@ import { UserOutlined, LockOutlined } from '@ant-design/icons'; import { AdminWrapper } from './Admin.styled'; import { useAdmin } from './useAdmin.hook'; -export function Admin() { - const [modal, modalContext] = Modal.useModal(); +export function Admin() { + + const [ modal, modalContext ] = Modal.useModal(); const { state, actions } = useAdmin(); const login = async () => { try { await actions.login(); - } catch (err) { + } + catch(err) { modal.error({ title: {state.strings.adminError}, content: {state.strings.adminMessage}, bodyStyle: { borderRadius: 8, padding: 16, ...state.menuStyle }, }); } - }; + } const keyDown = (e) => { if (e.key === 'Enter') { - login(); + login() } - }; + } return ( - {modalContext} + { modalContext }
Databag -
actions.navUser()} - > +
actions.navUser()}>
{state.strings.admin}
-
+ + - actions.setPassword(e.target.value)} - autoComplete="current-password" - onKeyDown={(e) => keyDown(e)} - prefix={} - size="large" - /> + actions.setPassword(e.target.value)} autoComplete="current-password" + onKeyDown={(e) => keyDown(e)} prefix={} size="large" />
- +
+
); -} +}; + diff --git a/net/web/src/access/admin/useAdmin.hook.ts b/net/web/src/access/admin/useAdmin.hook.ts index 8bc54ce9..8ab14909 100644 --- a/net/web/src/access/admin/useAdmin.hook.ts +++ b/net/web/src/access/admin/useAdmin.hook.ts @@ -1,5 +1,5 @@ import { useContext, useState, useEffect } from 'react'; -import { useNavigate } from 'react-router-dom'; +import { useNavigate } from "react-router-dom"; import { getNodeStatus } from 'api/getNodeStatus'; import { setNodeStatus } from 'api/setNodeStatus'; import { getNodeConfig } from 'api/getNodeConfig'; @@ -7,6 +7,7 @@ import { AppContext } from 'context/AppContext'; import { SettingsContext } from 'context/SettingsContext'; export function useAdmin() { + const [state, setState] = useState({ password: '', placeholder: '', @@ -22,15 +23,16 @@ export function useAdmin() { const updateState = (value) => { setState((s) => ({ ...s, ...value })); - }; + } useEffect(() => { const check = async () => { try { const unclaimed = await getNodeStatus(); updateState({ unclaimed }); - } catch (err) { - console.log('getNodeStatus failed'); + } + catch(err) { + console.log("getNodeStatus failed"); } }; check(); @@ -52,15 +54,16 @@ export function useAdmin() { } await getNodeConfig(state.password); updateState({ busy: false }); - app.actions.setAdmin(state.password); - } catch (err) { + app.actions.setAdmin(state.password); + } + catch(err) { console.log(err); updateState({ busy: false }); - throw new Error('login failed'); + throw new Error("login failed"); } } }, - }; + } useEffect(() => { const { strings, menuStyle } = settings.state; @@ -69,3 +72,4 @@ export function useAdmin() { return { state, actions }; } + diff --git a/net/web/src/access/createAccount/CreateAccount.styled.ts b/net/web/src/access/createAccount/CreateAccount.styled.ts index ededcf5b..6673167e 100644 --- a/net/web/src/access/createAccount/CreateAccount.styled.ts +++ b/net/web/src/access/createAccount/CreateAccount.styled.ts @@ -9,18 +9,18 @@ export const CreateAccountWrapper = styled.div` flex-direction: column; .disabled { - background-color: ${(props) => props.theme.disabledArea}; + background-color: ${props => props.theme.disabledArea}; button { - color: ${(props) => props.theme.idleText}; + color: ${props => props.theme.idleText}; } } .enabled { - background-color: ${(props) => props.theme.enabledArea}; + background-color: ${props => props.theme.enabledArea}; button { - color: ${(props) => props.theme.activeText}; + color: ${props => props.theme.activeText}; } } @@ -58,7 +58,7 @@ export const CreateAccountWrapper = styled.div` .form-space { height: 8px; } - + .form-button { display: flex; align-items: center; @@ -78,3 +78,5 @@ export const CreateAccountWrapper = styled.div` background-color: #444444; } `; + + diff --git a/net/web/src/access/createAccount/CreateAccount.tsx b/net/web/src/access/createAccount/CreateAccount.tsx index ae0ba75d..421ca7a0 100644 --- a/net/web/src/access/createAccount/CreateAccount.tsx +++ b/net/web/src/access/createAccount/CreateAccount.tsx @@ -3,100 +3,64 @@ import { SettingOutlined, LockOutlined, UserOutlined } from '@ant-design/icons'; import { CreateAccountWrapper } from './CreateAccount.styled'; import { useCreateAccount } from './useCreateAccount.hook'; -export function CreateAccount() { - const [modal, modalContext] = Modal.useModal(); +export function CreateAccount() { + + const [ modal, modalContext ] = Modal.useModal(); const { state, actions } = useCreateAccount(); const create = async () => { try { await actions.onCreateAccount(); - } catch (err) { + } + catch(err) { modal.error({ title: {state.strings.createError}, content: {state.strings.createMessage}, bodyStyle: { borderRadius: 8, padding: 16, ...state.menuStyle }, }); } - }; + } const keyDown = (e) => { if (e.key === 'Enter') { - create(); + create() } - }; + } return ( - {modalContext} + { modalContext }
Databag -
actions.onSettings()} - > +
actions.onSettings()}>
{state.strings.createAccount}
-
- - actions.setUsername(e.target.value)} - autoComplete="username" - autoCapitalize="none" - onKeyDown={(e) => keyDown(e)} - prefix={} - size="large" - /> + + + + actions.setUsername(e.target.value)} + autoComplete="username" autoCapitalize="none" onKeyDown={(e) => keyDown(e)} prefix={} size="large" />
- actions.setPassword(e.target.value)} - autoComplete="new-password" - onKeyDown={(e) => keyDown(e)} - prefix={} - size="large" - /> + actions.setPassword(e.target.value)} + autoComplete="new-password" onKeyDown={(e) => keyDown(e)} prefix={} size="large" /> - actions.setConfirm(e.target.value)} - autoComplete="new-password" - onKeyDown={(e) => keyDown(e)} - prefix={} - size="large" - /> + actions.setConfirm(e.target.value)} + autoComplete="new-password" onKeyDown={(e) => keyDown(e)} prefix={} size="large" />
-
@@ -104,17 +68,15 @@ export function CreateAccount() {
-
+
); -} +}; + diff --git a/net/web/src/access/createAccount/useCreateAccount.hook.ts b/net/web/src/access/createAccount/useCreateAccount.hook.ts index 7a414abc..4aed591f 100644 --- a/net/web/src/access/createAccount/useCreateAccount.hook.ts +++ b/net/web/src/access/createAccount/useCreateAccount.hook.ts @@ -1,10 +1,11 @@ import { useContext, useState, useEffect, useRef } from 'react'; import { AppContext } from 'context/AppContext'; import { SettingsContext } from 'context/SettingsContext'; -import { useNavigate, useLocation } from 'react-router-dom'; +import { useNavigate, useLocation } from "react-router-dom"; import { getUsername } from 'api/getUsername'; export function useCreateAccount() { + const [checked, setChecked] = useState(true); const [state, setState] = useState({ username: '', @@ -13,7 +14,7 @@ export function useCreateAccount() { busy: false, validatetatus: 'success', help: '', - strings: {} as Record, + strings: {} as Record, menuStyle: {}, }); @@ -25,30 +26,33 @@ export function useCreateAccount() { const updateState = (value) => { setState((s) => ({ ...s, ...value })); - }; + } const usernameSet = (name) => { - setChecked(false); - clearTimeout(debounce.current); + setChecked(false) + clearTimeout(debounce.current) debounce.current = setTimeout(async () => { if (name !== '') { try { - let valid = await getUsername(name, state.token); + let valid = await getUsername(name, state.token) if (!valid) { - updateState({ validateStatus: 'error', help: 'Username is not available' }); - } else { - updateState({ validateStatus: 'success', help: '' }); + updateState({ validateStatus: 'error', help: 'Username is not available' }) } - setChecked(true); - } catch (err) { + else { + updateState({ validateStatus: 'success', help: '' }) + } + setChecked(true) + } + catch(err) { console.log(err); } - } else { + } + else { updateState({ validateStatus: 'success', help: '' }); setChecked(true); } - }, 500); - }; + }, 500) + } const actions = { setUsername: (username) => { @@ -63,32 +67,27 @@ export function useCreateAccount() { }, isDisabled: () => { const restricted = new RegExp('[!@#$%^&*() ,.?":{}|<>]', 'i'); - if ( - state.username === '' || - restricted.test(state.username) || - state.password === '' || - state.password !== state.confirm || - !checked || - state.validateStatus === 'error' - ) { - return true; + if (state.username === '' || restricted.test(state.username) || state.password === '' || + state.password !== state.confirm || !checked || state.validateStatus === 'error') { + return true } - return false; + return false }, onSettings: () => { navigate('/admin'); }, onCreateAccount: async () => { if (!state.busy && state.username !== '' && state.password !== '' && state.password === state.confirm) { - updateState({ busy: true }); + updateState({ busy: true }) try { - await app.actions.create(state.username, state.password, state.token); - } catch (err) { + await app.actions.create(state.username, state.password, state.token) + } + catch (err) { console.log(err); - updateState({ busy: false }); + updateState({ busy: false }) throw new Error('create failed: check with your admin'); } - updateState({ busy: false }); + updateState({ busy: false }) } }, onLogin: () => { @@ -103,11 +102,12 @@ export function useCreateAccount() { useEffect(() => { let params = new URLSearchParams(search); - let token = params.get('add'); + let token = params.get("add"); if (token) { updateState({ token }); } - }, [app, navigate, search]); + }, [app, navigate, search]) return { state, actions }; } + diff --git a/net/web/src/access/login/Login.styled.ts b/net/web/src/access/login/Login.styled.ts index 0397d67d..829979d6 100644 --- a/net/web/src/access/login/Login.styled.ts +++ b/net/web/src/access/login/Login.styled.ts @@ -8,18 +8,18 @@ export const LoginWrapper = styled.div` flex-direction: column; .disabled { - background-color: ${(props) => props.theme.disabledArea}; + background-color: ${props => props.theme.disabledArea}; button { - color: ${(props) => props.theme.idleText}; + color: ${props => props.theme.idleText}; } } .enabled { - background-color: ${(props) => props.theme.enabledArea}; + background-color: ${props => props.theme.enabledArea}; button { - color: ${(props) => props.theme.activeText}; + color: ${props => props.theme.activeText}; } } @@ -29,10 +29,10 @@ export const LoginWrapper = styled.div` align-items: flex-start; justify-content: center; flex: 1; - color: ${(props) => props.theme.hintText}; + color: ${props => props.theme.hintText}; .settings { - color: ${(props) => props.theme.hintText}; + color: ${props => props.theme.hintText}; position: absolute; top: 0px; right: 0px; @@ -63,7 +63,7 @@ export const LoginWrapper = styled.div` .form-form { flex: 2; - + .form-button { display: flex; align-items: center; @@ -79,3 +79,5 @@ export const LoginWrapper = styled.div` background-color: #444444; } `; + + diff --git a/net/web/src/access/login/Login.tsx b/net/web/src/access/login/Login.tsx index e17965a0..481dac2d 100644 --- a/net/web/src/access/login/Login.tsx +++ b/net/web/src/access/login/Login.tsx @@ -3,103 +3,77 @@ import { SettingOutlined, LockOutlined, UserOutlined } from '@ant-design/icons'; import { LoginWrapper } from './Login.styled'; import { useLogin } from './useLogin.hook'; -export function Login() { - const [modal, modalContext] = Modal.useModal(); +export function Login() { + + const [ modal, modalContext ] = Modal.useModal(); const { state, actions } = useLogin(); const login = async () => { try { await actions.onLogin(); - } catch (err) { + } + catch(err) { modal.error({ title: {state.strings.loginError}, content: {state.strings.loginMessage}, bodyStyle: { borderRadius: 8, padding: 16, ...state.menuStyle }, }); } - }; + } const keyDown = (e) => { if (e.key === 'Enter') { - login(); + login() } - }; + } return ( - {modalContext} + { modalContext }
Databag -
actions.onSettings()} - > +
actions.onSettings()}>
-
{state.strings.login}
- {!state.available && state.availableSet &&
{state.strings.toCreate}
} +
{ state.strings.login }
+ { !state.available && state.availableSet && ( +
{ state.strings.toCreate }
+ )}
-
+ + - actions.setUsername(e.target.value)} - autoComplete="username" - autoCapitalize="none" - onKeyDown={(e) => keyDown(e)} - prefix={} - size="large" - /> + actions.setUsername(e.target.value)} + autoComplete="username" autoCapitalize="none" onKeyDown={(e) => keyDown(e)} prefix={} size="large" /> - actions.setPassword(e.target.value)} - autoComplete="current-password" - onKeyDown={(e) => keyDown(e)} - prefix={} - size="large" - /> + actions.setPassword(e.target.value)} + autoComplete="current-password" onKeyDown={(e) => keyDown(e)} prefix={} size="large" />
-
-
+
); -} +}; + diff --git a/net/web/src/access/login/useLogin.hook.ts b/net/web/src/access/login/useLogin.hook.ts index 56cc4db7..ffeca541 100644 --- a/net/web/src/access/login/useLogin.hook.ts +++ b/net/web/src/access/login/useLogin.hook.ts @@ -2,9 +2,10 @@ import { useContext, useState, useEffect } from 'react'; import { AppContext } from 'context/AppContext'; import { SettingsContext } from 'context/SettingsContext'; import { getAvailable } from 'api/getAvailable'; -import { useLocation, useNavigate } from 'react-router-dom'; +import { useLocation, useNavigate } from "react-router-dom"; export function useLogin() { + const [state, setState] = useState({ username: '', password: '', @@ -12,7 +13,7 @@ export function useLogin() { availableSet: false, disabled: true, busy: false, - strings: {} as Record, + strings: {} as Record, menuStyle: {}, }); @@ -23,7 +24,7 @@ export function useLogin() { const updateState = (value) => { setState((s) => ({ ...s, ...value })); - }; + } const actions = { setUsername: (username) => { @@ -34,24 +35,25 @@ export function useLogin() { }, isDisabled: () => { if (state.username === '' || state.password === '') { - return true; + return true } - return false; + return false }, onSettings: () => { navigate('/admin'); }, onLogin: async () => { if (!state.busy && state.username !== '' && state.password !== '') { - updateState({ busy: true }); + updateState({ busy: true }) try { - await app.actions.login(state.username, state.password); - } catch (err) { + await app.actions.login(state.username, state.password) + } + catch (err) { console.log(err); - updateState({ busy: false }); + updateState({ busy: false }) throw new Error('login failed: check your username and password'); } - updateState({ busy: false }); + updateState({ busy: false }) } }, onCreate: () => { @@ -62,43 +64,46 @@ export function useLogin() { useEffect(() => { const count = async () => { try { - const available = await getAvailable(); - updateState({ availableSet: true, available: available !== 0 }); - } catch (err) { + const available = await getAvailable() + updateState({ availableSet: true, available: available !== 0 }) + } + catch(err) { console.log(err); } - }; + } count(); // eslint-disable-next-line - }, []); + }, []) useEffect(() => { const { strings, menuStyle } = settings.state; updateState({ strings, menuStyle }); }, [settings.state]); - const access = async (token) => { + const access = async (token) => { if (!state.busy) { updateState({ busy: true }); try { await app.actions.access(token); - } catch (err) { + } + catch (err) { console.log(err); updateState({ busy: false }); throw new Error('access failed: check your token'); } updateState({ busy: false }); } - }; - + } + useEffect(() => { let params = new URLSearchParams(search); - let token = params.get('access'); + let token = params.get("access"); if (token) { access(token); } // eslint-disable-next-line - }, []); + }, []) return { state, actions }; } + diff --git a/net/web/src/access/useAccess.hook.ts b/net/web/src/access/useAccess.hook.ts index 7f47cb8f..fab82e8c 100644 --- a/net/web/src/access/useAccess.hook.ts +++ b/net/web/src/access/useAccess.hook.ts @@ -1,9 +1,10 @@ import { useContext, useState, useEffect } from 'react'; -import { useNavigate, useLocation } from 'react-router-dom'; +import { useNavigate, useLocation } from "react-router-dom"; import { AppContext } from 'context/AppContext'; import { SettingsContext } from 'context/SettingsContext'; export function useAccess() { + const [state, setState] = useState({ display: null, scheme: null, @@ -12,7 +13,7 @@ export function useAccess() { themes: [], language: null, languages: [], - strings: {} as Record, + strings: {} as Record, }); const navigate = useNavigate(); @@ -22,7 +23,7 @@ export function useAccess() { const updateState = (value) => { setState((s) => ({ ...s, ...value })); - }; + } useEffect(() => { if (app.state.status || app.state.adminToken) { @@ -31,21 +32,23 @@ export function useAccess() { }, [app.state, navigate]); useEffect(() => { - let params = new URLSearchParams(location + ''); - let token = params.get('access'); + let params = new URLSearchParams(location+""); + let token = params.get("access"); if (token) { const access = async () => { try { - await app.actions.access(token); - } catch (err) { + await app.actions.access(token) + } + catch (err) { console.log(err); } - }; + } access(); } // eslint-disable-next-line }, [navigate, location]); + useEffect(() => { const { theme, themes, strings, language, languages, colors, display, scheme } = settings.state; updateState({ theme, themes, language, languages, strings, colors, display, scheme }); @@ -62,3 +65,4 @@ export function useAccess() { return { state, actions }; } + diff --git a/net/web/src/api/addAccount.ts b/net/web/src/api/addAccount.ts index 78f6c721..5937c857 100644 --- a/net/web/src/api/addAccount.ts +++ b/net/web/src/api/addAccount.ts @@ -2,13 +2,14 @@ import { checkResponse, fetchWithCustomTimeout } from './fetchUtil'; var base64 = require('base-64'); export async function addAccount(username, password, token) { - let access = ''; + let access = ""; if (token) { - access = `?token=${token}`; + access = `?token=${token}` } - let headers = new Headers(); - headers.append('Credentials', 'Basic ' + base64.encode(username + ':' + password)); - let profile = await fetchWithCustomTimeout(`/account/profile${access}`, { method: 'POST', headers: headers }, 60000); + let headers = new Headers() + headers.append('Credentials', 'Basic ' + base64.encode(username + ":" + password)); + let profile = await fetchWithCustomTimeout(`/account/profile${access}`, { method: 'POST', headers: headers }, 60000) checkResponse(profile); - return await profile.json(); + return await profile.json() } + diff --git a/net/web/src/api/addAccountAccess.ts b/net/web/src/api/addAccountAccess.ts index 68067b4d..7553ee7f 100644 --- a/net/web/src/api/addAccountAccess.ts +++ b/net/web/src/api/addAccountAccess.ts @@ -1,9 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function addAccountAccess(token, accountId) { - let access = await fetchWithTimeout(`/admin/accounts/${accountId}/auth?token=${encodeURIComponent(token)}`, { - method: 'POST', - }); + let access = await fetchWithTimeout(`/admin/accounts/${accountId}/auth?token=${encodeURIComponent(token)}`, { method: 'POST' }) checkResponse(access); - return await access.json(); + return await access.json() } + diff --git a/net/web/src/api/addAccountCreate.ts b/net/web/src/api/addAccountCreate.ts index 146166e2..faed55be 100644 --- a/net/web/src/api/addAccountCreate.ts +++ b/net/web/src/api/addAccountCreate.ts @@ -1,7 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function addAccountCreate(token) { - let access = await fetchWithTimeout(`/admin/accounts?token=${encodeURIComponent(token)}`, { method: 'POST' }); + let access = await fetchWithTimeout(`/admin/accounts?token=${encodeURIComponent(token)}`, { method: 'POST' }) checkResponse(access); - return await access.json(); + return await access.json() } + diff --git a/net/web/src/api/addCall.ts b/net/web/src/api/addCall.ts index 8954e4c7..5fc03be6 100644 --- a/net/web/src/api/addCall.ts +++ b/net/web/src/api/addCall.ts @@ -1,9 +1,10 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function addCall(token, cardId) { - let param = '?agent=' + token; + let param = "?agent=" + token let call = await fetchWithTimeout('/talk/calls' + param, { method: 'POST', body: JSON.stringify(cardId) }); - checkResponse(call); - let ret = await call.json(); + checkResponse(call) + let ret = await call.json() return ret; } + diff --git a/net/web/src/api/addCard.ts b/net/web/src/api/addCard.ts index 1bbed375..8109c94b 100644 --- a/net/web/src/api/addCard.ts +++ b/net/web/src/api/addCard.ts @@ -1,7 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function addCard(token, message) { - let card = await fetchWithTimeout(`/contact/cards?agent=${token}`, { method: 'POST', body: JSON.stringify(message) }); + let card = await fetchWithTimeout(`/contact/cards?agent=${token}`, { method: 'POST', body: JSON.stringify(message)} ); checkResponse(card); return await card.json(); } + diff --git a/net/web/src/api/addChannel.ts b/net/web/src/api/addChannel.ts index 870112d9..3ad6d53f 100644 --- a/net/web/src/api/addChannel.ts +++ b/net/web/src/api/addChannel.ts @@ -1,11 +1,9 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; -export async function addChannel(token, type, cards, data) { +export async function addChannel(token, type, cards, data ) { let params = { dataType: type, data: JSON.stringify(data), groups: [], cards }; - let channel = await fetchWithTimeout(`/content/channels?agent=${token}`, { - method: 'POST', - body: JSON.stringify(params), - }); + let channel = await fetchWithTimeout(`/content/channels?agent=${token}`, { method: 'POST', body: JSON.stringify(params)} ); checkResponse(channel); return await channel.json(); } + diff --git a/net/web/src/api/addChannelTopic.ts b/net/web/src/api/addChannelTopic.ts index f066ad6d..f70e5a8d 100644 --- a/net/web/src/api/addChannelTopic.ts +++ b/net/web/src/api/addChannelTopic.ts @@ -1,34 +1,29 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; -export async function addChannelTopic(token, channelId, datatype, message, assets) { - if (message == null && (assets == null || assets.length === 0)) { - let topic = await fetchWithTimeout(`/content/channels/${channelId}/topics?agent=${token}`, { - method: 'POST', - body: JSON.stringify({}), - }); - checkResponse(topic); - let slot = await topic.json(); - return slot.id; - } else if (assets == null || assets.length === 0) { - let subject = { - data: JSON.stringify(message, (key, value) => { - if (value !== null) return value; - }), - datatype, - }; +export async function addChannelTopic(token, channelId, datatype, message, assets ) { - let topic = await fetchWithTimeout(`/content/channels/${channelId}/topics?agent=${token}&confirm=true`, { - method: 'POST', - body: JSON.stringify(subject), - }); + if (message == null && (assets == null || assets.length === 0)) { + let topic = await fetchWithTimeout(`/content/channels/${channelId}/topics?agent=${token}`, + { method: 'POST', body: JSON.stringify({}) }); checkResponse(topic); let slot = await topic.json(); return slot.id; - } else { - let topic = await fetchWithTimeout(`/content/channels/${channelId}/topics?agent=${token}`, { - method: 'POST', - body: JSON.stringify({}), - }); + } + else if (assets == null || assets.length === 0) { + let subject = { data: JSON.stringify(message, (key, value) => { + if (value !== null) return value + }), datatype }; + + let topic = await fetchWithTimeout(`/content/channels/${channelId}/topics?agent=${token}&confirm=true`, + { method: 'POST', body: JSON.stringify(subject) }); + checkResponse(topic); + let slot = await topic.json(); + return slot.id; + } + else { + + let topic = await fetchWithTimeout(`/content/channels/${channelId}/topics?agent=${token}`, + { method: 'POST', body: JSON.stringify({}) }); checkResponse(topic); let slot = await topic.json(); @@ -38,74 +33,61 @@ export async function addChannelTopic(token, channelId, datatype, message, asset if (asset.image) { const formData = new FormData(); formData.append('asset', asset.image); - let transform = encodeURIComponent(JSON.stringify(['ithumb;photo', 'icopy;photo'])); - let topicAsset = await fetch( - `/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, - { method: 'POST', body: formData }, - ); + let transform = encodeURIComponent(JSON.stringify(["ithumb;photo", "icopy;photo"])); + let topicAsset = await fetch(`/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); message.assets.push({ image: { - thumb: assetEntry.find((item) => item.transform === 'ithumb;photo').assetId, - full: assetEntry.find((item) => item.transform === 'icopy;photo').assetId, - }, + thumb: assetEntry.find(item => item.transform === 'ithumb;photo').assetId, + full: assetEntry.find(item => item.transform === 'icopy;photo').assetId, + } }); - } else if (asset.video) { + } + else if (asset.video) { const formData = new FormData(); formData.append('asset', asset.video); let thumb = 'vthumb;video;' + asset.position; - let transform = encodeURIComponent(JSON.stringify(['vlq;video', 'vhd;video', thumb])); - let topicAsset = await fetch( - `/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, - { method: 'POST', body: formData }, - ); + let transform = encodeURIComponent(JSON.stringify(["vlq;video", "vhd;video", thumb])); + let topicAsset = await fetch(`/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); message.assets.push({ video: { - thumb: assetEntry.find((item) => item.transform === thumb).assetId, - lq: assetEntry.find((item) => item.transform === 'vlq;video').assetId, - hd: assetEntry.find((item) => item.transform === 'vhd;video').assetId, - }, + thumb: assetEntry.find(item => item.transform === thumb).assetId, + lq: assetEntry.find(item => item.transform === 'vlq;video').assetId, + hd: assetEntry.find(item => item.transform === 'vhd;video').assetId, + } }); - } else if (asset.audio) { + } + else if (asset.audio) { const formData = new FormData(); formData.append('asset', asset.audio); - let transform = encodeURIComponent(JSON.stringify(['acopy;audio'])); - let topicAsset = await fetch( - `/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, - { method: 'POST', body: formData }, - ); + let transform = encodeURIComponent(JSON.stringify(["acopy;audio"])); + let topicAsset = await fetch(`/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); message.assets.push({ audio: { label: asset.label, - full: assetEntry.find((item) => item.transform === 'acopy;audio').assetId, - }, + full: assetEntry.find(item => item.transform === 'acopy;audio').assetId, + } }); } } - let subject = { - data: JSON.stringify(message, (key, value) => { - if (value !== null) return value; - }), - datatype, - }; - - let unconfirmed = await fetchWithTimeout( - `/content/channels/${channelId}/topics/${slot.id}/subject?agent=${token}`, - { method: 'PUT', body: JSON.stringify(subject) }, - ); + let subject = { data: JSON.stringify(message, (key, value) => { + if (value !== null) return value + }), datatype }; + + let unconfirmed = await fetchWithTimeout(`/content/channels/${channelId}/topics/${slot.id}/subject?agent=${token}`, + { method: 'PUT', body: JSON.stringify(subject) }); checkResponse(unconfirmed); - let confirmed = await fetchWithTimeout( - `/content/channels/${channelId}/topics/${slot.id}/confirmed?agent=${token}`, - { method: 'PUT', body: JSON.stringify('confirmed') }, - ); + let confirmed = await fetchWithTimeout(`/content/channels/${channelId}/topics/${slot.id}/confirmed?agent=${token}`, + { method: 'PUT', body: JSON.stringify('confirmed') }); checkResponse(confirmed); return slot.id; } } + diff --git a/net/web/src/api/addContactChannelTopic.ts b/net/web/src/api/addContactChannelTopic.ts index 13c31f9c..34c134ff 100644 --- a/net/web/src/api/addContactChannelTopic.ts +++ b/net/web/src/api/addContactChannelTopic.ts @@ -1,39 +1,32 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; -export async function addContactChannelTopic(server, token, channelId, datatype, message, assets) { - let host = ''; +export async function addContactChannelTopic(server, token, channelId, datatype, message, assets ) { + let host = ""; if (server) { - host = `https://${server}`; + host = `https://${server}` } if (message == null && (assets == null || assets.length === 0)) { - let topic = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics?contact=${token}`, { - method: 'POST', - body: JSON.stringify({}), - }); + let topic = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics?contact=${token}`, + { method: 'POST', body: JSON.stringify({}) }); checkResponse(topic); let slot = await topic.json(); return slot.id; - } else if (assets == null || assets.length === 0) { - let subject = { - data: JSON.stringify(message, (key, value) => { - if (value !== null) return value; - }), - datatype, - }; + } + else if (assets == null || assets.length === 0) { + let subject = { data: JSON.stringify(message, (key, value) => { + if (value !== null) return value + }), datatype }; - let topic = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics?contact=${token}&confirm=true`, { - method: 'POST', - body: JSON.stringify(subject), - }); + let topic = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics?contact=${token}&confirm=true`, + { method: 'POST', body: JSON.stringify(subject) }); checkResponse(topic); let slot = await topic.json(); return slot.id; - } else { - let topic = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics?contact=${token}`, { - method: 'POST', - body: JSON.stringify({}), - }); + } + else { + let topic = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics?contact=${token}`, + { method: 'POST', body: JSON.stringify({}) }); checkResponse(topic); let slot = await topic.json(); @@ -43,74 +36,61 @@ export async function addContactChannelTopic(server, token, channelId, datatype, if (asset.image) { const formData = new FormData(); formData.append('asset', asset.image); - let transform = encodeURIComponent(JSON.stringify(['ithumb;photo', 'icopy;photo'])); - let topicAsset = await fetch( - `${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, - { method: 'POST', body: formData }, - ); + let transform = encodeURIComponent(JSON.stringify(["ithumb;photo", "icopy;photo"])); + let topicAsset = await fetch(`${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); message.assets.push({ image: { - thumb: assetEntry.find((item) => item.transform === 'ithumb;photo').assetId, - full: assetEntry.find((item) => item.transform === 'icopy;photo').assetId, - }, + thumb: assetEntry.find(item => item.transform === 'ithumb;photo').assetId, + full: assetEntry.find(item => item.transform === 'icopy;photo').assetId, + } }); - } else if (asset.video) { + } + else if (asset.video) { const formData = new FormData(); formData.append('asset', asset.video); - let thumb = 'vthumb;video;' + asset.position; - let transform = encodeURIComponent(JSON.stringify(['vhd;video', 'vlq;video', thumb])); - let topicAsset = await fetch( - `${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, - { method: 'POST', body: formData }, - ); + let thumb = "vthumb;video;" + asset.position + let transform = encodeURIComponent(JSON.stringify(["vhd;video", "vlq;video", thumb])); + let topicAsset = await fetch(`${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); message.assets.push({ video: { - thumb: assetEntry.find((item) => item.transform === thumb).assetId, - lq: assetEntry.find((item) => item.transform === 'vlq;video').assetId, - hd: assetEntry.find((item) => item.transform === 'vhd;video').assetId, - }, + thumb: assetEntry.find(item => item.transform === thumb).assetId, + lq: assetEntry.find(item => item.transform === 'vlq;video').assetId, + hd: assetEntry.find(item => item.transform === 'vhd;video').assetId, + } }); - } else if (asset.audio) { + } + else if (asset.audio) { const formData = new FormData(); formData.append('asset', asset.audio); - let transform = encodeURIComponent(JSON.stringify(['acopy;audio'])); - let topicAsset = await fetch( - `${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, - { method: 'POST', body: formData }, - ); + let transform = encodeURIComponent(JSON.stringify(["acopy;audio"])); + let topicAsset = await fetch(`${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); message.assets.push({ audio: { label: asset.label, - full: assetEntry.find((item) => item.transform === 'acopy;audio').assetId, - }, + full: assetEntry.find(item => item.transform === 'acopy;audio').assetId, + } }); } } - let subject = { - data: JSON.stringify(message, (key, value) => { - if (value !== null) return value; - }), - datatype, - }; + let subject = { data: JSON.stringify(message, (key, value) => { + if (value !== null) return value + }), datatype }; - let unconfirmed = await fetchWithTimeout( - `${host}/content/channels/${channelId}/topics/${slot.id}/subject?contact=${token}`, - { method: 'PUT', body: JSON.stringify(subject) }, - ); + let unconfirmed = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics/${slot.id}/subject?contact=${token}`, + { method: 'PUT', body: JSON.stringify(subject) }); checkResponse(unconfirmed); - let confirmed = await fetchWithTimeout( - `${host}/content/channels/${channelId}/topics/${slot.id}/confirmed?contact=${token}`, - { method: 'PUT', body: JSON.stringify('confirmed') }, - ); + let confirmed = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics/${slot.id}/confirmed?contact=${token}`, + { method: 'PUT', body: JSON.stringify('confirmed') }); checkResponse(confirmed); return slot.id; } } + diff --git a/net/web/src/api/addContactRing.ts b/net/web/src/api/addContactRing.ts index 5639991d..2b8f5ab9 100644 --- a/net/web/src/api/addContactRing.ts +++ b/net/web/src/api/addContactRing.ts @@ -1,14 +1,12 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function addContactRing(server, token, call) { - let host = ''; + let host = ""; if (server) { - host = `https://${server}`; + host = `https://${server}` } - let ring = await fetchWithTimeout(`${host}/talk/rings?contact=${token}`, { - method: 'POST', - body: JSON.stringify(call), - }); + let ring = await fetchWithTimeout(`${host}/talk/rings?contact=${token}`, { method: 'POST', body: JSON.stringify(call) }); checkResponse(ring); } + diff --git a/net/web/src/api/clearChannelCard.ts b/net/web/src/api/clearChannelCard.ts index 256ecac1..7e182fe9 100644 --- a/net/web/src/api/clearChannelCard.ts +++ b/net/web/src/api/clearChannelCard.ts @@ -1,9 +1,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; -export async function clearChannelCard(token, channelId, cardId) { - let channel = await fetchWithTimeout(`/content/channels/${channelId}/cards/${cardId}?agent=${token}`, { - method: 'DELETE', - }); +export async function clearChannelCard(token, channelId, cardId ) { + let channel = await fetchWithTimeout(`/content/channels/${channelId}/cards/${cardId}?agent=${token}`, {method: 'DELETE'}); checkResponse(channel); return await channel.json(); } diff --git a/net/web/src/api/clearLogin.ts b/net/web/src/api/clearLogin.ts index 6ba4db14..cc2887ff 100644 --- a/net/web/src/api/clearLogin.ts +++ b/net/web/src/api/clearLogin.ts @@ -1,9 +1,11 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function clearLogin(token, all) { - console.log('LOGOUT: ', token, all); +console.log("LOGOUT: ", token, all); - const param = all ? '&all=true' : ''; - const logout = await fetchWithTimeout(`/account/apps?agent=${token}${param}`, { method: 'DELETE' }); - checkResponse(logout); + const param = all ? '&all=true' : '' + const logout = await fetchWithTimeout(`/account/apps?agent=${token}${param}`, { method: 'DELETE' }) + checkResponse(logout) } + + diff --git a/net/web/src/api/createAccount.ts b/net/web/src/api/createAccount.ts index a0078b05..659f9287 100644 --- a/net/web/src/api/createAccount.ts +++ b/net/web/src/api/createAccount.ts @@ -2,9 +2,10 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; var base64 = require('base-64'); export async function createAccount(username, password) { - let headers = new Headers(); - headers.append('Credentials', 'Basic ' + base64.encode(username + ':' + password)); - let profile = await fetchWithTimeout('/account/profile', { method: 'POST', headers: headers }); + let headers = new Headers() + headers.append('Credentials', 'Basic ' + base64.encode(username + ":" + password)); + let profile = await fetchWithTimeout("/account/profile", { method: 'POST', headers: headers }) checkResponse(profile); - return await profile.json(); + return await profile.json() } + diff --git a/net/web/src/api/fetchUtil.ts b/net/web/src/api/fetchUtil.ts index bf7b7c1f..20220a4f 100644 --- a/net/web/src/api/fetchUtil.ts +++ b/net/web/src/api/fetchUtil.ts @@ -7,25 +7,22 @@ export function createWebsocket(url) { } export function checkResponse(response) { - if (response.status >= 400 && response.status < 600) { - throw new Error(response.url + ' failed'); + if(response.status >= 400 && response.status < 600) { + throw new Error(response.url + " failed"); } } -export async function fetchWithTimeout(url, options): Promise { +export async function fetchWithTimeout(url, options):Promise { return Promise.race([ - fetch(url, options).catch((err) => { - throw new Error(url + ' failed'); - }), - new Promise((_, reject) => setTimeout(() => reject(new Error(url + ' timeout')), TIMEOUT)), + fetch(url, options).catch(err => { throw new Error(url + ' failed'); }), + new Promise((_, reject) => setTimeout(() => reject(new Error(url + ' timeout')), TIMEOUT)) ]); } -export async function fetchWithCustomTimeout(url, options, timeout): Promise { +export async function fetchWithCustomTimeout(url, options, timeout):Promise { return Promise.race([ - fetch(url, options).catch((err) => { - throw new Error(url + ' failed'); - }), - new Promise((_, reject) => setTimeout(() => reject(new Error(url + ' timeout')), timeout)), + fetch(url, options).catch(err => { throw new Error(url + ' failed'); }), + new Promise((_, reject) => setTimeout(() => reject(new Error(url + ' timeout')), timeout)) ]); } + diff --git a/net/web/src/api/getAccountImageUrl.ts b/net/web/src/api/getAccountImageUrl.ts index f6ca1ae4..98934c1d 100644 --- a/net/web/src/api/getAccountImageUrl.ts +++ b/net/web/src/api/getAccountImageUrl.ts @@ -1,3 +1,4 @@ export function getAccountImageUrl(token, accountId) { - return `/admin/accounts/${accountId}/image?token=${encodeURIComponent(token)}`; + return `/admin/accounts/${accountId}/image?token=${encodeURIComponent(token)}` } + diff --git a/net/web/src/api/getAccountStatus.ts b/net/web/src/api/getAccountStatus.ts index 729020f3..3f1f0fa6 100644 --- a/net/web/src/api/getAccountStatus.ts +++ b/net/web/src/api/getAccountStatus.ts @@ -3,5 +3,6 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getAccountStatus(token) { let status = await fetchWithTimeout('/account/status?agent=' + token, { method: 'GET' }); checkResponse(status); - return await status.json(); + return await status.json() } + diff --git a/net/web/src/api/getAvailable.ts b/net/web/src/api/getAvailable.ts index 0ba155d9..f16bd1a6 100644 --- a/net/web/src/api/getAvailable.ts +++ b/net/web/src/api/getAvailable.ts @@ -1,7 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getAvailable() { - let available = await fetchWithTimeout('/account/available', { method: 'GET' }); - checkResponse(available); - return await available.json(); + let available = await fetchWithTimeout("/account/available", { method: 'GET' }) + checkResponse(available) + return await available.json() } + diff --git a/net/web/src/api/getCardCloseMessage.ts b/net/web/src/api/getCardCloseMessage.ts index fab2daf3..a769c2f0 100644 --- a/net/web/src/api/getCardCloseMessage.ts +++ b/net/web/src/api/getCardCloseMessage.ts @@ -5,3 +5,4 @@ export async function getCardCloseMessage(token, cardId) { checkResponse(message); return await message.json(); } + diff --git a/net/web/src/api/getCardDetail.ts b/net/web/src/api/getCardDetail.ts index 83091d48..69be56ab 100644 --- a/net/web/src/api/getCardDetail.ts +++ b/net/web/src/api/getCardDetail.ts @@ -1,8 +1,9 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getCardDetail(token, cardId) { - let param = '?agent=' + token; + let param = "?agent=" + token let detail = await fetchWithTimeout(`/contact/cards/${cardId}/detail${param}`, { method: 'GET' }); checkResponse(detail); - return await detail.json(); + return await detail.json() } + diff --git a/net/web/src/api/getCardImageUrl.ts b/net/web/src/api/getCardImageUrl.ts index c1ad423d..40e130e6 100644 --- a/net/web/src/api/getCardImageUrl.ts +++ b/net/web/src/api/getCardImageUrl.ts @@ -1,3 +1,4 @@ export function getCardImageUrl(token, cardId, revision) { - return `/contact/cards/${cardId}/profile/image?agent=${token}&revision=${revision}`; + return `/contact/cards/${cardId}/profile/image?agent=${token}&revision=${revision}` } + diff --git a/net/web/src/api/getCardOpenMessage.ts b/net/web/src/api/getCardOpenMessage.ts index 24aeb621..130a6d89 100644 --- a/net/web/src/api/getCardOpenMessage.ts +++ b/net/web/src/api/getCardOpenMessage.ts @@ -5,3 +5,4 @@ export async function getCardOpenMessage(token, cardId) { checkResponse(message); return await message.json(); } + diff --git a/net/web/src/api/getCardProfile.ts b/net/web/src/api/getCardProfile.ts index e37caf83..974e6712 100644 --- a/net/web/src/api/getCardProfile.ts +++ b/net/web/src/api/getCardProfile.ts @@ -3,5 +3,6 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getCardProfile(token, cardId) { let profile = await fetchWithTimeout(`/contact/cards/${cardId}/profile?agent=${token}`, { method: 'GET' }); checkResponse(profile); - return await profile.json(); + return await profile.json() } + diff --git a/net/web/src/api/getCards.ts b/net/web/src/api/getCards.ts index 4b99f9dc..a05dad31 100644 --- a/net/web/src/api/getCards.ts +++ b/net/web/src/api/getCards.ts @@ -1,11 +1,12 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getCards(token, revision) { - let param = 'agent=' + token; + let param = "agent=" + token if (revision != null) { - param += '&revision=' + revision; + param += '&revision=' + revision } let cards = await fetchWithTimeout(`/contact/cards?${param}`, { method: 'GET' }); - checkResponse(cards); - return await cards.json(); + checkResponse(cards) + return await cards.json() } + diff --git a/net/web/src/api/getChannelDetail.ts b/net/web/src/api/getChannelDetail.ts index e73cd0c6..cd5b6f04 100644 --- a/net/web/src/api/getChannelDetail.ts +++ b/net/web/src/api/getChannelDetail.ts @@ -2,6 +2,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getChannelDetail(token, channelId) { let detail = await fetchWithTimeout(`/content/channels/${channelId}/detail?agent=${token}`, { method: 'GET' }); - checkResponse(detail); - return await detail.json(); + checkResponse(detail) + return await detail.json() } + diff --git a/net/web/src/api/getChannelSummary.ts b/net/web/src/api/getChannelSummary.ts index 932cdf2b..ca9ea8cf 100644 --- a/net/web/src/api/getChannelSummary.ts +++ b/net/web/src/api/getChannelSummary.ts @@ -2,6 +2,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getChannelSummary(token, channelId) { let summary = await fetchWithTimeout(`/content/channels/${channelId}/summary?agent=${token}`, { method: 'GET' }); - checkResponse(summary); - return await summary.json(); + checkResponse(summary) + return await summary.json() } + diff --git a/net/web/src/api/getChannelTopic.ts b/net/web/src/api/getChannelTopic.ts index d7a37ce4..550c73b4 100644 --- a/net/web/src/api/getChannelTopic.ts +++ b/net/web/src/api/getChannelTopic.ts @@ -1,9 +1,9 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getChannelTopic(token, channelId, topicId) { - let topic = await fetchWithTimeout(`/content/channels/${channelId}/topics/${topicId}/detail?agent=${token}`, { - method: 'GET', - }); - checkResponse(topic); - return await topic.json(); + let topic = await fetchWithTimeout(`/content/channels/${channelId}/topics/${topicId}/detail?agent=${token}`, + { method: 'GET' }); + checkResponse(topic) + return await topic.json() } + diff --git a/net/web/src/api/getChannelTopicAssetUrl.ts b/net/web/src/api/getChannelTopicAssetUrl.ts index 6094e2dd..c20fb234 100644 --- a/net/web/src/api/getChannelTopicAssetUrl.ts +++ b/net/web/src/api/getChannelTopicAssetUrl.ts @@ -1,3 +1,4 @@ export function getChannelTopicAssetUrl(token, channelId, topicId, assetId) { - return `/content/channels/${channelId}/topics/${topicId}/assets/${assetId}?agent=${token}`; + return `/content/channels/${channelId}/topics/${topicId}/assets/${assetId}?agent=${token}` } + diff --git a/net/web/src/api/getChannelTopics.ts b/net/web/src/api/getChannelTopics.ts index a1f37fe5..69cdd9e4 100644 --- a/net/web/src/api/getChannelTopics.ts +++ b/net/web/src/api/getChannelTopics.ts @@ -1,29 +1,29 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getChannelTopics(token, channelId, revision, count, begin, end) { - let rev = ''; + let rev = '' if (revision != null) { - rev = `&revision=${revision}`; + rev = `&revision=${revision}` } - let cnt = ''; + let cnt = '' if (count != null) { - cnt = `&count=${count}`; + cnt = `&count=${count}` } - let bgn = ''; + let bgn = '' if (begin != null) { - bgn = `&begin=${begin}`; + bgn = `&begin=${begin}` } - let edn = ''; + let edn = '' if (end != null) { - edn = `&end=${end}`; + edn = `&end=${end}` } - let topics = await fetchWithTimeout(`/content/channels/${channelId}/topics?agent=${token}${rev}${cnt}${bgn}${edn}`, { - method: 'GET', - }); - checkResponse(topics); - return { + let topics = await fetchWithTimeout(`/content/channels/${channelId}/topics?agent=${token}${rev}${cnt}${bgn}${edn}`, + { method: 'GET' }); + checkResponse(topics) + return { marker: topics.headers.get('topic-marker'), revision: topics.headers.get('topic-revision'), topics: await topics.json(), - }; + } } + diff --git a/net/web/src/api/getChannels.ts b/net/web/src/api/getChannels.ts index ae845245..0dafc671 100644 --- a/net/web/src/api/getChannels.ts +++ b/net/web/src/api/getChannels.ts @@ -1,14 +1,15 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getChannels(token, revision) { - let param = '?agent=' + token; + let param = "?agent=" + token if (revision != null) { - param += `&channelRevision=${revision}`; + param += `&channelRevision=${revision}` } - let types = encodeURIComponent(JSON.stringify(['sealed', 'superbasic'])); - param += `&types=${types}`; + let types = encodeURIComponent(JSON.stringify([ 'sealed', 'superbasic' ])); + param += `&types=${types}` let channels = await fetchWithTimeout('/content/channels' + param, { method: 'GET' }); - checkResponse(channels); - let ret = await channels.json(); + checkResponse(channels) + let ret = await channels.json() return ret; } + diff --git a/net/web/src/api/getContactChannelDetail.ts b/net/web/src/api/getContactChannelDetail.ts index 46489161..ef8e5499 100644 --- a/net/web/src/api/getContactChannelDetail.ts +++ b/net/web/src/api/getContactChannelDetail.ts @@ -1,13 +1,12 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getContactChannelDetail(server, token, channelId) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } - let detail = await fetchWithTimeout(`${host}/content/channels/${channelId}/detail?contact=${token}`, { - method: 'GET', - }); - checkResponse(detail); - return await detail.json(); + let detail = await fetchWithTimeout(`${host}/content/channels/${channelId}/detail?contact=${token}`, { method: 'GET' }); + checkResponse(detail) + return await detail.json() } + diff --git a/net/web/src/api/getContactChannelSummary.ts b/net/web/src/api/getContactChannelSummary.ts index 979e04c0..278cbfa6 100644 --- a/net/web/src/api/getContactChannelSummary.ts +++ b/net/web/src/api/getContactChannelSummary.ts @@ -1,13 +1,12 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getContactChannelSummary(server, token, channelId) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } - let summary = await fetchWithTimeout(`${host}/content/channels/${channelId}/summary?contact=${token}`, { - method: 'GET', - }); - checkResponse(summary); - return await summary.json(); + let summary = await fetchWithTimeout(`${host}/content/channels/${channelId}/summary?contact=${token}`, { method: 'GET' }); + checkResponse(summary) + return await summary.json() } + diff --git a/net/web/src/api/getContactChannelTopic.ts b/net/web/src/api/getContactChannelTopic.ts index 8751b65c..0715c122 100644 --- a/net/web/src/api/getContactChannelTopic.ts +++ b/net/web/src/api/getContactChannelTopic.ts @@ -1,15 +1,14 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getContactChannelTopic(server, token, channelId, topicId) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } - let topic = await fetchWithTimeout( - `${host}/content/channels/${channelId}/topics/${topicId}/detail?contact=${token}`, - { method: 'GET' }, - ); - checkResponse(topic); - return await topic.json(); + let topic = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics/${topicId}/detail?contact=${token}`, + { method: 'GET' }); + checkResponse(topic) + return await topic.json() } + diff --git a/net/web/src/api/getContactChannelTopicAssetUrl.ts b/net/web/src/api/getContactChannelTopicAssetUrl.ts index 811f8ded..ec531c2b 100644 --- a/net/web/src/api/getContactChannelTopicAssetUrl.ts +++ b/net/web/src/api/getContactChannelTopicAssetUrl.ts @@ -1,8 +1,9 @@ export function getContactChannelTopicAssetUrl(server, token, channelId, topicId, assetId) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } - return `${host}/content/channels/${channelId}/topics/${topicId}/assets/${assetId}?contact=${token}`; + return `${host}/content/channels/${channelId}/topics/${topicId}/assets/${assetId}?contact=${token}` } + diff --git a/net/web/src/api/getContactChannelTopics.ts b/net/web/src/api/getContactChannelTopics.ts index 1781b9c8..df5d621a 100644 --- a/net/web/src/api/getContactChannelTopics.ts +++ b/net/web/src/api/getContactChannelTopics.ts @@ -1,35 +1,34 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getContactChannelTopics(server, token, channelId, revision, count, begin, end) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } - let rev = ''; + let rev = '' if (revision != null) { - rev = `&revision=${revision}`; + rev = `&revision=${revision}` } - let cnt = ''; + let cnt = '' if (count != null) { - cnt = `&count=${count}`; + cnt = `&count=${count}` } - let bgn = ''; + let bgn = '' if (begin != null) { - bgn = `&begin=${begin}`; + bgn = `&begin=${begin}` } - let edn = ''; + let edn = '' if (end != null) { - edn = `&end=${end}`; + edn = `&end=${end}` } - let topics = await fetchWithTimeout( - `${host}/content/channels/${channelId}/topics?contact=${token}${rev}${cnt}${bgn}${edn}`, - { method: 'GET' }, - ); - checkResponse(topics); + let topics = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics?contact=${token}${rev}${cnt}${bgn}${edn}`, + { method: 'GET' }); + checkResponse(topics) return { marker: topics.headers.get('topic-marker'), revision: topics.headers.get('topic-revision'), topics: await topics.json(), - }; + } } + diff --git a/net/web/src/api/getContactChannels.ts b/net/web/src/api/getContactChannels.ts index 9d5ac132..9da7ead4 100644 --- a/net/web/src/api/getContactChannels.ts +++ b/net/web/src/api/getContactChannels.ts @@ -1,21 +1,22 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getContactChannels(server, token, viewRevision?, channelRevision?) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } - let param = '?contact=' + token; + let param = "?contact=" + token if (viewRevision != null) { - param += '&viewRevision=' + viewRevision; + param += '&viewRevision=' + viewRevision } if (channelRevision != null) { - param += '&channelRevision=' + channelRevision; + param += '&channelRevision=' + channelRevision } - let types = encodeURIComponent(JSON.stringify(['sealed', 'superbasic'])); - param += `&types=${types}`; + let types = encodeURIComponent(JSON.stringify([ 'sealed', 'superbasic' ])); + param += `&types=${types}` let channels = await fetchWithTimeout(`${host}/content/channels${param}`, { method: 'GET' }); - checkResponse(channels); - return await channels.json(); + checkResponse(channels) + return await channels.json() } + diff --git a/net/web/src/api/getContactProfile.ts b/net/web/src/api/getContactProfile.ts index 1db2cb8a..9747bfdc 100644 --- a/net/web/src/api/getContactProfile.ts +++ b/net/web/src/api/getContactProfile.ts @@ -1,12 +1,13 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getContactProfile(server, token) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } - let profile = await fetchWithTimeout(`${host}/profile/message?contact=${token}`, { method: 'GET' }); + let profile = await fetchWithTimeout(`${host}/profile/message?contact=${token}`, { method: 'GET', }); checkResponse(profile); - return await profile.json(); + return await profile.json() } + diff --git a/net/web/src/api/getGroups.ts b/net/web/src/api/getGroups.ts index a9f3d13b..a6a64a96 100644 --- a/net/web/src/api/getGroups.ts +++ b/net/web/src/api/getGroups.ts @@ -1,11 +1,13 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getGroups(token, revision) { - let param = 'agent=' + token; + let param = "agent=" + token if (revision != null) { - param += '&revision=' + revision; + param += '&revision=' + revision } let groups = await fetchWithTimeout(`/alias/groups?${param}`, { method: 'GET' }); - checkResponse(groups); - return await groups.json(); + checkResponse(groups) + return await groups.json() } + + diff --git a/net/web/src/api/getListing.ts b/net/web/src/api/getListing.ts index cdb638ed..8352e489 100644 --- a/net/web/src/api/getListing.ts +++ b/net/web/src/api/getListing.ts @@ -8,3 +8,4 @@ export async function getListing(server, filter) { checkResponse(listing); return await listing.json(); } + diff --git a/net/web/src/api/getListingImageUrl.ts b/net/web/src/api/getListingImageUrl.ts index e1df0e96..9399b0db 100644 --- a/net/web/src/api/getListingImageUrl.ts +++ b/net/web/src/api/getListingImageUrl.ts @@ -1,8 +1,10 @@ export function getListingImageUrl(server, guid) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } - return `${host}/account/listing/${guid}/image`; + return `${host}/account/listing/${guid}/image` } + + diff --git a/net/web/src/api/getListingMessage.ts b/net/web/src/api/getListingMessage.ts index 981c89ab..1bd9eba4 100644 --- a/net/web/src/api/getListingMessage.ts +++ b/net/web/src/api/getListingMessage.ts @@ -1,7 +1,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getListingMessage(server, guid) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } @@ -10,3 +10,4 @@ export async function getListingMessage(server, guid) { checkResponse(listing); return await listing.json(); } + diff --git a/net/web/src/api/getNodeAccounts.ts b/net/web/src/api/getNodeAccounts.ts index b61f5600..7b7d5a78 100644 --- a/net/web/src/api/getNodeAccounts.ts +++ b/net/web/src/api/getNodeAccounts.ts @@ -5,3 +5,4 @@ export async function getNodeAccounts(token) { checkResponse(accounts); return await accounts.json(); } + diff --git a/net/web/src/api/getNodeConfig.ts b/net/web/src/api/getNodeConfig.ts index 77f90dd6..85761c68 100644 --- a/net/web/src/api/getNodeConfig.ts +++ b/net/web/src/api/getNodeConfig.ts @@ -5,3 +5,4 @@ export async function getNodeConfig(token) { checkResponse(config); return await config.json(); } + diff --git a/net/web/src/api/getNodeStatus.ts b/net/web/src/api/getNodeStatus.ts index ff8c8ba4..9232bf0a 100644 --- a/net/web/src/api/getNodeStatus.ts +++ b/net/web/src/api/getNodeStatus.ts @@ -5,3 +5,4 @@ export async function getNodeStatus() { checkResponse(status); return await status.json(); } + diff --git a/net/web/src/api/getProfile.ts b/net/web/src/api/getProfile.ts index a020e00a..5fd6c1e2 100644 --- a/net/web/src/api/getProfile.ts +++ b/net/web/src/api/getProfile.ts @@ -2,6 +2,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getProfile(token) { let profile = await fetchWithTimeout(`/profile?agent=${token}`, { method: 'GET' }); - checkResponse(profile); - return await profile.json(); + checkResponse(profile) + return await profile.json() } + + diff --git a/net/web/src/api/getProfileImageUrl.ts b/net/web/src/api/getProfileImageUrl.ts index 8bddfe71..038a7544 100644 --- a/net/web/src/api/getProfileImageUrl.ts +++ b/net/web/src/api/getProfileImageUrl.ts @@ -1,3 +1,4 @@ export function getProfileImageUrl(token, revision) { - return '/profile/image?agent=' + token + '&revision=' + revision; + return '/profile/image?agent=' + token + "&revision=" + revision } + diff --git a/net/web/src/api/getUsername.ts b/net/web/src/api/getUsername.ts index 47218ff3..65854f7c 100644 --- a/net/web/src/api/getUsername.ts +++ b/net/web/src/api/getUsername.ts @@ -1,13 +1,12 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function getUsername(name, token) { - let access = ''; + let access = ""; if (token) { - access = `&token=${token}`; + access = `&token=${token}` } - let available = await fetchWithTimeout('/account/username?name=' + encodeURIComponent(name) + access, { - method: 'GET', - }); - checkResponse(available); - return await available.json(); + let available = await fetchWithTimeout('/account/username?name=' + encodeURIComponent(name) + access, { method: 'GET' }) + checkResponse(available) + return await available.json() } + diff --git a/net/web/src/api/keepCall.ts b/net/web/src/api/keepCall.ts index 388b7f79..f3f8e6ed 100644 --- a/net/web/src/api/keepCall.ts +++ b/net/web/src/api/keepCall.ts @@ -1,7 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function keepCall(token, callId) { - let param = '?agent=' + token; + let param = "?agent=" + token let call = await fetchWithTimeout(`/talk/calls/${callId}` + param, { method: 'PUT' }); - checkResponse(call); + checkResponse(call) } + diff --git a/net/web/src/api/removeAccount.ts b/net/web/src/api/removeAccount.ts index 03251ead..2e8da8ee 100644 --- a/net/web/src/api/removeAccount.ts +++ b/net/web/src/api/removeAccount.ts @@ -1,8 +1,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function removeAccount(token, accountId) { - let res = await fetchWithTimeout(`/admin/accounts/${accountId}?token=${encodeURIComponent(token)}`, { - method: 'DELETE', - }); + let res = await fetchWithTimeout(`/admin/accounts/${accountId}?token=${encodeURIComponent(token)}`, { method: 'DELETE' }) checkResponse(res); } + diff --git a/net/web/src/api/removeCall.ts b/net/web/src/api/removeCall.ts index f40ee4cd..9261a1b6 100644 --- a/net/web/src/api/removeCall.ts +++ b/net/web/src/api/removeCall.ts @@ -1,7 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function removeCall(token, callId) { - let param = '?agent=' + token; + let param = "?agent=" + token let call = await fetchWithTimeout(`/talk/calls/${callId}` + param, { method: 'DELETE' }); - checkResponse(call); + checkResponse(call) } + diff --git a/net/web/src/api/removeCard.ts b/net/web/src/api/removeCard.ts index 8f5441a1..3effc5c8 100644 --- a/net/web/src/api/removeCard.ts +++ b/net/web/src/api/removeCard.ts @@ -1,7 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function removeCard(token, cardId) { - let card = await fetchWithTimeout(`/contact/cards/${cardId}?agent=${token}`, { method: 'DELETE' }); + let card = await fetchWithTimeout(`/contact/cards/${cardId}?agent=${token}`, { method: 'DELETE' } ); checkResponse(card); return await card.json(); } + diff --git a/net/web/src/api/removeChannel.ts b/net/web/src/api/removeChannel.ts index de3074b9..81cbd84a 100644 --- a/net/web/src/api/removeChannel.ts +++ b/net/web/src/api/removeChannel.ts @@ -1,6 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function removeChannel(token, channelId) { - let channel = await fetchWithTimeout(`/content/channels/${channelId}?agent=${token}`, { method: 'DELETE' }); + + let channel = await fetchWithTimeout(`/content/channels/${channelId}?agent=${token}`, + { method: 'DELETE' }); checkResponse(channel); } diff --git a/net/web/src/api/removeChannelTopic.ts b/net/web/src/api/removeChannelTopic.ts index 7bd1e653..bfe0ece5 100644 --- a/net/web/src/api/removeChannelTopic.ts +++ b/net/web/src/api/removeChannelTopic.ts @@ -1,8 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function removeChannelTopic(token, channelId, topicId) { - let channel = await fetchWithTimeout(`/content/channels/${channelId}/topics/${topicId}?agent=${token}`, { - method: 'DELETE', - }); + + let channel = await fetchWithTimeout(`/content/channels/${channelId}/topics/${topicId}?agent=${token}`, + { method: 'DELETE' }); checkResponse(channel); } diff --git a/net/web/src/api/removeContactCall.ts b/net/web/src/api/removeContactCall.ts index 4d14144e..d2679ee2 100644 --- a/net/web/src/api/removeContactCall.ts +++ b/net/web/src/api/removeContactCall.ts @@ -1,11 +1,12 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function removeContactCall(server, token, callId) { - let host = ''; + let host = ""; if (server) { - host = `https://${server}`; + host = `https://${server}` } const call = await fetchWithTimeout(`${host}/talk/calls/${callId}?contact=${token}`, { method: 'DELETE' }); checkResponse(call); } + diff --git a/net/web/src/api/removeContactChannel.ts b/net/web/src/api/removeContactChannel.ts index fd9c17e9..fc3c38c6 100644 --- a/net/web/src/api/removeContactChannel.ts +++ b/net/web/src/api/removeContactChannel.ts @@ -1,11 +1,12 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function removeContactChannel(server, token, channelId) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } - - let channel = await fetchWithTimeout(`${host}/content/channels/${channelId}?contact=${token}`, { method: 'DELETE' }); + + let channel = await fetchWithTimeout(`${host}/content/channels/${channelId}?contact=${token}`, + { method: 'DELETE' }); checkResponse(channel); } diff --git a/net/web/src/api/removeContactChannelTopic.ts b/net/web/src/api/removeContactChannelTopic.ts index 45ac2937..ffd46a31 100644 --- a/net/web/src/api/removeContactChannelTopic.ts +++ b/net/web/src/api/removeContactChannelTopic.ts @@ -1,13 +1,12 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function removeContactChannelTopic(server, token, channelId, topicId) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } - let channel = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics/${topicId}?contact=${token}`, { - method: 'DELETE', - }); + let channel = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics/${topicId}?contact=${token}`, + { method: 'DELETE' }); checkResponse(channel); } diff --git a/net/web/src/api/setAccountAccess.ts b/net/web/src/api/setAccountAccess.ts index 25794d6a..761a7268 100644 --- a/net/web/src/api/setAccountAccess.ts +++ b/net/web/src/api/setAccountAccess.ts @@ -1,10 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setAccountAccess(token, appName, appVersion, platform) { - let access = await fetchWithTimeout( - `/account/access?token=${token}&appName=${appName}&appVersion=${appVersion}&platform=${platform}`, - { method: 'PUT', body: JSON.stringify([]) }, - ); - checkResponse(access); - return await access.json(); + let access = await fetchWithTimeout(`/account/access?token=${token}&appName=${appName}&appVersion=${appVersion}&platform=${platform}`, { method: 'PUT', body: JSON.stringify([]) }) + checkResponse(access) + return await access.json() } + diff --git a/net/web/src/api/setAccountLogin.ts b/net/web/src/api/setAccountLogin.ts index bd043d10..cb108f74 100644 --- a/net/web/src/api/setAccountLogin.ts +++ b/net/web/src/api/setAccountLogin.ts @@ -2,8 +2,9 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; var base64 = require('base-64'); export async function setAccountLogin(token, username, password) { - let headers = new Headers(); - headers.append('Credentials', 'Basic ' + base64.encode(username + ':' + password)); - let res = await fetchWithTimeout(`/account/login?agent=${token}`, { method: 'PUT', headers }); + let headers = new Headers() + headers.append('Credentials', 'Basic ' + base64.encode(username + ":" + password)); + let res = await fetchWithTimeout(`/account/login?agent=${token}`, { method: 'PUT', headers }) checkResponse(res); } + diff --git a/net/web/src/api/setAccountSeal.ts b/net/web/src/api/setAccountSeal.ts index 9907f557..9f8aab19 100644 --- a/net/web/src/api/setAccountSeal.ts +++ b/net/web/src/api/setAccountSeal.ts @@ -1,6 +1,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setAccountSeal(token, seal) { - let res = await fetchWithTimeout('/account/seal?agent=' + token, { method: 'PUT', body: JSON.stringify(seal) }); + let res = await fetchWithTimeout('/account/seal?agent=' + token, { method: 'PUT', body: JSON.stringify(seal) }) checkResponse(res); } + diff --git a/net/web/src/api/setAccountSearchable.ts b/net/web/src/api/setAccountSearchable.ts index 30f537fc..84f357e5 100644 --- a/net/web/src/api/setAccountSearchable.ts +++ b/net/web/src/api/setAccountSearchable.ts @@ -1,6 +1,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setAccountSearchable(token, flag) { - let res = await fetchWithTimeout('/account/searchable?agent=' + token, { method: 'PUT', body: JSON.stringify(flag) }); + let res = await fetchWithTimeout('/account/searchable?agent=' + token, { method: 'PUT', body: JSON.stringify(flag) }) checkResponse(res); } + diff --git a/net/web/src/api/setAccountStatus.ts b/net/web/src/api/setAccountStatus.ts index e1fb34fc..2762cbcd 100644 --- a/net/web/src/api/setAccountStatus.ts +++ b/net/web/src/api/setAccountStatus.ts @@ -1,9 +1,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setAccountStatus(token, accountId, disabled) { - let res = await fetchWithTimeout(`/admin/accounts/${accountId}/status?token=${encodeURIComponent(token)}`, { - method: 'PUT', - body: JSON.stringify(disabled), - }); + let res = await fetchWithTimeout(`/admin/accounts/${accountId}/status?token=${encodeURIComponent(token)}`, { method: 'PUT', body: JSON.stringify(disabled) }) checkResponse(res); } + diff --git a/net/web/src/api/setCardCloseMessage.ts b/net/web/src/api/setCardCloseMessage.ts index a5472de3..f479224e 100644 --- a/net/web/src/api/setCardCloseMessage.ts +++ b/net/web/src/api/setCardCloseMessage.ts @@ -1,7 +1,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setCardCloseMessage(server, message) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } @@ -10,3 +10,4 @@ export async function setCardCloseMessage(server, message) { checkResponse(status); return await status.json(); } + diff --git a/net/web/src/api/setCardOpenMessage.ts b/net/web/src/api/setCardOpenMessage.ts index 317f1dcd..f89bcd93 100644 --- a/net/web/src/api/setCardOpenMessage.ts +++ b/net/web/src/api/setCardOpenMessage.ts @@ -1,7 +1,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setCardOpenMessage(server, message) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } @@ -10,3 +10,4 @@ export async function setCardOpenMessage(server, message) { checkResponse(status); return await status.json(); } + diff --git a/net/web/src/api/setCardProfile.ts b/net/web/src/api/setCardProfile.ts index bcaf7d2f..7c6a2215 100644 --- a/net/web/src/api/setCardProfile.ts +++ b/net/web/src/api/setCardProfile.ts @@ -1,10 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setCardProfile(token, cardId, message) { - let profile = await fetchWithTimeout(`/contact/cards/${cardId}/profile?agent=${token}`, { - method: 'PUT', - body: JSON.stringify(message), - }); + let profile = await fetchWithTimeout(`/contact/cards/${cardId}/profile?agent=${token}`, { method: 'PUT', body: JSON.stringify(message) }); checkResponse(profile); - return await profile.json(); + return await profile.json() } + diff --git a/net/web/src/api/setCardStatus.ts b/net/web/src/api/setCardStatus.ts index 374cb29e..843bda2b 100644 --- a/net/web/src/api/setCardStatus.ts +++ b/net/web/src/api/setCardStatus.ts @@ -1,28 +1,20 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setCardConnecting(token, cardId) { - let card = await fetchWithTimeout(`/contact/cards/${cardId}/status?agent=${token}`, { - method: 'PUT', - body: JSON.stringify('connecting'), - }); + let card = await fetchWithTimeout(`/contact/cards/${cardId}/status?agent=${token}`, { method: 'PUT', body: JSON.stringify('connecting') } ); checkResponse(card); return await card.json(); } export async function setCardConnected(token, cardId, access, view, article, channel, profile) { - let card = await fetchWithTimeout( - `/contact/cards/${cardId}/status?agent=${token}&token=${access}&viewRevision=${view}&articleRevision=${article}&channelRevision=${channel}&profileRevision=${profile}`, - { method: 'PUT', body: JSON.stringify('connected') }, - ); + let card = await fetchWithTimeout(`/contact/cards/${cardId}/status?agent=${token}&token=${access}&viewRevision=${view}&articleRevision=${article}&channelRevision=${channel}&profileRevision=${profile}`, { method: 'PUT', body: JSON.stringify('connected') } ); checkResponse(card); return await card.json(); } export async function setCardConfirmed(token, cardId) { - let card = await fetchWithTimeout(`/contact/cards/${cardId}/status?agent=${token}`, { - method: 'PUT', - body: JSON.stringify('confirmed'), - }); + let card = await fetchWithTimeout(`/contact/cards/${cardId}/status?agent=${token}`, { method: 'PUT', body: JSON.stringify('confirmed') } ); checkResponse(card); return await card.json(); } + diff --git a/net/web/src/api/setChannelCard.ts b/net/web/src/api/setChannelCard.ts index 36cb97be..c9da3287 100644 --- a/net/web/src/api/setChannelCard.ts +++ b/net/web/src/api/setChannelCard.ts @@ -1,9 +1,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; -export async function setChannelCard(token, channelId, cardId) { - let channel = await fetchWithTimeout(`/content/channels/${channelId}/cards/${cardId}?agent=${token}`, { - method: 'PUT', - }); +export async function setChannelCard(token, channelId, cardId ) { + let channel = await fetchWithTimeout(`/content/channels/${channelId}/cards/${cardId}?agent=${token}`, {method: 'PUT'}); checkResponse(channel); return await channel.json(); } diff --git a/net/web/src/api/setChannelSubject.ts b/net/web/src/api/setChannelSubject.ts index 6f29782f..8dd6a080 100644 --- a/net/web/src/api/setChannelSubject.ts +++ b/net/web/src/api/setChannelSubject.ts @@ -1,11 +1,8 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; -export async function setChannelSubject(token, channelId, dataType, data) { +export async function setChannelSubject(token, channelId, dataType, data ) { let params = { dataType, data: JSON.stringify(data) }; - let channel = await fetchWithTimeout(`/content/channels/${channelId}/subject?agent=${token}`, { - method: 'PUT', - body: JSON.stringify(params), - }); + let channel = await fetchWithTimeout(`/content/channels/${channelId}/subject?agent=${token}`, { method: 'PUT', body: JSON.stringify(params)} ); checkResponse(channel); return await channel.json(); } diff --git a/net/web/src/api/setChannelTopicAsset.ts b/net/web/src/api/setChannelTopicAsset.ts index 83d66ad3..116b4801 100644 --- a/net/web/src/api/setChannelTopicAsset.ts +++ b/net/web/src/api/setChannelTopicAsset.ts @@ -4,52 +4,45 @@ export async function setChannelTopicSubject(token, channelId, topicId, asset) { if (asset.image) { const formData = new FormData(); formData.append('asset', asset.image); - let transform = encodeURIComponent(JSON.stringify(['ithumb;photo', 'icopy;photo'])); - let topicAsset = await fetch( - `/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, - { method: 'POST', body: formData }, - ); + let transform = encodeURIComponent(JSON.stringify(["ithumb;photo", "icopy;photo"])); + let topicAsset = await fetch(`/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); return { image: { - thumb: assetEntry.find((item) => item.transform === 'ithumb;photo').assetId, - full: assetEntry.find((item) => item.transform === 'icopy;photo').assetId, - }, + thumb: assetEntry.find(item => item.transform === 'ithumb;photo').assetId, + full: assetEntry.find(item => item.transform === 'icopy;photo').assetId, + } }; - } else if (asset.video) { + } + else if (asset.video) { const formData = new FormData(); formData.append('asset', asset.video); let thumb = 'vthumb;video;' + asset.position; - let transform = encodeURIComponent(JSON.stringify(['vlq;video', 'vhd;video', thumb])); - let topicAsset = await fetch( - `/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, - { method: 'POST', body: formData }, - ); + let transform = encodeURIComponent(JSON.stringify(["vlq;video", "vhd;video", thumb])); + let topicAsset = await fetch(`/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); return { video: { - thumb: assetEntry.find((item) => item.transform === thumb).assetId, - lq: assetEntry.find((item) => item.transform === 'vlq;video').assetId, - hd: assetEntry.find((item) => item.transform === 'vhd;video').assetId, - }, + thumb: assetEntry.find(item => item.transform === thumb).assetId, + lq: assetEntry.find(item => item.transform === 'vlq;video').assetId, + hd: assetEntry.find(item => item.transform === 'vhd;video').assetId, + } }; - } else if (asset.audio) { + } + else if (asset.audio) { const formData = new FormData(); formData.append('asset', asset.audio); - let transform = encodeURIComponent(JSON.stringify(['acopy;audio'])); - let topicAsset = await fetch( - `/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, - { method: 'POST', body: formData }, - ); + let transform = encodeURIComponent(JSON.stringify(["acopy;audio"])); + let topicAsset = await fetch(`/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&agent=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); return { audio: { label: asset.label, - full: assetEntry.find((item) => item.transform === 'acopy;audio').assetId, - }, + full: assetEntry.find(item => item.transform === 'acopy;audio').assetId, + } }; } } diff --git a/net/web/src/api/setChannelTopicSubject.ts b/net/web/src/api/setChannelTopicSubject.ts index c3e7aae2..22410919 100644 --- a/net/web/src/api/setChannelTopicSubject.ts +++ b/net/web/src/api/setChannelTopicSubject.ts @@ -1,16 +1,11 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setChannelTopicSubject(token, channelId, topicId, datatype, data) { - let subject = { - data: JSON.stringify(data, (key, value) => { - if (value !== null) return value; - }), - datatype, - }; + let subject = { data: JSON.stringify(data, (key, value) => { + if (value !== null) return value + }), datatype }; - let channel = await fetchWithTimeout( - `/content/channels/${channelId}/topics/${topicId}/subject?agent=${token}&confirm=true`, - { method: 'PUT', body: JSON.stringify(subject) }, - ); + let channel = await fetchWithTimeout(`/content/channels/${channelId}/topics/${topicId}/subject?agent=${token}&confirm=true`, + { method: 'PUT', body: JSON.stringify(subject) }); checkResponse(channel); } diff --git a/net/web/src/api/setContactChannelTopicAsset.ts b/net/web/src/api/setContactChannelTopicAsset.ts index 8955b0dc..eda4244a 100644 --- a/net/web/src/api/setContactChannelTopicAsset.ts +++ b/net/web/src/api/setContactChannelTopicAsset.ts @@ -1,7 +1,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setContactChannelTopicSubject(server, token, channelId, topicId, asset) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } @@ -9,52 +9,45 @@ export async function setContactChannelTopicSubject(server, token, channelId, to if (asset.image) { const formData = new FormData(); formData.append('asset', asset.image); - let transform = encodeURIComponent(JSON.stringify(['ithumb;photo', 'icopy;photo'])); - let topicAsset = await fetch( - `${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, - { method: 'POST', body: formData }, - ); + let transform = encodeURIComponent(JSON.stringify(["ithumb;photo", "icopy;photo"])); + let topicAsset = await fetch(`${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); return { image: { - thumb: assetEntry.find((item) => item.transform === 'ithumb;photo').assetId, - full: assetEntry.find((item) => item.transform === 'icopy;photo').assetId, - }, + thumb: assetEntry.find(item => item.transform === 'ithumb;photo').assetId, + full: assetEntry.find(item => item.transform === 'icopy;photo').assetId, + } }; - } else if (asset.video) { + } + else if (asset.video) { const formData = new FormData(); formData.append('asset', asset.video); - let thumb = 'vthumb;video;' + asset.position; - let transform = encodeURIComponent(JSON.stringify(['vhd;video', 'vlq;video', thumb])); - let topicAsset = await fetch( - `${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, - { method: 'POST', body: formData }, - ); + let thumb = "vthumb;video;" + asset.position + let transform = encodeURIComponent(JSON.stringify(["vhd;video", "vlq;video", thumb])); + let topicAsset = await fetch(`${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); return { video: { - thumb: assetEntry.find((item) => item.transform === thumb).assetId, - lq: assetEntry.find((item) => item.transform === 'vlq;video').assetId, - hd: assetEntry.find((item) => item.transform === 'vhd;video').assetId, - }, + thumb: assetEntry.find(item => item.transform === thumb).assetId, + lq: assetEntry.find(item => item.transform === 'vlq;video').assetId, + hd: assetEntry.find(item => item.transform === 'vhd;video').assetId, + } }; - } else if (asset.audio) { + } + else if (asset.audio) { const formData = new FormData(); formData.append('asset', asset.audio); - let transform = encodeURIComponent(JSON.stringify(['acopy;audio'])); - let topicAsset = await fetch( - `${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, - { method: 'POST', body: formData }, - ); + let transform = encodeURIComponent(JSON.stringify(["acopy;audio"])); + let topicAsset = await fetch(`${host}/content/channels/${channelId}/topics/${slot.id}/assets?transforms=${transform}&contact=${token}`, { method: 'POST', body: formData }); checkResponse(topicAsset); let assetEntry = await topicAsset.json(); return { audio: { label: asset.label, - full: assetEntry.find((item) => item.transform === 'acopy;audio').assetId, - }, + full: assetEntry.find(item => item.transform === 'acopy;audio').assetId, + } }; } } diff --git a/net/web/src/api/setContactChannelTopicSubject.ts b/net/web/src/api/setContactChannelTopicSubject.ts index 661c0c2d..d6be6042 100644 --- a/net/web/src/api/setContactChannelTopicSubject.ts +++ b/net/web/src/api/setContactChannelTopicSubject.ts @@ -1,21 +1,16 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setContactChannelTopicSubject(server, token, channelId, topicId, datatype, data) { - let host = ''; + let host = ""; if (server) { host = `https://${server}`; } - let subject = { - data: JSON.stringify(data, (key, value) => { - if (value !== null) return value; - }), - datatype, - }; + let subject = { data: JSON.stringify(data, (key, value) => { + if (value !== null) return value + }), datatype }; - let channel = await fetchWithTimeout( - `${host}/content/channels/${channelId}/topics/${topicId}/subject?contact=${token}&confirm=true`, - { method: 'PUT', body: JSON.stringify(subject) }, - ); + let channel = await fetchWithTimeout(`${host}/content/channels/${channelId}/topics/${topicId}/subject?contact=${token}&confirm=true`, + { method: 'PUT', body: JSON.stringify(subject) }); checkResponse(channel); } diff --git a/net/web/src/api/setLogin.ts b/net/web/src/api/setLogin.ts index 09f60a9b..df40a604 100644 --- a/net/web/src/api/setLogin.ts +++ b/net/web/src/api/setLogin.ts @@ -3,13 +3,9 @@ var base64 = require('base-64'); export async function setLogin(username, password, appName, appVersion, userAgent) { const platform = encodeURIComponent(userAgent); - let headers = new Headers(); - headers.append('Authorization', 'Basic ' + base64.encode(username + ':' + password)); - let login = await fetchWithTimeout(`/account/apps?appName=${appName}&appVersion=${appVersion}&platform=${platform}`, { - method: 'POST', - body: JSON.stringify([]), - headers: headers, - }); - checkResponse(login); - return await login.json(); + let headers = new Headers() + headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password)); + let login = await fetchWithTimeout(`/account/apps?appName=${appName}&appVersion=${appVersion}&platform=${platform}`, { method: 'POST', body: JSON.stringify([]), headers: headers }) + checkResponse(login) + return await login.json() } diff --git a/net/web/src/api/setNodeConfig.ts b/net/web/src/api/setNodeConfig.ts index 0ad7bdf8..cf24d510 100644 --- a/net/web/src/api/setNodeConfig.ts +++ b/net/web/src/api/setNodeConfig.ts @@ -2,9 +2,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setNodeConfig(token, config) { let body = JSON.stringify(config); - let settings = await fetchWithTimeout(`/admin/config?setOpenAccess=true&token=${encodeURIComponent(token)}`, { - method: 'PUT', - body, - }); + let settings = await fetchWithTimeout(`/admin/config?setOpenAccess=true&token=${encodeURIComponent(token)}`, { method: 'PUT', body }); checkResponse(settings); } + diff --git a/net/web/src/api/setNodeStatus.ts b/net/web/src/api/setNodeStatus.ts index 4ee877d2..8836ed6f 100644 --- a/net/web/src/api/setNodeStatus.ts +++ b/net/web/src/api/setNodeStatus.ts @@ -4,3 +4,4 @@ export async function setNodeStatus(token) { let status = await fetchWithTimeout(`/admin/status?token=${encodeURIComponent(token)}`, { method: 'PUT' }); checkResponse(status); } + diff --git a/net/web/src/api/setProfileData.ts b/net/web/src/api/setProfileData.ts index 56c3617d..00a405fc 100644 --- a/net/web/src/api/setProfileData.ts +++ b/net/web/src/api/setProfileData.ts @@ -3,6 +3,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setProfileData(token, name, location, description) { let data = { name: name, location: location, description: description }; let profile = await fetchWithTimeout(`/profile/data?agent=${token}`, { method: 'PUT', body: JSON.stringify(data) }); - checkResponse(profile); - return await profile.json(); + checkResponse(profile) + return await profile.json() } + diff --git a/net/web/src/api/setProfileImage.ts b/net/web/src/api/setProfileImage.ts index 16d4a1b8..9eb46a11 100644 --- a/net/web/src/api/setProfileImage.ts +++ b/net/web/src/api/setProfileImage.ts @@ -2,6 +2,7 @@ import { checkResponse, fetchWithTimeout } from './fetchUtil'; export async function setProfileImage(token, image) { let profile = await fetchWithTimeout(`/profile/image?agent=${token}`, { method: 'PUT', body: JSON.stringify(image) }); - checkResponse(profile); - return await profile.json(); + checkResponse(profile) + return await profile.json() } + diff --git a/net/web/src/carousel/Carousel.styled.ts b/net/web/src/carousel/Carousel.styled.ts index f9f5ac47..87d48845 100644 --- a/net/web/src/carousel/Carousel.styled.ts +++ b/net/web/src/carousel/Carousel.styled.ts @@ -24,7 +24,7 @@ export const CarouselWrapper = styled.div` height: 128px; display: flex; align-items: center; - justify-content: center; + justify-content: center; color: #888888; background-color: #eeeeee; margin-left: 72px; @@ -71,8 +71,8 @@ export const CarouselWrapper = styled.div` } .arrow:hover { - opacity: 1; - } + opacity: 1; + } .item { margin-right: 32px; @@ -113,3 +113,4 @@ export const CarouselWrapper = styled.div` object-fit: contain; } `; + diff --git a/net/web/src/carousel/Carousel.tsx b/net/web/src/carousel/Carousel.tsx index 2c419746..d40265e1 100644 --- a/net/web/src/carousel/Carousel.tsx +++ b/net/web/src/carousel/Carousel.tsx @@ -3,64 +3,52 @@ import { CarouselWrapper } from './Carousel.styled'; import { CloseOutlined } from '@ant-design/icons'; import ReactResizeDetector from 'react-resize-detector'; interface Props { - pad?: any; - items?: any; - itemRenderer?: any; - itemRemove?: any; + pad?:any + items?:any + itemRenderer?:any + itemRemove?:any + } -export function Carousel({ pad, items, itemRenderer, itemRemove }: Props) { +export function Carousel({ pad, items, itemRenderer, itemRemove }:Props) { const [slots, setSlots] = useState([]); let carousel = useRef(); const RemoveItem = ({ index }) => { if (itemRemove) { - return ( -
itemRemove(index)} - > - -
- ); + return
itemRemove(index)}>
} - return <>; - }; + return <> + } useEffect(() => { let assets = []; for (let i = 0; i < items.length; i++) { - assets.push( - + assets.push(( + {({ width, height }) => { return (
-
{itemRenderer(items[i], i)}
+
{ itemRenderer(items[i], i) }
); }} -
, - ); +
+ )); } if (items.length > 0) { - assets.push(
); + assets.push(
) } setSlots(assets); }, [items, itemRenderer]); return ( -
+
{slots}
); } + diff --git a/net/web/src/carousel/useCarousel.ts b/net/web/src/carousel/useCarousel.ts index 2df8abf8..24d66170 100644 --- a/net/web/src/carousel/useCarousel.ts +++ b/net/web/src/carousel/useCarousel.ts @@ -2,15 +2,20 @@ import { useContext, useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; export function useCarousel() { - const [state, setState] = useState({}); + + const [state, setState] = useState({ + }); const updateState = (value) => { setState((s) => ({ ...s, ...value })); - }; + } const navigate = useNavigate(); - const actions = {}; + const actions = { + }; return { state, actions }; } + + diff --git a/net/web/src/constants/Colors.ts b/net/web/src/constants/Colors.ts index 5a327366..feb68f97 100644 --- a/net/web/src/constants/Colors.ts +++ b/net/web/src/constants/Colors.ts @@ -21,7 +21,7 @@ export const Colors = { itemDivider: '#eeeeee', - unsaved: '#ffff00', + unsaved: '#ffff00', connected: '#44cc44', connecting: '#dd88ff', requested: '#4488ff', @@ -70,7 +70,7 @@ export const LightTheme = { sectionBorder: '#bbbbbb', headerBorder: '#aaaaaa', drawerBorder: '#cccccc', - unsaved: '#ffff00', + unsaved: '#ffff00', connected: '#44cc44', connecting: '#dd88ff', requested: '#4488ff', @@ -109,10 +109,11 @@ export const DarkTheme = { sectionBorder: '#777777', headerBorder: '#aaaaaa', drawerBorder: '#444444', - unsaved: '#ffff00', + unsaved: '#ffff00', connected: '#44cc44', connecting: '#dd88ff', requested: '#4488ff', pending: '#22aaaa', confirmed: '#aaaaaa', }; + diff --git a/net/web/src/constants/Strings.ts b/net/web/src/constants/Strings.ts index 83d03289..41464d56 100644 --- a/net/web/src/constants/Strings.ts +++ b/net/web/src/constants/Strings.ts @@ -14,7 +14,7 @@ export const en = { newMessage: 'New Message', topics: 'Topics', unsetSealing: 'Unset Sealing Key', - newTopic: 'New Topic', + newTopic: 'New Topic', noContacts: 'No Contacts', noTopics: 'No Topics', @@ -65,7 +65,7 @@ export const en = { password: 'Password', newPassword: 'New Password', confirmPassword: 'Confirm Password', - deleteKey: "Type 'delete' to remove key", + deleteKey: 'Type \'delete\' to remove key', delete: 'delete', remove: 'Delete', username: 'Username', @@ -101,7 +101,7 @@ export const en = { createAccount: 'Create Account', accountLogin: 'Account Login', toCreate: 'Accounts are created through a link generated from the admin dashboard.', - admin: 'Admin', + admin: 'Admin', loginError: 'Login Error', loginMessage: 'Please confirm your username and password.', createError: 'Create Account Error', @@ -170,7 +170,7 @@ export const en = { host: 'Host', guest: 'Guest', editSubject: 'Edit Subject', - editMembership: 'Edit Membership', + editMembership: 'Edit Membership', deleteTopic: 'Delete Topic', leaveTopic: 'Leave Topic', @@ -237,7 +237,7 @@ export const fr = { node: 'Serveur', location: 'Emplacement', description: 'Description', - timeFormat: "Format de l'heure", + timeFormat: 'Format de l\'heure', dateFormat: 'Format de la date', theme: 'Thème', language: 'Langue', @@ -255,10 +255,10 @@ export const fr = { password: 'Mot de Passe', newPassword: 'Nouveau Mot de Passe', confirmPassword: 'Confirmer le Mot de Passe', - deleteKey: "Tapez 'supprimer' pour supprimer la clé", + deleteKey: 'Tapez \'supprimer\' pour supprimer la clé', delete: 'supprimer', remove: 'Supprimer', - username: "Nom d'Utilisateur", + username: 'Nom d\'Utilisateur', updateProfile: 'Mettre à Jour le Profil', syncError: 'Erreur de Synchronisation', @@ -290,13 +290,13 @@ export const fr = { create: 'Créer', createAccount: 'Créer un Compte', accountLogin: 'Connexion au Compte', - toCreate: "Les comptes sont créés via un lien généré depuis le tableau de bord d'administration.", + toCreate: 'Les comptes sont créés via un lien généré depuis le tableau de bord d\'administration.', admin: 'Administrateur', loginError: 'Erreur de connexion', - loginMessage: "Veuillez confirmer votre nom d'utilisateur et votre mot de passe.", + loginMessage: 'Veuillez confirmer votre nom d\'utilisateur et votre mot de passe.', createError: 'Erreur de création de compte', createMessage: 'Veuillez vérifier auprès de votre administrateur.', - adminError: "Erreur d'Accès", + adminError: 'Erreur d\'Accès', adminMessage: 'Veuillez confirmer votre mot de passe', confirmDelete: 'Suppression de Compte', @@ -325,16 +325,16 @@ export const fr = { allowUnsealed: 'Autoriser les Sujets non Sécurisés', topicContent: 'Contenu du Sujet:', enableImage: 'Activer les Images du Sujet', - imageHint: "Autoriser la publication d'images dans des sujets", - enableAudio: "Activer l'Audio du Suject", - audioHint: "Autoriser la publication d'audio dans des sujets", + imageHint: 'Autoriser la publication d\'images dans des sujets', + enableAudio: 'Activer l\'Audio du Suject', + audioHint: 'Autoriser la publication d\'audio dans des sujets', enableVideo: 'Activer les Videos du Sujet', videoHint: 'Autoriser la publication de video dans des sujets', enableWeb: 'Activer les Appels WebRTC', webHint: 'Autoriser les appels audio et vidéo aux contacts', serverUrl: 'URL du Serveur WebRTC', urlHint: 'turn:ip:port?transport=udp', - webUsername: "Nom d'Utilisateur WebRTC", + webUsername: 'Nom d\'Utilisateur WebRTC', webPassword: 'Mot de Passe WebRTC', failedLoad: 'Échec du Chargement', limit: 'Limite', @@ -446,7 +446,7 @@ export const sp = { password: 'Contraseña', newPassword: 'Nueva Contraseña', confirmPassword: 'Confirmar Contraseña', - deleteKey: "Escribe 'borrar' para Eliminar la Clave", + deleteKey: 'Escribe \'borrar\' para Eliminar la Clave', delete: 'borrar', remove: 'Eliminar', username: 'Nombre de usuario', @@ -567,7 +567,7 @@ export const sp = { confirmRemove: '¿Estás seguro de que quieres eliminar el contacto?', message: 'Mensaje', sealedMessage: 'Mensaje Seguro', -}; +} export const pt = { code: 'pt', @@ -636,7 +636,7 @@ export const pt = { password: 'Senha', newPassword: 'Nova senha', confirmPassword: 'Confirmar senha', - deleteKey: "Digite 'excluir' para deletar a chave", + deleteKey: 'Digite \'excluir\' para deletar a chave', delete: 'excluir', remove: 'Remover', username: 'Nome de usuário', @@ -757,7 +757,7 @@ export const pt = { confirmRemove: 'Tem certeza de que deseja remover o contato?', message: 'Mensagem', sealedMessage: 'Mensagem Segura', -}; +} export const de = { code: 'de', @@ -826,7 +826,7 @@ export const de = { password: 'Passwort', newPassword: 'Neues Passwort', confirmPassword: 'Passwort bestätigen', - deleteKey: "'löschen' eingeben, um den Schlüssel zu löschen", + deleteKey: '\'löschen\' eingeben, um den Schlüssel zu löschen', delete: 'löschen', remove: 'Entfernen', username: 'Benutzername', @@ -947,7 +947,7 @@ export const de = { confirmRemove: 'Sind Sie sicher, dass Sie den Kontakt löschen möchten?', message: 'Nachricht', sealedMessage: 'Gesicherte Nachricht', -}; +} export const ru = { code: 'ru', @@ -1016,7 +1016,7 @@ export const ru = { password: 'Пароль', newPassword: 'Новый пароль', confirmPassword: 'Подтвердите пароль', - deleteKey: "Введите 'удалить', чтобы удалить ключ", + deleteKey: 'Введите \'удалить\', чтобы удалить ключ', delete: 'удалить', remove: 'Удалить', username: 'Имя пользователя', @@ -1137,4 +1137,4 @@ export const ru = { confirmRemove: 'Вы уверены, что хотите удалить контакт?', message: 'Cообщение', sealedMessage: 'Защищенное Cообщение', -}; +} diff --git a/net/web/src/context/AccountContext.tsx b/net/web/src/context/AccountContext.tsx index 43eb73e1..fc28247c 100644 --- a/net/web/src/context/AccountContext.tsx +++ b/net/web/src/context/AccountContext.tsx @@ -5,5 +5,10 @@ export const AccountContext = createContext(defaultAccountContext); export function AccountContextProvider({ children }) { const { state, actions } = useAccountContext(); - return {children}; + return ( + + {children} + + ); } + diff --git a/net/web/src/context/AppContext.tsx b/net/web/src/context/AppContext.tsx index b6b06ae8..1836b955 100644 --- a/net/web/src/context/AppContext.tsx +++ b/net/web/src/context/AppContext.tsx @@ -5,5 +5,10 @@ export const AppContext = createContext(defaultAppContext); export function AppContextProvider({ children }) { const { state, actions } = useAppContext(); - return {children}; + return ( + + {children} + + ); } + diff --git a/net/web/src/context/CardContext.tsx b/net/web/src/context/CardContext.tsx index ca57a574..1a017df9 100644 --- a/net/web/src/context/CardContext.tsx +++ b/net/web/src/context/CardContext.tsx @@ -5,5 +5,10 @@ export const CardContext = createContext(defaultCardContext); export function CardContextProvider({ children }) { const { state, actions } = useCardContext(); - return {children}; + return ( + + {children} + + ); } + diff --git a/net/web/src/context/ChannelContext.tsx b/net/web/src/context/ChannelContext.tsx index 86a47deb..ef30b6c4 100644 --- a/net/web/src/context/ChannelContext.tsx +++ b/net/web/src/context/ChannelContext.tsx @@ -5,5 +5,10 @@ export const ChannelContext = createContext(defaultChannelContext); export function ChannelContextProvider({ children }) { const { state, actions } = useChannelContext(); - return {children}; + return ( + + {children} + + ); } + diff --git a/net/web/src/context/ConversationContext.tsx b/net/web/src/context/ConversationContext.tsx index 4af62149..6d96c8c2 100644 --- a/net/web/src/context/ConversationContext.tsx +++ b/net/web/src/context/ConversationContext.tsx @@ -5,5 +5,10 @@ export const ConversationContext = createContext(defaultConversionContext); export function ConversationContextProvider({ children }) { const { state, actions } = useConversationContext(); - return {children}; + return ( + + {children} + + ); } + diff --git a/net/web/src/context/ProfileContext.tsx b/net/web/src/context/ProfileContext.tsx index 0477c902..ebbcf37f 100644 --- a/net/web/src/context/ProfileContext.tsx +++ b/net/web/src/context/ProfileContext.tsx @@ -5,5 +5,10 @@ export const ProfileContext = createContext(defaultProfileContext); export function ProfileContextProvider({ children }) { const { state, actions } = useProfileContext(); - return {children}; + return ( + + {children} + + ); } + diff --git a/net/web/src/context/RingContext.tsx b/net/web/src/context/RingContext.tsx index 1e25a1d1..5c24f5c3 100644 --- a/net/web/src/context/RingContext.tsx +++ b/net/web/src/context/RingContext.tsx @@ -5,5 +5,10 @@ export const RingContext = createContext(defaultRingContext); export function RingContextProvider({ children }) { const { state, actions } = useRingContext(); - return {children}; + return ( + + {children} + + ); } + diff --git a/net/web/src/context/SettingsContext.tsx b/net/web/src/context/SettingsContext.tsx index 14d828be..dc9b45ad 100644 --- a/net/web/src/context/SettingsContext.tsx +++ b/net/web/src/context/SettingsContext.tsx @@ -5,5 +5,10 @@ export const SettingsContext = createContext(defaultSettingsContext); export function SettingsContextProvider({ children }) { const { state, actions } = useSettingsContext(); - return {children}; + return ( + + {children} + + ); } + diff --git a/net/web/src/context/StoreContext.tsx b/net/web/src/context/StoreContext.tsx index 5b737a3c..6690204d 100644 --- a/net/web/src/context/StoreContext.tsx +++ b/net/web/src/context/StoreContext.tsx @@ -5,5 +5,10 @@ export const StoreContext = createContext(defaultStoreContext); export function StoreContextProvider({ children }) { const { state, actions } = useStoreContext(); - return {children}; + return ( + + {children} + + ); } + diff --git a/net/web/src/context/UploadContext.tsx b/net/web/src/context/UploadContext.tsx index 91c66116..09b9769d 100644 --- a/net/web/src/context/UploadContext.tsx +++ b/net/web/src/context/UploadContext.tsx @@ -5,5 +5,10 @@ export const UploadContext = createContext(defaultUploadContext); export function UploadContextProvider({ children }) { const { state, actions } = useUploadContext(); - return {children}; + return ( + + {children} + + ); } + diff --git a/net/web/src/context/cardUtil.ts b/net/web/src/context/cardUtil.ts index 044ad069..a6182258 100644 --- a/net/web/src/context/cardUtil.ts +++ b/net/web/src/context/cardUtil.ts @@ -1,7 +1,7 @@ export function getCardByGuid(cards, guid) { let card = null; cards.forEach((value, key, map) => { - if (value?.data?.cardProfile?.guid === guid) { + if(value?.data?.cardProfile?.guid === guid) { card = value; } }); @@ -13,7 +13,8 @@ export function getProfileByGuid(cards, guid) { if (card?.data?.cardProfile) { const { name, handle, imageSet, node } = card.data.cardProfile; const cardId = card.id; - return { cardId, name, handle, imageSet, node }; + return { cardId, name, handle, imageSet, node } } return {}; } + diff --git a/net/web/src/context/sealUtil.ts b/net/web/src/context/sealUtil.ts index 298bea46..5483a501 100644 --- a/net/web/src/context/sealUtil.ts +++ b/net/web/src/context/sealUtil.ts @@ -1,5 +1,5 @@ import CryptoJS from 'crypto-js'; -import { JSEncrypt } from 'jsencrypt'; +import { JSEncrypt } from 'jsencrypt' export function getChannelSeals(subject) { const { seals } = JSON.parse(subject); @@ -21,22 +21,23 @@ export function getContentKey(seals, sealKey) { let crypto = new JSEncrypt(); crypto.setPrivateKey(sealKey.private); return crypto.decrypt(seals[i].sealedKey); + } } - throw new Error('unsealKey not available'); + throw new Error("unsealKey not available"); } export function encryptChannelSubject(subject, publicKeys) { const key = CryptoJS.lib.WordArray.random(256 / 8); const iv = CryptoJS.lib.WordArray.random(128 / 8); const encrypted = CryptoJS.AES.encrypt(JSON.stringify({ subject }), key, { iv: iv }); - const subjectEncrypted = encrypted.ciphertext.toString(CryptoJS.enc.Base64); + const subjectEncrypted = encrypted.ciphertext.toString(CryptoJS.enc.Base64) const subjectIv = iv.toString(); const keyHex = key.toString(); let seals = []; let crypto = new JSEncrypt(); - publicKeys.forEach((publicKey) => { + publicKeys.forEach(publicKey => { crypto.setPublicKey(publicKey); const sealedKey = crypto.encrypt(keyHex); seals.push({ publicKey, sealedKey }); @@ -49,7 +50,7 @@ export function updateChannelSubject(subject, contentKey) { const key = CryptoJS.enc.Hex.parse(contentKey); const iv = CryptoJS.lib.WordArray.random(128 / 8); const encrypted = CryptoJS.AES.encrypt(JSON.stringify({ subject }), key, { iv: iv }); - const subjectEncrypted = encrypted.ciphertext.toString(CryptoJS.enc.Base64); + const subjectEncrypted = encrypted.ciphertext.toString(CryptoJS.enc.Base64) const subjectIv = iv.toString(); return { subjectEncrypted, subjectIv }; @@ -59,7 +60,7 @@ export function encryptBlock(block, contentKey) { const key = CryptoJS.enc.Hex.parse(contentKey); const iv = CryptoJS.lib.WordArray.random(128 / 8); const encrypted = CryptoJS.AES.encrypt(block, key, { iv: iv }); - const blockEncrypted = encrypted.ciphertext.toString(CryptoJS.enc.Base64); + const blockEncrypted = encrypted.ciphertext.toString(CryptoJS.enc.Base64) const blockIv = iv.toString(); return { blockEncrypted, blockIv }; @@ -94,7 +95,7 @@ export function encryptTopicSubject(subject, contentKey) { const iv = CryptoJS.lib.WordArray.random(128 / 8); const key = CryptoJS.enc.Hex.parse(contentKey); const encrypted = CryptoJS.AES.encrypt(JSON.stringify(subject), key, { iv: iv }); - const messageEncrypted = encrypted.ciphertext.toString(CryptoJS.enc.Base64); + const messageEncrypted = encrypted.ciphertext.toString(CryptoJS.enc.Base64) const messageIv = iv.toString(); return { messageEncrypted, messageIv }; } @@ -112,23 +113,22 @@ export function decryptTopicSubject(subject, contentKey) { function convertPem(pem) { var lines = pem.split('\n'); var encoded = ''; - for (var i = 0; i < lines.length; i++) { - if ( - lines[i].trim().length > 0 && - lines[i].indexOf('-BEGIN RSA PRIVATE KEY-') < 0 && - lines[i].indexOf('-BEGIN RSA PUBLIC KEY-') < 0 && - lines[i].indexOf('-BEGIN PUBLIC KEY-') < 0 && - lines[i].indexOf('-END PUBLIC KEY-') < 0 && - lines[i].indexOf('-END RSA PRIVATE KEY-') < 0 && - lines[i].indexOf('-END RSA PUBLIC KEY-') < 0 - ) { + for(var i = 0;i < lines.length;i++){ + if (lines[i].trim().length > 0 && + lines[i].indexOf('-BEGIN RSA PRIVATE KEY-') < 0 && + lines[i].indexOf('-BEGIN RSA PUBLIC KEY-') < 0 && + lines[i].indexOf('-BEGIN PUBLIC KEY-') < 0 && + lines[i].indexOf('-END PUBLIC KEY-') < 0 && + lines[i].indexOf('-END RSA PRIVATE KEY-') < 0 && + lines[i].indexOf('-END RSA PUBLIC KEY-') < 0) { encoded += lines[i].trim(); } } - return encoded; -} + return encoded +}; export async function generateSeal(password) { + // generate key to encrypt private key const salt = CryptoJS.lib.WordArray.random(128 / 8); const aes = CryptoJS.PBKDF2(password, salt, { @@ -137,7 +137,7 @@ export async function generateSeal(password) { }); // generate rsa key for sealing channel, delay for activity indicators - await new Promise((r) => setTimeout(r, 1000)); + await new Promise(r => setTimeout(r, 1000)); const crypto = new JSEncrypt({ default_key_size: 2048 }); crypto.getKey(); @@ -153,16 +153,17 @@ export async function generateSeal(password) { privateKeyIv: iv.toString(), privateKeyEncrypted: enc.ciphertext.toString(CryptoJS.enc.Base64), publicKey: publicKey, - }; + } const sealKey = { public: publicKey, private: privateKey, - }; + } return { seal, sealKey }; } export function unlockSeal(seal, password) { + // generate key to encrypt private key const salt = CryptoJS.enc.Hex.parse(seal.passwordSalt); const aes = CryptoJS.PBKDF2(password, salt, { @@ -172,25 +173,26 @@ export function unlockSeal(seal, password) { // decrypt private key const iv = CryptoJS.enc.Hex.parse(seal.privateKeyIv); - const enc = CryptoJS.enc.Base64.parse(seal.privateKeyEncrypted); + const enc = CryptoJS.enc.Base64.parse(seal.privateKeyEncrypted) let cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: enc, - iv: iv, + iv: iv }); const dec = CryptoJS.AES.decrypt(cipherParams, aes, { iv: iv }); - const privateKey = dec.toString(CryptoJS.enc.Utf8); + const privateKey = dec.toString(CryptoJS.enc.Utf8) // store ke const sealKey = { public: seal.publicKey, private: privateKey, - }; + } return sealKey; } export function updateSeal(seal, sealKey, password) { + // generate key to encrypt private key const salt = CryptoJS.lib.WordArray.random(128 / 8); const aes = CryptoJS.PBKDF2(password, salt, { @@ -208,7 +210,7 @@ export function updateSeal(seal, sealKey, password) { privateKeyIv: iv.toString(), privateKeyEncrypted: enc.ciphertext.toString(CryptoJS.enc.Base64), publicKey: seal.publicKey, - }; + } return { seal: updated, sealKey }; } diff --git a/net/web/src/context/useAccountContext.hook.ts b/net/web/src/context/useAccountContext.hook.ts index 482255b8..ccf1866e 100644 --- a/net/web/src/context/useAccountContext.hook.ts +++ b/net/web/src/context/useAccountContext.hook.ts @@ -22,8 +22,8 @@ export const defaultAccountContext = { unlockSeal: (sealKey: any) => Promise.reject(), setLogin: (username: any, password: any) => Promise.reject(), resync: () => Promise.reject(), - }, -}; +} +} export function useAccountContext(): typeof defaultAccountContext { const [state, setState] = useState(defaultAccountContext.state); @@ -31,13 +31,13 @@ export function useAccountContext(): typeof defaultAccountContext { const setRevision = useRef(null); const curRevision = useRef(null); const syncing = useRef(false); - const force = useRef(false); + const force = useRef(false); const storeContext = useContext(StoreContext); const updateState = (value) => { - setState((s) => ({ ...s, ...value })); - }; + setState((s) => ({ ...s, ...value })) + } useEffect(() => { updateState({ sealKey: storeContext.state.sealKey }); @@ -54,7 +54,8 @@ export function useAccountContext(): typeof defaultAccountContext { const status = await getAccountStatus(token); setRevision.current = revision; updateState({ offsync: false, status, seal: status.seal }); - } catch (err) { + } + catch (err) { console.log(err); syncing.current = false; updateState({ offsync: true }); @@ -64,12 +65,12 @@ export function useAccountContext(): typeof defaultAccountContext { syncing.current = false; await sync(); } - }; + } const actions = { setToken: (token) => { if (access.current || syncing.current) { - throw new Error('invalid account session state'); + throw new Error("invalid account session state"); } access.current = token; curRevision.current = null; @@ -88,14 +89,14 @@ export function useAccountContext(): typeof defaultAccountContext { }, setSeal: async (seal, sealKey) => { await setAccountSeal(access.current, seal); - await storeContext.actions.setValue('sealKey', sealKey); + await storeContext.actions.setValue("sealKey", sealKey); updateState({ sealKey }); }, updateSeal: async (seal) => { await setAccountSeal(access.current, seal); }, unlockSeal: async (sealKey) => { - await storeContext.actions.setValue('sealKey', sealKey); + await storeContext.actions.setValue("sealKey", sealKey); updateState({ sealKey }); }, setLogin: async (username, password) => { @@ -105,7 +106,9 @@ export function useAccountContext(): typeof defaultAccountContext { force.current = true; await sync(); }, - }; + } - return { state, actions }; + return { state, actions } } + + diff --git a/net/web/src/context/useAppContext.hook.ts b/net/web/src/context/useAppContext.hook.ts index 8cb71d96..f6873f72 100644 --- a/net/web/src/context/useAppContext.hook.ts +++ b/net/web/src/context/useAppContext.hook.ts @@ -11,21 +11,21 @@ import { StoreContext } from './StoreContext'; import { UploadContext } from './UploadContext'; import { RingContext } from './RingContext'; import { createWebsocket } from 'api/fetchUtil'; -const defaultState = { +const defaultState ={ status: null, adminToken: null, -}; +} export const defaultAppContext = { - state: defaultState, - actions: {} as ReturnType['actions'], -}; +state:defaultState, +actions: {}as ReturnType["actions"], +} export function useAppContext() { const [state, setState] = useState(defaultState); const [appRevision, setAppRevision] = useState(); - const appName = 'Databag'; - const appVersion = '1.0.0'; + const appName = "Databag"; + const appVersion = "1.0.0"; const userAgent = window.navigator.userAgent; const checked = useRef(false); @@ -33,8 +33,8 @@ export function useAppContext() { const ws = useRef(null); const updateState = (value) => { - setState((s) => ({ ...s, ...value })); - }; + setState((s) => ({ ...s, ...value })) + } const ringContext = useContext(RingContext); const uploadContext = useContext(UploadContext); @@ -51,7 +51,8 @@ export function useAppContext() { cardContext.actions.setToken(token); channelContext.actions.setToken(token); ringContext.actions.setToken(token); - } catch (err) { + } + catch (err) { accountContext.actions.clearToken(); profileContext.actions.clearToken(); cardContext.actions.clearToken(); @@ -60,7 +61,7 @@ export function useAppContext() { throw err; } setWebsocket(token); - }; + } const clearSession = () => { uploadContext.actions.clear(); @@ -72,20 +73,20 @@ export function useAppContext() { cardContext.actions.clearToken(); channelContext.actions.clearToken(); clearWebsocket(); - }; + } const actions = { logout: async (all) => { await appLogout(all); }, access: async (token) => { - await appAccess(token); + await appAccess(token) }, login: async (username, password) => { - await appLogin(username, password); + await appLogin(username, password) }, create: async (username, password, token) => { - await appCreate(username, password, token); + await appCreate(username, password, token) }, setAdmin: (token) => { updateState({ adminToken: token }); @@ -93,7 +94,7 @@ export function useAppContext() { clearAdmin: () => { updateState({ adminToken: null }); }, - }; + } const appCreate = async (username, password, token) => { if (appToken.current || !checked.current) { @@ -105,15 +106,12 @@ export function useAppContext() { setSession(access.appToken); appToken.current = access.appToken; - localStorage.setItem( - 'session', - JSON.stringify({ - access: access.appToken, - timestamp: access.created, - }), - ); + localStorage.setItem("session", JSON.stringify({ + access: access.appToken, + timestamp: access.created, + })); return access.created; - }; + } const appLogin = async (username, password) => { if (appToken.current || !checked.current) { @@ -124,15 +122,12 @@ export function useAppContext() { setSession(access.appToken); appToken.current = access.appToken; - localStorage.setItem( - 'session', - JSON.stringify({ - access: access.appToken, - timestamp: access.created, - }), - ); + localStorage.setItem("session", JSON.stringify({ + access: access.appToken, + timestamp: access.created, + })); return access.created; - }; + } const appAccess = async (token) => { if (appToken.current || !checked.current) { @@ -143,25 +138,23 @@ export function useAppContext() { setSession(access.appToken); appToken.current = access.appToken; - localStorage.setItem( - 'session', - JSON.stringify({ - access: access.appToken, - timestamp: access.created, - }), - ); + localStorage.setItem("session", JSON.stringify({ + access: access.appToken, + timestamp: access.created, + })); return access.created; - }; + } const appLogout = async (all) => { clearSession(); try { await clearLogin(appToken.current, all); - } catch (err) { + } + catch (err) { console.log(err); } appToken.current = null; - localStorage.removeItem('session'); + localStorage.removeItem("session"); }; useEffect(() => { @@ -173,17 +166,18 @@ export function useAppContext() { } // eslint-disable-next-line }, [appRevision]); - + const setWebsocket = (token) => { let protocol; if (window.location.protocol === 'http:') { protocol = 'ws://'; - } else { + } + else { protocol = 'wss://'; } updateState({ status: 'connecting' }); - ws.current = createWebsocket(protocol + window.location.host + '/status?mode=ring'); + ws.current = createWebsocket(protocol + window.location.host + "/status?mode=ring"); ws.current.onmessage = (ev) => { try { if (ev.data === '') { @@ -194,63 +188,69 @@ export function useAppContext() { updateState({ status: 'connected' }); if (activity.revision) { setAppRevision(activity.revision); - } else if (activity.ring) { + } + else if (activity.ring) { const { cardId, callId, calleeToken, iceUrl, iceUsername, icePassword } = activity.ring; ringContext.actions.ring(cardId, callId, calleeToken, iceUrl, iceUsername, icePassword); - } else { + } + else { setAppRevision(activity); } - } catch (err) { + } + catch (err) { console.log(err); ws.current.close(); } - }; + } ws.current.onclose = (e) => { - console.log(e); + console.log(e) updateState({ status: 'disconnected' }); setTimeout(() => { if (ws.current != null) { - ws.current.onmessage = () => {}; - ws.current.onclose = () => {}; - ws.current.onopen = () => {}; - ws.current.onerror = () => {}; + ws.current.onmessage = () => {} + ws.current.onclose = () => {} + ws.current.onopen = () => {} + ws.current.onerror = () => {} setWebsocket(token); } }, 1000); - }; + } ws.current.onopen = () => { - ws.current.send(JSON.stringify({ AppToken: token })); - }; + ws.current.send(JSON.stringify({ AppToken: token })) + } ws.current.error = (e) => { - console.log(e); + console.log(e) ws.current.close(); - }; - }; - - const clearWebsocket = () => { - ws.current.onclose = () => {}; - ws.current.close(); - ws.current = null; + } + } + + const clearWebsocket = () => { + ws.current.onclose = () => {} + ws.current.close() + ws.current = null updateState({ status: null }); - }; + } useEffect(() => { const storage = localStorage.getItem('session'); if (storage != null) { try { - const session = JSON.parse(storage); + const session = JSON.parse(storage) if (session?.access) { const access = session.access; setSession(access); appToken.current = access; } - } catch (err) { - console.log(err); + } + catch(err) { + console.log(err) } } checked.current = true; // eslint-disable-next-line }, []); - return { state, actions }; + return { state, actions } } + + diff --git a/net/web/src/context/useCardContext.hook.ts b/net/web/src/context/useCardContext.hook.ts index ff7d3dac..c1acfec6 100644 --- a/net/web/src/context/useCardContext.hook.ts +++ b/net/web/src/context/useCardContext.hook.ts @@ -24,14 +24,14 @@ import { addCard } from 'api/addCard'; import { removeCard } from 'api/removeCard'; import { UploadContext } from 'context/UploadContext'; -const defaultState = { +const defaultState = { offsync: false, cards: new Map(), -}; +} export const defaultCardContext = { - state: defaultState, - actions: {} as ReturnType['actions'], -}; + state:defaultState, + actions: {} as ReturnType["actions"], +} export function useCardContext() { const [state, setState] = useState(defaultState); @@ -44,14 +44,15 @@ export function useCardContext() { const force = useRef(false); const updateState = (value) => { - setState((s) => ({ ...s, ...value })); - }; + setState((s) => ({ ...s, ...value })) + } const resync = async () => { try { force.current = true; await sync(); - } catch (err) { + } + catch (err) { console.log(err); } }; @@ -71,7 +72,8 @@ export function useCardContext() { card.offsync = false; cards.current.set(cardId, card); updateState({ cards: cards.current }); - } catch (err) { + } + catch(err) { console.log(err); success = false; } @@ -79,7 +81,7 @@ export function useCardContext() { await sync(); } return success; - }; + } const sync = async () => { if (!syncing.current && (setRevision.current !== curRevision.current || force.current)) { @@ -94,13 +96,14 @@ export function useCardContext() { if (card.data) { let cur = cards.current.get(card.id); if (cur == null) { - cur = { id: card.id, data: { articles: new Map() }, offsync: false, channels: new Map() }; + cur = { id: card.id, data: { articles: new Map() }, offsync: false, channels: new Map() } } if (cur.revision !== card.revision) { if (cur.data.detailRevision !== card.data.detailRevision) { if (card.data.cardDetail != null) { cur.data.cardDetail = card.data.cardDetail; - } else { + } + else { cur.data.cardDetail = await getCardDetail(access.current, card.id); } cur.data.detailRevision = card.data.detailRevision; @@ -108,7 +111,8 @@ export function useCardContext() { if (cur.data.profileRevision !== card.data.profileRevision) { if (card.data.cardProfile != null) { cur.data.cardProfile = card.data.cardProfile; - } else { + } + else { cur.data.cardProfile = await getCardProfile(access.current, card.id); } cur.data.profileRevision = card.data.profileRevision; @@ -121,7 +125,8 @@ export function useCardContext() { cur.data.curNotifiedChannel = card.data.notifiedChannel; try { await syncCard(token, cur); - } catch (err) { + } + catch (err) { console.log(err); cur.offsync = true; } @@ -129,14 +134,16 @@ export function useCardContext() { cur.revision = card.revision; cards.current.set(card.id, cur); } - } else { + } + else { cards.current.delete(card.id); } } setRevision.current = revision; updateState({ offsync: false, cards: cards.current }); - } catch (err) { + } + catch (err) { console.log(err); syncing.current = false; updateState({ offsync: true }); @@ -147,7 +154,7 @@ export function useCardContext() { await sync(); } }; - + const syncCard = async (token, card) => { const { cardProfile, cardDetail } = card.data; // sync profile @@ -161,25 +168,19 @@ export function useCardContext() { card.data.setNotifiedProfile = card.data.curNotifiedProfile; // sync channels & articles - if ( - card.data.setNotifiedArticle !== card.data.curNotifiedArticle || - card.data.setNotifiedView !== card.data.curNotifiedView - ) { + if (card.data.setNotifiedArticle !== card.data.curNotifiedArticle || card.data.setNotifiedView !== card.data.curNotifiedView) { await syncCardArticles(card); } - if ( - card.data.setNotifiedChannel !== card.data.curNotifiedChannel || - card.data.setNotifiedView !== card.data.curNotifiedView - ) { + if (card.data.setNotifiedChannel !== card.data.curNotifiedChannel || card.data.setNotifiedView !== card.data.curNotifiedView) { await syncCardChannels(card); } card.data.setNotifiedArticle = card.data.curNotifiedArticle; card.data.setNotifiedChannel = card.data.curNotifiedChannel; card.data.setNotifiedView = card.data.curNotifiedView; card.offsync = false; - }; + } - const syncCardArticles = async (card) => {}; + const syncCardArticles = async (card) => {} const syncCardChannels = async (card) => { const { cardProfile, cardDetail, setNotifiedView, setNotifiedChannel } = card.data; @@ -189,7 +190,8 @@ export function useCardContext() { if (card.data.setNotifiedView !== card.data.curNotifiedView) { card.channels = new Map(); delta = await getContactChannels(node, token); - } else { + } + else { delta = await getContactChannels(node, token, setNotifiedView, setNotifiedChannel); } @@ -202,7 +204,8 @@ export function useCardContext() { if (cur.data.detailRevision !== channel.data.detailRevision) { if (channel.data.channelDetail != null) { cur.data.channelDetail = channel.data.channelDetail; - } else { + } + else { cur.data.channelDetail = await getContactChannelDetail(node, token, channel.id); } cur.data.detailRevision = channel.data.detailRevision; @@ -210,23 +213,25 @@ export function useCardContext() { if (cur.data.topicRevision !== channel.data.topicRevision) { if (channel.data.channelSummary != null) { cur.data.channelSummary = channel.data.channelSummary; - } else { + } + else { cur.data.channelSummary = await getContactChannelSummary(node, token, channel.id); } cur.data.topicRevision = channel.data.topicRevision; } cur.revision = channel.revision; card.channels.set(channel.id, cur); - } else { + } + else { card.channels.delete(channel.id); } } - }; + } const actions = { setToken: (token) => { if (access.current || syncing.current) { - throw new Error('invalid card session state'); + throw new Error("invalid card session state"); } access.current = token; cards.current = new Map(); @@ -251,15 +256,8 @@ export function useCardContext() { return await setCardConnecting(access.current, cardId); }, setCardConnected: async (cardId, token, rev) => { - return await setCardConnected( - access.current, - cardId, - token, - rev.viewRevision, - rev.articleRevision, - rev.channelRevision, - rev.profileRevision, - ); + return await setCardConnected(access.current, cardId, token, + rev.viewRevision, rev.articleRevision, rev.channelRevision, rev.profileRevision); }, setCardConfirmed: async (cardId) => { return await setCardConfirmed(access.current, cardId); @@ -280,7 +278,7 @@ export function useCardContext() { const card = cards.current.get(cardId); if (card) { const revision = card.data.profileRevision; - return getCardImageUrl(access.current, cardId, revision); + return getCardImageUrl(access.current, cardId, revision) } }, removeChannel: async (cardId, channelId) => { @@ -296,25 +294,19 @@ export function useCardContext() { if (files?.length) { const topicId = await addContactChannelTopic(node, token, channelId, null, null, null); const contact = { server: node, cardId }; - upload.actions.addTopic( - token, - channelId, - topicId, - files, - async (assets) => { - const subject = message(assets); - await setContactChannelTopicSubject(node, token, channelId, topicId, type, subject); - }, - async () => { - try { - await removeContactChannelTopic(node, token, channelId, topicId); - } catch (err) { - console.log(err); - } - }, - contact, - ); - } else { + upload.actions.addTopic(token, channelId, topicId, files, async (assets) => { + const subject = message(assets); + await setContactChannelTopicSubject(node, token, channelId, topicId, type, subject); + }, async () => { + try { + await removeContactChannelTopic(node, token, channelId, topicId); + } + catch(err) { + console.log(err); + } + }, contact); + } + else { const subject = message([]); await addContactChannelTopic(node, token, channelId, type, subject, files); } @@ -378,7 +370,9 @@ export function useCardContext() { resyncCard: async (cardId) => { return await resyncCard(cardId); }, - }; + } - return { state, actions }; + return { state, actions } } + + diff --git a/net/web/src/context/useChannelContext.hook.ts b/net/web/src/context/useChannelContext.hook.ts index 09321e3e..9c6f5000 100644 --- a/net/web/src/context/useChannelContext.hook.ts +++ b/net/web/src/context/useChannelContext.hook.ts @@ -18,11 +18,13 @@ import { UploadContext } from 'context/UploadContext'; const defaultState = { offsync: false, channels: new Map(), -}; +} export const defaultChannelContext = { - state: defaultState, - actions: {} as ReturnType['actions'], -}; + +state: defaultState, +actions: {} as ReturnType["actions"] + +} export function useChannelContext() { const [state, setState] = useState(defaultState); @@ -35,14 +37,15 @@ export function useChannelContext() { const force = useRef(false); const updateState = (value) => { - setState((s) => ({ ...s, ...value })); - }; + setState((s) => ({ ...s, ...value })) + } const resync = async () => { try { force.current = true; await sync(); - } catch (err) { + } + catch (err) { console.log(err); } }; @@ -60,13 +63,14 @@ export function useChannelContext() { if (channel.data) { let cur = channels.current.get(channel.id); if (cur == null) { - cur = { id: channel.id, data: {} }; + cur = { id: channel.id, data: { } } } if (cur.revision !== channel.revision) { if (cur.data.detailRevision !== channel.data.detailRevision) { if (channel.data.channelDetail != null) { cur.data.channelDetail = channel.data.channelDetail; - } else { + } + else { let detail = await getChannelDetail(token, channel.id); cur.data.channelDetail = detail; } @@ -75,7 +79,8 @@ export function useChannelContext() { if (cur.data.topicRevision !== channel.data.topicRevision) { if (channel.data.channelSummary != null) { cur.data.channelSummary = channel.data.channelSummary; - } else { + } + else { let summary = await getChannelSummary(token, channel.id); cur.data.channelSummary = summary; } @@ -84,13 +89,15 @@ export function useChannelContext() { cur.revision = channel.revision; channels.current.set(channel.id, cur); } - } else { + } + else { channels.current.delete(channel.id); } } setRevision.current = revision; updateState({ offsync: false, channels: channels.current }); - } catch (err) { + } + catch(err) { console.log(err); syncing.current = false; updateState({ offsync: true }); @@ -100,12 +107,12 @@ export function useChannelContext() { syncing.current = false; await sync(); } - }; + } const actions = { setToken: (token) => { if (access.current || syncing.current) { - throw new Error('invalid channel session state'); + throw new Error("invalid channel session state"); } access.current = token; channels.current = new Map(); @@ -138,24 +145,19 @@ export function useChannelContext() { addTopic: async (channelId, type, message, files) => { if (files?.length) { const topicId = await addChannelTopic(access.current, channelId, null, null, null); - upload.actions.addTopic( - access.current, - channelId, - topicId, - files, - async (assets) => { - const subject = message(assets); - await setChannelTopicSubject(access.current, channelId, topicId, type, subject); - }, - async () => { - try { - await removeChannelTopic(access.current, channelId, topicId); - } catch (err) { - console.log(err); - } - }, - ); - } else { + upload.actions.addTopic(access.current, channelId, topicId, files, async (assets) => { + const subject = message(assets); + await setChannelTopicSubject(access.current, channelId, topicId, type, subject); + }, async () => { + try { + await removeChannelTopic(access.current, channelId, topicId); + } + catch(err) { + console.log(err); + } + }); + } + else { const subject = message([]); await addChannelTopic(access.current, channelId, type, subject, undefined); } @@ -183,5 +185,7 @@ export function useChannelContext() { }, }; - return { state, actions }; + return { state, actions } } + + diff --git a/net/web/src/context/useConversationContext.hook.ts b/net/web/src/context/useConversationContext.hook.ts index af24266b..ba528618 100644 --- a/net/web/src/context/useConversationContext.hook.ts +++ b/net/web/src/context/useConversationContext.hook.ts @@ -2,17 +2,17 @@ import { useEffect, useState, useRef, useContext } from 'react'; import { CardContext } from 'context/CardContext'; import { ChannelContext } from 'context/ChannelContext'; -const defaultState = { +const defaultState ={ offsync: false, topics: new Map(), card: null, channel: null, topicRevision: null, -}; +} export const defaultConversionContext = { state: defaultState, - actions: {} as ReturnType['actions'], -}; + actions: {}as ReturnType["actions"] +} export function useConversationContext() { const COUNT = 32; @@ -34,28 +34,29 @@ export function useConversationContext() { const topics = useRef(new Map()); const updateState = (value) => { - setState((s) => ({ ...s, ...value })); - }; + setState((s) => ({ ...s, ...value })) + } const getTopicDelta = async (cardId, channelId, revision, count, begin, end) => { if (cardId) { return await card.actions.getTopics(cardId, channelId, revision, count, begin, end); } return await channel.actions.getTopics(channelId, revision, count, begin, end); - }; + } const getTopic = async (cardId, channelId, topicId) => { if (cardId) { return await card.actions.getTopic(cardId, channelId, topicId); } return await channel.actions.getTopic(channelId, topicId); - }; + } const removeChannel = async (cardId, channelId) => { if (cardId) { await card.actions.removeChannel(cardId, channelId); - await card.actions.resync(); - } else { + await card.actions.resync(); + } + else { await channel.actions.removeChannel(channelId); await channel.actions.resync(); } @@ -64,24 +65,27 @@ export function useConversationContext() { const setChannelSubject = async (cardId, channelId, type, subject) => { if (cardId) { console.log('cannot update channel subject'); - } else { + } + else { await channel.actions.setChannelSubject(channelId, type, subject); } - }; + } const setChannelCard = async (cardId, channelId, id) => { if (cardId) { console.log('cannot update channel card'); - } else { + } + else { await channel.actions.setChannelCard(channelId, id); await channel.actions.resync(); } - }; + } const clearChannelCard = async (cardId, channelId, id) => { if (cardId) { console.log('cannot update channel card'); - } else { + } + else { await channel.actions.clearChannelCard(channelId, id); await channel.actions.resync(); } @@ -90,7 +94,8 @@ export function useConversationContext() { const addTopic = async (cardId, channelId, type, message, files) => { if (cardId) { await card.actions.addTopic(cardId, channelId, type, message, files); - } else { + } + else { await channel.actions.addTopic(channelId, type, message, files); } resync(); @@ -99,7 +104,8 @@ export function useConversationContext() { const removeTopic = async (cardId, channelId, topicId) => { if (cardId) { await card.actions.removeTopic(cardId, channelId, topicId); - } else { + } + else { await channel.actions.removeTopic(channelId, topicId); } await resync(); @@ -108,7 +114,8 @@ export function useConversationContext() { const setTopicSubject = async (cardId, channelId, topicId, type, subject) => { if (cardId) { await card.actions.setTopicSubject(cardId, channelId, topicId, type, subject); - } else { + } + else { await channel.actions.setTopicSubject(channelId, topicId, type, subject); } await resync(); @@ -117,7 +124,8 @@ export function useConversationContext() { const getTopicAssetUrl = (cardId, channelId, topicId, assetId) => { if (cardId) { return card.actions.getTopicAssetUrl(cardId, channelId, topicId, assetId); - } else { + } + else { return channel.actions.getTopicAssetUrl(channelId, topicId, assetId); } }; @@ -127,7 +135,8 @@ export function useConversationContext() { if (cardId) { const setCard = card.state.cards.get(cardId); setChannel = setCard?.channels.get(channelId); - } else { + } + else { setChannel = channel.state.channels.get(channelId); } if (setChannel) { @@ -136,29 +145,26 @@ export function useConversationContext() { curTopicRevision.current = topicRevision; curDetailRevision.current = detailRevision; } - } else { + } + else { console.log('conversation not found'); } - }; + } const resync = async () => { try { force.current = true; await sync(); - } catch (err) { + } + catch (err) { console.log(err); } }; const sync = async () => { - if ( - !syncing.current && - (reset.current || - force.current || - loadMore.current || - setDetailRevision.current !== curDetailRevision.current || - setTopicRevision.current !== curTopicRevision.current) - ) { + if (!syncing.current && (reset.current || force.current || loadMore.current || + setDetailRevision.current !== curDetailRevision.current || setTopicRevision.current !== curTopicRevision.current)) { + const more = loadMore.current; const update = force.current; const topicRevision = more ? setTopicRevision.current : curTopicRevision.current; @@ -174,7 +180,7 @@ export function useConversationContext() { setTopicRevision.current = null; setDetailRevision.current = null; topics.current = new Map(); - updateState({ offsync: false, channel: null, topics: new Map() }); + updateState({ offsync: false, channel: null, topics: new Map() }); } if (conversationId.current) { @@ -187,15 +193,17 @@ export function useConversationContext() { if (cardId) { cardSync = card.state.cards.get(cardId); channelSync = cardSync?.channels.get(channelId); - } else { + } + else { channelSync = channel.state.channels.get(channelId); } if (channelSync) { setDetailRevision.current = detailRevision; updateState({ card: cardSync, channel: channelSync }); - } else { + } + else { syncing.current = false; - console.log('converstaion not found'); + console.log("converstaion not found"); return; } } @@ -206,25 +214,29 @@ export function useConversationContext() { let delta; if (!marker.current) { delta = await getTopicDelta(cardId, channelId, null, COUNT, null, null); - } else if (more) { + } + else if (more) { delta = await getTopicDelta(cardId, channelId, null, COUNT, null, marker.current); - } else { + } + else { delta = await getTopicDelta(cardId, channelId, setTopicRevision.current, null, marker.current, null); } for (let topic of delta?.topics) { if (topic.data == null) { topics.current.delete(topic.id); - } else { + } + else { let cur = topics.current.get(topic.id); if (cur == null) { cur = { id: topic.id, data: {} }; } if (topic.data.detailRevision !== cur.data.detailRevision) { - if (topic.data.topicDetail) { + if(topic.data.topicDetail) { cur.data.topicDetail = topic.data.topicDetail; cur.data.detailRevision = topic.data.detailRevision; - } else { + } + else { const slot = await getTopic(cardId, channelId, topic.id); cur.data.topicDetail = slot.data.topicDetail; cur.data.detailRevision = slot.data.detailRevision; @@ -240,7 +252,8 @@ export function useConversationContext() { updateState({ offsync: false, topicRevision: topicRevision, topics: topics.current }); } - } catch (err) { + } + catch (err) { console.log(err); updateState({ offsync: true }); syncing.current = false; @@ -316,7 +329,9 @@ export function useConversationContext() { force.current = true; await sync(); }, - }; + } - return { state, actions }; + return { state, actions } } + + diff --git a/net/web/src/context/useProfileContext.hook.ts b/net/web/src/context/useProfileContext.hook.ts index c57d38ca..8924bc0b 100644 --- a/net/web/src/context/useProfileContext.hook.ts +++ b/net/web/src/context/useProfileContext.hook.ts @@ -5,25 +5,26 @@ import { setProfileData } from 'api/setProfileData'; import { setProfileImage } from 'api/setProfileImage'; import { getProfileImageUrl } from 'api/getProfileImageUrl'; -interface Identity { +interface Identity { guid: string; name: string; handle: string; node: any; revision: string; - seal: string; + seal: string version: string; image: string; location: string; description: string; + } export const defaultProfileContext = { - state: { - offsync: false, - identity: {} as Partial, - imageUrl: null, - }, - actions: { +state:{ + offsync: false, + identity: {} as Partial, + imageUrl: null, +}, +actions: { setToken: (token: any) => {}, clearToken: () => {}, setRevision: (rev: any) => Promise.reject(), @@ -31,8 +32,8 @@ export const defaultProfileContext = { setProfileImage: (image: any) => Promise.reject(), getHandleStatus: (name: any) => Promise.reject(), resync: () => Promise.reject(), - }, -}; +} +} export function useProfileContext(): typeof defaultProfileContext { const [state, setState] = useState(defaultProfileContext.state); const access = useRef(null); @@ -41,8 +42,8 @@ export function useProfileContext(): typeof defaultProfileContext { const syncing = useRef(false); const updateState = (value) => { - setState((s) => ({ ...s, ...value })); - }; + setState((s) => ({ ...s, ...value })) + } const sync = async () => { if (!syncing.current && setRevision.current !== curRevision.current) { @@ -55,7 +56,8 @@ export function useProfileContext(): typeof defaultProfileContext { const imageUrl = identity.image ? getProfileImageUrl(token, identity.revision) : null; setRevision.current = revision; updateState({ offsync: false, identity, imageUrl }); - } catch (err) { + } + catch(err) { console.log(err); syncing.current = false; updateState({ offsync: true }); @@ -65,12 +67,12 @@ export function useProfileContext(): typeof defaultProfileContext { syncing.current = false; await sync(); } - }; + } const actions = { setToken: (token) => { if (access.current || syncing.current) { - throw new Error('invalid profile session state'); + throw new Error("invalid profile session state"); } access.current = token; curRevision.current = null; @@ -96,7 +98,9 @@ export function useProfileContext(): typeof defaultProfileContext { resync: async () => { await sync(); }, - }; + } - return { state, actions }; + return { state, actions } } + + diff --git a/net/web/src/context/useRingContext.hook.ts b/net/web/src/context/useRingContext.hook.ts index d6c6ca5c..d155a86b 100644 --- a/net/web/src/context/useRingContext.hook.ts +++ b/net/web/src/context/useRingContext.hook.ts @@ -5,7 +5,7 @@ import { addCall } from 'api/addCall'; import { keepCall } from 'api/keepCall'; import { removeCall } from 'api/removeCall'; import { removeContactCall } from 'api/removeContactCall'; -type Actions = ReturnType['actions']; +type Actions = ReturnType["actions"] const defaultState = { ringing: new Map(), callStatus: null, @@ -16,19 +16,19 @@ const defaultState = { remoteStream: null, remoteVideo: false, remoteAudio: false, -}; -export const defaultRingContext = { - state: defaultState, - actions: {} as Actions, -}; +} +export const defaultRingContext={ + state:defaultState, + actions: {} as Actions +} export function useRingContext() { const [state, setState] = useState(defaultState); const access = useRef(null); - const EXPIRE = 3000; - const RING = 2000; - const RING_COUNT = 10; + const EXPIRE = 3000 + const RING = 2000 + const RING_COUNT = 10 const ringing = useRef(new Map()); const calling = useRef(null); const ws = useRef(null); @@ -44,8 +44,8 @@ export function useRingContext() { const candidates = useRef([]); const updateState = (value) => { - setState((s) => ({ ...s, ...value })); - }; + setState((s) => ({ ...s, ...value })) + } const polite = async () => { if (processing.current || !connected.current) { @@ -67,9 +67,10 @@ export function useRingContext() { const offer = await pc.current.createOffer(); await pc.current.setLocalDescription(offer); ws.current.send(JSON.stringify({ description: pc.current.localDescription })); - } else { + } + else { if (description.type === 'offer' && pc.current.signalingState !== 'stable') { - await pc.current.setLocalDescription({ type: 'rollback' }); + await pc.current.setLocalDescription({ type: "rollback" }); } await pc.current.setRemoteDescription(description); if (description.type === 'offer') { @@ -84,13 +85,14 @@ export function useRingContext() { } } } - } catch (err) { + } + catch (err) { alert('webrtc error:' + err.toString()); } } processing.current = false; - }; + } const impolite = async () => { if (processing.current || !connected.current) { @@ -111,7 +113,8 @@ export function useRingContext() { const offer = await pc.current.createOffer(); await pc.current.setLocalDescription(offer); ws.current.send(JSON.stringify({ description: pc.current.localDescription })); - } else { + } + else { if (description.type === 'offer' && pc.current.signalingState !== 'stable') { continue; } @@ -127,36 +130,39 @@ export function useRingContext() { await pc.current.addIceCandidate(servers[0]); } } - } catch (err) { + } + catch (err) { alert('webrtc error:' + err.toString()); } } } processing.current = false; - }; + } const getAudioStream = async (audioId) => { try { if (audioId) { return await navigator.mediaDevices.getUserMedia({ video: false, audio: { deviceId: audioId } }); } - } catch (err) { + } + catch (err) { console.log(err); } return await navigator.mediaDevices.getUserMedia({ video: false, audio: true }); - }; + } const getVideoStream = async (videoId) => { try { if (videoId) { return await navigator.mediaDevices.getUserMedia({ video: { deviceId: videoId }, audio: false }); } - } catch (err) { + } + catch (err) { console.log(err); } return await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - }; + } const transmit = async (policy, ice, audioId) => { pc.current = new RTCPeerConnection({ iceServers: ice }); @@ -167,12 +173,13 @@ export function useRingContext() { } if (ev.track.kind === 'audio') { updateState({ remoteAudio: true }); - } else if (ev.track.kind === 'video') { + } + else if (ev.track.kind === 'video') { updateState({ remoteVideo: true }); } stream.current.addTrack(ev.track); }; - pc.current.onicecandidate = ({ candidate }) => { + pc.current.onicecandidate = ({candidate}) => { ws.current.send(JSON.stringify({ candidate })); }; pc.current.onnegotiationneeded = async () => { @@ -195,24 +202,19 @@ export function useRingContext() { } pc.current.addTrack(track); } - } catch (err) { + } + catch (err) { console.log(err); } - }; + } const connect = async (policy, audioId, node, token, clearRing, clearAlive, ice) => { + // connect signal socket connected.current = false; candidates.current = []; pc.current = null; - updateState({ - remoteVideo: false, - remoteAudio: false, - remoteStream: null, - localVideo: false, - localAudio: false, - localStream: null, - }); + updateState({ remoteVideo: false, remoteAudio: false, remoteStream: null, localVideo: false, localAudio: false, localStream: null }); videoTrack.current = false; audioTrack.current = false; @@ -227,15 +229,17 @@ export function useRingContext() { const signal = JSON.parse(ev.data); if (signal.status === 'connected') { clearRing(); - updateState({ callStatus: 'connected' }); + updateState({ callStatus: "connected" }); if (policy === 'polite') { connected.current = true; transmit('polite', ice, audioId); polite(); } - } else if (signal.status === 'closed') { + } + else if (signal.status === 'closed') { ws.current.close(); - } else if (signal.description) { + } + else if (signal.description) { offers.current.push(signal.description); if (policy === 'polite') { polite(); @@ -243,17 +247,20 @@ export function useRingContext() { if (policy === 'impolite') { impolite(); } - } else if (signal.candidate) { + } + else if (signal.candidate) { if (pc.current.remoteDescription == null) { candidates.current.push(signal.candidate); - } else { + } + else { await pc.current.addIceCandidate(signal.candidate); } } - } catch (err) { + } + catch (err) { console.log(err); } - }; + } ws.current.onclose = (e) => { // update state to disconnected if (pc.current) { @@ -270,16 +277,8 @@ export function useRingContext() { audioTrack.current.stop(); audioTrack.current = null; } - updateState({ - callStatus: null, - removeStream: null, - localStream: null, - remoteVideo: false, - remoteAudio: false, - localVideo: false, - localAudio: false, - }); - }; + updateState({ callStatus: null, removeStream: null, localStream: null, remoteVideo: false, remoteAudio: false, localVideo: false, localAudio: false }); + } ws.current.onopen = async () => { ws.current.send(JSON.stringify({ AppToken: token })); if (policy === 'impolite') { @@ -287,17 +286,17 @@ export function useRingContext() { transmit('impolite', ice, audioId); impolite(); } - }; + } ws.current.error = (e) => { - console.log(e); + console.log(e) ws.current.close(); - }; - }; + } + } const actions = { setToken: (token) => { if (access.current) { - throw new Error('invalid ring state'); + throw new Error("invalid ring state"); } access.current = token; ringing.current = new Map(); @@ -308,8 +307,8 @@ export function useRingContext() { access.current = null; }, ring: (cardId, callId, calleeToken, iceUrl, iceUsername, icePassword) => { - const key = `${cardId}:${callId}`; - const call = ringing.current.get(key) || { cardId, calleeToken, callId, iceUrl, iceUsername, icePassword }; + const key = `${cardId}:${callId}` + const call = ringing.current.get(key) || { cardId, calleeToken, callId, iceUrl, iceUsername, icePassword } call.expires = Date.now() + EXPIRE; ringing.current.set(key, call); updateState({ ringing: ringing.current }); @@ -318,62 +317,45 @@ export function useRingContext() { }, EXPIRE); }, ignore: (cardId, callId) => { - const key = `${cardId}:${callId}`; + const key = `${cardId}:${callId}` const call = ringing.current.get(key); if (call) { - call.status = 'ignored'; + call.status = 'ignored' ringing.current.set(key, call); updateState({ ringing: ringing.current }); } }, decline: async (cardId, contactNode, contactToken, callId) => { - const key = `${cardId}:${callId}`; + const key = `${cardId}:${callId}` const call = ringing.current.get(key); if (call) { - call.status = 'declined'; + call.status = 'declined' ringing.current.set(key, call); updateState({ ringing: ringing.current }); try { await removeContactCall(contactNode, contactToken, callId); - } catch (err) { + } + catch (err) { console.log(err); } } }, - accept: async ( - cardId, - callId, - contactNode, - contactToken, - calleeToken, - iceUrl, - iceUsername, - icePassword, - audioId, - ) => { + accept: async (cardId, callId, contactNode, contactToken, calleeToken, iceUrl, iceUsername, icePassword, audioId) => { if (calling.current) { - throw new Error('active session'); + throw new Error("active session"); } const ice = [{ urls: iceUrl, username: iceUsername, credential: icePassword }]; - const key = `${cardId}:${callId}`; + const key = `${cardId}:${callId}` const call = ringing.current.get(key); if (call) { - call.status = 'accepted'; + call.status = 'accepted' ringing.current.set(key, call); - updateState({ ringing: ringing.current, callStatus: 'connecting', cardId }); + updateState({ ringing: ringing.current, callStatus: "connecting", cardId }); calling.current = { callId, contactNode, contactToken, host: false }; - await connect( - 'impolite', - audioId, - contactNode, - calleeToken, - () => {}, - () => {}, - ice, - ); + await connect('impolite', audioId, contactNode, calleeToken, () => {}, () => {}, ice); } }, end: async () => { @@ -382,10 +364,12 @@ export function useRingContext() { const { host, callId, contactNode, contactToken } = calling.current; if (host) { await removeCall(access.current, callId); - } else { + } + else { await removeContactCall(contactNode, contactToken, callId); } - } catch (err) { + } + catch (err) { console.log(err); } if (ws.current) { @@ -403,47 +387,35 @@ export function useRingContext() { }, call: async (cardId, contactNode, contactToken, audioId) => { if (calling.current) { - throw new Error('active session'); + throw new Error("active session"); } calling.current = {}; - updateState({ callStatus: 'dialing', cardId }); + updateState({ callStatus: "dialing", cardId }); // create call let call; try { call = await addCall(access.current, cardId); - } catch (err) { + } + catch (err) { calling.current = null; - updateState({ - callStatus: null, - remoteStream: null, - localStream: null, - remoteVideo: false, - remoteAudio: false, - localVideo: false, - localAudio: false, - }); + updateState({ callStatus: null, remoteStream: null, localStream: null, remoteVideo: false, remoteAudio: false, localVideo: false, localAudio: false }); } let index = 0; const { id, keepAlive, callerToken, calleeToken, iceUrl, iceUsername, icePassword } = call; try { - await addContactRing(contactNode, contactToken, { - index, - callId: id, - calleeToken, - iceUrl, - iceUsername, - icePassword, - }); - } catch (err) { + await addContactRing(contactNode, contactToken, { index, callId: id, calleeToken, iceUrl, iceUsername, icePassword }); + } + catch (err) { console.log(err); } const aliveInterval = setInterval(async () => { try { await keepCall(access.current, id); - } catch (err) { + } + catch (err) { console.log(err); } }, keepAlive * 1000); @@ -453,34 +425,21 @@ export function useRingContext() { if (ws.current) { ws.current.close(); } - } else { - await addContactRing(contactNode, contactToken, { - index, - callId: id, - calleeToken, - iceUrl, - iceUsername, - icePassword, - }); + } + else { + await addContactRing(contactNode, contactToken, { index, callId: id, calleeToken, iceUrl, iceUsername, icePassword }); index += 1; } - } catch (err) { + } + catch (err) { console.log(err); } }, RING); - updateState({ callStatus: 'ringing' }); + updateState({ callStatus: "ringing" }); calling.current = { callId: id, host: true }; const ice = [{ urls: iceUrl, username: iceUsername, credential: icePassword }]; - await connect( - 'polite', - audioId, - window.location.host, - callerToken, - () => clearInterval(ringInterval), - () => clearInterval(aliveInterval), - ice, - ); + await connect('polite', audioId, window.location.host, callerToken, () => clearInterval(ringInterval), () => clearInterval(aliveInterval), ice); }, enableVideo: async (videoId) => { if (!accessVideo.current) { @@ -497,7 +456,8 @@ export function useRingContext() { } pc.current.addTrack(track); } - } else { + } + else { videoTrack.current.enabled = true; } updateState({ localVideo: true, localAudio: true }); @@ -523,23 +483,23 @@ export function useRingContext() { getDevices: async (type) => { const filtered = new Map(); const devices = await navigator.mediaDevices.enumerateDevices(); - devices - .filter((item) => item.kind === type + 'input') - .forEach((item) => { - if (item && item.label) { - const entry = filtered.get(item.groupId); - if (entry) { - if (item.label && item.label.length < entry.label.length) { - filtered.set(item.groupId, item); - } - } else { + devices.filter(item => item.kind === type + 'input').forEach(item => { + if (item && item.label) { + const entry = filtered.get(item.groupId); + if (entry) { + if (item.label && item.label.length < entry.label.length) { filtered.set(item.groupId, item); } } - }); + else { + filtered.set(item.groupId, item); + } + } + }); return Array.from(filtered.values()); }, - }; + } - return { state, actions }; + return { state, actions } } + diff --git a/net/web/src/context/useSettingsContext.hook.ts b/net/web/src/context/useSettingsContext.hook.ts index b6f3771a..1919bafb 100644 --- a/net/web/src/context/useSettingsContext.hook.ts +++ b/net/web/src/context/useSettingsContext.hook.ts @@ -2,26 +2,16 @@ import { useEffect, useState } from 'react'; import { LightTheme, DarkTheme } from 'constants/Colors'; import { en, fr, sp, pt, de, ru } from 'constants/Strings'; -const defaultState = { +const defaultState = { display: null, width: null, height: null, - themes: [ - { value: 'dark', label: 'Dark' }, - { value: 'light', label: 'Light' }, - ], + themes: [{ value: 'dark', label: 'Dark' }, { value: 'light', label: 'Light' }], theme: null, scheme: null, - colors: {} as Record, + colors: {} as Record, menuStyle: {}, - languages: [ - { value: 'en', label: 'English' }, - { value: 'fr', label: 'Français' }, - { value: 'sp', label: 'Español' }, - { value: 'pt', label: 'Português' }, - { value: 'de', label: 'Deutsch' }, - { value: 'ru', label: 'Русский' }, - ], + languages: [{ value: 'en', label: 'English' }, { value: 'fr', label: 'Français' }, { value: 'sp', label: 'Español' }, { value: 'pt', label: 'Português' }, { value: 'de', label: 'Deutsch' }, { value: 'ru', label: 'Русский' }], language: null, strings: en, dateFormat: 'mm/dd', @@ -30,12 +20,13 @@ const defaultState = { audioInputs: [], videoId: null, videoInputs: [], -}; +} export const defaultSettingsContext = { state: defaultState, - actions: {} as ReturnType['actions'], -}; + actions: {} as ReturnType["actions"] +} export function useSettingsContext() { + const [state, setState] = useState(defaultState); const SMALL_MEDIUM = 650; @@ -49,11 +40,14 @@ export function useSettingsContext() { const handleResize = () => { if (window.innerWidth < SMALL_MEDIUM) { updateState({ display: 'small', width: window.innerWidth, height: window.innerHeight }); - } else if (window.innerWidth < MEDIUM_LARGE) { + } + else if (window.innerWidth < MEDIUM_LARGE) { updateState({ display: 'medium', width: window.innerWidth, height: window.innerHeight }); - } else if (window.innerWidth < LARGE_XLARGE) { + } + else if (window.innerWidth < LARGE_XLARGE) { updateState({ display: 'large', width: window.innerWidth, height: window.innerHeight }); - } else { + } + else { updateState({ display: 'xlarge', width: window.innerWidth, height: window.innerHeight }); } }; @@ -66,29 +60,28 @@ export function useSettingsContext() { const filtered = new Map(); const devices = await navigator.mediaDevices.enumerateDevices(); - devices - .filter((item) => item.kind === type + 'input') - .forEach((item) => { - if (item) { - const label = item.label ? item.label : state.strings.integrated; - const entry = filtered.get(item.groupId); - if (entry) { - if (item.label && label.length < entry.label.length) { - filtered.set(item.groupId, { value: item.deviceId, label }); - } - } else { + devices.filter(item => item.kind === type + 'input').forEach(item => { + if (item) { + const label = item.label ? item.label : state.strings.integrated; + const entry = filtered.get(item.groupId); + if (entry) { + if (item.label && label.length < entry.label.length) { filtered.set(item.groupId, { value: item.deviceId, label }); } } - }); + else { + filtered.set(item.groupId, { value: item.deviceId, label }); + } + } + }); return Array.from(filtered.values()); - }; + } useEffect(() => { - getDevices('audio').then((audio) => { + getDevices('audio').then(audio => { updateState({ audioInputs: audio }); }); - getDevices('video').then((video) => { + getDevices('video').then(video => { updateState({ videoInputs: video }); }); // eslint-disable-next-line @@ -104,162 +97,74 @@ export function useSettingsContext() { const scheme = localStorage.getItem('color_scheme'); if (scheme === 'dark') { - updateState({ - theme: scheme, - scheme: 'dark', - colors: DarkTheme, - menuStyle: { backgroundColor: DarkTheme.modalArea, color: DarkTheme.mainText }, - }); - } else if (scheme === 'light') { - updateState({ - theme: scheme, - scheme: 'light', - colors: LightTheme, - menuStyle: { backgroundColor: LightTheme.modalArea, color: LightTheme.mainText }, - }); - } else { - if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { - updateState({ - theme: null, - scheme: 'dark', - colors: DarkTheme, - menuStyle: { backgroundColor: DarkTheme.modalArea, color: DarkTheme.mainText }, - }); - } else { - updateState({ - theme: null, - scheme: 'light', - colors: LightTheme, - menuStyle: { backgroundColor: LightTheme.modalArea, color: LightTheme.mainText }, - }); + updateState({ theme: scheme, scheme: 'dark', colors: DarkTheme, menuStyle: { backgroundColor: DarkTheme.modalArea, color: DarkTheme.mainText } }); + } + else if (scheme === 'light') { + updateState({ theme: scheme, scheme: 'light', colors: LightTheme, menuStyle: { backgroundColor: LightTheme.modalArea, color: LightTheme.mainText } }) + } + else { + if(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { + updateState({ theme: null, scheme: 'dark', colors: DarkTheme, menuStyle: { backgroundColor: DarkTheme.modalArea, color: DarkTheme.mainText } }); + } + else { + updateState({ theme: null, scheme: 'light', colors: LightTheme, menuStyle: { backgroundColor: LightTheme.modalArea, color: LightTheme.mainText } }); } } const timeFormat = localStorage.getItem('time_format'); if (timeFormat === '24h') { updateState({ timeFormat }); - } else { + } + else { updateState({ timeFormat: '12h' }); } const dateFormat = localStorage.getItem('date_format'); if (dateFormat === 'dd/mm') { updateState({ dateFormat }); - } else { + } + else { updateState({ dateFormat: 'mm/dd' }); } const language = localStorage.getItem('language'); if (language && language.startsWith('fr')) { - updateState({ - language: 'fr', - strings: fr, - themes: [ - { value: 'dark', label: fr.dark }, - { value: 'light', label: fr.light }, - ], - }); - } else if (language && language.startsWith('sp')) { - updateState({ - language: 'sp', - strings: sp, - themes: [ - { value: 'dark', label: sp.dark }, - { value: 'light', label: sp.light }, - ], - }); - } else if (language && language.startsWith('en')) { - updateState({ - language: 'en', - strings: en, - themes: [ - { value: 'dark', label: en.dark }, - { value: 'light', label: en.light }, - ], - }); - } else if (language && language.startsWith('pt')) { - updateState({ - language: 'pt', - strings: pt, - themes: [ - { value: 'dark', label: pt.dark }, - { value: 'light', label: pt.light }, - ], - }); - } else if (language && language.startsWith('de')) { - updateState({ - language: 'de', - strings: de, - themes: [ - { value: 'dark', label: de.dark }, - { value: 'light', label: de.light }, - ], - }); - } else if (language && language.startsWith('ru')) { - updateState({ - language: 'ru', - strings: ru, - themes: [ - { value: 'dark', label: ru.dark }, - { value: 'light', label: ru.light }, - ], - }); - } else { + updateState({ language: 'fr', strings: fr, themes: [{ value: 'dark', label: fr.dark }, { value: 'light', label: fr.light }]}); + } + else if (language && language.startsWith('sp')) { + updateState({ language: 'sp', strings: sp, themes: [{ value: 'dark', label: sp.dark }, { value: 'light', label: sp.light }]}); + } + else if (language && language.startsWith('en')) { + updateState({ language: 'en', strings: en, themes: [{ value: 'dark', label: en.dark }, { value: 'light', label: en.light }]}); + } + else if (language && language.startsWith('pt')) { + updateState({ language: 'pt', strings: pt, themes: [{ value: 'dark', label: pt.dark }, { value: 'light', label: pt.light }]}); + } + else if (language && language.startsWith('de')) { + updateState({ language: 'de', strings: de, themes: [{ value: 'dark', label: de.dark }, { value: 'light', label: de.light }]}); + } + else if (language && language.startsWith('ru')) { + updateState({ language: 'ru', strings: ru, themes: [{ value: 'dark', label: ru.dark }, { value: 'light', label: ru.light }]}); + } + else { const browser = navigator.language; if (browser && browser.startsWith('fr')) { - updateState({ - language: null, - strings: fr, - themes: [ - { value: 'dark', label: fr.dark }, - { value: 'light', label: fr.light }, - ], - }); - } else if (browser && browser.startsWith('sp')) { - updateState({ - language: null, - strings: sp, - themes: [ - { value: 'dark', label: sp.dark }, - { value: 'light', label: sp.light }, - ], - }); - } else if (browser && browser.startsWith('pt')) { - updateState({ - language: null, - strings: pt, - themes: [ - { value: 'dark', label: pt.dark }, - { value: 'light', label: pt.light }, - ], - }); - } else if (browser && browser.startsWith('de')) { - updateState({ - language: null, - strings: de, - themes: [ - { value: 'dark', label: de.dark }, - { value: 'light', label: de.light }, - ], - }); - } else if (browser && browser.startsWith('ru')) { - updateState({ - language: null, - strings: ru, - themes: [ - { value: 'dark', label: ru.dark }, - { value: 'light', label: ru.light }, - ], - }); - } else { - updateState({ - language: null, - strings: en, - themes: [ - { value: 'dark', label: en.dark }, - { value: 'light', label: en.light }, - ], - }); + updateState({ language: null, strings: fr, themes: [{ value: 'dark', label: fr.dark }, { value: 'light', label: fr.light }]}); + } + else if (browser && browser.startsWith('sp')) { + updateState({ language: null, strings: sp, themes: [{ value: 'dark', label: sp.dark }, { value: 'light', label: sp.light }]}); + } + else if (browser && browser.startsWith('pt')) { + updateState({ language: null, strings: pt, themes: [{ value: 'dark', label: pt.dark }, { value: 'light', label: pt.light }]}); + } + else if (browser && browser.startsWith('de')) { + updateState({ language: null, strings: de, themes: [{ value: 'dark', label: de.dark }, { value: 'light', label: de.light }]}); + } + else if (browser && browser.startsWith('ru')) { + updateState({ language: null, strings: ru, themes: [{ value: 'dark', label: ru.dark }, { value: 'light', label: ru.light }]}); + } + else { + updateState({ language: null, strings: en, themes: [{ value: 'dark', label: en.dark }, { value: 'light', label: en.light }]}); } } @@ -270,7 +175,7 @@ export function useSettingsContext() { return () => { window.removeEventListener('resize', handleResize); window.removeEventListener('orientationchange', handleResize); - }; + } // eslint-disable-next-line }, []); @@ -278,157 +183,67 @@ export function useSettingsContext() { setTheme: (theme) => { if (theme === 'dark') { localStorage.setItem('color_scheme', 'dark'); - updateState({ - theme: 'dark', - scheme: 'dark', - colors: DarkTheme, - menuStyle: { backgroundColor: DarkTheme.modalArea, color: DarkTheme.mainText }, - }); - } else if (theme === 'light') { + updateState({ theme: 'dark', scheme: 'dark', colors: DarkTheme, menuStyle: { backgroundColor: DarkTheme.modalArea, color: DarkTheme.mainText } }); + } + else if (theme === 'light') { localStorage.setItem('color_scheme', 'light'); - updateState({ - theme: 'light', - scheme: 'light', - colors: LightTheme, - menuStyle: { backgroundColor: LightTheme.modalArea, color: LightTheme.mainText }, - }); - } else { + updateState({ theme: 'light', scheme: 'light', colors: LightTheme, menuStyle: { backgroundColor: LightTheme.modalArea, color: LightTheme.mainText } }); + } + else { localStorage.removeItem('color_scheme'); - if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { - updateState({ - theme: null, - scheme: 'dark', - colors: DarkTheme, - menuStyle: { backgroundColor: DarkTheme.modalArea, color: DarkTheme.mainText }, - }); - } else { - updateState({ - theme: null, - scheme: 'ligth', - colors: LightTheme, - menuStyle: { backgroundColor: LightTheme.modalArea, color: LightTheme.mainText }, - }); + if(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { + updateState({ theme: null, scheme: 'dark', colors: DarkTheme, menuStyle: { backgroundColor: DarkTheme.modalArea, color: DarkTheme.mainText } }); + } + else { + updateState({ theme: null, scheme: 'ligth', colors: LightTheme, menuStyle: { backgroundColor: LightTheme.modalArea, color: LightTheme.mainText } }); } } }, setLanguage: (code) => { if (code && code.startsWith('fr')) { localStorage.setItem('language', 'fr'); - updateState({ - language: 'fr', - strings: fr, - themes: [ - { value: 'dark', label: fr.dark }, - { value: 'light', label: fr.light }, - ], - }); - } else if (code && code.startsWith('sp')) { + updateState({ language: 'fr', strings: fr, themes: [{ value: 'dark', label: fr.dark }, { value: 'light', label: fr.light }]}); + } + else if (code && code.startsWith('sp')) { localStorage.setItem('language', 'sp'); - updateState({ - language: 'sp', - strings: sp, - themes: [ - { value: 'dark', label: sp.dark }, - { value: 'light', label: sp.light }, - ], - }); - } else if (code && code.startsWith('en')) { + updateState({ language: 'sp', strings: sp, themes: [{ value: 'dark', label: sp.dark }, { value: 'light', label: sp.light }]}); + } + else if (code && code.startsWith('en')) { localStorage.setItem('language', 'en'); - updateState({ - language: 'en', - strings: en, - themes: [ - { value: 'dark', label: en.dark }, - { value: 'light', label: en.light }, - ], - }); - } else if (code && code.startsWith('pt')) { + updateState({ language: 'en', strings: en, themes: [{ value: 'dark', label: en.dark }, { value: 'light', label: en.light }]}); + } + else if (code && code.startsWith('pt')) { localStorage.setItem('language', 'pt'); - updateState({ - language: 'pt', - strings: pt, - themes: [ - { value: 'dark', label: pt.dark }, - { value: 'light', label: pt.light }, - ], - }); - } else if (code && code.startsWith('de')) { + updateState({ language: 'pt', strings: pt, themes: [{ value: 'dark', label: pt.dark }, { value: 'light', label: pt.light }]}); + } + else if (code && code.startsWith('de')) { localStorage.setItem('language', 'de'); - updateState({ - language: 'de', - strings: de, - themes: [ - { value: 'dark', label: de.dark }, - { value: 'light', label: de.light }, - ], - }); - } else if (code && code.startsWith('ru')) { + updateState({ language: 'de', strings: de, themes: [{ value: 'dark', label: de.dark }, { value: 'light', label: de.light }]}); + } + else if (code && code.startsWith('ru')) { localStorage.setItem('language', 'ru'); - updateState({ - language: 'ru', - strings: ru, - themes: [ - { value: 'dark', label: ru.dark }, - { value: 'light', label: ru.light }, - ], - }); - } else { + updateState({ language: 'ru', strings: ru, themes: [{ value: 'dark', label: ru.dark }, { value: 'light', label: ru.light }]}); + } + else { localStorage.removeItem('language'); const browser = navigator.language; if (browser && browser.startsWith('fr')) { - updateState({ - language: null, - strings: fr, - themes: [ - { value: 'dark', label: fr.dark }, - { value: 'light', label: fr.light }, - ], - }); - } else if (browser && browser.startsWith('sp')) { - updateState({ - language: null, - strings: sp, - themes: [ - { value: 'dark', label: sp.dark }, - { value: 'light', label: sp.light }, - ], - }); - } else if (browser && browser.startsWith('pt')) { - updateState({ - language: null, - strings: pt, - themes: [ - { value: 'dark', label: pt.dark }, - { value: 'light', label: pt.light }, - ], - }); - } else if (browser && browser.startsWith('de')) { - updateState({ - language: null, - strings: de, - themes: [ - { value: 'dark', label: de.dark }, - { value: 'light', label: de.light }, - ], - }); - } else if (browser && browser.startsWith('ru')) { - updateState({ - language: null, - strings: ru, - themes: [ - { value: 'dark', label: ru.dark }, - { value: 'light', label: ru.light }, - ], - }); - } else { - updateState({ - language: null, - strings: en, - themes: [ - { value: 'dark', label: en.dark }, - { value: 'light', label: en.light }, - ], - }); + updateState({ language: null, strings: fr, themes: [{ value: 'dark', label: fr.dark }, { value: 'light', label: fr.light }]}); + } + else if (browser && browser.startsWith('sp')) { + updateState({ language: null, strings: sp, themes: [{ value: 'dark', label: sp.dark }, { value: 'light', label: sp.light }]}); + } + else if (browser && browser.startsWith('pt')) { + updateState({ language: null, strings: pt, themes: [{ value: 'dark', label: pt.dark }, { value: 'light', label: pt.light }]}); + } + else if (browser && browser.startsWith('de')) { + updateState({ language: null, strings: de, themes: [{ value: 'dark', label: de.dark }, { value: 'light', label: de.light }]}); + } + else if (browser && browser.startsWith('ru')) { + updateState({ language: null, strings: ru, themes: [{ value: 'dark', label: ru.dark }, { value: 'light', label: ru.light }]}); + } + else { + updateState({ language: null, strings: en, themes: [{ value: 'dark', label: en.dark }, { value: 'light', label: en.light }]}); } } }, @@ -448,7 +263,9 @@ export function useSettingsContext() { localStorage.setItem('video_input', videoId); updateState({ videoId }); }, - }; + } - return { state, actions }; + return { state, actions } } + + diff --git a/net/web/src/context/useStoreContext.hook.ts b/net/web/src/context/useStoreContext.hook.ts index ca8e46a7..a7585dfb 100644 --- a/net/web/src/context/useStoreContext.hook.ts +++ b/net/web/src/context/useStoreContext.hook.ts @@ -1,20 +1,21 @@ import { useEffect, useState } from 'react'; -export const defaultStoreContext = { +export const defaultStoreContext = { state: {} as Record, actions: { - clear: () => {}, - setValue: (key: any, value: any) => {}, - getValue: (key: any) => undefined as any, - }, -}; + clear: () => {}, + setValue: (key: any, value: any) => {}, + getValue: (key: any) => undefined as any, + } +} export function useStoreContext() { + const [state, setState] = useState({}); const resetState = () => { setState((s) => { localStorage.setItem('store', JSON.stringify({})); - return {}; + return {} }); }; @@ -42,8 +43,10 @@ export function useStoreContext() { }, getValue: (key) => { return state[key]; - }, - }; + } + } - return { state, actions }; + return { state, actions } } + + diff --git a/net/web/src/context/useUploadContext.hook.ts b/net/web/src/context/useUploadContext.hook.ts index 9e952e9b..f15427f7 100644 --- a/net/web/src/context/useUploadContext.hook.ts +++ b/net/web/src/context/useUploadContext.hook.ts @@ -1,21 +1,22 @@ import { useState, useRef } from 'react'; import axios from 'axios'; -import Resizer from 'react-image-file-resizer'; +import Resizer from "react-image-file-resizer"; -const ENCRYPTED_BLOCK_SIZE = 256 * 1024; -const IMAGE_SCALE_SIZE = 128 * 1024; +const ENCRYPTED_BLOCK_SIZE = (256 * 1024); +const IMAGE_SCALE_SIZE = (128 * 1024); const GIF_TYPE = 'image/gif'; const WEBP_TYPE = 'image/webp'; const defaultState = { progress: new Map(), -}; +} export const defaultUploadContext = { - state: defaultState, - actions: {} as ReturnType['actions'], -}; + state:defaultState, + actions: {} as ReturnType["actions"] +} export function useUploadContext() { + const [state, setState] = useState(defaultState); const channels = useRef(new Map()); const index = useRef(0); @@ -30,7 +31,7 @@ export function useUploadContext() { topics.delete(topic); } updateProgress(); - }; + } const updateProgress = () => { let progress = new Map(); @@ -49,14 +50,11 @@ export function useUploadContext() { }); }); if (assets.length) { - progress.set( - channel, - assets.sort((a, b) => (a.upload < b.upload ? 1 : -1)), - ); + progress.set(channel, assets.sort((a, b) => (a.upload < b.upload) ? 1 : -1)); } }); updateState({ progress }); - }; + } const abort = (channelId, topicId) => { const channel = channels.current.get(channelId); @@ -68,16 +66,16 @@ export function useUploadContext() { updateProgress(); } } - }; + } const actions = { addTopic: (token, channelId, topicId, files, success, failure, contact?) => { if (contact) { const { server, cardId } = contact; - let host = ''; + let host = ""; if (server) { - host = `https://${server}`; + host = `https://${server}` } const controller = new AbortController(); @@ -92,7 +90,7 @@ export function useUploadContext() { success, failure, cancel: controller, - }; + } index.current += 1; const key = `${cardId}:${channelId}`; if (!channels.current.has(key)) { @@ -100,10 +98,9 @@ export function useUploadContext() { } const topics = channels.current.get(key); topics.set(topicId, entry); - upload(entry, updateProgress, () => { - updateComplete(key, topicId); - }); - } else { + upload(entry, updateProgress, () => { updateComplete(key, topicId) }); + } + else { const controller = new AbortController(); const entry = { index: index.current, @@ -116,7 +113,7 @@ export function useUploadContext() { success, failure, cancel: controller, - }; + } index.current += 1; const key = `:${channelId}`; if (!channels.current.has(key)) { @@ -124,15 +121,14 @@ export function useUploadContext() { } const topics = channels.current.get(key); topics.set(topicId, entry); - upload(entry, updateProgress, () => { - updateComplete(key, topicId); - }); + upload(entry, updateProgress, () => { updateComplete(key, topicId) } ); } }, cancelTopic: (channelId, topicId, cardId) => { if (cardId) { abort(`${cardId}:${channelId}`, topicId); - } else { + } + else { abort(`:${channelId}`, topicId); } }, @@ -157,10 +153,10 @@ export function useUploadContext() { }); channels.current.clear(); updateProgress(); - }, - }; + } + } - return { state, actions }; + return { state, actions } } function getImageThumb(data) { @@ -174,21 +170,12 @@ function getImageThumb(data) { reader.onerror = function (error) { reject(); }; - } else { - Resizer.imageFileResizer( - data, - 192, - 192, - 'JPEG', - 50, - 0, - (uri) => { - resolve(uri); - }, - 'base64', - 128, - 128, - ); + } + else { + Resizer.imageFileResizer(data, 192, 192, 'JPEG', 50, 0, + uri => { + resolve(uri); + }, 'base64', 128, 128 ); } }); } @@ -196,29 +183,30 @@ function getImageThumb(data) { function getVideoThumb(data, pos) { return new Promise((resolve, reject) => { const url = URL.createObjectURL(data); - var video = document.createElement('video'); + var video = document.createElement("video"); var timeupdate = function (ev) { - video.removeEventListener('timeupdate', timeupdate); + video.removeEventListener("timeupdate", timeupdate); video.pause(); setTimeout(() => { - var canvas = document.createElement('canvas'); + var canvas = document.createElement("canvas"); if (video.videoWidth > video.videoHeight) { canvas.width = 192; - canvas.height = Math.floor((192 * video.videoHeight) / video.videoWidth); - } else { - canvas.height = 192; - canvas.width = Math.floor((192 * video.videoWidth) / video.videoHeight); + canvas.height = Math.floor((192 * video.videoHeight / video.videoWidth)); } - canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height); - var image = canvas.toDataURL('image/jpeg', 0.75); + else { + canvas.height = 192; + canvas.width = Math.floor((192 * video.videoWidth / video.videoHeight)); + } + canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height); + var image = canvas.toDataURL("image/jpeg", 0.75); resolve(image); canvas.remove(); video.remove(); URL.revokeObjectURL(url); }, 1000); }; - video.addEventListener('timeupdate', timeupdate); - video.preload = 'metadata'; + video.addEventListener("timeupdate", timeupdate); + video.preload = "metadata"; video.src = url; video.muted = true; video.playsInline = true; @@ -228,11 +216,14 @@ function getVideoThumb(data, pos) { } async function getThumb(data, type, position) { + if (type === 'image') { return await getImageThumb(data); - } else if (type === 'video') { + } + else if (type === 'video') { return await getVideoThumb(data, position); - } else { + } + else { return null; } } @@ -241,103 +232,102 @@ async function upload(entry, update, complete) { if (!entry.files?.length) { entry.success(entry.assets); complete(); - } else { + } + else { const file = entry.files.shift(); entry.active = {}; try { if (file.encrypted) { const { size, getEncryptedBlock, position, label, extension, image, video, audio, binary } = file; - const { data, type } = image - ? { data: image, type: 'image' } - : video - ? { data: video, type: 'video' } - : audio - ? { data: audio, type: 'audio' } - : { data: binary, type: 'binary' }; + const { data, type } = image ? { data: image, type: 'image' } : video ? { data: video, type: 'video' } : audio ? { data: audio, type: 'audio' } : { data: binary, type: 'binary' } const thumb = await getThumb(data, type, position); const parts = []; for (let pos = 0; pos < size; pos += ENCRYPTED_BLOCK_SIZE) { const len = pos + ENCRYPTED_BLOCK_SIZE > size ? size - pos : ENCRYPTED_BLOCK_SIZE; const { blockEncrypted, blockIv } = await getEncryptedBlock(pos, len); const part = await axios.post(`${entry.baseUrl}blocks${entry.urlParams}`, blockEncrypted, { - headers: { 'Content-Type': 'text/plain' }, + headers: {'Content-Type': 'text/plain'}, signal: entry.cancel.signal, onUploadProgress: (ev) => { const { loaded, total } = ev; - const partLoaded = pos + Math.floor((len * loaded) / total); - entry.active = { loaded: partLoaded, total: size }; + const partLoaded = pos + Math.floor(len * loaded / total); + entry.active = { loaded: partLoaded, total: size } update(); - }, + } }); parts.push({ blockIv, partId: part.data.assetId }); } entry.assets.push({ - encrypted: { type, thumb, label, extension, parts }, + encrypted: { type, thumb, label, extension, parts } }); - } else if (file.image) { + } + else if (file.image) { const formData = new FormData(); formData.append('asset', file.image); - let transform = encodeURIComponent(JSON.stringify(['ithumb;photo', 'ilg;photo'])); + let transform = encodeURIComponent(JSON.stringify(["ithumb;photo", "ilg;photo"])); let asset = await axios.post(`${entry.baseUrl}assets${entry.urlParams}&transforms=${transform}`, formData, { signal: entry.cancel.signal, onUploadProgress: (ev) => { const { loaded, total } = ev; - entry.active = { loaded, total }; + entry.active = { loaded, total } update(); }, }); entry.assets.push({ image: { - thumb: asset.data.find((item) => item.transform === 'ithumb;photo').assetId, - full: asset.data.find((item) => item.transform === 'ilg;photo').assetId, - }, + thumb: asset.data.find(item => item.transform === 'ithumb;photo').assetId, + full: asset.data.find(item => item.transform === 'ilg;photo').assetId, + } }); - } else if (file.video) { + } + else if (file.video) { const formData = new FormData(); formData.append('asset', file.video); let thumb = 'vthumb;video;' + file.position; - let transform = encodeURIComponent(JSON.stringify(['vlq;video', 'vhd;video', thumb])); + let transform = encodeURIComponent(JSON.stringify(["vlq;video", "vhd;video", thumb])); let asset = await axios.post(`${entry.baseUrl}assets${entry.urlParams}&transforms=${transform}`, formData, { signal: entry.cancel.signal, onUploadProgress: (ev) => { const { loaded, total } = ev; - entry.active = { loaded, total }; + entry.active = { loaded, total } update(); }, }); entry.assets.push({ video: { - thumb: asset.data.find((item) => item.transform === thumb).assetId, - lq: asset.data.find((item) => item.transform === 'vlq;video').assetId, - hd: asset.data.find((item) => item.transform === 'vhd;video').assetId, - }, + thumb: asset.data.find(item => item.transform === thumb).assetId, + lq: asset.data.find(item => item.transform === 'vlq;video').assetId, + hd: asset.data.find(item => item.transform === 'vhd;video').assetId, + } }); - } else if (file.audio) { + } + else if (file.audio) { const formData = new FormData(); formData.append('asset', file.audio); - let transform = encodeURIComponent(JSON.stringify(['acopy;audio'])); + let transform = encodeURIComponent(JSON.stringify(["acopy;audio"])); let asset = await axios.post(`${entry.baseUrl}assets${entry.urlParams}&transforms=${transform}`, formData, { signal: entry.cancel.signal, onUploadProgress: (ev) => { const { loaded, total } = ev; - entry.active = { loaded, total }; + entry.active = { loaded, total } update(); }, }); entry.assets.push({ audio: { label: file.label, - full: asset.data.find((item) => item.transform === 'acopy;audio').assetId, - }, + full: asset.data.find(item => item.transform === 'acopy;audio').assetId, + } }); - } else if (file.binary) { + } + else if (file.binary) { const formData = new FormData(); formData.append('asset', file.binary); let asset = await axios.post(`${entry.baseUrl}blocks${entry.urlParams}&body=multipart`, formData, { signal: entry.cancel.signal, onUploadProgress: (ev) => { const { loaded, total } = ev; - entry.active = { loaded, total }; + entry.active = { loaded, total } update(); }, }); @@ -346,12 +336,13 @@ async function upload(entry, update, complete) { label: file.label, extension: file.extension, data: asset.data.assetId, - }, + } }); } entry.active = null; upload(entry, update, complete); - } catch (err) { + } + catch (err) { console.log(err); entry.failure(); entry.error = true; @@ -359,3 +350,4 @@ async function upload(entry, update, complete) { } } } + diff --git a/net/web/src/dashboard/Dashboard.styled.ts b/net/web/src/dashboard/Dashboard.styled.ts index 52c8e1d6..6c990b0d 100644 --- a/net/web/src/dashboard/Dashboard.styled.ts +++ b/net/web/src/dashboard/Dashboard.styled.ts @@ -11,9 +11,9 @@ export const DashboardWrapper = styled.div` height: 100%; padding-left: 8px; padding-right: 8px; - background-color: ${(props) => props.theme.baseArea}; - color: ${(props) => props.theme.hintText}; - + background-color: ${props => props.theme.baseArea}; + color: ${props => props.theme.hintText}; + .container { display: flex; flex-direction: column; @@ -23,21 +23,21 @@ export const DashboardWrapper = styled.div` border-radius: 4px; max-width: 100%; max-height: 80%; - background-color: ${(props) => props.theme.itemArea}; + background-color: ${props => props.theme.itemArea}; .header { - color: ${(props) => props.theme.hintText}; + color: ${props => props.theme.hintText}; display: flex; flex-direction: row; font-size: 20px; - border-bottom: 1px solid ${(props) => props.theme.headerBorder}; + border-bottom: 1px solid ${props => props.theme.headerBorder}; } .body { padding-top: 8px; min-height: 0; overflow: auto; - border-bottom: 1px solid ${(props) => props.theme.headerBorder}; + border-bottom: 1px solid ${props => props.theme.headerBorder}; margin-bottom: 16px; } @@ -83,7 +83,7 @@ export const AlertIcon = styled.div` align-items: center; color: ${Colors.alert}; padding-left: 8px; -`; +` export const SettingsLayout = styled(Space)` width: 100%; @@ -151,8 +151,8 @@ export const CreateLayout = styled.div` white-space: nowrap; min-width: 0; padding-right: 8px; - } - + } + .link { text-overflow: ellipsis; overflow: hidden; @@ -162,4 +162,4 @@ export const CreateLayout = styled.div` padding-right: 8px; } } -`; +` diff --git a/net/web/src/dashboard/Dashboard.tsx b/net/web/src/dashboard/Dashboard.tsx index 407f23f5..d3cb2d84 100644 --- a/net/web/src/dashboard/Dashboard.tsx +++ b/net/web/src/dashboard/Dashboard.tsx @@ -1,25 +1,13 @@ -import { - AlertIcon, - DashboardWrapper, - SettingsButton, - AddButton, - SettingsLayout, - CreateLayout, -} from './Dashboard.styled'; +import { AlertIcon, DashboardWrapper, SettingsButton, AddButton, SettingsLayout, CreateLayout } from './Dashboard.styled'; import { Tooltip, Switch, Select, Button, Space, Modal, Input, InputNumber, List } from 'antd'; -import { - ExclamationCircleOutlined, - SettingOutlined, - UserAddOutlined, - LogoutOutlined, - ReloadOutlined, -} from '@ant-design/icons'; -import { ThemeProvider } from 'styled-components'; +import { ExclamationCircleOutlined, SettingOutlined, UserAddOutlined, LogoutOutlined, ReloadOutlined } from '@ant-design/icons'; +import { ThemeProvider } from "styled-components"; import { useDashboard } from './useDashboard.hook'; import { AccountItem } from './accountItem/AccountItem'; import { CopyButton } from './copyButton/CopyButton'; export function Dashboard() { + const { state, actions } = useDashboard(); const onClipboard = async (value) => { @@ -35,158 +23,63 @@ export function Dashboard() {
-
{state.strings.accounts}
- {state.display === 'small' && ( +
{ state.strings.accounts }
+ { state.display === 'small' && ( <>
- - } - onClick={() => actions.reload()} - > + } + onClick={() => actions.reload()}>
- - } - onClick={() => actions.setShowSettings(true)} - > + } + onClick={() => actions.setShowSettings(true)}>
- - } - onClick={() => actions.logout()} - > + } + onClick={() => actions.logout()}>
- {(state.configError || state.accountsError) && ( + { (state.configError || state.accountsError) && ( - + )}
- - } - loading={state.createBusy} - onClick={() => actions.setCreateLink()} - > + } + loading={state.createBusy} onClick={() => actions.setCreateLink()}>
)} - {state.display !== 'small' && ( + { state.display !== 'small' && ( <>
- - - } - onClick={() => actions.reload()} - > + + } + onClick={() => actions.reload()}>
- - - } - onClick={() => actions.setShowSettings(true)} - > + + } + onClick={() => actions.setShowSettings(true)}>
- - - } - onClick={() => actions.logout()} - > + + } + onClick={() => actions.logout()}>
- {(state.configError || state.accountsError) && ( - + { (state.configError || state.accountsError) && ( + - + )}
- - - } - loading={state.createBusy} - onClick={() => actions.setCreateLink()} - > + + } + loading={state.createBusy} onClick={() => actions.setCreateLink()}>
@@ -198,212 +91,109 @@ export function Dashboard() { itemLayout="horizontal" dataSource={state.accounts} loading={state.loading} - renderItem={(item) => ( - - )} + renderItem={item => ()} />
- actions.setShowSettings(false)} - > - + actions.setShowSettings(false)}> +
{state.strings.settings}
-
{state.strings.federatedHost}
- actions.setHost(e.target.value)} - value={state.domain} - /> +
{ state.strings.federatedHost }
+ actions.setHost(e.target.value)} + value={state.domain} />
{state.strings.storageLimit}
- actions.setStorage(e)} - placeholder={state.strings.storageHint} - value={state.accountStorage} - /> + actions.setStorage(e)} + placeholder={state.strings.storageHint} value={state.accountStorage} />
{state.strings.keyType}
- actions.setKeyType(o.value)}> RSA 2048 RSA 4096
- +
{state.strings.accountCreation}
- actions.setEnableOpenAccess(e)} - size="small" - defaultChecked={false} - checked={state.enableOpenAccess} - /> - {state.enableOpenAccess && ( - actions.setOpenAccessLimit(e)} - placeholder={state.strings.limit} - value={state.openAccessLimit} - /> + actions.setEnableOpenAccess(e)} size="small" + defaultChecked={false} checked={state.enableOpenAccess} /> + { state.enableOpenAccess && ( + actions.setOpenAccessLimit(e)} + placeholder={state.strings.limit} value={state.openAccessLimit} /> )}
{state.strings.enablePush}
- actions.setPushSupported(e)} - size="small" - defaultChecked={true} - checked={state.pushSupported} - /> + actions.setPushSupported(e)} size="small" + defaultChecked={true} checked={state.pushSupported} />
- {state.transformSupported && ( + { state.transformSupported && (
{state.strings.allowUnsealed}
- actions.setAllowUnsealed(e)} - size="small" - defaultChecked={true} - checked={state.allowUnsealed} - /> + actions.setAllowUnsealed(e)} size="small" + defaultChecked={true} checked={state.allowUnsealed} />
)}
{state.strings.topicContent}
- +
{state.strings.enableImage}
- actions.setEnableImage(e)} - size="small" - defaultChecked={true} - checked={state.enableImage} - /> + actions.setEnableImage(e)} size="small" + defaultChecked={true} checked={state.enableImage} />
- +
{state.strings.enableAudio}
- actions.setEnableAudio(e)} - size="small" - defaultChecked={true} - checked={state.enableAudio} - /> + actions.setEnableAudio(e)} size="small" + defaultChecked={true} checked={state.enableAudio} />
- +
{state.strings.enableVideo}
- actions.setEnableVideo(e)} - size="small" - defaultChecked={true} - checked={state.enableVideo} - /> + actions.setEnableVideo(e)} size="small" + defaultChecked={true} checked={state.enableVideo} />
- +
{state.strings.enableWeb}
- actions.setEnableIce(e)} - size="small" - defaultChecked={false} - checked={state.enableIce} - /> + actions.setEnableIce(e)} size="small" + defaultChecked={false} checked={state.enableIce} />
{state.strings.serverUrl}
- actions.setIceUrl(e.target.value)} - disabled={!state.enableIce} - value={state.iceUrl} - /> + actions.setIceUrl(e.target.value)} + disabled={!state.enableIce} value={state.iceUrl} />
{state.strings.webUsername}
- actions.setIceUsername(e.target.value)} - disabled={!state.enableIce} - value={state.iceUsername} - /> + actions.setIceUsername(e.target.value)} + disabled={!state.enableIce} value={state.iceUsername} />
{state.strings.webPassword}
- actions.setIcePassword(e.target.value)} - disabled={!state.enableIce} - value={state.icePassword} - /> + actions.setIcePassword(e.target.value)} + disabled={!state.enableIce} value={state.icePassword} />
- - + +
- actions.setShowCreate(false)} - > + actions.setShowCreate(false)}>
{state.strings.createAccount}
@@ -417,16 +207,12 @@ export function Dashboard() { await onClipboard(state.createToken)} />
- +
-
+
); } + diff --git a/net/web/src/dashboard/accountItem/AccountItem.styled.ts b/net/web/src/dashboard/accountItem/AccountItem.styled.ts index 6f4f31ff..72d5b6c8 100644 --- a/net/web/src/dashboard/accountItem/AccountItem.styled.ts +++ b/net/web/src/dashboard/accountItem/AccountItem.styled.ts @@ -10,12 +10,12 @@ export const AccountItemWrapper = styled.div` padding-right: 16px; padding-top: 2px; padding-bottom: 2px; - border-bottom: 1px solid ${(props) => props.theme.itemBorder}; + border-bottom: 1px solid ${props => props.theme.itemBorder}; align-items: center; - color: ${(props) => props.theme.mainText}; + color: ${props => props.theme.mainText}; &:hover { - background-color: ${(props) => props.theme.hoverArea}; + background-color: ${props => props.theme.hoverArea}; } .avatar { @@ -53,9 +53,9 @@ export const AccountItemWrapper = styled.div` } .storage { - color: ${(props) => props.theme.hintText}; + color: ${props => props.theme.hintText}; padding-left: 8px; - } + } .guid { font-size: 0.8em; @@ -87,7 +87,7 @@ export const ResetButton = styled(Button)` export const DeleteButton = styled(Button)` color: red; -`; +` export const AccessLayout = styled.div` .control { @@ -119,8 +119,8 @@ export const AccessLayout = styled.div` white-space: nowrap; min-width: 0; padding-right: 8px; - } - + } + .link { text-overflow: ellipsis; overflow: hidden; @@ -130,4 +130,4 @@ export const AccessLayout = styled.div` padding-right: 8px; } } -`; +` diff --git a/net/web/src/dashboard/accountItem/AccountItem.tsx b/net/web/src/dashboard/accountItem/AccountItem.tsx index 996035a4..9e341a26 100644 --- a/net/web/src/dashboard/accountItem/AccountItem.tsx +++ b/net/web/src/dashboard/accountItem/AccountItem.tsx @@ -1,25 +1,13 @@ import { Logo } from 'logo/Logo'; -import { - AccountItemWrapper, - AccessLayout, - DeleteButton, - EnableButton, - DisableButton, - ResetButton, -} from './AccountItem.styled'; +import { AccountItemWrapper, AccessLayout, DeleteButton, EnableButton, DisableButton, ResetButton } from './AccountItem.styled'; import { useAccountItem } from './useAccountItem.hook'; -import { - ExclamationCircleOutlined, - UserDeleteOutlined, - UnlockOutlined, - CloseCircleOutlined, - CheckCircleOutlined, -} from '@ant-design/icons'; +import { ExclamationCircleOutlined, UserDeleteOutlined, UnlockOutlined, CloseCircleOutlined, CheckCircleOutlined } from '@ant-design/icons'; import { Modal, Tooltip, Button } from 'antd'; import { CopyButton } from '../copyButton/CopyButton'; export function AccountItem({ item, remove }) { - const [modal, modalContext] = Modal.useModal(); + + const [ modal, modalContext ] = Modal.useModal(); const { state, actions } = useAccountItem(item, remove); const removeAccount = () => { @@ -35,43 +23,46 @@ export function AccountItem({ item, remove }) { }, onCancel() {}, }); - }; + } const applyRemoveAccount = async () => { try { await actions.remove(); - } catch (err) { + } + catch(err) { modal.error({ title: {state.strings.operationFailed}, content: {state.strings.tryAgain}, bodyStyle: { borderRadius: 8, padding: 16, ...state.menuStyle }, }); } - }; + } const applyAccountStatus = async (status) => { try { await actions.setStatus(status); - } catch (err) { + } + catch(err) { modal.error({ title: {state.strings.operationFailed}, content: {state.strings.tryAgain}, bodyStyle: { borderRadius: 8, padding: 16, ...state.menuStyle }, }); } - }; + } const setAccountAccess = async () => { try { await actions.setAccessLink(); - } catch (err) { + } + catch(err) { modal.error({ title: {state.strings.operationFailed}, content: {state.strings.tryAgain}, bodyStyle: { borderRadius: 8, padding: 16, ...state.menuStyle }, }); } - }; + } const onClipboard = (value) => { navigator.clipboard.writeText(value); @@ -83,151 +74,81 @@ export function AccountItem({ item, remove }) { return ( - {modalContext} + { modalContext }
- +
- {state.handle} - {state?.storage > 0 && ( - - {state.storage} {state.storageUnit} - + { state.handle } + { state?.storage > 0 && ( + { state.storage } { state.storageUnit } )}
-
{state.guid}
+
{ state.guid }
- {state.display === 'small' && ( + { state.display === 'small' && ( <> - } - loading={state.accessBusy} - onClick={setAccountAccess} - > - {state.disabled && ( - } - loading={state.statusBusy} - onClick={() => applyAccountStatus(false)} - > + } + loading={state.accessBusy} onClick={setAccountAccess}> + { state.disabled && ( + } + loading={state.statusBusy} onClick={() => applyAccountStatus(false)}> )} - {!state.disabled && ( - } - loading={state.statusBusy} - onClick={() => applyAccountStatus(true)} - > + { !state.disabled && ( + } + loading={state.statusBusy} onClick={() => applyAccountStatus(true)}> )} - } - loading={state.removeBusy} - onClick={removeAccount} - > + } + loading={state.removeBusy} onClick={removeAccount}> )} - {state.display !== 'small' && ( + { state.display !== 'small' && ( <> - - } - loading={state.accessBusy} - onClick={setAccountAccess} - > + + } + loading={state.accessBusy} onClick={setAccountAccess}> - {state.disabled && ( - - } - loading={state.statusBusy} - onClick={() => applyAccountStatus(false)} - > + { state.disabled && ( + + } + loading={state.statusBusy} onClick={() => applyAccountStatus(false)}> )} - {!state.disabled && ( - - } - loading={state.statusBusy} - onClick={() => applyAccountStatus(true)} - > + { !state.disabled && ( + + } + loading={state.statusBusy} onClick={() => applyAccountStatus(true)}> )} - - } - loading={state.removeBusy} - onClick={removeAccount} - > + + } + loading={state.removeBusy} onClick={removeAccount}> )}
- actions.setShowAccess(false)} - > + actions.setShowAccess(false)}> -
{state.strings.accessAccount}
+
{ state.strings.accessAccount }
-
{state.strings.browserLink}
+
{ state.strings.browserLink }
{accessLink()}
await onClipboard(accessLink())} />
-
{state.strings.mobileToken}
+
{ state.strings.mobileToken }
{state.accessToken}
await onClipboard(state.accessToken)} />
- +
-
+
); } + diff --git a/net/web/src/dashboard/accountItem/useAccountItem.hook.ts b/net/web/src/dashboard/accountItem/useAccountItem.hook.ts index 5edd6cb6..62e88503 100644 --- a/net/web/src/dashboard/accountItem/useAccountItem.hook.ts +++ b/net/web/src/dashboard/accountItem/useAccountItem.hook.ts @@ -6,6 +6,7 @@ import { SettingsContext } from 'context/SettingsContext'; import { AppContext } from 'context/AppContext'; export function useAccountItem(item, remove) { + const [state, setState] = useState({ statusBusy: false, removeBusy: false, @@ -13,17 +14,18 @@ export function useAccountItem(item, remove) { showAccess: false, display: null, menuStyle: {}, - strings: {} as Record, + strings: {} as Record, }); - + const app = useContext(AppContext); - const settings = useContext(SettingsContext); + const settings = useContext(SettingsContext); const updateState = (value) => { setState((s) => ({ ...s, ...value })); - }; + } useEffect(() => { + updateState({ disabled: item?.disabled, activeClass: item?.disabled ? 'inactive' : 'active', @@ -31,13 +33,11 @@ export function useAccountItem(item, remove) { name: item?.name, guid: item?.guid, handle: item?.handle, - storage: Math.floor( - item?.storageUsed > 1073741824 ? item?.storageUsed / 1073741824 : item?.storageUsed / 1048576, - ), + storage: Math.floor(item?.storageUsed > 1073741824 ? item?.storageUsed / 1073741824 : item?.storageUsed / 1048576), storageUnit: item?.storageUsed > 1073741824 ? state.strings.gb : state.strings.mb, imageUrl: item?.imageSet ? getAccountImageUrl(app.state.adminToken, item?.accountId) : null, }); - }, [app.state.adminToken, item, state.strings]); + }, [app.state.adminToken, item, state.strings]); useEffect(() => { const { display, menuStyle, strings } = settings.state; @@ -51,7 +51,8 @@ export function useAccountItem(item, remove) { try { const access = await addAccountAccess(app.state.adminToken, item.accountId); updateState({ accessToken: access, showAccess: true, accessBusy: false }); - } catch (err) { + } + catch (err) { console.log(err); updateState({ accessBusy: false }); throw new Error('failed to generate token'); @@ -67,7 +68,8 @@ export function useAccountItem(item, remove) { try { await remove(state.accountId); updateState({ removeBusy: false }); - } catch (err) { + } + catch(err) { console.log(err); updateState({ removeBusy: false }); throw new Error('failed to remove account'); @@ -80,10 +82,11 @@ export function useAccountItem(item, remove) { try { await setAccountStatus(app.state.adminToken, item.accountId, disabled); updateState({ statusBusy: false, disabled, activeClass: disabled ? 'inactive' : 'active' }); - } catch (err) { + } + catch(err) { console.log(err); updateState({ statusBusy: false }); - throw new Error('failed to set account status'); + throw new Error('failed to set account status'); } } }, diff --git a/net/web/src/dashboard/copyButton/CopyButton.tsx b/net/web/src/dashboard/copyButton/CopyButton.tsx index 04efbd12..f9eb4769 100644 --- a/net/web/src/dashboard/copyButton/CopyButton.tsx +++ b/net/web/src/dashboard/copyButton/CopyButton.tsx @@ -3,21 +3,13 @@ import { Tooltip, Button } from 'antd'; import { CopyOutlined } from '@ant-design/icons'; export function CopyButton({ onCopy }) { + const { state, actions } = useCopyButton(); return ( - -
); } setRinging(incoming); @@ -102,26 +88,26 @@ export function Session() { const closeAccount = () => { actions.closeProfile(); actions.closeAccount(); - }; + } const openAccount = () => { actions.openAccount(); actions.closeCards(); actions.closeContact(); actions.closeListing(); - }; + } const closeCards = () => { actions.closeCards(); actions.closeContact(); actions.closeListing(); - }; + } const openCards = () => { actions.openCards(); actions.closeProfile(); actions.closeAccount(); - }; + } const openConversation = (channelId, cardId) => { actions.openConversation(channelId, cardId); @@ -129,37 +115,30 @@ export function Session() { actions.closeContact(); actions.closeAccount(); actions.closeProfile(); - }; + } const closeConversation = () => { actions.closeConversation(); actions.closeDetails(); - }; + } const drawerStyle = { overscrollBehavior: 'none', padding: 0, backgroundColor: settings.state.colors.baseArea }; return ( - {state.display === 'xlarge' && ( + { (state.display === 'xlarge') && (
- +
- + }} />
- {state.loading && ( + { state.loading && (
@@ -169,97 +148,62 @@ export function Session() {
- {state.conversation && ( + { state.conversation && (
- +
)} - {state.contact && ( + { state.contact && (
- +
)} - {state.profile && ( + { state.profile && (
)}
- {(state.conversation || state.details) && ( + { (state.conversation || state.details) && (
-
+
)} - {state.cards && ( + { state.cards && (
- - - + + +
)} - {(state.profile || state.account) && ( + { (state.profile || state.account) && (
- +
)}
)} - {(state.display === 'large' || state.display === 'medium') && ( + { (state.display === 'large' || state.display === 'medium') && (
- +
- + }} />
- {state.loading && ( + { state.loading && (
@@ -269,309 +213,169 @@ export function Session() {
- {state.conversation && ( + { state.conversation && (
- +
)} - - {state.details && ( -
+ + { state.details && ( +
)} - - {state.cards && ( - + + { state.cards && ( + )} - - + + - - {state.contact && ( - + + { state.contact && ( + )} - - {(state.profile || state.account) && } + + { (state.profile || state.account) && ( + + )}
)} - {state.display === 'small' && ( + { (state.display === 'small') && (
- + }} />
- {state.conversation && ( + { state.conversation && (
- +
)} - {state.details && ( + { state.details && (
-
+
)} - {state.cards && ( + { state.cards && (
- +
)} - {state.listing && ( + { state.listing && (
- +
)} - {state.contact && ( + { state.contact && (
- +
)} - {state.loading && ( + { state.loading && (
)} - {(state.profile || state.account) && ( + { (state.profile || state.account) && (
)}
- +
)} - 0 && state.callStatus == null} - footer={null} - closable={false} - > + 0 && state.callStatus == null} footer={null} closable={false}> -
{ringing}
+
+ {ringing} +
- + -
+
- {!state.remoteVideo && ( + { !state.remoteVideo && (
- {state.callLogo && ( - logo + { state.callLogo && ( + logo )} - {!state.callLogo && ( - default logo + { !state.callLogo && ( + default logo )}
)} - {state.remoteStream && ( -