1#!/usr/bin/python
2
3#
4# Copyright (C) 2019 The Android Open Source Project
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# 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
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19"""
20Parses a given bugreport for specific device Id.
21If parsing is successful, then generate respective
22JSON configuration.
23
24"""
25import json
26import os
27import re
28import sys
29import zipfile
30
31"""
32Store static camera characteristics in given
33JSON configuration file.
34"""
35def storeJsonConfigration(filePath, chars):
36    with open(filePath, 'w') as jsonFile:
37        json.dump(chars, jsonFile, sort_keys=True, indent=1)
38
39"""
40Parse media.camera dump section and populate the camera
41characteristics list of dictionaries.
42"""
43def parseCameraDump(deviceId, cameraDumpPath, tagList):
44    deviceRegExp = "== Camera HAL device device@[0-9]+\.[0-9]+/{0} \(v3.".format(deviceId)
45    physicalDeviceRegExp = "Physical camera [0-9] characteristics:"
46    tagRegExp = " {4}android[a-zA-Z0-9\.]+ \([a-z0-9]+\): "
47    tagValueRegExp = "[^a-zA-Z0-9-\._]"
48    with open(cameraDumpPath, "r") as file:
49        devices = re.split(deviceRegExp, file.read())
50        if len(devices) != 3 and len(devices) != 2:
51            print "Camera device id: {0} not found".format(deviceId)
52            sys.exit()
53
54        physicalDevices = re.split(physicalDeviceRegExp, devices[1])
55        physicalIdx = 0
56        for physicalDevice in physicalDevices:
57            physicalIdx += 1
58            tags = re.split(tagRegExp, physicalDevice)
59            tagsContent = re.findall(tagRegExp, physicalDevice)
60            i = 0;
61            parseEnd = False
62            deviceChars = dict()
63            for tag in tags[1:]:
64                if parseEnd:
65                    break
66
67                lines = tag.splitlines()
68                if len(lines) < 2:
69                    print "Empty tag entry, skipping!"
70                    continue
71                tagName = tagsContent[i].split()[0]
72
73                if tagName is None or len(tagName) < 1:
74                    print "Invalid tag found, skipping!"
75                    continue
76
77                i += 1
78                for line in lines[1:]:
79                    if line.startswith('== Camera HAL device device'):
80                        parseEnd = True
81                        break
82
83                    values = re.split(r' {8}', line)
84                    if len(values) == 2:
85                        key = tagName
86                        tagValues = filter(None, re.split(tagValueRegExp, values[1]))
87                        if deviceChars.has_key(key):
88                            deviceChars[key] = deviceChars[key] + tagValues
89                        else:
90                            deviceChars[key] = tagValues
91                    else:
92                        break
93            tagList.append(deviceChars)
94    os.remove(cameraDumpPath)
95
96if __name__ == '__main__':
97    argc = len(sys.argv)
98    deviceId = ""
99    bugreportPath = ""
100    configPath = ""
101    if argc >= 4:
102        bugreportPath = str(sys.argv[1])
103        deviceId = str(sys.argv[2])
104        configPath = str(sys.argv[3])
105    else:
106        print "Usage: parse_bugreport.py PathToBugreport DeviceId JSONConfigurationPath"
107        sys.exit();
108
109    with zipfile.ZipFile(bugreportPath) as bugzip:
110        cameraDumpFile = ""
111        for name in bugzip.namelist():
112            if re.match("bugreport", name) is not None:
113                cameraDumpFile = name
114                break
115
116        if len(cameraDumpFile) == 0:
117            print("Camera dump not found in bugreport!")
118            sys.exit()
119
120        tagList = list()
121        parseCameraDump(deviceId, bugzip.extract(cameraDumpFile), tagList)
122        storeJsonConfigration(configPath, tagList)
123
124