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.internal.actions import media_action
22from telemetry.internal.actions import page_action
23from telemetry.internal.actions import utils
24
25
26class SeekAction(media_action.MediaAction):
27  def __init__(self, seconds, selector=None, timeout_in_seconds=0,
28               log_time=True, label=''):
29    super(SeekAction, self).__init__()
30    self._seconds = seconds
31    self._selector = selector if selector else ''
32    self._timeout_in_seconds = timeout_in_seconds
33    self._log_time = log_time
34    self._label = label
35
36  def WillRunAction(self, tab):
37    """Load the media metrics JS code prior to running the action."""
38    super(SeekAction, self).WillRunAction(tab)
39    utils.InjectJavaScript(tab, 'seek.js')
40
41  def RunAction(self, tab):
42    try:
43      tab.ExecuteJavaScript(
44          'window.__seekMedia('
45              '{{ selector }}, {{ seconds }}, {{ log_time }}, {{ label}});',
46          selector=self._selector,
47          seconds=str(self._seconds),
48          log_time=self._log_time,
49          label=self._label)
50      if self._timeout_in_seconds > 0:
51        self.WaitForEvent(tab, self._selector, 'seeked',
52                          self._timeout_in_seconds)
53    except exceptions.EvaluateException:
54      raise page_action.PageActionFailed('Cannot seek media element(s) with '
55                                         'selector = %s.' % self._selector)
56