Create wt-odlux directory
[ccsdk/features.git] / sdnr / wt-odlux / odlux / framework / src / views / about.tsx
1 /**
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt odlux
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  */
18 import React, { FC, useEffect, useState } from 'react';
19 import * as marked from 'marked';
20 import * as hljs from 'highlight.js';
21 import { requestRestExt } from '../services/restService';
22 import { Button, Typography } from '@mui/material';
23
24 const defaultRenderer = new marked.Renderer();
25 defaultRenderer.link = (href, title, text) => (
26   `<a target="_blank" rel="noopener noreferrer" href="${href}" title="${title}">${text}</a>`
27 );
28
29 type OdluxVersion= {version:string,build:string, framework: string, 
30   applications:{
31     configurationApp: string,
32     connectApp: string,
33     eventLogApp: string,
34     faultApp: string,
35     helpApp: string,
36     inventoryApp: string,
37     microwaveApp: string,
38     maintenanceApp: string,
39     mediatorApp: string,
40     networkMapApp: string,
41     permanceHistoryApp: string,
42     siteManagerApp: string,
43   }};
44
45 type TopologyVersion = {version: string, buildTimestamp: string};
46
47 const AboutComponent: FC = (props) => {
48   
49   const textareaRef = React.createRef<HTMLTextAreaElement>();
50   const [content, setContent] = useState<string | null>(null);
51   const [isCopiedSuccessfully, setCopySuccess] = useState(false);
52   const [isContetLoaded, setContentLoaded] = useState(false);
53
54   useEffect(()=>{
55     loadAboutContent();
56   },[]);
57
58   const getMarkOdluxVersionMarkdownTable = (data:OdluxVersion|null|undefined):string => {
59     if(!data) {
60       return "";
61     }else{
62       let applicationVersions= '';
63       if(data.applications){
64
65         applicationVersions = `| Framework | ${data.framework}|\n `+
66         `| ConnectApp | ${data.applications.connectApp}|\n `+
67         `| FaultApp | ${data.applications.faultApp}|\n `+
68         `| MaintenanceApp | ${data.applications.maintenanceApp}|\n `+
69         `| ConfigurationApp | ${data.applications.configurationApp}|\n `+
70         `| PerformanceHistoryApp | ${data.applications.permanceHistoryApp}|\n `+
71         `| InventoryApp | ${data.applications.inventoryApp}|\n `+
72         `| EventLogApp | ${data.applications.eventLogApp}|\n `+
73         `| MediatorApp | ${data.applications.mediatorApp}|\n `+
74         `| NetworkMapApp | ${data.applications.networkMapApp}|\n `+
75         `| MicrowaveApp | ${data.applications.microwaveApp}|\n `+
76         `| SiteManagerApp | ${data.applications.siteManagerApp}|\n `+
77         `| HelpApp | ${data.applications.helpApp}|\n `;
78       }
79     
80     return `| | |\n| --- | --- |\n| Version | ${data.version} |\n| Build timestamp | ${data.build}|\n`+
81     applicationVersions;
82     }
83   }
84
85   const getTopologyVersionMarkdownTable = (data: TopologyVersion|null|undefined) => { 
86     if(!data){
87       return "No version";
88     }
89     else
90     {
91       const topologyInfo = `| | |\n| --- | --- |\n| Version | ${data.version} |\n` +
92                            `| Build timestamp | ${data.buildTimestamp} |\n`;
93       return topologyInfo;
94     }
95   }
96
97   const loadAboutContent = (): void => {
98     const baseUri = window.location.pathname.substring(0,window.location.pathname.lastIndexOf("/")+1);
99     const init = {
100       'method': 'GET',
101       headers: {
102         'Content-Type': 'application/json',
103         'Accept': 'text/markdown',
104       }
105     };
106     const p1 = requestRestExt<string>('/about',init);
107     const p2 = requestRestExt<OdluxVersion>(`${baseUri}version.json`);
108     const p3 = requestRestExt<any>(`/topology/info/version`);
109
110     Promise.all([p1,p2, p3]).then((responses) => {
111       const response = responses[0];
112       const response2 = responses[1]; 
113       const response3 = responses[2];   
114       const content = response.status == 200 ? response.data : `${response.status} ${response.message}` || "Server error";
115       const content2 = `\n## ODLUX Version Info\n`+(response2.status == 200 ? getMarkOdluxVersionMarkdownTable(response2.data) : `${response2.message}` || "ODLUX Server error");
116       const content3 =  `\n## Topology API Version Info\n`+(response3.status == 200 ? getTopologyVersionMarkdownTable(response3.data): `Topology API not available`);
117       const loadedSucessfully = response.status == 200 ? true : false;
118       setContent((content + content2 + content3 ) || null);
119       setContentLoaded(loadedSucessfully);
120     }).catch((error) => {
121       setContent(error);
122     });
123   }
124
125   const copyToClipboard = (e: React.MouseEvent<HTMLButtonElement>) =>{
126     e.preventDefault();
127
128     if(textareaRef.current!==null){
129       textareaRef.current.select();
130       document.execCommand('copy');
131       if(e.currentTarget != null){ // refocus on button, otherwhise the textarea would be focused
132         e.currentTarget.focus();
133       }
134       setCopySuccess(true);
135       window.setTimeout(()=>{ setCopySuccess(false);},2000);
136     }
137   }
138
139     const markedOptions: marked.MarkedOptions = {
140       gfm: true,
141       breaks: false,
142       pedantic: false,
143       sanitize: true,
144       smartLists: true,
145       smartypants: false,
146       langPrefix: 'hljs ',
147       ...({}),
148       highlight: (code, lang) => {
149         if (!!(lang && hljs.getLanguage(lang))) {
150           return hljs.highlight(lang, code).value;
151         }
152         return code;
153       }
154     };
155
156
157     const className = "about-table"
158     const style: React.CSSProperties = {};
159     const containerStyle = { overflow: "auto", paddingRight: "20px" }
160
161     const html = (marked(content || 'loading', { renderer: markedOptions && markedOptions.renderer || defaultRenderer }));
162
163     return (
164       <div style={containerStyle}>
165         { isContetLoaded &&
166         <div style={{float: "right", marginRight: "10px"}}>
167         <Button aria-label="copy-version-information-button" color="inherit" variant="contained" onClick={e => copyToClipboard(e)}>
168            Copy to clipboard
169         </Button>
170           {
171             isCopiedSuccessfully && 
172             <Typography variant="body1" style={{color: "green"}} align="center">
173              copied successfully
174             </Typography>
175           }
176         </div>
177       }
178        
179         <div
180           dangerouslySetInnerHTML={{ __html: html }}
181           className={className}
182           style={style}
183         />
184          <form>
185           <textarea
186            style={{opacity: ".01"}}
187             ref={textareaRef}
188             value={content || ''}
189           />
190         </form>
191       </div>
192     );
193 };
194
195 export const About = AboutComponent;
196 export default About;