1# Copyright 2014 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
6
7from telemetry.core import exceptions
8from telemetry.core import util
9from telemetry.core import web_contents
10
11
12class Oobe(web_contents.WebContents):
13  def __init__(self, inspector_backend, backend_list):
14    super(Oobe, self).__init__(inspector_backend, backend_list)
15
16  def _GaiaLoginContext(self):
17    max_context_id = self.EnableAllContexts()
18    logging.debug('%d contexts in Gaia page' % max_context_id)
19    for gaia_context in range(max_context_id + 1):
20      try:
21        if self.EvaluateJavaScriptInContext(
22            "document.readyState == 'complete' && "
23            "document.getElementById('Email') != null",
24            gaia_context):
25          return gaia_context
26      except exceptions.EvaluateException:
27        pass
28    return None
29
30  def _ExecuteOobeApi(self, api, *args):
31    logging.info('Invoking %s' % api)
32    self.WaitForJavaScriptExpression("typeof Oobe == 'function'", 20)
33
34    if self.EvaluateJavaScript("typeof %s == 'undefined'" % api):
35      raise exceptions.LoginException('%s js api missing' % api)
36
37    js = api + '(' + ("'%s'," * len(args)).rstrip(',') + ');'
38    self.ExecuteJavaScript(js % args)
39
40  def NavigateGuestLogin(self):
41    """Logs in as guest."""
42    self._ExecuteOobeApi('Oobe.guestLoginForTesting')
43
44  def NavigateFakeLogin(self, username, password):
45    """Fake user login."""
46    self._ExecuteOobeApi('Oobe.loginForTesting', username, password)
47
48  def NavigateGaiaLogin(self, username, password):
49    """Logs in to GAIA with provided credentials."""
50    self._ExecuteOobeApi('Oobe.addUserForTesting')
51
52    gaia_context = util.WaitFor(self._GaiaLoginContext, timeout=30)
53
54    self.ExecuteJavaScriptInContext("""
55        document.getElementById('Email').value='%s';
56        document.getElementById('Passwd').value='%s';
57        document.getElementById('signIn').click();"""
58            % (username, password),
59        gaia_context)
60