• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / gui / 988636826

01 Sep 2023 04:04AM UTC coverage: 82.384% (-17.6%) from 99.964%
988636826

Pull #3969

gitlab-ci

web-flow
chore: Bump autoprefixer from 10.4.14 to 10.4.15

Bumps [autoprefixer](https://github.com/postcss/autoprefixer) from 10.4.14 to 10.4.15.
- [Release notes](https://github.com/postcss/autoprefixer/releases)
- [Changelog](https://github.com/postcss/autoprefixer/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/autoprefixer/compare/10.4.14...10.4.15)

---
updated-dependencies:
- dependency-name: autoprefixer
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Pull Request #3969: chore: Bump autoprefixer from 10.4.14 to 10.4.15

4346 of 6321 branches covered (0.0%)

8259 of 10025 relevant lines covered (82.38%)

192.73 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

58.47
/src/js/components/devices/dialogs/troubleshootdialog.js
1
// Copyright 2021 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14
import React, { useCallback, useEffect, useRef, useState } from 'react';
15
import Dropzone from 'react-dropzone';
16
import { useDispatch, useSelector } from 'react-redux';
17
import { Link } from 'react-router-dom';
18

19
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Tab, Tabs } from '@mui/material';
20
import { makeStyles } from 'tss-react/mui';
21

22
import { mdiConsole as ConsoleIcon } from '@mdi/js';
23
import moment from 'moment';
24
import momentDurationFormatSetup from 'moment-duration-format';
25

26
import { setSnackbar } from '../../../actions/appActions';
27
import { deviceFileUpload, getDeviceFileDownloadLink } from '../../../actions/deviceActions';
28
import { BEGINNING_OF_TIME, TIMEOUTS } from '../../../constants/appConstants';
29
import { createDownload } from '../../../helpers';
30
import { getFeatures, getIsEnterprise, getIsPreview, getTenantCapabilities, getUserCapabilities } from '../../../selectors';
31
import { useSession } from '../../../utils/sockethook';
32
import { TwoColumns } from '../../common/configurationobject';
33
import MaterialDesignIcon from '../../common/materialdesignicon';
34
import { MaybeTime } from '../../common/time';
35
import FileTransfer from '../troubleshoot/filetransfer';
36
import Terminal from '../troubleshoot/terminal';
37
import ListOptions from '../widgets/listoptions';
38
import DeviceIdentityDisplay from './../../common/deviceidentity';
39
import { getCode } from './make-gateway-dialog';
40

41
momentDurationFormatSetup(moment);
12✔
42

43
const useStyles = makeStyles()(theme => ({
12✔
44
  content: { padding: 0, margin: '0 24px', height: '75vh' },
45
  title: { marginRight: theme.spacing(0.5) },
46
  connectionButton: { background: theme.palette.text.primary },
47
  connectedIcon: { color: theme.palette.success.main, marginLeft: theme.spacing() },
48
  disconnectedIcon: { color: theme.palette.error.main, marginLeft: theme.spacing() },
49
  sessionInfo: { maxWidth: 'max-content' },
50
  terminalContent: {
51
    display: 'grid',
52
    gridTemplateRows: 'max-content 0',
53
    flexGrow: 1,
54
    overflow: 'hidden',
55
    '&.device-connected': {
56
      gridTemplateRows: 'max-content minmax(min-content, 1fr)'
57
    }
58
  },
59
  terminalStatePlaceholder: {
60
    width: 280
61
  }
62
}));
63

64
const ConnectionIndicator = ({ isConnected }) => {
12✔
65
  const { classes } = useStyles();
1✔
66
  return (
1✔
67
    <div className="flexbox center-aligned">
68
      Remote terminal {<MaterialDesignIcon className={isConnected ? classes.connectedIcon : classes.disconnectedIcon} path={ConsoleIcon} />}
1!
69
    </div>
70
  );
71
};
72

73
const tabs = {
12✔
74
  terminal: {
75
    link: 'session logs',
76
    title: ConnectionIndicator,
77
    value: 'terminal',
78
    canShow: ({ canTroubleshoot, canWriteDevices }) => canTroubleshoot && canWriteDevices
1✔
79
  },
80
  transfer: { link: 'file transfer logs', title: () => 'File transfer', value: 'transfer', canShow: ({ canTroubleshoot }) => canTroubleshoot }
1✔
81
};
82

83
export const TroubleshootDialog = ({ device, onCancel, open, setSocketClosed, type = tabs.terminal.value }) => {
12✔
84
  const [currentTab, setCurrentTab] = useState(type);
2✔
85
  const [availableTabs, setAvailableTabs] = useState(Object.values(tabs));
2✔
86
  const [downloadPath, setDownloadPath] = useState('');
2✔
87
  const [elapsed, setElapsed] = useState(moment());
2✔
88
  const [file, setFile] = useState();
2✔
89
  const [socketInitialized, setSocketInitialized] = useState(undefined);
2✔
90
  const [startTime, setStartTime] = useState();
2✔
91
  const [uploadPath, setUploadPath] = useState('');
2✔
92
  const [terminalInput, setTerminalInput] = useState('');
2✔
93
  const [snackbarAlreadySet, setSnackbarAlreadySet] = useState(false);
2✔
94
  const snackTimer = useRef();
2✔
95
  const timer = useRef();
2✔
96
  const termRef = useRef({ terminal: React.createRef(), terminalRef: React.createRef() });
2✔
97
  const { classes } = useStyles();
2✔
98
  const { isHosted } = useSelector(getFeatures);
2✔
99
  const isEnterprise = useSelector(getIsEnterprise);
2✔
100
  const canPreview = useSelector(getIsPreview);
2✔
101
  const userCapabilities = useSelector(getUserCapabilities);
2✔
102
  const { canAuditlog, canTroubleshoot, canWriteDevices } = userCapabilities;
2✔
103
  const { hasAuditlogs } = useSelector(getTenantCapabilities);
2✔
104
  const dispatch = useDispatch();
2✔
105
  const dispatchedSetSnackbar = useCallback((...args) => dispatch(setSnackbar(...args)), [dispatch]);
2✔
106

107
  const onNotify = useCallback(
2✔
108
    content => {
109
      if (snackbarAlreadySet) {
×
110
        return;
×
111
      }
112
      setSnackbarAlreadySet(true);
×
113
      dispatchedSetSnackbar(content, TIMEOUTS.threeSeconds);
×
114
      snackTimer.current = setTimeout(() => setSnackbarAlreadySet(false), TIMEOUTS.threeSeconds + TIMEOUTS.debounceShort);
×
115
    },
116
    [dispatchedSetSnackbar, snackbarAlreadySet]
117
  );
118

119
  const onHealthCheckFailed = useCallback(() => {
2✔
120
    if (!socketInitialized) {
×
121
      return;
×
122
    }
123
    onNotify('Health check failed: connection with the device lost.');
×
124
  }, [onNotify, socketInitialized]);
125

126
  const onSocketClose = useCallback(
2✔
127
    event => {
128
      if (!socketInitialized) {
×
129
        return;
×
130
      }
131
      if (event.wasClean) {
×
132
        onNotify(`Connection with the device closed.`);
×
133
      } else if (event.code == 1006) {
×
134
        // 1006: abnormal closure
135
        onNotify('Connection to the remote terminal is forbidden.');
×
136
      } else {
137
        onNotify('Connection with the device died.');
×
138
      }
139
      setSocketClosed(true);
×
140
    },
141
    [onNotify, setSocketClosed, socketInitialized]
142
  );
143

144
  const onMessageReceived = useCallback(message => {
2✔
145
    if (!termRef.current.terminal.current) {
×
146
      return;
×
147
    }
148
    termRef.current.terminal.current.write(new Uint8Array(message));
×
149
  }, []);
150

151
  const [connect, sendMessage, close, sessionState, sessionId] = useSession({
2✔
152
    onClose: onSocketClose,
153
    onHealthCheckFailed,
154
    onMessageReceived,
155
    onNotify,
156
    onOpen: setSocketInitialized
157
  });
158

159
  useEffect(() => {
2✔
160
    setDownloadPath('');
1✔
161
    setUploadPath('');
1✔
162
    setFile();
1✔
163
    if (open) {
1!
164
      setCurrentTab(type);
1✔
165
      setSocketInitialized(undefined);
1✔
166
      setStartTime();
1✔
167
      return;
1✔
168
    }
169
    return () => {
×
170
      clearTimeout(snackTimer.current);
×
171
      if (!open) {
×
172
        close();
×
173
      }
174
    };
175
  }, [open, type, close]);
176

177
  useEffect(() => {
2✔
178
    const allowedTabs = Object.values(tabs).reduce((accu, tab) => {
1✔
179
      if (tab.canShow(userCapabilities)) {
2!
180
        accu.push(tab);
2✔
181
      }
182
      return accu;
2✔
183
    }, []);
184
    setAvailableTabs(allowedTabs);
1✔
185
  }, [canTroubleshoot, canWriteDevices, userCapabilities]);
186

187
  useEffect(() => {
2✔
188
    if (socketInitialized === undefined) {
1!
189
      return;
1✔
190
    }
191
    clearInterval(timer.current);
×
192
    if (socketInitialized) {
×
193
      setStartTime(new Date());
×
194
      dispatchedSetSnackbar('Connection with the device established.', TIMEOUTS.fiveSeconds);
×
195
      timer.current = setInterval(() => setElapsed(moment()), TIMEOUTS.halfASecond);
×
196
    } else {
197
      close();
×
198
    }
199
    return () => {
×
200
      clearInterval(timer.current);
×
201
    };
202
  }, [close, dispatchedSetSnackbar, socketInitialized]);
203

204
  useEffect(() => {
2✔
205
    if (!open || sessionState !== WebSocket.OPEN) {
1!
206
      return;
×
207
    }
208
    return close;
1✔
209
  }, [close, open, sessionState]);
210

211
  useEffect(() => {
2✔
212
    if (!canTroubleshoot || !open || sessionId || sessionState !== WebSocket.CLOSED) {
1!
213
      return;
×
214
    }
215
    connect(device.id);
1✔
216
  }, [canTroubleshoot, connect, device.id, open, sessionId, sessionState]);
217

218
  const onConnectionToggle = () => {
2✔
219
    if (sessionState === WebSocket.CLOSED) {
×
220
      setSocketInitialized(undefined);
×
221
      connect(device.id);
×
222
    } else {
223
      close();
×
224
    }
225
  };
226

227
  const onDrop = acceptedFiles => {
2✔
228
    if (acceptedFiles.length === 1) {
×
229
      setFile(acceptedFiles[0]);
×
230
      setUploadPath(`/tmp/${acceptedFiles[0].name}`);
×
231
      setCurrentTab(tabs.transfer.value);
×
232
    }
233
  };
234

235
  const onDownloadClick = useCallback(
2✔
236
    path => {
237
      setDownloadPath(path);
×
238
      dispatch(getDeviceFileDownloadLink(device.id, path)).then(address => {
×
239
        const filename = path.substring(path.lastIndexOf('/') + 1) || 'file';
×
240
        createDownload(address, filename);
×
241
      });
242
    },
243
    [dispatch, device.id]
244
  );
245

246
  const onMakeGatewayClick = () => {
2✔
247
    const code = getCode(canPreview);
×
248
    setTerminalInput(code);
×
249
  };
250

251
  const commandHandlers = isHosted && isEnterprise ? [{ key: 'thing', onClick: onMakeGatewayClick, title: 'Promote to Mender gateway' }] : [];
2!
252

253
  const visibilityToggle = !socketInitialized ? { maxHeight: 0, overflow: 'hidden' } : {};
2!
254
  return (
2✔
255
    <Dialog open={open} fullWidth={true} maxWidth="lg">
256
      <DialogTitle className="flexbox">
257
        <div className={classes.title}>Troubleshoot -</div>
258
        <DeviceIdentityDisplay device={device} isEditable={false} />
259
      </DialogTitle>
260
      <DialogContent className={`dialog-content flexbox column ${classes.content}`}>
261
        <Tabs value={currentTab} onChange={(e, tab) => setCurrentTab(tab)} textColor="primary" TabIndicatorProps={{ className: 'hidden' }}>
×
262
          {availableTabs.map(({ title: Title, value }) => (
263
            <Tab key={value} label={<Title isConnected={socketInitialized} />} value={value} />
4✔
264
          ))}
265
        </Tabs>
266
        {currentTab === tabs.transfer.value && (
2!
267
          <FileTransfer
268
            deviceId={device.id}
269
            downloadPath={downloadPath}
270
            file={file}
271
            onDownload={onDownloadClick}
272
            onUpload={(...args) => dispatch(deviceFileUpload(...args))}
×
273
            setDownloadPath={setDownloadPath}
274
            setFile={setFile}
275
            setUploadPath={setUploadPath}
276
            uploadPath={uploadPath}
277
            userCapabilities={userCapabilities}
278
          />
279
        )}
280
        <div className={`${classes.terminalContent} ${socketInitialized ? 'device-connected' : ''} ${currentTab === tabs.terminal.value ? '' : 'hidden'}`}>
4!
281
          <TwoColumns
282
            className={`margin-top-small margin-bottom-small ${classes.sessionInfo}`}
283
            items={{
284
              'Session status': socketInitialized ? 'connected' : 'disconnected',
2!
285
              'Connection start': <MaybeTime value={startTime} />,
286
              'Duration': startTime ? `${moment.duration(elapsed.diff(moment(startTime))).format('hh:mm:ss', { trim: false })}` : '-'
2!
287
            }}
288
          />
289
          <Dropzone activeClassName="active" rejectClassName="active" multiple={false} onDrop={onDrop} noClick>
290
            {({ getRootProps }) => (
291
              <div {...getRootProps()} style={{ position: 'relative', ...visibilityToggle }}>
1✔
292
                <Terminal
293
                  onDownloadClick={onDownloadClick}
294
                  sendMessage={sendMessage}
295
                  setSnackbar={dispatchedSetSnackbar}
296
                  socketInitialized={socketInitialized}
297
                  style={{ position: 'absolute', width: '100%', height: '100%', ...visibilityToggle }}
298
                  textInput={terminalInput}
299
                  xtermRef={termRef}
300
                />
301
              </div>
302
            )}
303
          </Dropzone>
304
          {!socketInitialized && (
4✔
305
            <div className={`flexbox centered ${classes.connectionButton}`}>
306
              <Button variant="contained" color="secondary" onClick={onConnectionToggle}>
307
                Connect Terminal
308
              </Button>
309
            </div>
310
          )}
311
        </div>
312
      </DialogContent>
313
      <DialogActions className="flexbox space-between">
314
        <div>
315
          {currentTab === tabs.terminal.value ? (
2!
316
            <Button onClick={onConnectionToggle}>{socketInitialized ? 'Disconnect' : 'Connect'} Terminal</Button>
2!
317
          ) : (
318
            <div className={classes.terminalStatePlaceholder} />
319
          )}
320
          {canAuditlog && hasAuditlogs && (
4!
321
            <Button component={Link} to={`/auditlog?objectType=device&objectId=${device.id}&startDate=${BEGINNING_OF_TIME}`}>
322
              View {tabs[currentTab].link} for this device
323
            </Button>
324
          )}
325
        </div>
326
        <div>
327
          {currentTab === tabs.terminal.value && socketInitialized && !!commandHandlers.length && (
4!
328
            <ListOptions options={commandHandlers} title="Quick commands" />
329
          )}
330
          <Button onClick={onCancel}>Close</Button>
331
        </div>
332
      </DialogActions>
333
    </Dialog>
334
  );
335
};
336

337
export default TroubleshootDialog;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc