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 "seek" action on media elements.
6
7Action parameters are:
8- seconds: The media time to seek to. Test fails if not provided.
9- selector: If no selector is defined then the action attempts to seek the first
10            media element on the page. If 'all' then seek all media elements.
11- timeout_in_seconds: Maximum waiting time for the "seeked" event
12                      (dispatched when the seeked operation completes)
13                      to be fired.  0 means do not wait.
14- log_time: If true the seek time is recorded, otherwise media
15            measurement will not be aware of the seek action. Used to
16            perform multiple seeks. Default true.
17- label: A suffix string to name the seek perf measurement.
18"""
19
20from telemetry.core import exceptions
21from telemetry.page.actions import media_action
22from telemetry.page.actions import page_action
23
24
25class SeekAction(media_action.MediaAction):
26  def __init__(self, seconds, selector=None, timeout_in_seconds=0,
27               log_time=True, label=''):
28    super(SeekAction, self).__init__()
29    self._seconds = seconds
30    self._selector = selector if selector else ''
31    self._timeout_in_seconds = timeout_in_seconds
32    self._log_time = log_time
33    self._label = label
34
35  def WillRunAction(self, tab):
36    """Load the media metrics JS code prior to running the action."""
37    super(SeekAction, self).WillRunAction(tab)
38    self.LoadJS(tab, 'seek.js')
39
40  def RunAction(self, tab):
41    try:
42      tab.ExecuteJavaScript(
43          'window.__seekMedia("%s", "%s", %i, "%s");' %
44          (self._selector, self._seconds, self._log_time, self._label))
45      if self._timeout_in_seconds > 0:
46        self.WaitForEvent(tab, self._selector, 'seeked',
47                          self._timeout_in_seconds)
48    except exceptions.EvaluateException:
49      raise page_action.PageActionFailed('Cannot seek media element(s) with '
50                                         'selector = %s.' % self._selector)
51