1# Copyright 2015 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
5from telemetry.core import exceptions
6from telemetry.internal.actions import media_action
7from telemetry.internal.actions import page_action
8from telemetry.internal.actions import utils
9
10
11class LoadMediaAction(media_action.MediaAction):
12  """ For calling load() on media elements and waiting for an event to fire.
13  """
14
15  def __init__(self, selector=None, timeout_in_seconds=0,
16               event_to_await='canplaythrough'):
17    super(LoadMediaAction, self).__init__()
18    self._selector = selector or ''
19    self._timeout_in_seconds = timeout_in_seconds
20    self._event_to_await = event_to_await
21
22  def WillRunAction(self, tab):
23    """Load the JS code prior to running the action."""
24    super(LoadMediaAction, self).WillRunAction(tab)
25    utils.InjectJavaScript(tab, 'load_media.js')
26
27  def RunAction(self, tab):
28    try:
29      tab.ExecuteJavaScript(
30          'window.__loadMediaAndAwait({{ selector }}, {{ event }});',
31          selector=self._selector, event=self._event_to_await)
32      if self._timeout_in_seconds > 0:
33        self.WaitForEvent(tab, self._selector, self._event_to_await,
34                          self._timeout_in_seconds)
35    except exceptions.EvaluateException:
36      raise page_action.PageActionFailed('Failed waiting for event "%s" on '
37                                         'elements with selector = %s.' %
38                                         (self._event_to_await, self._selector))
39