OLD | NEW |
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
4 | 4 |
5 import json | 5 import json |
6 import logging | 6 import logging |
7 import re | 7 import re |
8 | 8 |
| 9 import third_party.json_schema_compiler.json_comment_eater as json_comment_eater |
| 10 import third_party.json_schema_compiler.model as model |
| 11 import url_constants |
| 12 |
9 DEFAULT_ICON_PATH = '/images/sample-default-icon.png' | 13 DEFAULT_ICON_PATH = '/images/sample-default-icon.png' |
10 | 14 |
11 class SamplesDataSource(object): | 15 class SamplesDataSource(object): |
12 """Constructs a list of samples and their respective files and api calls. | 16 """Constructs a list of samples and their respective files and api calls. |
13 """ | 17 """ |
14 | 18 |
15 class Factory(object): | 19 class Factory(object): |
16 """A factory to create SamplesDataSource instances bound to individual | 20 """A factory to create SamplesDataSource instances bound to individual |
17 Requests. | 21 Requests. |
18 """ | 22 """ |
19 def __init__(self, branch, file_system, cache_builder, samples_path): | 23 def __init__(self, |
| 24 branch, |
| 25 file_system, |
| 26 github_file_system, |
| 27 cache_builder, |
| 28 github_cache_builder, |
| 29 samples_path): |
| 30 self._file_system = file_system |
| 31 self._github_file_system = github_file_system |
20 self._static_path = ((('/' + branch) if branch != 'local' else '') + | 32 self._static_path = ((('/' + branch) if branch != 'local' else '') + |
21 '/static') | 33 '/static') |
22 self._file_system = file_system | 34 self._extensions_cache = cache_builder.build(self._MakeSamplesList) |
23 self._cache = cache_builder.build(self._MakeSamplesList) | 35 self._apps_cache = github_cache_builder.build( |
| 36 lambda x: self._MakeSamplesList(x, is_apps=True)) |
24 self._samples_path = samples_path | 37 self._samples_path = samples_path |
25 | 38 |
26 def Create(self, request): | 39 def Create(self, request): |
27 """Returns a new SamplesDataSource bound to |request|. | 40 """Returns a new SamplesDataSource bound to |request|. |
28 """ | 41 """ |
29 return SamplesDataSource(self._cache, | 42 return SamplesDataSource(self._extensions_cache, |
| 43 self._apps_cache, |
30 self._samples_path, | 44 self._samples_path, |
31 request) | 45 request) |
32 | 46 |
33 def _GetApiItems(self, js_file): | 47 def _GetApiItems(self, js_file): |
34 return set(re.findall('(chrome\.[a-zA-Z0-9\.]+)', js_file)) | 48 return set(re.findall('(chrome\.[a-zA-Z0-9\.]+)', js_file)) |
35 | 49 |
36 def _MakeApiLink(self, prefix, item): | 50 def _MakeApiLink(self, prefix, item): |
37 api, name = item.replace('chrome.', '').split('.', 1) | 51 api, name = item.replace('chrome.', '').split('.', 1) |
38 return api + '.html#' + prefix + '-' + name | 52 return api + '.html#' + prefix + '-' + name |
39 | 53 |
40 def _GetDataFromManifest(self, path): | 54 def _GetDataFromManifest(self, path, file_system): |
41 manifest = self._file_system.ReadSingle(path + '/manifest.json') | 55 manifest = file_system.ReadSingle(path + '/manifest.json') |
42 manifest_json = json.loads(manifest) | 56 manifest_json = json.loads(json_comment_eater.Nom(manifest)) |
43 l10n_data = { | 57 l10n_data = { |
44 'name': manifest_json.get('name', ''), | 58 'name': manifest_json.get('name', ''), |
45 'description': manifest_json.get('description', ''), | 59 'description': manifest_json.get('description', ''), |
46 'icon': manifest_json.get('icons', {}).get('128', None), | 60 'icon': manifest_json.get('icons', {}).get('128', None), |
47 'default_locale': manifest_json.get('default_locale', None), | 61 'default_locale': manifest_json.get('default_locale', None), |
48 'locales': {} | 62 'locales': {} |
49 } | 63 } |
50 if not l10n_data['default_locale']: | 64 if not l10n_data['default_locale']: |
51 return l10n_data | 65 return l10n_data |
52 locales_path = path + '/_locales/' | 66 locales_path = path + '/_locales/' |
53 locales_dir = self._file_system.ReadSingle(locales_path) | 67 locales_dir = file_system.ReadSingle(locales_path) |
54 if locales_dir: | 68 if locales_dir: |
55 locales_files = self._file_system.Read( | 69 locales_files = file_system.Read( |
56 [locales_path + f + 'messages.json' for f in locales_dir]).Get() | 70 [locales_path + f + 'messages.json' for f in locales_dir]).Get() |
57 locales_json = [(path, json.loads(contents)) | 71 locales_json = [(path, json.loads(contents)) |
58 for path, contents in locales_files.iteritems()] | 72 for path, contents in locales_files.iteritems()] |
59 for path, json_ in locales_json: | 73 for path, json_ in locales_json: |
60 l10n_data['locales'][path[len(locales_path):].split('/')[0]] = json_ | 74 l10n_data['locales'][path[len(locales_path):].split('/')[0]] = json_ |
61 return l10n_data | 75 return l10n_data |
62 | 76 |
63 def _MakeSamplesList(self, files): | 77 def _MakeSamplesList(self, files, is_apps=False): |
| 78 file_system = self._github_file_system if is_apps else self._file_system |
64 samples_list = [] | 79 samples_list = [] |
65 for filename in sorted(files): | 80 for filename in sorted(files): |
66 if filename.rsplit('/')[-1] != 'manifest.json': | 81 if filename.rsplit('/')[-1] != 'manifest.json': |
67 continue | 82 continue |
68 # This is a little hacky, but it makes a sample page. | 83 # This is a little hacky, but it makes a sample page. |
69 sample_path = filename.rsplit('/', 1)[-2] | 84 sample_path = filename.rsplit('/', 1)[-2] |
70 sample_files = [path for path in files | 85 sample_files = [path for path in files |
71 if path.startswith(sample_path + '/')] | 86 if path.startswith(sample_path + '/')] |
72 js_files = [path for path in sample_files if path.endswith('.js')] | 87 js_files = [path for path in sample_files if path.endswith('.js')] |
73 js_contents = self._file_system.Read(js_files).Get() | 88 js_contents = file_system.Read(js_files).Get() |
74 api_items = set() | 89 api_items = set() |
75 for js in js_contents.values(): | 90 for js in js_contents.values(): |
76 api_items.update(self._GetApiItems(js)) | 91 api_items.update(self._GetApiItems(js)) |
77 | 92 |
78 api_calls = [] | 93 api_calls = [] |
79 for item in api_items: | 94 for item in api_items: |
80 if len(item.split('.')) < 3: | 95 if len(item.split('.')) < 3: |
81 continue | 96 continue |
82 if item.endswith('.addListener'): | 97 if item.endswith('.addListener'): |
83 item = item.replace('.addListener', '') | 98 item = item.replace('.addListener', '') |
84 api_calls.append({ | 99 api_calls.append({ |
85 'name': item, | 100 'name': item, |
86 'link': self._MakeApiLink('event', item) | 101 'link': self._MakeApiLink('event', item) |
87 }) | 102 }) |
88 else: | 103 else: |
89 api_calls.append({ | 104 api_calls.append({ |
90 'name': item, | 105 'name': item, |
91 'link': self._MakeApiLink('method', item) | 106 'link': self._MakeApiLink('method', item) |
92 }) | 107 }) |
93 l10n_data = self._GetDataFromManifest(sample_path) | 108 manifest_data = self._GetDataFromManifest(sample_path, file_system) |
| 109 |
94 sample_base_path = sample_path.split('/', 1)[1] | 110 sample_base_path = sample_path.split('/', 1)[1] |
95 if l10n_data['icon'] is None: | 111 if is_apps: |
| 112 url = url_constants.GITHUB_BASE + '/' + sample_base_path |
| 113 icon_base = url_constants.RAW_GITHUB_BASE + '/' + sample_base_path |
| 114 download_url = url |
| 115 else: |
| 116 url = sample_base_path |
| 117 icon_base = sample_base_path |
| 118 download_url = sample_base_path + '.zip' |
| 119 |
| 120 if manifest_data['icon'] is None: |
96 icon_path = self._static_path + DEFAULT_ICON_PATH | 121 icon_path = self._static_path + DEFAULT_ICON_PATH |
97 else: | 122 else: |
98 icon_path = '/' + sample_base_path + '/' + l10n_data['icon'] | 123 icon_path = icon_base + '/' + manifest_data['icon'] |
99 l10n_data.update({ | 124 manifest_data.update({ |
100 'icon': icon_path, | 125 'icon': icon_path, |
101 'path': sample_base_path, | 126 'download_url': download_url, |
| 127 'url': url, |
102 'files': [f.replace(sample_path + '/', '') for f in sample_files], | 128 'files': [f.replace(sample_path + '/', '') for f in sample_files], |
103 'api_calls': api_calls | 129 'api_calls': api_calls |
104 }) | 130 }) |
105 samples_list.append(l10n_data) | 131 samples_list.append(manifest_data) |
106 | 132 |
107 return samples_list | 133 return samples_list |
108 | 134 |
109 def __init__(self, cache, samples_path, request): | 135 def __init__(self, extensions_cache, apps_cache, samples_path, request): |
110 self._cache = cache | 136 self._extensions_cache = extensions_cache |
| 137 self._apps_cache = apps_cache |
111 self._samples_path = samples_path | 138 self._samples_path = samples_path |
112 self._request = request | 139 self._request = request |
113 | 140 |
114 def GetSamplesForAPI(self, api_name): | |
115 samples = self.values() | |
116 api_search = '.' + api_name + '.' | |
117 return [sample for sample in samples | |
118 if any(api_search in api['name'] for api in sample['api_calls'])] | |
119 | |
120 def _GetAcceptedLanguages(self): | 141 def _GetAcceptedLanguages(self): |
121 accept_language = self._request.headers.get('Accept-Language', None) | 142 accept_language = self._request.headers.get('Accept-Language', None) |
122 if accept_language is None: | 143 if accept_language is None: |
123 return [] | 144 return [] |
124 return [lang_with_q.split(';')[0].strip() | 145 return [lang_with_q.split(';')[0].strip() |
125 for lang_with_q in accept_language.split(',')] | 146 for lang_with_q in accept_language.split(',')] |
126 | 147 |
127 def __getitem__(self, key): | 148 def FilterSamples(self, key, api_name): |
128 return self.get(key) | 149 """Fetches and filters the list of samples specified by |key|, returning |
| 150 only the samples that use the API |api_name|. |key| is either 'apps' or |
| 151 'extensions'. |
| 152 """ |
| 153 api_search = '_' + api_name + '_' |
| 154 samples_list = [] |
| 155 try: |
| 156 for sample in self.get(key): |
| 157 api_calls_unix = [model.UnixName(call['name']) |
| 158 for call in sample['api_calls']] |
| 159 for call in api_calls_unix: |
| 160 if api_search in call: |
| 161 samples_list.append(sample) |
| 162 break |
| 163 except NotImplementedError: |
| 164 # If we're testing, the GithubFileSystem can't fetch samples. |
| 165 # Bug: http://crbug.com/141910 |
| 166 return [] |
| 167 return samples_list |
129 | 168 |
130 def values(self): | 169 def _CreateSamplesDict(self, key): |
131 return self.get('') | 170 if key == 'apps': |
132 | 171 samples_list = self._apps_cache.GetFromFileListing('/') |
133 def get(self, key): | 172 else: |
134 samples_list = self._cache.GetFromFileListing(self._samples_path + '/') | 173 samples_list = self._extensions_cache.GetFromFileListing( |
| 174 self._samples_path + '/') |
135 return_list = [] | 175 return_list = [] |
136 for dict_ in samples_list: | 176 for dict_ in samples_list: |
137 name = dict_['name'] | 177 name = dict_['name'] |
138 description = dict_['description'] | 178 description = dict_['description'] |
139 if name.startswith('__MSG_') or description.startswith('__MSG_'): | 179 if name.startswith('__MSG_') or description.startswith('__MSG_'): |
140 try: | 180 try: |
141 # Copy the sample dict so we don't change the dict in the cache. | 181 # Copy the sample dict so we don't change the dict in the cache. |
142 sample_data = dict_.copy() | 182 sample_data = dict_.copy() |
143 name_key = name[len('__MSG_'):-len('__')] | 183 name_key = name[len('__MSG_'):-len('__')] |
144 description_key = description[len('__MSG_'):-len('__')] | 184 description_key = description[len('__MSG_'):-len('__')] |
145 locale = sample_data['default_locale'] | 185 locale = sample_data['default_locale'] |
146 for lang in self._GetAcceptedLanguages(): | 186 for lang in self._GetAcceptedLanguages(): |
147 if lang in sample_data['locales']: | 187 if lang in sample_data['locales']: |
148 locale = lang | 188 locale = lang |
149 break | 189 break |
150 locale_data = sample_data['locales'][locale] | 190 locale_data = sample_data['locales'][locale] |
151 sample_data['name'] = locale_data[name_key]['message'] | 191 sample_data['name'] = locale_data[name_key]['message'] |
152 sample_data['description'] = locale_data[description_key]['message'] | 192 sample_data['description'] = locale_data[description_key]['message'] |
153 except Exception as e: | 193 except Exception as e: |
154 logging.error(e) | 194 logging.error(e) |
155 # Revert the sample to the original dict. | 195 # Revert the sample to the original dict. |
156 sample_data = dict_ | 196 sample_data = dict_ |
157 return_list.append(sample_data) | 197 return_list.append(sample_data) |
158 else: | 198 else: |
159 return_list.append(dict_) | 199 return_list.append(dict_) |
160 return return_list | 200 return return_list |
| 201 |
| 202 def __getitem__(self, key): |
| 203 return self.get(key) |
| 204 |
| 205 def get(self, key): |
| 206 return { |
| 207 'apps': lambda: self._CreateSamplesDict('apps'), |
| 208 'extensions': lambda: self._CreateSamplesDict('extensions') |
| 209 }.get(key, lambda: {})() |
OLD | NEW |