samples_data_source.py revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
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.
4
5import logging
6import traceback
7
8from data_source import DataSource
9from extensions_paths import EXAMPLES
10from future import All, Future
11from platform_util import GetPlatforms
12
13
14def _GetSampleId(sample_name):
15  return sample_name.lower().replace(' ', '-')
16
17
18def GetAcceptedLanguages(request):
19  if request is None:
20    return []
21  accept_language = request.headers.get('Accept-Language', None)
22  if accept_language is None:
23    return []
24  return [lang_with_q.split(';')[0].strip()
25          for lang_with_q in accept_language.split(',')]
26
27
28def CreateSamplesView(samples_list, request):
29  return_list = []
30  for dict_ in samples_list:
31    name = dict_['name']
32    description = dict_['description']
33    if description is None:
34      description = ''
35    if name.startswith('__MSG_') or description.startswith('__MSG_'):
36      try:
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']:
44            locale = lang
45            break
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'])
50      except Exception:
51        logging.error(traceback.format_exc())
52        # Revert the sample to the original dict.
53        sample_data = dict_
54      return_list.append(sample_data)
55    else:
56      dict_['id'] = _GetSampleId(name)
57      return_list.append(dict_)
58  return return_list
59
60
61class SamplesDataSource(DataSource):
62  '''Constructs a list of samples and their respective files and api calls.
63  '''
64  def __init__(self, server_instance, request):
65    self._platform_bundle = server_instance.platform_bundle
66    self._request = request
67
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)
73
74  def get(self, platform):
75    return self._GetImpl(platform).Get()
76
77  def GetRefreshPaths(self):
78    return [platform for platform in GetPlatforms()]
79
80  def Refresh(self, path):
81    return self._GetImpl(path)
82