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

mendersoftware / gui / 914712491

pending completion
914712491

Pull #3798

gitlab-ci

mzedel
refac: refactored signup page to make better use of form capabilities

Signed-off-by: Manuel Zedel <manuel.zedel@northern.tech>
Pull Request #3798: MEN-3530 - refactored forms

4359 of 6322 branches covered (68.95%)

92 of 99 new or added lines in 11 files covered. (92.93%)

1715 existing lines in 159 files now uncovered.

8203 of 9941 relevant lines covered (82.52%)

150.06 hits per line

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

67.15
/src/js/components/help/downloads.js
1
// Copyright 2022 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, useMemo, useState } from 'react';
15
import { useDispatch, useSelector } from 'react-redux';
16

17
import { ArrowDropDown, ExpandMore, FileDownloadOutlined as FileDownloadIcon, Launch } from '@mui/icons-material';
18
import { Accordion, AccordionDetails, AccordionSummary, Chip, Menu, MenuItem, Typography } from '@mui/material';
19

20
import copy from 'copy-to-clipboard';
21
import Cookies from 'universal-cookie';
22

23
import { setSnackbar } from '../../actions/appActions';
24
import { getToken } from '../../auth';
25
import { canAccess } from '../../constants/appConstants';
26
import { detectOsIdentifier, toggle } from '../../helpers';
27
import { getCurrentUser, getDocsVersion, getIsEnterprise, getTenantCapabilities, getVersionInformation } from '../../selectors';
28
import Tracking from '../../tracking';
29
import Time from '../common/time';
30

31
const cookies = new Cookies();
4✔
32

33
const osMap = {
4✔
34
  MacOs: 'darwin',
35
  Unix: 'linux',
36
  Linux: 'linux'
37
};
38

39
const architectures = {
4✔
40
  all: 'all',
41
  amd64: 'amd64',
42
  arm64: 'arm64',
43
  armhf: 'armhf'
44
};
45

46
const defaultArchitectures = [architectures.armhf, architectures.arm64, architectures.amd64];
4✔
47
const defaultOSVersions = ['debian+buster', 'debian+bullseye', 'ubuntu+bionic', 'ubuntu+focal'];
4✔
48

49
const getVersion = (versions, id) => versions[id] || 'master';
65!
50

51
const downloadLocations = {
4✔
52
  public: 'https://downloads.mender.io',
53
  private: 'https://downloads.customer.mender.io/content/hosted'
54
};
55

56
const defaultLocationFormatter = ({ os, tool, versionInfo }) => {
4✔
57
  const { id, location = downloadLocations.public, osList = [], title } = tool;
2!
58
  let locations = [{ location: `${location}/${id}/${getVersion(versionInfo, id)}/linux/${id}`, title }];
2✔
59
  if (osList.length) {
2!
60
    locations = osList.reduce((accu, supportedOs) => {
2✔
61
      const title = Object.entries(osMap).find(entry => entry[1] === supportedOs)[0];
6✔
62
      accu.push({
4✔
63
        location: `${location}/${id}/${getVersion(versionInfo, id)}/${supportedOs}/${id}`,
64
        title,
65
        isUserOs: osMap[os] === supportedOs
66
      });
67
      return accu;
4✔
68
    }, []);
69
  }
70
  return { locations };
2✔
71
};
72

73
const osArchLocationReducer = ({ archList, location = downloadLocations.public, packageName, packageId, id, osList, versionInfo }) =>
4✔
74
  osList.reduce((accu, os) => {
8✔
75
    const osArchitectureLocations = archList.map(arch => ({
56✔
76
      location: `${location}/repos/debian/pool/main/${id[0]}/${packageName || packageId || id}/${encodeURIComponent(
100!
77
        `${packageId}_${getVersion(versionInfo, id)}-1+${os}_${arch}.deb`
78
      )}`,
79
      title: `${os} - ${arch}`
80
    }));
81
    accu.push(...osArchitectureLocations);
32✔
82
    return accu;
32✔
83
  }, []);
84

85
const multiArchLocationFormatter = ({ tool, versionInfo }) => {
4✔
86
  const { id, packageId: packageName, packageExtras = [] } = tool;
5✔
87
  const packageId = packageName || id;
5✔
88
  const locations = osArchLocationReducer({ ...tool, packageId, versionInfo });
5✔
89
  const extraLocations = packageExtras.reduce((accu, extra) => {
5✔
90
    accu[extra.packageId] = osArchLocationReducer({ ...tool, ...extra, packageName: packageId, versionInfo });
3✔
91
    return accu;
3✔
92
  }, {});
93
  return { locations, ...extraLocations };
5✔
94
};
95

96
const nonOsLocationFormatter = ({ tool, versionInfo }) => {
4✔
97
  const { id, location = downloadLocations.public, title } = tool;
1!
98
  return {
1✔
99
    locations: [
100
      {
101
        location: `${location}/${id}/${getVersion(versionInfo, id)}/${id}-${getVersion(versionInfo, id)}.tar.xz`,
102
        title
103
      }
104
    ]
105
  };
106
};
107

108
const getAuthHeader = (headerFlag, tokens) => {
4✔
UNCOV
109
  let header = `${headerFlag} "Cookie: JWT=${getToken()}"`;
×
UNCOV
110
  if (tokens.length) {
×
UNCOV
111
    header = `${headerFlag} "Authorization: Bearer ${tokens[0]}"`;
×
112
  }
UNCOV
113
  return header;
×
114
};
115

116
const defaultCurlDownload = ({ location, tokens }) => `curl ${getAuthHeader('-H', tokens)} -LO ${location}`;
4✔
117

118
const defaultWgetDownload = ({ location, tokens }) => `wget ${getAuthHeader('--header', tokens)} ${location}`;
4✔
119

120
const defaultGitlabJob = ({ location, tokens }) => {
4✔
UNCOV
121
  const filename = location.substring(location.lastIndexOf('/') + 1);
×
UNCOV
122
  return `
×
123
download:mender-tools:
124
  image: curlimages/curl
125
  stage: download
126
  variables:
127
    ${tokens.length ? `MENDER_TOKEN: ${tokens}` : `MENDER_JWT: ${getToken()}`}
×
128
  script:
129
    - if [ -n "$MENDER_TOKEN" ]; then
130
    - curl -H "Authorization: Bearer $MENDER_TOKEN" -LO ${location}
131
    - else
132
    - ${defaultCurlDownload({ location, tokens })}
133
    - fi
134
  artifacts:
135
    expire_in: 1w
136
    paths:
137
      - ${filename}
138
`;
139
};
140

141
const tools = [
4✔
142
  {
143
    id: 'mender',
144
    packageId: 'mender-client',
145
    packageExtras: [{ packageId: 'mender-client-dev', archList: [architectures.all] }],
146
    title: 'Mender Client Debian package',
147
    getLocations: multiArchLocationFormatter,
148
    canAccess,
149
    osList: defaultOSVersions,
150
    archList: defaultArchitectures
151
  },
152
  {
153
    id: 'mender-artifact',
154
    title: 'Mender Artifact',
155
    getLocations: defaultLocationFormatter,
156
    canAccess,
157
    osList: [osMap.MacOs, osMap.Linux]
158
  },
159
  {
160
    id: 'mender-binary-delta',
161
    title: 'Mender Binary Delta generator and Update Module',
162
    getLocations: nonOsLocationFormatter,
163
    location: downloadLocations.private,
164
    canAccess: ({ isEnterprise, tenantCapabilities }) => isEnterprise || tenantCapabilities.canDelta
1!
165
  },
166
  {
167
    id: 'mender-cli',
168
    title: 'Mender CLI',
169
    getLocations: defaultLocationFormatter,
170
    canAccess,
171
    osList: [osMap.MacOs, osMap.Linux]
172
  },
173
  {
174
    id: 'mender-configure-module',
175
    packageId: 'mender-configure',
176
    packageExtras: [
177
      { packageId: 'mender-configure-demo', archList: [architectures.all] },
178
      { packageId: 'mender-configure-timezone', archList: [architectures.all] }
179
    ],
180
    title: 'Mender Configure',
181
    getLocations: multiArchLocationFormatter,
182
    canAccess: ({ tenantCapabilities }) => tenantCapabilities.hasDeviceConfig,
1✔
183
    osList: defaultOSVersions,
184
    archList: [architectures.all]
185
  },
186
  {
187
    id: 'mender-connect',
188
    title: 'Mender Connect',
189
    getLocations: multiArchLocationFormatter,
190
    canAccess,
191
    osList: defaultOSVersions,
192
    archList: defaultArchitectures
193
  },
194
  {
195
    id: 'mender-convert',
196
    title: 'Mender Convert',
197
    getLocations: ({ versionInfo }) => ({
1✔
198
      locations: [
199
        {
200
          location: `https://github.com/mendersoftware/mender-convert/archive/refs/tags/${getVersion(versionInfo, 'mender-convert')}.zip`,
201
          title: 'Mender Convert'
202
        }
203
      ]
204
    }),
205
    canAccess
206
  },
207
  {
208
    id: 'mender-gateway',
209
    title: 'Mender Gateway',
210
    getLocations: multiArchLocationFormatter,
211
    location: downloadLocations.private,
212
    canAccess: ({ isEnterprise }) => isEnterprise,
1✔
213
    osList: defaultOSVersions,
214
    archList: defaultArchitectures
215
  },
216
  {
217
    id: 'monitor-client',
218
    packageId: 'mender-monitor',
219
    title: 'Mender Monitor',
220
    getLocations: multiArchLocationFormatter,
221
    location: downloadLocations.private,
222
    canAccess: ({ tenantCapabilities }) => tenantCapabilities.hasMonitor,
1✔
223
    osList: defaultOSVersions,
224
    archList: [architectures.all]
225
  }
226
];
227

228
const copyOptions = [
4✔
229
  { id: 'curl', title: 'Curl command', format: defaultCurlDownload },
230
  { id: 'wget', title: 'Wget command', format: defaultWgetDownload },
231
  { id: 'gitlab', title: 'Gitlab Job definition', format: defaultGitlabJob }
232
];
233

234
const DocsLink = ({ className = '', docsVersion, path, title }) => (
4✔
235
  <a className={className} href={`https://docs.mender.io/${docsVersion}${path}`} target="_blank" rel="noopener noreferrer">
10✔
236
    {title} <Launch style={{ verticalAlign: 'text-bottom' }} fontSize="small" />
237
  </a>
238
);
239

240
const DownloadableComponents = ({ locations, onMenuClick }) => {
4✔
241
  const onLocationClick = (location, title) => {
12✔
UNCOV
242
    console.log(location);
×
UNCOV
243
    Tracking.event({ category: 'download', action: title });
×
UNCOV
244
    cookies.set('JWT', getToken(), { path: '/', maxAge: 60, domain: '.mender.io', sameSite: false });
×
UNCOV
245
    const link = document.createElement('a');
×
UNCOV
246
    link.href = location;
×
UNCOV
247
    link.rel = 'noopener noreferrer';
×
UNCOV
248
    link.target = '_blank';
×
UNCOV
249
    document.body.appendChild(link);
×
UNCOV
250
    link.click();
×
UNCOV
251
    link.remove();
×
252
  };
253

254
  return locations.map(({ isUserOs, location, title }) => (
12✔
255
    <React.Fragment key={location}>
62✔
256
      <Chip
257
        avatar={<FileDownloadIcon />}
258
        className="margin-bottom-small margin-right-small"
259
        clickable
UNCOV
260
        onClick={() => onLocationClick(location, title)}
×
261
        variant={isUserOs ? 'filled' : 'outlined'}
62✔
262
        onDelete={onMenuClick}
263
        deleteIcon={<ArrowDropDown value={location} />}
264
        label={title}
265
      />
266
    </React.Fragment>
267
  ));
268
};
269

270
const DownloadSection = ({ docsVersion, item, isEnterprise, onMenuClick, os, versionInformation }) => {
4✔
271
  const [open, setOpen] = useState(false);
9✔
272
  const { id, getLocations, packageId, title } = item;
9✔
273
  const { locations, ...extraLocations } = getLocations({ isEnterprise, tool: item, versionInfo: versionInformation.repos, os });
9✔
274

275
  return (
9✔
UNCOV
276
    <Accordion className="margin-bottom-small" square expanded={open} onChange={() => setOpen(toggle)}>
×
277
      <AccordionSummary expandIcon={<ExpandMore />}>
278
        <div>
279
          <Typography variant="subtitle2">{title}</Typography>
280
          <Typography variant="caption" className="muted">
281
            Updated: {<Time format="YYYY-MM-DD" value={versionInformation.releaseDate} />}
282
          </Typography>
283
        </div>
284
      </AccordionSummary>
285
      <AccordionDetails>
286
        <div>
287
          <DownloadableComponents locations={locations} onMenuClick={onMenuClick} />
288
          {Object.entries(extraLocations).map(([key, locations]) => (
289
            <React.Fragment key={key}>
3✔
290
              <h5 className="margin-bottom-none muted">{key}</h5>
291
              <DownloadableComponents locations={locations} onMenuClick={onMenuClick} />
292
            </React.Fragment>
293
          ))}
294
        </div>
295
        <DocsLink docsVersion={docsVersion} path={`release-information/release-notes-changelog/${packageId || id}`} title="Changelog" />
15✔
296
      </AccordionDetails>
297
    </Accordion>
298
  );
299
};
300

301
export const Downloads = () => {
4✔
302
  const [anchorEl, setAnchorEl] = useState();
1✔
303
  const [currentLocation, setCurrentLocation] = useState('');
1✔
304
  const [os] = useState(detectOsIdentifier());
1✔
305
  const dispatch = useDispatch();
1✔
306
  const { tokens = [] } = useSelector(getCurrentUser);
1✔
307
  const docsVersion = useSelector(getDocsVersion);
1✔
308
  const isEnterprise = useSelector(getIsEnterprise);
1✔
309
  const tenantCapabilities = useSelector(getTenantCapabilities);
1✔
310
  const { latestRelease: versions = { repos: {}, releaseDate: '' } } = useSelector(getVersionInformation);
1!
311

312
  const availableTools = useMemo(
1✔
313
    () =>
314
      tools.reduce((accu, tool) => {
1✔
315
        if (!tool.canAccess({ isEnterprise, tenantCapabilities })) {
9!
UNCOV
316
          return accu;
×
317
        }
318
        accu.push(tool);
9✔
319
        return accu;
9✔
320
      }, []),
321
    [isEnterprise, tenantCapabilities]
322
  );
323

324
  const handleToggle = event => {
1✔
UNCOV
325
    setAnchorEl(current => (current ? null : event?.currentTarget.parentElement));
×
UNCOV
326
    const location = event?.target.getAttribute('value') || '';
×
UNCOV
327
    console.log(location);
×
UNCOV
328
    setCurrentLocation(location);
×
329
  };
330

331
  const handleSelection = useCallback(
1✔
332
    event => {
UNCOV
333
      const value = event?.target.getAttribute('value') || 'curl';
×
UNCOV
334
      const option = copyOptions.find(item => item.id === value);
×
UNCOV
335
      copy(option.format({ location: currentLocation, tokens }));
×
UNCOV
336
      dispatch(setSnackbar('Copied to clipboard'));
×
337
    },
338
    [currentLocation, tokens]
339
  );
340

341
  return (
1✔
342
    <div>
343
      <h2>Downloads</h2>
344
      <p>To get the most out of Mender, download the tools listed below.</p>
345
      {availableTools.map(tool => (
346
        <DownloadSection
9✔
347
          docsVersion={docsVersion}
348
          key={tool.id}
349
          item={tool}
350
          isEnterprise={isEnterprise}
351
          onMenuClick={handleToggle}
352
          os={os}
353
          versionInformation={versions}
354
        />
355
      ))}
356
      <Menu id="download-options-menu" anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={handleToggle} variant="menu">
357
        {copyOptions.map(option => (
358
          <MenuItem key={option.id} value={option.id} onClick={handleSelection}>
3✔
359
            Copy {option.title}
360
          </MenuItem>
361
        ))}
362
      </Menu>
363
      <p>
364
        To learn more about the tools availabe for Mender, read the{' '}
365
        <DocsLink docsVersion={docsVersion} path="downloads" title="Downloads section in our documentation" />.
366
      </p>
367
    </div>
368
  );
369
};
370

371
export default Downloads;
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