1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
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 */
15
16import { SpRecordTrace } from '../trace/component/SpRecordTrace';
17import { CmdConstant } from './CmdConstant';
18import { HdcDeviceManager } from '../hdc/HdcDeviceManager';
19
20export class Cmd {
21  static CmdSendPostUtils(uri: string, callback: Function, requestData: unknown): void {
22    // @ts-ignore
23    if (window.useWb) {
24      return;
25    }
26    fetch(uri, {
27      method: 'POST',
28      headers: {
29        'Content-Type': 'application/json',
30      },
31      body: JSON.stringify(requestData),
32    }).then((response): void => {
33      if (response.ok) {
34        let result = response.text();
35        result.then((output) => {
36          callback(output);
37        });
38      }
39    });
40  }
41
42  /**
43   * exec objdump to disassembling binary and find addr to show 100 line
44   * @param command  obj dump command
45   * @param addr addr of select line
46   * @param callback result callback
47   */
48  static execObjDump(command: string, addr: string, callback: Function): void {
49    // @ts-ignore
50    if (window.useWb) {
51      return;
52    }
53    const data = { cmd: command, addr: addr };
54    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/exec`;
55    Cmd.CmdSendPostUtils(uri, callback, data);
56  }
57
58  static execHdcCmd(command: string, callback: Function): void {
59    // @ts-ignore
60    if (window.useWb) {
61      return;
62    }
63    const data = {
64      cmd: command,
65      tag: 'shell',
66    };
67    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/hdcCmd`;
68    Cmd.CmdSendPostUtils(uri, callback, data);
69  }
70
71  static async execFileRecv(command: string, filePath: string, callback: Function): Promise<void> {
72    // @ts-ignore
73    if (window.useWb) {
74      return;
75    }
76    let fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
77    const data = {
78      cmd: command,
79      tag: 'file',
80      fileName: fileName,
81    };
82    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/hdcCmd`;
83    let buf = await fetch(uri, {
84      method: 'POST',
85      headers: {
86        'Content-Type': 'application/json',
87      },
88      body: JSON.stringify(data),
89    }).then((res) => res.arrayBuffer());
90    callback(buf);
91  }
92
93  static execHdcTraceCmd(command: string, serialNumber: string, callback: Function): void {
94    // @ts-ignore
95    if (window.useWb) {
96      return;
97    }
98    const data = {
99      cmd: command,
100      tag: 'hiprofiler_cmd',
101      serialNumber: serialNumber,
102    };
103    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/hdcCmd`;
104    Cmd.CmdSendPostUtils(uri, callback, data);
105  }
106
107  static formatString(string: string, params: string[]): string {
108    if (params.length === 0) {
109      return string;
110    }
111    for (let i = 0; i < params.length; i++) {
112      string = string.replace(new RegExp('\\{' + i + '\\}', 'g'), params[i]);
113    }
114    return string;
115  }
116
117  static showSaveFile(callback: Function): void {
118    // @ts-ignore
119    if (window.useWb) {
120      return;
121    }
122    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/showSaveDialog`;
123    fetch(uri, {
124      method: 'GET',
125    }).then((response) => {
126      if (response.ok) {
127        let result = response.text();
128        result.then((output) => {
129          callback(output);
130        });
131      }
132    });
133  }
134
135  static uploadFile(fd: FormData, callback: Function): void {
136    // @ts-ignore
137    if (window.useWb) {
138      return;
139    }
140    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/upload`;
141    fetch(uri, {
142      method: 'POST',
143      body: fd,
144    }).then((response): void => {
145      callback(response);
146    });
147  }
148
149  static copyFile(fileName: string, distFile: string, callback: Function): void {
150    // @ts-ignore
151    if (window.useWb) {
152      return;
153    }
154    const data = {
155      filename: fileName,
156      distfile: distFile,
157    };
158    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/copyfile`;
159    fetch(uri, {
160      method: 'POST',
161      headers: {
162        'Content-Type': 'application/json',
163      },
164      body: JSON.stringify(data),
165    }).then((response): void => {
166      callback(response);
167    });
168  }
169
170  static async openFileDialog(): Promise<string> {
171    // @ts-ignore
172    if (window.useWb) {
173      return '';
174    }
175    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/showOpenDialog`;
176    let res = await fetch(uri, { method: 'POST' });
177    let result = res.ok ? await res.text() : '';
178    return result;
179  }
180
181  static convertOutProcessList(res: string): string[] {
182    let processData: string[] = [];
183    if (res) {
184      let lineValues: string[] = res.replace(/\r\n/g, '\r').replace(/\n/g, '\r').split(/\r/);
185      for (let lineVal of lineValues) {
186        lineVal = lineVal.trim();
187        if (lineVal.indexOf('__progname') !== -1 || lineVal.indexOf('CMD') !== -1 || lineVal.length === 0) {
188          continue;
189        } else {
190          let process: string[] = lineVal.split(' ');
191          if (process.length === 2) {
192            processData.push(`${process[1]}(${process[0]})`);
193          }
194        }
195      }
196    }
197    return processData;
198  }
199  static convertOutPackageList(res: string): string[] {
200    let packageData: string[] = [];
201    res ? (packageData = res.replace(/\r\n/g, '\r').replace(/\n\t/g, '\r').split(/\r/)) : [];
202    packageData.shift();
203    return packageData;
204  }
205
206  static getDebugProcess(): Promise<string[]> {
207    return new Promise((resolve, reject) => {
208      if (SpRecordTrace.isVscode) {
209        let cmd = Cmd.formatString(CmdConstant.CMD_GET_DEBUG_PROCESS_DEVICES, [SpRecordTrace.serialNumber]);
210        Cmd.execHdcCmd(cmd, (res: string) => {
211          resolve(Cmd.convertOutProcessList(res));
212        });
213      } else {
214        HdcDeviceManager.connect(SpRecordTrace.serialNumber).then((conn) => {
215          if (conn) {
216            HdcDeviceManager.shellResultAsString(CmdConstant.CMD_GET_DEBUG_PROCESS, false).then((res) => {
217              resolve(Cmd.convertOutProcessList(res));
218            });
219          } else {
220            reject(-1);
221          }
222        });
223      }
224    });
225  }
226
227  static getProcess(): Promise<string[]> {
228    return new Promise((resolve, reject): void => {
229      if (SpRecordTrace.isVscode) {
230        let cmd = Cmd.formatString(CmdConstant.CMD_GET_PROCESS_DEVICES, [SpRecordTrace.serialNumber]);
231        Cmd.execHdcCmd(cmd, (res: string): void => {
232          resolve(Cmd.convertOutProcessList(res));
233        });
234      } else {
235        HdcDeviceManager.connect(SpRecordTrace.serialNumber).then((conn): void => {
236          if (conn) {
237            HdcDeviceManager.shellResultAsString(CmdConstant.CMD_GET_PROCESS, false).then((res): void => {
238              resolve(Cmd.convertOutProcessList(res));
239            });
240          } else {
241            reject(-1);
242          }
243        });
244      }
245    });
246  }
247  static getPackage(): Promise<string[]> {
248    return new Promise((resolve, reject): void => {
249      HdcDeviceManager.connect(SpRecordTrace.serialNumber).then((conn) => {
250        if (conn) {
251          HdcDeviceManager.shellResultAsString(CmdConstant.CMD_GET_PACKAGE, false).then((res): void => {
252            resolve(Cmd.convertOutPackageList(res));
253          });
254        } else {
255          reject(-1);
256        }
257      });
258    });
259  }
260}
261