1# Copyright 2013 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
5"""A Telemetry page_action that performs the "play" action on media elements.
6
7Media elements can be specified by a selector argument. If no selector is
8defined then then the action attempts to play the first video element or audio
9element on the page. A selector can also be 'all' to play all media elements.
10
11Other arguments to use are: playing_event_timeout_in_seconds and
12ended_event_timeout_in_seconds, which forces the action to wait until
13playing and ended events get fired respectively.
14"""
15
16from telemetry.core import exceptions
17from telemetry.page.actions import media_action
18from telemetry.page.actions import page_action
19
20
21class PlayAction(media_action.MediaAction):
22  def __init__(self, selector=None,
23               playing_event_timeout_in_seconds=0,
24               ended_event_timeout_in_seconds=0):
25    super(PlayAction, self).__init__()
26    self._selector = selector if selector else ''
27    self._playing_event_timeout_in_seconds = playing_event_timeout_in_seconds
28    self._ended_event_timeout_in_seconds = ended_event_timeout_in_seconds
29
30  def WillRunAction(self, tab):
31    """Load the media metrics JS code prior to running the action."""
32    super(PlayAction, self).WillRunAction(tab)
33    self.LoadJS(tab, 'play.js')
34
35  def RunAction(self, tab):
36    try:
37      tab.ExecuteJavaScript('window.__playMedia("%s");' % self._selector)
38      # Check if we need to wait for 'playing' event to fire.
39      if self._playing_event_timeout_in_seconds > 0:
40        self.WaitForEvent(tab, self._selector, 'playing',
41                          self._playing_event_timeout_in_seconds)
42      # Check if we need to wait for 'ended' event to fire.
43      if self._ended_event_timeout_in_seconds > 0:
44        self.WaitForEvent(tab, self._selector, 'ended',
45                          self._ended_event_timeout_in_seconds)
46    except exceptions.EvaluateException:
47      raise page_action.PageActionFailed('Cannot play media element(s) with '
48                                         'selector = %s.' % self._selector)
49