1/*
2 * Copyright 2020, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import JSZip from 'jszip';
18
19export default {
20  name: 'SaveAsZip',
21  methods: {
22    saveAs(blob, filename) {
23      const a = document.createElement('a');
24      a.style = 'display: none';
25      document.body.appendChild(a);
26
27      const url = window.URL.createObjectURL(blob);
28
29      a.href = url;
30      a.download = filename;
31      a.click();
32      window.URL.revokeObjectURL(url);
33
34      document.body.removeChild(a);
35    },
36    /**
37     * Returns the file name, if the file has an extension use its default,
38     * otherwise use ".mp4" for screen recording (name from proxy script) and
39     * ".winscope" for traces
40     * @param {*} fileName
41     */
42    getFileName(fileName) {
43      var re = /(?:\.([^.]+))?$/;
44      var extension = re.exec(fileName)[1];
45      if (!extension) {
46        extension = "";
47      }
48      switch (extension) {
49        case "": {
50          if (fileName == "Screen recording") {
51            return fileName + ".mp4"
52          }
53          return fileName + ".winscope"
54        }
55        default: return fileName
56      }
57    },
58    async downloadAsZip(traces) {
59      const zip = new JSZip();
60      this.buttonClicked("Download All")
61
62      for (const trace of traces) {
63        const traceFolder = zip.folder(trace.type);
64        for (const file of trace.files) {
65          var fileName = this.getFileName(file.filename);
66          const blob = await fetch(file.blobUrl).then((r) => r.blob());
67          traceFolder.file(fileName, blob);
68        }
69      }
70
71      const zipFile = await zip.generateAsync({type: 'blob'});
72
73      this.saveAs(zipFile, 'winscope.zip');
74    },
75  },
76};
77