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

mendersoftware / gui / 1113439055

19 Dec 2023 09:01PM UTC coverage: 82.752% (-17.2%) from 99.964%
1113439055

Pull #4258

gitlab-ci

mender-test-bot
chore: Types update

Signed-off-by: Mender Test Bot <mender@northern.tech>
Pull Request #4258: chore: Types update

4326 of 6319 branches covered (0.0%)

8348 of 10088 relevant lines covered (82.75%)

189.39 hits per line

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

75.0
/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 { canAccess } from '../../constants/appConstants';
25
import { detectOsIdentifier, toggle } from '../../helpers';
26
import { getCurrentSession, getCurrentUser, getIsEnterprise, getTenantCapabilities, getVersionInformation } from '../../selectors';
27
import Tracking from '../../tracking';
28
import CommonDocsLink from '../common/docslink';
29
import Time from '../common/time';
30

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

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

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

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

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

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

56
const defaultLocationFormatter = ({ os, tool, versionInfo }) => {
3✔
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 }) =>
3✔
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 }) => {
3✔
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 }) => {
3✔
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, personalAccessTokens, token) => {
3✔
109
  let header = `${headerFlag} "Cookie: JWT=${token}"`;
×
110
  if (personalAccessTokens.length) {
×
111
    header = `${headerFlag} "Authorization: Bearer ${personalAccessTokens[0]}"`;
×
112
  }
113
  return header;
×
114
};
115

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

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

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

141
const tools = [
3✔
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 = [
3✔
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 = ({ title, ...remainder }) => (
3✔
235
  <CommonDocsLink
10✔
236
    {...remainder}
237
    title={
238
      <>
239
        {title} <Launch style={{ verticalAlign: 'text-bottom' }} fontSize="small" />
240
      </>
241
    }
242
  />
243
);
244

245
const DownloadableComponents = ({ locations, onMenuClick, token }) => {
3✔
246
  const onLocationClick = (location, title) => {
12✔
247
    Tracking.event({ category: 'download', action: title });
×
248
    cookies.set('JWT', token, { path: '/', maxAge: 60, domain: '.mender.io', sameSite: false });
×
249
    const link = document.createElement('a');
×
250
    link.href = location;
×
251
    link.rel = 'noopener noreferrer';
×
252
    link.target = '_blank';
×
253
    document.body.appendChild(link);
×
254
    link.click();
×
255
    link.remove();
×
256
  };
257

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

274
const DownloadSection = ({ item, isEnterprise, onMenuClick, os, token, versionInformation }) => {
3✔
275
  const [open, setOpen] = useState(false);
9✔
276
  const { id, getLocations, packageId, title } = item;
9✔
277
  const { locations, ...extraLocations } = getLocations({ isEnterprise, tool: item, versionInfo: versionInformation.repos, os });
9✔
278

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

305
export const Downloads = () => {
3✔
306
  const [anchorEl, setAnchorEl] = useState();
1✔
307
  const [currentLocation, setCurrentLocation] = useState('');
1✔
308
  const [os] = useState(detectOsIdentifier());
1✔
309
  const dispatch = useDispatch();
1✔
310
  const { tokens = [] } = useSelector(getCurrentUser);
1✔
311
  const { token } = useSelector(getCurrentSession);
1✔
312
  const isEnterprise = useSelector(getIsEnterprise);
1✔
313
  const tenantCapabilities = useSelector(getTenantCapabilities);
1✔
314
  const { latestRelease: versions = { repos: {}, releaseDate: '' } } = useSelector(getVersionInformation);
1!
315

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

328
  const handleToggle = event => {
1✔
329
    setAnchorEl(current => (current ? null : event?.currentTarget.parentElement));
×
330
    const location = event?.target.getAttribute('value') || '';
×
331
    setCurrentLocation(location);
×
332
  };
333

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

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

365
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