9f61231c08f037d90d8293900d5c98253127fba6
[platform/framework/web/crosswalk.git] / src / xwalk / app / tools / android / manifest_json_parser.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2013, 2014 Intel Corporation. All rights reserved.
4 # Use of this source code is governed by a BSD-style license that can be
5 # found in the LICENSE file.
6
7 """
8 Parse JSON-format manifest configuration file and
9 provide the specific fields, which have to be integrated with
10 packaging tool(e.g. make_apk.py) to generate xml-format manifest file.
11
12 Sample usage from shell script:
13 python manifest_json_parser.py --jsonfile=/path/to/manifest.json
14 """
15
16 import json
17 import optparse
18 import os
19 import re
20 import sys
21
22 def HandlePermissionList(permission_list):
23   """This function is used to handle the permission list and return the string
24   of permissions.
25
26   Args:
27     permission_list: the permission list, e.g.["permission1", "permission2"].
28
29   Returns:
30     The string of permissions with ':' as separator.
31     e.g. "permission1:permission2".
32   """
33   permissions = list(permission_list)
34   reg_permission = re.compile(r'^[a-zA-Z\.]*$')
35   for permission in permissions:
36     if not reg_permission.match(permission):
37       print('\'Permissions\' field error, only alphabets and '
38             '\'.\' are allowed.')
39       sys.exit(1)
40   return ':'.join(permissions)
41
42
43 class ManifestJsonParser(object):
44   """ The class is used to parse json-format manifest file, recompose the fields
45   and provide the field interfaces required by the packaging tool.
46
47   Args:
48     input_path: the full path of the json-format manifest file.
49   """
50   def __init__(self, input_path):
51     self.input_path = input_path
52     input_file = open(self.input_path)
53     try:
54       input_src = input_file.read()
55       self.data_src = json.JSONDecoder().decode(input_src)
56       self.ret_dict = self._output_items()
57     except (TypeError, ValueError, IOError):
58       print('There is a parser error in manifest.json file.')
59       sys.exit(1)
60     except KeyError:
61       print('There is a field error in manifest.json file.')
62       sys.exit(1)
63     finally:
64       input_file.close()
65
66   def _output_items(self):
67     """ The manifest field items are reorganized and returned as a
68     dictionary to support single or multiple values of keys.
69
70     Returns:
71       A dictionary to the corresponding items. the dictionary keys are
72       described as follows, the value is set to "" if the value of the
73       key is not set.
74     app_name:         The application name.
75     version:          The version number.
76     icons:            An array of icons.
77     app_url:          The url of application, e.g. hosted app.
78     description:      The description of application.
79     app_root:         The root path of the web, this flag allows to package
80                       local web application as apk.
81     app_local_path:   The relative path of entry file based on app_root,
82                       this flag should work with "--app-root" together.
83     permissions:      The permission list.
84     required_version: The required crosswalk runtime version.
85     plugin:           The plug-in information.
86     fullscreen:       The fullscreen flag of the application.
87     launch_screen:    The launch screen configuration.
88     """
89     ret_dict = {}
90     if 'name' not in self.data_src:
91       print('Error: no \'name\' field in manifest.json file.')
92       sys.exit(1)
93     ret_dict['app_name'] = self.data_src['name']
94     if 'version' not in self.data_src:
95       print('Error: no \'version\' field in manifest.json file.')
96       sys.exit(1)
97     ret_dict['version'] = self.data_src['version']
98     if 'launch_path' in self.data_src:
99       app_url = self.data_src['launch_path']
100     elif ('app' in self.data_src and
101         'launch' in self.data_src['app'] and
102             'local_path' in self.data_src['app']['launch']):
103       app_url = self.data_src['app']['launch']['local_path']
104     else:
105       app_url = ''
106     if app_url.lower().startswith(('http://', 'https://')):
107       app_local_path = ''
108     else:
109       app_local_path = app_url
110       app_url = ''
111     file_path_prefix = os.path.split(self.input_path)[0]
112     if 'icons' in self.data_src:
113       ret_dict['icons'] = self.data_src['icons']
114     else:
115       ret_dict['icons'] = {}
116     app_root = file_path_prefix
117     ret_dict['description'] = ''
118     if 'description' in self.data_src:
119       ret_dict['description'] = self.data_src['description']
120     ret_dict['app_url'] = app_url
121     ret_dict['app_root'] = app_root
122     ret_dict['app_local_path'] = app_local_path
123     ret_dict['permissions'] = ''
124     if 'permissions' in self.data_src:
125       try:
126         permission_list = self.data_src['permissions']
127         ret_dict['permissions'] = HandlePermissionList(permission_list)
128       except (TypeError, ValueError, IOError):
129         print('\'Permissions\' field error in manifest.json file.')
130         sys.exit(1)
131     ret_dict['required_version'] = ''
132     if 'required_version' in self.data_src:
133       ret_dict['required_version'] = self.data_src['required_version']
134     ret_dict['plugin'] = ''
135     if 'plugin' in self.data_src:
136       ret_dict['plugin'] = self.data_src['plugin']
137     if 'display' in self.data_src and 'fullscreen' in self.data_src['display']:
138       ret_dict['fullscreen'] = 'true'
139     else:
140       ret_dict['fullscreen'] = ''
141     ret_dict['launch_screen_img'] = ''
142     if 'launch_screen' in self.data_src:
143       if 'default' not in self.data_src['launch_screen']:
144         print('Error: no \'default\' field for \'launch_screen\'.')
145         sys.exit(1)
146       default = self.data_src['launch_screen']['default']
147       if 'image' not in default:
148         print('Error: no \'image\' field for \'launch_screen.default\'.')
149         sys.exit(1)
150       ret_dict['launch_screen_img'] = default['image']
151     return ret_dict
152
153   def ShowItems(self):
154     """Show the processed results, it is used for command-line
155     internal debugging."""
156     print("app_name: %s" % self.GetAppName())
157     print("version: %s" % self.GetVersion())
158     print("description: %s" % self.GetDescription())
159     print("icons: %s" % self.GetIcons())
160     print("app_url: %s" % self.GetAppUrl())
161     print("app_root: %s" % self.GetAppRoot())
162     print("app_local_path: %s" % self.GetAppLocalPath())
163     print("permissions: %s" % self.GetPermissions())
164     print("required_version: %s" % self.GetRequiredVersion())
165     print("plugins: %s" % self.GetPlugins())
166     print("fullscreen: %s" % self.GetFullScreenFlag())
167     print('launch_screen.default.image: %s' % self.GetLaunchScreenImg())
168
169
170   def GetAppName(self):
171     """Return the application name."""
172     return self.ret_dict['app_name']
173
174   def GetVersion(self):
175     """Return the version number."""
176     return self.ret_dict['version']
177
178   def GetIcons(self):
179     """Return the icons."""
180     return self.ret_dict['icons']
181
182   def GetAppUrl(self):
183     """Return the URL of the application."""
184     return self.ret_dict['app_url']
185
186   def GetDescription(self):
187     """Return the description of the application."""
188     return self.ret_dict['description']
189
190   def GetAppRoot(self):
191     """Return the root path of the local web application."""
192     return self.ret_dict['app_root']
193
194   def GetAppLocalPath(self):
195     """Return the local relative path of the local web application."""
196     return self.ret_dict['app_local_path']
197
198   def GetPermissions(self):
199     """Return the permissions."""
200     return self.ret_dict['permissions']
201
202   def GetRequiredVersion(self):
203     """Return the required crosswalk runtime version."""
204     return self.ret_dict['required_version']
205
206   def GetPlugins(self):
207     """Return the plug-in path and file name."""
208     return self.ret_dict['plugin']
209
210   def GetFullScreenFlag(self):
211     """Return the set fullscreen flag of the application."""
212     return self.ret_dict['fullscreen']
213
214   def GetLaunchScreenImg(self):
215     """Return the default img for launch_screen."""
216     return self.ret_dict['launch_screen_img']
217
218
219 def main(argv):
220   """Respond to command mode and show the processed field values."""
221   parser = optparse.OptionParser()
222   info = ('The input json-format file name. Such as: '
223           '--jsonfile=manifest.json')
224   parser.add_option('-j', '--jsonfile', action='store', dest='jsonfile',
225                     help=info)
226   opts, _ = parser.parse_args()
227   if len(argv) == 1:
228     parser.print_help()
229     return 0
230   json_parser = ManifestJsonParser(opts.jsonfile)
231   json_parser.ShowItems()
232   return 0
233
234
235 if __name__ == '__main__':
236   sys.exit(main(sys.argv))