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.internal.actions import media_action
18from telemetry.internal.actions import page_action
19from telemetry.internal.actions import utils
20
21
22class PlayAction(media_action.MediaAction):
23  def __init__(self, selector=None,
24               playing_event_timeout_in_seconds=0,
25               ended_event_timeout_in_seconds=0):
26    super(PlayAction, self).__init__()
27    self._selector = selector if selector else ''
28    self._playing_event_timeout_in_seconds = playing_event_timeout_in_seconds
29    self._ended_event_timeout_in_seconds = ended_event_timeout_in_seconds
30
31  def WillRunAction(self, tab):
32    """Load the media metrics JS code prior to running the action."""
33    super(PlayAction, self).WillRunAction(tab)
34    utils.InjectJavaScript(tab, 'play.js')
35
36  def RunAction(self, tab):
37    try:
38      tab.ExecuteJavaScript(
39          'window.__playMedia({{ selector }});', selector=self._selector)
40      # Check if we need to wait for 'playing' event to fire.
41      if self._playing_event_timeout_in_seconds > 0:
42        self.WaitForEvent(tab, self._selector, 'playing',
43                          self._playing_event_timeout_in_seconds)
44      # Check if we need to wait for 'ended' event to fire.
45      if self._ended_event_timeout_in_seconds > 0:
46        self.WaitForEvent(tab, self._selector, 'ended',
47                          self._ended_event_timeout_in_seconds)
48    except exceptions.EvaluateException:
49      raise page_action.PageActionFailed('Cannot play media element(s) with '
50                                         'selector = %s.' % self._selector)
51