Поиск по этому блогу

суббота, 21 ноября 2015 г.

Файлы и настройка плагина simplePlayer jQuery

Это моя первая проба использования Ipython Notebook для освоения и настройки плагина javascript. Я здесь сначала загружал файл в ячейку, потом редактировал код и сохранял в тот же файл. А для того, чтобы сохранить первоначальный вариант, просто скопировал всю папку с плагином и работал с копией. И чего ради? Таки для этого есть GitHub... Да, я графоман, и мои заказчики не любят Гитхаб, таки будем пробовать дальше...

simplePlayer.js is a lighweight jQuery plugin that makes it easy to embed Youtube Videos in your webpage, with custom Play button, screenshot and player controls
IPython's Rich Display System (6) "IPython in Depth, SciPy2013 Tutorial, Part 2 of 3"
IPython's Rich Display System
Коррида
Tubular is a jQuery plugin that lets you set a YouTube video as your page background. Just attach it to your page wrapper element, set some options, and you're on your way.

Сначала посмотрим, что за файлы мы загрузили

In [44]:
!chcp 65001
!dir files
Active code page: 65001
 Volume in drive F is MYLINUXLIVE
 Volume Serial Number is CE7F-8134

 Directory of F:\IPython Notebooks\2015_11\files

15.11.2015  21:16    <DIR>          .
15.11.2015  21:16    <DIR>          ..
14.03.2015  12:38    <DIR>          Lightweight-jQuery-Youtube-Video-Player-simplePlayer-js
14.03.2015  12:38    <DIR>          Lightweight_myhacks
               0 File(s)              0 bytes
               4 Dir(s)   4В 463В 632В 384 bytes free

В папке Lightweight-jQuery-Youtube-Video-Player-simplePlayer-js распакованный плагин, а в папке Lightweight_myhacks тот же плагин с моими хаками.

In [5]:
from IPython.display import HTML, Javascript, display
In [ ]:
# %load F:\\IPython Notebooks\\2015_11\\files\\Lightweight-jQuery-Youtube-Video-Player-simplePlayer-js\\readme.md
# simplePlayer.js
A lightweight, easy-to-use jQuery plugin for playing YouTube videos.

**Note:** To test this plugin, you must have your file running on a webserver, as the YouTube player restricts 
    calls between local files and the internet.
In [ ]:
# %load F:\\IPython Notebooks\\2015_11\\files\\Lightweight-jQuery-Youtube-Video-Player-simplePlayer-js\\simplePlayer.js

var YTdeferred = jQuery.Deferred();

window.onYouTubeIframeAPIReady = function() {
 YTdeferred.resolve(window.YT);
};

(function( $ ) {

 $.ajaxSetup({
  cache: true
 });

 $.getScript( "https://www.youtube.com/iframe_api")
  .done(function( script, textStatus ) {
 });

 $.fn.simplePlayer = function() {

  var video = $(this);

  var play = $('<div />', { id: 'play' }).hide();

  var defaults = {
    autoplay: 1,
    autohide: 1,
    border: 0,
    wmode: 'opaque',
    enablejsapi: 1,
    modestbranding: 1,
    version: 3,
    hl: 'en_US',
    rel: 0,
    showinfo: 0,
    hd: 1,
    iv_load_policy: 3 // add origin
   };

  // onYouTubeIframeAPIReady

  YTdeferred.done(function(YT) {
   play.appendTo( video ).fadeIn('slow');
  });

  function onPlayerStateChange(event) {
   if (event.data == YT.PlayerState.ENDED) {
    play.fadeIn(500);
   }
  }

  function onPlayerReady(event) {
   var replay = document.getElementById('play');
   replay.addEventListener('click', function() {
    player.playVideo();
   });
  }

  play.bind('click', function () {

   if ( !$('#player' ).length ) {

    $('<iframe />', {
     id: 'player',
     src: 'https://www.youtube.com/embed/' + video.data('video') + '?' + $.param(defaults)
    })
    .attr({ width: video.width(), height: video.height(), seamless: 'seamless' })
    .css('border', 'none')
    .appendTo( video );

    video.children('img').hide();

    $(this).css('background-image', 'url(play-button.png), url(' + video.children().attr('src') + ')').hide();
 
    player = new YT.Player('player', {events: {'onStateChange': onPlayerStateChange, 'onReady': onPlayerReady}});
   }

   $(this).hide();
  });

  return this;
 };
}( jQuery ));
In [22]:
# %load F:\\IPython Notebooks\\2015_11\\files\\Lightweight-jQuery-Youtube-Video-Player-simplePlayer-js\\demo.html
frame_se="""
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>simplePlayer.js jQuery Plugin Demo</title>
<style>
#video {
  position: relative;
  background: #000;
  width: 640px;
  margin: 20px auto;
}

#video img,
#video iframe { display: block; }

#play {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
  background: url('play-button.png') no-repeat 50% 50%;
  background-size: auto, cover;
  z-index: 9999;
}

#play:hover { background-color: rgba(0,0,0,0.2) !important; }
</style>
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="simplePlayer.js"></script>
<script>
 $("document").ready(function() {
  $("#video").simplePlayer();
 });
</script>
</head>

<body>
<div id="jquery-script-menu">
<div class="jquery-script-center">
<ul>
<li><a href="http://www.jqueryscript.net/other/Lightweight-jQuery-Youtube-Video-Player-simplePlayer-js.html">
Download This Plugin</a></li>
<li><a href="http://www.jqueryscript.net/">Back To jQueryScript.Net</a></li>
</ul>
<div class="jquery-script-ads"><script type="text/javascript"><!--
google_ad_client = "ca-pub-2783044520727903";
/* jQuery_demo */
google_ad_slot = "2780937993";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<div class="jquery-script-clear"></div>
</div>
</div>
<h1 style="margin-top:150px; text-align:center;">simplePlayer.js jQuery Plugin Demo</h1>
<div data-video="be0aFAqIhXk" id="video"> <img src="screenshot.jpg" alt="Use your own screenshot."> </div>
</body>
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-36251023-1']);
  _gaq.push(['_setDomainName', 'jqueryscript.net']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
</html>
"""
In [30]:
from IPython.display import IFrame

SEC7117: Сетевой запрос к file:///F:/IPython%20Notebooks/2015_11/files/Lightweight-jQuery-Youtube-Video-Player-simplePlayer-js/demo.html завершился неудачно. Этот экземпляр Internet Explorer не имеет следующих возможностей: privateNetworkClientServer

Здесь пришлось немного помудрить, оказалось что можно взять путь из строки после localhost:8888, оказывается, здесь теперь еще папка tree...

In [ ]:
IFrame('/tree/2015_11/files/Lightweight-jQuery-Youtube-Video-Player-simplePlayer-js/demo.html', width=700, height=700)
In [33]:
help(IFrame)
Help on class IFrame in module IPython.lib.display:

class IFrame(__builtin__.object)
 |  Generic class to embed an iframe in an IPython notebook
 |  
 |  Methods defined here:
 |  
 |  __init__(self, src, width, height, **kwargs)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  iframe = '\n        <iframe\n            width="{width}"\n   ...      ...

In [ ]:
transparent
theme=light
modestbranding: 0,
    controls=0
In [ ]:
IFrame('/tree/2015_11/files/Lightweight_myhacks/demo.html', width=700, height=700)
In [ ]:
# %load F:\\IPython Notebooks\\2015_11\\files\\Lightweight_myhacks\\simplePlayer.js
In [54]:
%%writefile "F:\\IPython Notebooks\\2015_11\\files\\Lightweight_myhacks\\simplePlayer.js"
var YTdeferred = jQuery.Deferred();

window.onYouTubeIframeAPIReady = function() {
 YTdeferred.resolve(window.YT);
};

(function( $ ) {

 $.ajaxSetup({
  cache: true
 });

 $.getScript( "https://www.youtube.com/iframe_api")
  .done(function( script, textStatus ) {
 });

 $.fn.simplePlayer = function() {

  var video = $(this);

  var play = $('<div />', { id: 'play' }).hide();

  var defaults = {
    autoplay: 1,
    autohide: 1,
    border: 0,
    wmode: 'transparent',
    enablejsapi: 1,
    modestbranding: 0,
    version: 3,
    hl: 'en_US',
    rel: 0,
    showinfo: 0,
    hd: 1,
                controls: 0,
                theme: 'light',
    iv_load_policy: 3 // add origin
   };

  // onYouTubeIframeAPIReady

  YTdeferred.done(function(YT) {
   play.appendTo( video ).fadeIn('slow');
  });

  function onPlayerStateChange(event) {
   if (event.data == YT.PlayerState.ENDED) {
    play.fadeIn(500);
   }
  }

  function onPlayerReady(event) {
   var replay = document.getElementById('play');
   replay.addEventListener('click', function() {
    player.playVideo();
   });
  }

  play.bind('click', function () {

   if ( !$('#player' ).length ) {

    $('<iframe />', {
     id: 'player',
     src: 'https://www.youtube.com/embed/' + video.data('video') + '?' + $.param(defaults)
    })
    .attr({ width: video.width(), height: video.height(), seamless: 'seamless' })
    .css('border', 'none')
    .appendTo( video );

    video.children('img').hide();

    $(this).css('background-image', 'url(play-button.png), url(' + video.children().attr('src') + ')').hide();
 
    player = new YT.Player('player', {events: {'onStateChange': onPlayerStateChange, 'onReady': onPlayerReady}});
   }

   $(this).hide();
  });

  return this;
 };
}( jQuery ));
Overwriting F:\\IPython Notebooks\\2015_11\\files\\Lightweight_myhacks\\simplePlayer.js
In [ ]:
37209047_Janusz_Mulak.jpg
In [ ]:
# %load F:\\IPython Notebooks\\2015_11\\files\\Lightweight_myhacks\\demo.html
In [53]:
%%writefile "F:\\IPython Notebooks\\2015_11\\files\\Lightweight_myhacks\\demo.html"
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>simplePlayer.js jQuery Plugin Demo</title>
<style>
#video {
  position: relative;
  background: #000;
  width: 640px;
  margin: 20px auto;
}

#video img,
#video iframe { display: block; }

#play {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
  background: url('play-button.png') no-repeat 50% 50%;
  background-size: auto, cover;
  z-index: 9999;
}

#play:hover { background-color: rgba(0,0,0,0.2) !important; }
</style>
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="simplePlayer.js"></script>
<script>
 $("document").ready(function() {
  $("#video").simplePlayer();
 });
</script>
</head>

<body>
<div id="jquery-script-menu">
<div class="jquery-script-center">
<ul>
<li><a href="http://www.jqueryscript.net/other/Lightweight-jQuery-Youtube-Video-Player-simplePlayer-js.html">Download This Plugin</a></li>
<li><a href="http://www.jqueryscript.net/">Back To jQueryScript.Net</a></li>
</ul>
<div class="jquery-script-ads"><script type="text/javascript"><!--
google_ad_client = "ca-pub-2783044520727903";
/* jQuery_demo */
google_ad_slot = "2780937993";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<div class="jquery-script-clear"></div>
</div>
</div>
<h1 style="margin-top:150px; text-align:center;">simplePlayer.js jQuery Plugin Demo</h1>
<div data-video="be0aFAqIhXk" id="video"> <img src="37209047_Janusz_Mulak.jpg" alt="Use your own screenshot."> </div>
</body>
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-36251023-1']);
  _gaq.push(['_setDomainName', 'jqueryscript.net']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
</html>
Overwriting F:\\IPython Notebooks\\2015_11\\files\\Lightweight_myhacks\\demo.html

Вот так можно показать мой фрейм

In [ ]:
IFrame('/tree/2015_11/files/Lightweight_myhacks/demo.html', width=700, height=700)

А вот так можно добавить параметры в строку источника фрейма

In [ ]:
https://www.youtube.com/embed/be0aFAqIhXk?autoplay=1&autohide=1&border=0
    &wmode=transparent&enablejsapi=1&modestbranding=0&version=3
    &hl=en_US&rel=0&showinfo=0&hd=1&theme=light&iv_load_policy=3
In [ ]:
var defaults = {
    autoplay: 1,
    autohide: 1,
    border: 0,
    wmode: 'transparent',
    enablejsapi: 1,
    modestbranding: 0,
    version: 3,
    hl: 'en_US',
    rel: 0,
    showinfo: 0,
    hd: 1,
                controls: 0,
                theme: 'light',
    iv_load_policy: 3 // add origin
   };


Посты чуть ниже также могут вас заинтересовать

Комментариев нет: