video_background

use video as page background

  1. // ==UserScript==
  2. // @name video_background
  3. // @name:zh-CN video_background
  4. // @name:zh-TW video_background
  5. // @name:ja video_background
  6. // @namespace video_background
  7. // @supportURL https://github.com/zhuzemin
  8. // @description:zh-CN use video as page background
  9. // @description:zh-TW use video as page background
  10. // @description:ja use video as page background
  11. // @description use video as page background
  12. // @include https://*
  13. // @include http://*
  14. // @exclude *://*.jpg
  15. // @exclude *://*.gif
  16. // @exclude *://*.png
  17. // @exclude *://*.mp4
  18. // @exclude *://*.swf
  19. // @exclude *://*.pdf
  20. // @exclude https://anime1.me
  21. // @version 1.94
  22. // @grant GM_xmlhttpRequest
  23. // @grant GM_registerMenuCommand
  24. // @grant GM_setValue
  25. // @grant GM_getValue
  26. // @run-at document-start
  27. // @author zhuzemin
  28. // @license Mozilla Public License 2.0; http://www.mozilla.org/MPL/2.0/
  29. // @license CC Attribution-ShareAlike 4.0 International; http://creativecommons.org/licenses/by-sa/4.0/
  30. // @connect-src 127.0.0.1
  31. // ==/UserScript==
  32. var config = {
  33. 'debug':false
  34. }
  35. var debug = config.debug ? console.log.bind(console) : function () {
  36. };
  37. var host='http://127.0.0.1/';
  38. var bgColor='#D8E0E0';
  39. var rndStart=true;
  40. var videoList;
  41. var dirList;
  42. var urlRoot;
  43. var usedList=[];
  44. var dirCount=0;
  45. var hostname;
  46. var textColorList;
  47. var ytbList;
  48. var ytbEnable;
  49. // prepare UserPrefs
  50. setUserPref(
  51. 'urlRoot',
  52. host+'******',
  53. 'Set root url',
  54. `Url from HFS.(.mp4 or dir)`,
  55. ','
  56. );
  57. setUserPref(
  58. 'ytbPlaylistUrl',
  59. 'https://www.youtube.com/playlist?list=PLmlTcWwPyp188O1lK2fyYA_WFckZNrb0b',
  60. 'Set Youtube Playlist url',
  61. `Youtube Playlist url`,
  62. ','
  63. );
  64. /*setUserPref(
  65. 'textBGcolorOpacity',
  66. '0.95',
  67. 'Set Text BG-Color Opacity',
  68. `Opacity: `,
  69. ','
  70. );*/
  71.  
  72. class ObjectRequest{
  73. constructor(url) {
  74. this.method = 'GET';
  75. this.url = url;
  76. this.data=null,
  77. this.headers = {
  78. 'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
  79. 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
  80. //'Accept': 'application/atom+xml,application/xml,text/xml',
  81. //'Referer': window.location.href,
  82. };
  83. this.charset = 'text/plain;charset=utf8';
  84. this.other=null;
  85. }
  86. }
  87.  
  88. var init = function () {
  89. if (window.self === window.top || window.location.href.includes('https://www.youtube.com/embed/')) {
  90. textBGcolorOpacity = GM_getValue('textBGcolorOpacity');
  91. if (textBGcolorOpacity == undefined || textBGcolorOpacity == '') {
  92. textBGcolorOpacity = 0.95;
  93. }
  94. else{
  95. textBGcolorOpacity=parseFloat(textBGcolorOpacity);
  96. }
  97. ytbEnable = GM_getValue('ytbEnable');
  98. if (ytbEnable != undefined) {
  99. if (ytbEnable == 'true') {
  100. ytbEnable = true;
  101.  
  102. }
  103. else if (ytbEnable == 'false') {
  104. ytbEnable = false;
  105. }
  106. }
  107. ytbList = GM_getValue('ytbList');
  108. if (ytbList == undefined || ytbList == '') {
  109. ytbList = [];
  110. }
  111. urlRoot = GM_getValue('urlRoot');
  112. if (urlRoot == undefined || urlRoot == '') {
  113. urlRoot = null;
  114. }
  115. videoList = GM_getValue('videoList');
  116. if (videoList == undefined || videoList == '') {
  117. videoList = [];
  118. }
  119. /*dirList = GM_getValue('dirList');
  120. if (dirList == undefined || dirList == '') {
  121. dirList = [];
  122. }
  123. debug(dirList);*/
  124. var blockList = GM_getValue('blockList');
  125. if (blockList == undefined || blockList == '') {
  126. blockList = [];
  127. }
  128. else {
  129. blockList= blockList.filter(function(item, pos) {
  130. return blockList.indexOf(item) == pos;
  131. })
  132. }
  133. debug('blockList: '+blockList);
  134. textColorList = GM_getValue('textColorList');
  135. if (textColorList == undefined || textColorList == '') {
  136. textColorList = [];
  137. }
  138. else {
  139. textColorList= textColorList.filter(function(item, pos) {
  140. return textColorList.indexOf(item) == pos;
  141. })
  142. }
  143. debug('textColorList: '+textColorList);
  144.  
  145. /*var lastTime=GM_getValue('lastTime')||0;
  146. var present=parseInt(new Date(). getTime()/1000);
  147. debug(present-parseInt(lastTime));
  148. if(present-parseInt(lastTime)>86400){
  149. videoList=[];
  150. dirList=[];
  151. GM_setValue('lastTime',present);
  152. GM_setValue('videoList',JSON.stringify(videoList));
  153. GM_setValue('dirList',JSON.stringify(dirList));
  154. }*/
  155. if (!window.location.href.includes('https://www.youtube.com/embed/')) {
  156.  
  157. hostname = getLocation(window.location.href).hostname;
  158. CreateButton('Text BG-color', function () {
  159. var index = textColorList.indexOf(hostname);
  160. var divList = document.querySelectorAll('div');
  161. if (index == -1) {
  162.  
  163. for (var div of divList) {
  164. div.style.backgroundColor = bgColor;
  165. //div.style.opacity=textBGcolorOpacity;
  166. }
  167. textColorList.push(hostname);
  168. }
  169. else {
  170. for (var div of divList) {
  171. div.style.backgroundColor = '';
  172. //div.style.opacity=1;
  173. }
  174. textColorList.splice(index, 1);
  175.  
  176. }
  177. debug('textColorList: '+textColorList);
  178. GM_setValue('textColorList', textColorList);
  179.  
  180. }, 36);
  181. CreateButton('Clear file list', function () {
  182. dirList = [];
  183. videoList = [];
  184. ytbList = [];
  185. GM_setValue('videoList', videoList);
  186. GM_setValue('dirList', dirList);
  187. GM_setValue('ytbList', ytbList);
  188. }, 72);
  189.  
  190. CreateButton('Add/Del Block List', function (e) {
  191. var msg;
  192. var index = blockList.indexOf(hostname);
  193. if (index > -1) {
  194. blockList.splice(index, 1);
  195. msg = 'Del Success';
  196. }
  197. else {
  198. blockList.push(hostname);
  199. msg = 'Add Success';
  200. }
  201. GM_setValue('blockList', blockList);
  202. e.target.innerHTML = msg;
  203. setTimeout(function () {
  204. e.target.innerHTML = 'Add/Del Block List';
  205. }, 1000);
  206. }, 108);
  207.  
  208. CreateButton('Youtube Enable/Disable', function (e) {
  209. var msg;
  210. if (ytbEnable) {
  211. ytbEnable = false;
  212. msg = 'Youtube Disable';
  213. }
  214. else {
  215. ytbEnable = true;
  216. msg = 'Youtube Enable';
  217. }
  218. GM_setValue('ytbEnable', ytbEnable);
  219. e.target.innerHTML = msg;
  220. setTimeout(function () {
  221. e.target.innerHTML = 'Youtube Enable/Disable';
  222. }, 1000);
  223. }, 144);
  224.  
  225. if (!blockList.includes(hostname)) {
  226. if (urlRoot != null && !ytbEnable) {
  227. urlRoot = urlRoot.replace(/http:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\//, host);
  228. if (/\.mp4$/.test(urlRoot)) {
  229. insertVideo(urlRoot);
  230. }
  231. else {
  232. if (videoList.length == 0) {
  233. //var obj = new ObjectRequest(urlRoot);
  234. var obj = new ObjectRequest(urlRoot + '?tpl=list&folders-filter=\\\\&recursive');
  235. request(obj, HandleHFS);
  236. debug(urlRoot);
  237.  
  238. }
  239. else {
  240. videoShuffle(insertVideo);
  241.  
  242. }
  243.  
  244. }
  245. }
  246. else if (ytbEnable) {
  247. if (ytbList.length == 0) {
  248. var ytbPlaylistUrl = GM_getValue('ytbPlaylistUrl');
  249. if (ytbPlaylistUrl == undefined || ytbPlaylistUrl == '') {
  250. ytbPlaylistUrl = null;
  251. }
  252. if (ytbPlaylistUrl != null) {
  253. ytbPlaylistUrl = ytbPlaylistUrl.match(/https:\/\/www.youtube.com\/playlist\?list=(.*)$/);
  254. if (ytbPlaylistUrl != null) {
  255. ytbPlaylistUrl = ytbPlaylistUrl[1];
  256. ytbPlaylistUrl = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2C+id&playlistId=' + ytbPlaylistUrl + '&key=AIzaSyAbzugt7o1RRhBVDyPyZxZTeriH-3Ogtkg';
  257.  
  258. debug('ytbPlaylistUrl: ' + ytbPlaylistUrl);
  259. var obj = new ObjectRequest(ytbPlaylistUrl);
  260. request(obj, function (respObj) {
  261. var json = JSON.parse(respObj.responseText);
  262. debug('json: ' + json);
  263. for (var item of json.items) {
  264. var videoId = item.snippet.resourceId.videoId;
  265. var videoUrl = 'https://www.youtube.com/embed/' + videoId + '?controls=0&autoplay=1&mute=1';
  266. ytbList.push(videoUrl);
  267. }
  268. GM_setValue('ytbList', ytbList);
  269. videoList = ytbList;
  270. videoShuffle(insertYtb);
  271.  
  272. });
  273. }
  274.  
  275. }
  276. }
  277. else {
  278. videoList = ytbList;
  279. videoShuffle(insertYtb);
  280. }
  281. }
  282. }
  283.  
  284. }
  285. else if (window.location.href.includes('https://www.youtube.com/embed/')) {
  286. var video = document.querySelector('video.video-stream.html5-main-video');
  287. setTimeout(function () {
  288. var randomNum = Math.floor(Math.random() * (video.duration - 0));
  289. video.currentTime=randomNum;
  290. },5000);
  291. var interval=setInterval(function () {
  292. if(parseInt(video.currentTime)==parseInt(video.duration)){
  293. videoList=ytbList;
  294. videoShuffle(insertYtb);
  295. clearInterval(interval);
  296.  
  297. }
  298. },15000);
  299. var frame=document.querySelector('#video_bg');
  300. window.addEventListener('message', function (e) {
  301. debug(e.data);
  302. if (e.data == "pause") {
  303. if(frame!=null){
  304. frame.contentWindow.postMessage("pause", "*");
  305. }
  306. else {
  307. video.pause();
  308.  
  309. }
  310.  
  311. }
  312. else if (e.data == 'play') {
  313. if(frame!=null){
  314. frame.contentWindow.postMessage("play", "*");
  315. }
  316. else {
  317. video.play();
  318. }
  319. }
  320. });
  321.  
  322.  
  323. }
  324.  
  325. }
  326. }
  327. function CreateButton(text,func,positionBtm){
  328. var btn=document.createElement("button");
  329. btn.type="button";
  330. btn.innerHTML=text;
  331. btn.style=`
  332. position: fixed;
  333. right: 0px;
  334. bottom: `+positionBtm+`px;
  335. z-index: 10000;
  336. opacity:0.1;
  337. `;
  338. if(positionBtm!=0&&positionBtm!=36){
  339. btn.style.display='none';
  340. document.body.firstChild.addEventListener('mouseover',function () {
  341. btn.style.display='block';
  342. });
  343. document.body.firstChild.addEventListener('mouseout',function () {
  344. setTimeout(function () {
  345. btn.style.display='none';
  346. },3000);
  347. });
  348. }
  349. btn.addEventListener('click',func);
  350. btn.addEventListener('mouseout',function () {
  351. btn.style.opacity=0.1;
  352.  
  353. });
  354. btn.addEventListener('mouseover',function () {
  355. btn.style.opacity=1;
  356. });
  357. document.body.insertBefore(btn,document.body.firstChild);
  358. }
  359. function HandleHFS(responseObj) {
  360. if (responseObj.status == 200) {
  361. var fileList=responseObj.responseText.split('\r\n');
  362. debug(fileList);
  363. for(var file of fileList){
  364. if(/\.mp4$/.test(file)){
  365. videoList.push(file);
  366. GM_setValue('videoList',videoList);
  367.  
  368. }
  369. }
  370. videoShuffle(insertVideo);
  371. }
  372. }
  373. /*
  374. function HandleHFS(responseObj){
  375. if(responseObj.status==200){
  376. if(dirCount!=0){
  377.  
  378. dirCount--;
  379. }
  380. debug('dirCount: '+dirCount);
  381. var dom = new DOMParser().parseFromString(responseObj.responseText, "text/html");
  382. var files = dom.querySelector('#files');
  383. var trList=files.querySelectorAll("tr");
  384. for(var tr of trList){
  385. var a=tr.querySelector('a');
  386. debug('a.href: '+a.href);
  387. var url=a.href.replace(/https?:\/\/.*\/([^\/]*((\.mp4)|\/)$)/, function(match, $1, $2, offset, original){ return responseObj.finalUrl+$1;})
  388. debug('url: '+url);
  389. if(/\.mp4$/.test(a.textContent)&&!videoList.includes(url)){
  390. videoList.push(url);
  391. GM_setValue('videoList',JSON.stringify(videoList));
  392. }
  393. else if(a.textContent!='Name'){
  394. var img=a.querySelector('img');
  395. debug(img.src);
  396. if(img.src.includes('/~img_folder')){
  397. if(dirList.length!=0){
  398. debug(dirList)
  399. for(var existUrl of dirList){
  400. if(existUrl.includes(url)){
  401. break;
  402. }
  403. else if(existUrl==dirList[dirList.length-1]){
  404. debug('existUrl: '+existUrl+' & '+'url: '+url);
  405. dirCount++;
  406. var obj=new ObjectRequest(url);
  407. dirList.push(url);
  408. GM_setValue('dirList',JSON.stringify(dirList));
  409. request(obj,HandleHFS);
  410.  
  411.  
  412.  
  413. }
  414. }
  415.  
  416. }
  417. else {
  418. dirCount++;
  419. dirList.push(url);
  420. GM_setValue('dirList',JSON.stringify(dirList));
  421. var obj=new ObjectRequest(url);
  422. request(obj,HandleHFS);
  423.  
  424. }
  425.  
  426. }
  427.  
  428. }
  429.  
  430.  
  431. if (tr==trList[trList.length-1]&&dirCount==0) {
  432. videoShuffle();
  433. if (textColorList.includes(hostname)) {
  434. var divList=document.querySelectorAll('div');
  435. for (var div of divList){
  436. div.style.backgroundColor='#D8E0E0';
  437. }
  438. }
  439. }
  440. }
  441. dirCount--;
  442. }
  443. }
  444. */
  445. window.addEventListener('DOMContentLoaded', init);
  446. function request(object,func) {
  447.  
  448. var retries = 3;
  449. GM_xmlhttpRequest({
  450. method: object.method,
  451. url: object.url,
  452. data: object.data,
  453. headers: object.headers,
  454. overrideMimeType: object.charset,
  455. timeout:120000,
  456. //synchronous: true
  457. onload: function (responseDetails) {
  458. //debug(responseDetails);
  459. if (responseDetails.status != 200&&responseDetails.status != 302) {
  460. // retry
  461. if (retries--) { // *** Recurse if we still have retries
  462. setTimeout(request,2000);
  463. return;
  464. }
  465. }
  466. //Dowork
  467. func(responseDetails,object.other);
  468. },
  469. ontimeout: function (responseDetails) {
  470. debug(responseDetails);
  471. //Dowork
  472. func(responseDetails,object.other);
  473.  
  474. },
  475. ononerror: function (responseDetails) {
  476. debug(responseDetails);
  477. //Dowork
  478. func(responseDetails,object.other);
  479.  
  480. }
  481. })
  482. }
  483. function setUserPref(varName, defaultVal, menuText, promtText, sep){
  484. GM_registerMenuCommand(menuText, function() {
  485. var val = prompt(promtText, GM_getValue(varName, defaultVal));
  486. if (val === null) { return; } // end execution if clicked CANCEL
  487. // prepare string of variables separated by the separator
  488. if (sep && val){
  489. var pat1 = new RegExp('\\s*' + sep + '+\\s*', 'g'); // trim space/s around separator & trim repeated separator
  490. var pat2 = new RegExp('(?:^' + sep + '+|' + sep + '+$)', 'g'); // trim starting & trailing separator
  491. //val = val.replace(pat1, sep).replace(pat2, '');
  492. }
  493. //val = val.replace(/\s{2,}/g, ' ').trim(); // remove multiple spaces and trim
  494. GM_setValue(varName, val);
  495. // Apply changes (immediately if there are no existing highlights, or upon reload to clear the old ones)
  496. //if(!document.body.querySelector(".THmo")) THmo_doHighlight(document.body);
  497. //else location.reload();
  498. });
  499. }
  500. function videoShuffle(func) {
  501. debug('videoShuffle');
  502. debug('videoList: '+videoList);
  503. for(var used of usedList){
  504.  
  505. var index = videoList.indexOf(used);
  506. if (index > -1) {
  507. videoList.splice(index, 1);
  508. }
  509. }
  510. var randomNum = Math.floor(Math.random() * (videoList.length - 0));
  511. if(window.location.href.includes('https://www.youtube.com/embed/')){
  512.  
  513. videoList = ytbList;
  514. }
  515. var url=videoList[randomNum];
  516. /*if(rndStart){
  517. if(ytbEnable&&!window.location.href.includes('https://www.youtube.com/embed/')){
  518. var videoId=url.match(/https:\/\/www.youtube.com\/embed\/(.*)\?controls=0&autoplay=1&mute=1/);
  519. videoId=videoId[1];
  520. var urlVidInfo='https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id='+videoId+'&key=AIzaSyAbzugt7o1RRhBVDyPyZxZTeriH-3Ogtkg';
  521. var obj=new ObjectRequest(urlVidInfo);
  522. request(obj,function (respObj) {
  523. var json=JSON.parse(respObj.responseText);
  524. for(var item of json.items){
  525. if(item.id==videoId){
  526. debug(JSON.stringify(json));
  527. var duration=item.contentDetails.duration;
  528. debug(duration);
  529. var reptms = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/;
  530. var hours = 0, minutes = 0, seconds = 0, totalseconds;
  531.  
  532. if (reptms.test(duration)) {
  533. var matches = reptms.exec(duration);
  534. debug(matches);
  535. if (matches[1]) hours = Number(matches[1]);
  536. if (matches[2]) minutes = Number(matches[2]);
  537. if (matches[3]) seconds = Number(matches[3]);
  538. totalseconds = hours * 3600 + minutes * 60 + seconds;
  539. }
  540. randomNum = Math.floor(Math.random() * (totalseconds - 0));
  541. url='https://www.youtube.com/embed/'+videoId+'?controls=0&autoplay=1&mute=1&start='+randomNum;
  542. debug(url);
  543. func(url);
  544. }
  545. }
  546. })
  547.  
  548. }
  549. else{
  550. func(url);
  551.  
  552. }
  553.  
  554. }*/
  555. func(url);
  556. if (textColorList.includes(hostname)) {
  557. var divList=document.querySelectorAll('div');
  558. for (var div of divList){
  559. div.style.backgroundColor=bgColor;
  560. //div.style.opacity=textBGcolorOpacity;
  561. }
  562. }
  563.  
  564. }
  565. function insertVideo(url) {
  566. debug('insertVideo');
  567. var video = document.createElement("video");
  568. video.style = 'width:100%';
  569. video.src = url;
  570. video.autoplay = true;
  571. video.muted=true;
  572. var div = document.createElement("div");
  573. div.style = "width:100%; position: fixed; top: 0; left: 0; z-index: -100;";
  574. div.insertBefore(video, null);
  575. debug(url);
  576. document.body.insertBefore(div, null);
  577.  
  578. window.addEventListener("focus", function () {
  579. video.play();
  580. });
  581. window.addEventListener("blur", function () {
  582. video.pause();
  583. });
  584. video.addEventListener('onended',function () {
  585. document.removeChild(div);
  586. videoShuffle(insertVideo);
  587. });
  588. video.addEventListener('loadeddata', (event) => {
  589. var randomNum = Math.floor(Math.random() * (video.duration - 0));
  590. video.currentTime=randomNum;
  591. });
  592. usedList.push(url);
  593. }
  594. function getLocation(href) {
  595. var l = document.createElement("a");
  596. l.href = href;
  597. return l;
  598. }
  599. function insertYtb(url) {
  600. debug('insertYtb');
  601. if(window.location.href.includes('https://www.youtube.com/embed/')) {
  602. while (document.body.firstChild) {
  603. document.body.removeChild(document.body.firstChild);
  604. }
  605. }
  606. var iframe = document.createElement("iframe");
  607. iframe.id='video_bg';
  608. iframe.style = 'width:100%;height:100%;';
  609. iframe.src = url;
  610. iframe.allow = "accelerometer;";
  611. iframe.frameborder='0';
  612. var div = document.createElement("div");
  613. div.style = "width:100%; height:100%;position: fixed; top: 0; left: 0; z-index: -100;";
  614. div.insertBefore(iframe, null);
  615. debug(url);
  616. document.body.insertBefore(div, null);
  617.  
  618. window.addEventListener("focus", function () {
  619. iframe.contentWindow.postMessage("play", "*");
  620. });
  621. window.addEventListener("blur", function () {
  622. iframe.contentWindow.postMessage("pause", "*");
  623. });
  624.  
  625. usedList.push(url);
  626. }
  627. function iframeRef( frameRef ) {
  628. return frameRef.contentWindow
  629. ? frameRef.contentWindow.document
  630. : frameRef.contentDocument
  631. }