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
3 # found in the LICENSE file.
8 from data_source import DataSource
9 from extensions_paths import EXAMPLES
10 from future import All, Future
11 from platform_util import GetPlatforms
14 def _GetSampleId(sample_name):
15 return sample_name.lower().replace(' ', '-')
18 def GetAcceptedLanguages(request):
21 accept_language = request.headers.get('Accept-Language', None)
22 if accept_language is None:
24 return [lang_with_q.split(';')[0].strip()
25 for lang_with_q in accept_language.split(',')]
28 def CreateSamplesView(samples_list, request):
30 for dict_ in samples_list:
32 description = dict_['description']
33 if description is None:
35 if name.startswith('__MSG_') or description.startswith('__MSG_'):
37 # Copy the sample dict so we don't change the dict in the cache.
38 sample_data = dict_.copy()
39 name_key = name[len('__MSG_'):-len('__')]
40 description_key = description[len('__MSG_'):-len('__')]
41 locale = sample_data['default_locale']
42 for lang in GetAcceptedLanguages(request):
43 if lang in sample_data['locales']:
46 locale_data = sample_data['locales'][locale]
47 sample_data['name'] = locale_data[name_key]['message']
48 sample_data['description'] = locale_data[description_key]['message']
49 sample_data['id'] = _GetSampleId(sample_data['name'])
51 logging.error(traceback.format_exc())
52 # Revert the sample to the original dict.
54 return_list.append(sample_data)
56 dict_['id'] = _GetSampleId(name)
57 return_list.append(dict_)
61 class SamplesDataSource(DataSource):
62 '''Constructs a list of samples and their respective files and api calls.
64 def __init__(self, server_instance, request):
65 self._platform_bundle = server_instance.platform_bundle
66 self._request = request
68 def _GetImpl(self, platform):
69 cache = self._platform_bundle.GetSamplesModel(platform).GetCache()
70 create_view = lambda samp_list: CreateSamplesView(samp_list, self._request)
71 return cache.GetFromFileListing('' if platform == 'apps'
72 else EXAMPLES).Then(create_view)
74 def get(self, platform):
75 return self._GetImpl(platform).Get()
78 return All([self._GetImpl(platform) for platform in GetPlatforms()])