Skip to content

Commit

Permalink
Code cleaning + add comments
Browse files Browse the repository at this point in the history
  • Loading branch information
besuper committed May 17, 2022
1 parent 22ba3d4 commit f15fd20
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 442 deletions.
122 changes: 91 additions & 31 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,43 @@
const settings = {
chat: {
enabled: true,
},
current_watch: {
"id": "",
"link": "",
"title": "",
"time": 0.0,
"max_time": 0.0
}
};

chrome.storage.local.get(['chat_toggle'], function (result) {
settings.chat.enabled = result.chat_toggle;
});

$(window).on('load', function () {

setTimeout(() => {

let checkSub = getElementByXpath('//div[contains(@data-a-target, "player-overlay-content-gate")]');
// Check if the page contains Sub only VOD message
const checkSub = $("div[data-a-target='player-overlay-content-gate']");

if (checkSub.length) {

if (checkSub != undefined) {
// Replace sub only message with a loading gif
checkSub.html('<img src="https://i.ibb.co/NTpWgM1/Rolling-1s-200px.gif" alt="Loading VOD">');

checkSub.innerHTML = '<img src="https://i.ibb.co/NTpWgM1/Rolling-1s-200px.gif" alt="Loading VOD">';
// Get the current twitch player
const video = $("div[class*=persistent-player]");
const className = video.attr("class");

const video = getElementByXpath('//div[contains(@class, "persistent-player")]');
const className = video.className;
const vodID = window.location.toString().split("/").pop();

const contentStream = getElementByXpath('//div[contains(@data-target, "persistent-player-content")]');
settings.current_watch["link"] = vodID;

// Fetch VOD data
$.ajax({
url: "https://api.twitch.tv/kraken/videos/" + window.location.toString().split("/").pop(),
url: "https://api.twitch.tv/kraken/videos/" + vodID,
headers: {
"Client-Id": "kimne78kx3ncx6brgo4mv6wki5h1ko",
"Accept": "application/vnd.twitchtv.v5+json"
Expand All @@ -27,21 +50,20 @@ $(window).on('load', function () {
const domain = animated_preview_url.split("/storyboards")[0].trim();

setTimeout(() => {
// Remove the current player
video.remove();

const chanels = getElementsByXPath('//a[contains(@data-test-selector, "followed-channel")]');

chanels.forEach(chanel => {
chanel.onclick = on_click;
// Add on click event on every left tab channels
$("a[data-test-selector*='followed-channel']").click(() => {
on_click();
});

const vods = getElementsByXPath('//img[contains(@src, "vods/")]');
vods.forEach(vod => {
vod.onclick = on_click;
// Add on click event on every vods
$("img[src*='vods/']").click(() => {
on_click();
});

retrieveVOD(domain, contentStream, className);

retrieveVOD(domain, className);
}, 1000);
}
}
Expand All @@ -50,51 +72,72 @@ $(window).on('load', function () {
}, 1500);
})

// Refresh current page on click to remove the extension player
function on_click() {
setTimeout(() => {
document.location.reload();
}, 200);
}

function getDomain(url) {
return url.replace("http://", "").replace("https://", "").split("/")[0];
}
function retrieveVOD(domain, className) {
// Content twitch player
const contentStream = $("div[data-target='persistent-player-content']");

function retrieveVOD(domain, contentStream, className) {
const key = domain.split("/")[3];
const fullUrl = domain + "/chunked/index-dvr.m3u8";

let fullUrl = domain + "/chunked/index-dvr.m3u8";

checkUrl(fullUrl).then((data, statut) => {
checkUrl(fullUrl).then((_, statut) => {
if (statut === "success") {
contentStream.innerHTML = '<div data-setup="{}" preload="auto" class="video-js vjs-16-9 vjs-big-play-centered vjs-controls-enabled vjs-workinghover vjs-v7 player-dimensions vjs-has-started vjs-paused vjs-user-inactive ' + className + '" id="player" tabindex="-1" lang="en" role="region" aria-label="Video Player"> <video id="video" class="vjs-tech vjs-matrix" controls><source src="' + fullUrl + '" type="application/x-mpegURL" id="vod"></video></div>';

// Insert the new player
contentStream.html(
`<div data-setup="{}" preload="auto" class="video-js vjs-16-9 vjs-big-play-centered vjs-controls-enabled vjs-workinghover vjs-v7 player-dimensions vjs-has-started vjs-paused vjs-user-inactive ${className}" id="player" tabindex="-1" lang="en" role="region" aria-label="Video Player">
<video id="video" class="vjs-tech vjs-matrix" controls>
<source src="${fullUrl}" type="application/x-mpegURL" id="vod">
</video>
</div>`
);

document.getElementById('video').onloadedmetadata = () => {
let time = window.localStorage.getItem(key + "_time");
settings.current_watch["title"] = $("h2[data-a-target='stream-title']").text();
settings.current_watch["id"] = key;
settings.current_watch["max_time"] = player.currentTime() + player.remainingTime();

if (time != undefined) {
player.currentTime(time);
}
// Fetch current VOD time from background (local storage)
chrome.runtime.sendMessage({ type: "fetch_data", id: key }, function (response) {
if (response.success) {
settings.current_watch["time"] = response.data["time"];

let volume = window.localStorage.getItem("volume");
player.currentTime(settings.current_watch["time"]);
}
});

// Fetch current volume from local storage
const volume = window.localStorage.getItem("volume");

if (volume != undefined) {
player.volume(volume);
}

// Save new volume in local storage
player.on('volumechange', () => {
window.localStorage.setItem("volume", player.volume());
});

// Save new time in local storage
player.on('timeupdate', () => {
window.localStorage.setItem(key + "_time", player.currentTime());
settings.current_watch["time"] = player.currentTime();

chrome.runtime.sendMessage({ type: "update_time", data: settings.current_watch }, function (response) { });
});
};

// Add playback speed settings
var player = videojs('video', {
playbackRates: [0.5, 1, 1.25, 1.5, 2],
});

// Patch the m3u8 VOD file to be readable
videojs.Hls.xhr.beforeRequest = function (options) {
options.uri = options.uri.replace('unmuted.ts', 'muted.ts');
return options;
Expand All @@ -105,13 +148,18 @@ function retrieveVOD(domain, contentStream, className) {
document.addEventListener('keydown', (event) => {
const name = event.key;

// Backward and forward with arrow keys
if (name == "ArrowLeft") {
player.currentTime(player.currentTime() - 5);
} else if (name == "ArrowRight") {
player.currentTime(player.currentTime() + 5);
}
}, false);

if (!settings.chat.enabled) {
return;
}

setTimeout(() => {
let index = 0;

Expand All @@ -124,7 +172,7 @@ function retrieveVOD(domain, contentStream, className) {
});

setInterval(() => {
if (!player.paused() && messages != undefined && messages.comments.length > 0) {
if (!player.paused() && messages != undefined && messages.comments.length > 0 && settings.chat.enabled) {

if (messages.comments.length == index) {
fetchChat(player.currentTime(), messages._next).done(data => {
Expand All @@ -146,4 +194,16 @@ function retrieveVOD(domain, contentStream, className) {
}, 1200);
}
});
}

function checkUrl(url) {
return $.ajax({
url: url,
type: 'GET',
dataType: 'html',
async: false,
success: function (_, statut) {
return statut === "success";
}
});
}
18 changes: 10 additions & 8 deletions src/scripts/chat.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Chat need rework

let chat = undefined;

function addMessage(comment) {
Expand All @@ -6,8 +8,8 @@ function addMessage(comment) {
let user_color = comment.message.user_color;
let message = comment.message.body;

if (chat == undefined) {
chat = getElementByXpath('//ul[contains(@class, "InjectLayout")]');
if (chat == undefined || !chat.length) {
chat = $("ul[class*='InjectLayout']");
}

let injectLayout = document.createElement("li");
Expand All @@ -23,12 +25,12 @@ function addMessage(comment) {
<a data-test-selector="comment-author-selector" data-tt_content="tab_videos"
data-tt_medium="video-message-author"
class="ScCoreLink-udwpw5-0 FXIKh tw-link video-chat__message-author"
rel="noopener noreferrer" target="_blank" href="/`+ username + `"><span><span
rel="noopener noreferrer" target="_blank" href="/${username}"><span><span
class="chat-author__display-name" data-a-target="chat-message-username"
data-a-user="`+ username + `" data-test-selector="message-username"
style="color: `+ user_color + `;">` + username + `</span></span></a>
data-a-user="${username}" data-test-selector="message-username"
style="color: ${user_color};">${username}</span></span></a>
<span class="InjectLayout-sc-588ddc-0 cQDIBe">: </span><span class=""><span
class="text-fragment" data-a-target="chat-message-text">`+ message + `</span></span>
class="text-fragment" data-a-target="chat-message-text">${message}</span></span>
</div>
</div>
<div class="sc-AxjAm YOLYM video-chat__message-menu" data-test-selector="menu-options-wrapper">
Expand All @@ -38,9 +40,9 @@ function addMessage(comment) {
</div>
</div>`;

chat.appendChild(injectLayout);
chat.append(injectLayout);

if (getElementByXpath('//div[contains(@class, "unsynced")]') == undefined) {
if (!$("div[class*='unsynced']").length) {
injectLayout.scrollIntoView();
}

Expand Down
Loading

0 comments on commit f15fd20

Please sign in to comment.