1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
|
import './Connections.css';
import React from 'react';
import { Pause, Play, X as IconClose } from 'react-feather';
import { useTranslation } from 'react-i18next';
import { Tab, TabList, TabPanel, Tabs } from 'react-tabs';
import { ConnectionItem } from 'src/api/connections';
import { State } from 'src/store/types';
import * as connAPI from '../api/connections';
import useRemainingViewPortHeight from '../hooks/useRemainingViewPortHeight';
import { getClashAPIConfig } from '../store/app';
import s from './Connections.module.scss';
import ConnectionTable from './ConnectionTable';
import ContentHeader from './ContentHeader';
import ModalCloseAllConnections from './ModalCloseAllConnections';
import { Action, Fab, position as fabPosition } from './shared/Fab';
import { connect } from './StateProvider';
import SvgYacd from './SvgYacd';
const { useEffect, useState, useRef, useCallback } = React;
const paddingBottom = 30;
function arrayToIdKv<T extends { id: string }>(items: T[]) {
const o = {};
for (let i = 0; i < items.length; i++) {
const item = items[i];
o[item.id] = item;
}
return o;
}
type FormattedConn = {
id: string;
upload: number;
download: number;
start: number;
chains: string;
rule: string;
destinationPort: string;
destinationIP: string;
sourceIP: string;
sourcePort: string;
source: string;
host: string;
type: string;
network: string;
downloadSpeedCurr?: number;
uploadSpeedCurr?: number;
};
function hasSubstring(s: string, pat: string) {
return s.toLowerCase().includes(pat.toLowerCase());
}
function filterConns(conns: FormattedConn[], keyword: string) {
return !keyword
? conns
: conns.filter((conn) =>
[
conn.host,
conn.sourceIP,
conn.sourcePort,
conn.destinationIP,
conn.chains,
conn.rule,
conn.type,
conn.network,
].some((field) => hasSubstring(field, keyword))
);
}
function formatConnectionDataItem(
i: ConnectionItem,
prevKv: Record<string, { upload: number; download: number }>,
now: number
): FormattedConn {
const { id, metadata, upload, download, start, chains, rule, rulePayload } = i;
const { host, destinationPort, destinationIP, network, type, sourceIP, sourcePort } = metadata;
// host could be an empty string if it's direct IP connection
let host2 = host;
if (host2 === '') host2 = destinationIP;
const prev = prevKv[id];
const ret = {
id,
upload,
download,
start: now - new Date(start).valueOf(),
chains: chains.reverse().join(' / '),
rule: !rulePayload ? rule : `${rule}(${rulePayload})`,
...metadata,
host: `${host2}:${destinationPort}`,
type: `${type}(${network})`,
source: `${sourceIP}:${sourcePort}`,
downloadSpeedCurr: download - (prev ? prev.download : 0),
uploadSpeedCurr: upload - (prev ? prev.upload : 0),
};
return ret;
}
function renderTableOrPlaceholder(conns: FormattedConn[]) {
return conns.length > 0 ? (
<ConnectionTable data={conns} />
) : (
<div className={s.placeHolder}>
<SvgYacd width={200} height={200} c1="var(--color-text)" />
</div>
);
}
function ConnQty({ qty }) {
return qty < 100 ? '' + qty : '99+';
}
function Conn({ apiConfig }) {
const [refContainer, containerHeight] = useRemainingViewPortHeight();
const [conns, setConns] = useState([]);
const [closedConns, setClosedConns] = useState([]);
const [filterKeyword, setFilterKeyword] = useState('');
const filteredConns = filterConns(conns, filterKeyword);
const filteredClosedConns = filterConns(closedConns, filterKeyword);
const [isCloseAllModalOpen, setIsCloseAllModalOpen] = useState(false);
const openCloseAllModal = useCallback(() => setIsCloseAllModalOpen(true), []);
const closeCloseAllModal = useCallback(() => setIsCloseAllModalOpen(false), []);
const [isRefreshPaused, setIsRefreshPaused] = useState(false);
const toggleIsRefreshPaused = useCallback(() => {
setIsRefreshPaused((x) => !x);
}, []);
const closeAllConnections = useCallback(() => {
connAPI.closeAllConnections(apiConfig);
closeCloseAllModal();
}, [apiConfig, closeCloseAllModal]);
const prevConnsRef = useRef(conns);
const read = useCallback(
({ connections }) => {
const prevConnsKv = arrayToIdKv(prevConnsRef.current);
const now = Date.now();
const x = connections.map((c: ConnectionItem) =>
formatConnectionDataItem(c, prevConnsKv, now)
);
const closed = [];
for (const c of prevConnsRef.current) {
const idx = x.findIndex((conn: ConnectionItem) => conn.id === c.id);
if (idx < 0) closed.push(c);
}
setClosedConns((prev) => {
// keep max 100 entries
return [...closed, ...prev].slice(0, 101);
});
// if previous connections and current connections are both empty
// arrays, we wont update state to avaoid rerender
if (x && (x.length !== 0 || prevConnsRef.current.length !== 0) && !isRefreshPaused) {
prevConnsRef.current = x;
setConns(x);
} else {
prevConnsRef.current = x;
}
},
[setConns, isRefreshPaused]
);
useEffect(() => {
return connAPI.fetchData(apiConfig, read);
}, [apiConfig, read]);
const { t } = useTranslation();
return (
<div>
<ContentHeader title={t('Connections')} />
<Tabs>
<div
style={{
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-between',
}}
>
<TabList>
<Tab>
<span>{t('Active')}</span>
<span className={s.connQty}>
{/* @ts-expect-error ts-migrate(2786) FIXME: 'ConnQty' cannot be used as a JSX component. */}
<ConnQty qty={filteredConns.length} />
</span>
</Tab>
<Tab>
<span>{t('Closed')}</span>
<span className={s.connQty}>
{/* @ts-expect-error ts-migrate(2786) FIXME: 'ConnQty' cannot be used as a JSX component. */}
<ConnQty qty={filteredClosedConns.length} />
</span>
</Tab>
</TabList>
<div className={s.inputWrapper}>
<input
type="text"
name="filter"
autoComplete="off"
className={s.input}
placeholder="Filter"
onChange={(e) => setFilterKeyword(e.target.value)}
/>
</div>
</div>
<div ref={refContainer} style={{ padding: 30, paddingBottom, paddingTop: 0 }}>
<div
style={{
height: containerHeight - paddingBottom,
overflow: 'auto',
}}
>
<TabPanel>
<>{renderTableOrPlaceholder(filteredConns)}</>
<Fab
icon={isRefreshPaused ? <Play size={16} /> : <Pause size={16} />}
mainButtonStyles={isRefreshPaused ? { background: '#e74c3c' } : {}}
style={fabPosition}
text={isRefreshPaused ? t('Resume Refresh') : t('Pause Refresh')}
onClick={toggleIsRefreshPaused}
>
<Action text="Close All Connections" onClick={openCloseAllModal}>
<IconClose size={10} />
</Action>
</Fab>
</TabPanel>
<TabPanel>{renderTableOrPlaceholder(filteredClosedConns)}</TabPanel>
</div>
</div>
<ModalCloseAllConnections
isOpen={isCloseAllModalOpen}
primaryButtonOnTap={closeAllConnections}
onRequestClose={closeCloseAllModal}
/>
</Tabs>
</div>
);
}
const mapState = (s: State) => ({
apiConfig: getClashAPIConfig(s),
});
export default connect(mapState)(Conn);
|