Skip to content

Commit

Permalink
Add CR Beta player compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
Mateus7G committed Jan 27, 2022
1 parent 6c7fc98 commit 432daad
Show file tree
Hide file tree
Showing 7 changed files with 229 additions and 98 deletions.
13 changes: 13 additions & 0 deletions Crunchyroll_Premium/background.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
const newHeader = {name: 'Access-Control-Allow-Origin', value: '*'};
const responseHeaders = details.responseHeaders.concat(newHeader);
return { responseHeaders };
},
{
urls: ["https://*.mateus7g.github.io/*", "https://pl.crunchyroll.com/*", "https://www.crunchyroll.com/*", "http://localhost/*"],
types : ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
},
["blocking","responseHeaders", "extraHeaders"]
)

242 changes: 168 additions & 74 deletions Crunchyroll_Premium/content.js
Original file line number Diff line number Diff line change
@@ -1,84 +1,178 @@
var HTML = document.documentElement.innerHTML;
const query = qry => document.body.querySelector(qry)
var preservedState = null

//function que pega algo dentro dentro do html.
function pegaString(str, first_character, last_character) {
if(str.match(first_character + "(.*)" + last_character) == null){
return null;
}else{
new_str = str.match(first_character + "(.*)" + last_character)[1].trim()
return(new_str)
}
if(str.match(first_character + "(.*)" + last_character) == null){
return null;
} else {
new_str = str.match(first_character + "(.*)" + last_character)[1].trim()
return new_str;
}
}

//function para remover elementos da página
function remove(element, name, untilRemoved = false, callback = () => {}) {
let tries = 0;
if (untilRemoved) {
const finishRemove = setInterval(() => {
if (query(element) != null) {
clearInterval(finishRemove)
console.log(`[CR Premium] Removendo ${name}...`);
const closeBtn = query(element + ' > .close-button')
if (closeBtn) closeBtn.click()
else query(element).style.display = 'none';

callback()
}
else if (tries > 250) clearInterval(finishRemove)
else tries++
}, 20)
} else if (query(element) != null) {
console.log(`[CR Premium] Removendo ${name}...`);
query(element).style.display = 'none';
}
}

//function que mudar o player para um mais simples.
function importPlayer(){
console.log("[CR Premium] Removendo player da Crunchyroll...");
var elem = document.getElementById('showmedia_video_player');
elem.parentNode.removeChild(elem);

console.log("[CR Premium] Pegando dados da stream...");
var video_config_media = JSON.parse(pegaString(HTML, "vilos.config.media = ", ";"));

console.log("[CR Premium] Adicionando o jwplayer...");
ifrm = document.createElement("iframe");
ifrm.setAttribute("id", "frame");
ifrm.setAttribute("src", "https://mateus7g.github.io/crp-iframe-player/");
ifrm.setAttribute("width","100%");
ifrm.setAttribute("height","100%");
ifrm.setAttribute("frameborder","0");
ifrm.setAttribute("scrolling","no");
ifrm.setAttribute("allowfullscreen","allowfullscreen");
ifrm.setAttribute("allow","autoplay; encrypted-media *");

if(document.body.querySelector("#showmedia_video_box") != null){
document.body.querySelector("#showmedia_video_box").appendChild(ifrm);
}else{
document.body.querySelector("#showmedia_video_box_wide").appendChild(ifrm);
}

//Remove Nota do topo sobre experimentar o premium
if (document.body.querySelector(".freetrial-note") != null) {
console.log("[CR Premium] Removendo Free Trial Note...");
document.body.querySelector(".freetrial-note").style.display = "none";
}

//Remove avisos q o video nn pode ser visto
if(document.body.querySelector(".showmedia-trailer-notice") != null){
console.log("[CR Premium] Removendo Trailer Notice...");
document.body.querySelector(".showmedia-trailer-notice").style.display = "none";
}

//Remove sugestão de inscrever-se para o trial gratuito
if(document.body.querySelector("#showmedia_free_trial_signup") != null){
console.log("[CR Premium] Removendo Free Trial Signup...");
document.body.querySelector("#showmedia_free_trial_signup").style.display = "none";
}

// Simular interação do usuário para deixar em fullscreen automaticamente
var element = document.getElementById("template_scroller");
if (element) element.click();

const series = document.querySelector('meta[property="og:title"]');
const up_next = document.querySelector('link[rel=next]');
chrome.storage.sync.get(['aseguir', 'cooldown'], function(items) {
ifrm.onload = function(){
ifrm.contentWindow.postMessage({
'video_config_media': [JSON.stringify(video_config_media)],
'lang': [pegaString(HTML, 'LOCALE = "', '",')],
'series': series ? series.content : undefined,
'up_next': up_next ? up_next.href : undefined,
'up_next_cooldown': items.cooldown === undefined ? 5 : items.cooldown,
'up_next_enable': items.aseguir === undefined ? true : items.aseguir,
'version': "1.0.3"
},"*");
};
});

//console.log(video_config_media);
var HTML = document.documentElement.innerHTML;
console.log("[CR Old] Removendo player da Crunchyroll...");
var elem = document.getElementById('showmedia_video_player');
elem.parentNode.removeChild(elem);

console.log("[CR Old] Pegando dados da stream...");
var video_config_media = JSON.parse(pegaString(HTML, "vilos.config.media = ", ";"));

//Remove Nota do topo sobre experimentar o premium
//Remove avisos q o video nn pode ser visto
//Remove sugestão de inscrever-se para o trial gratuito
remove(".freetrial-note", "Free Trial Note")
remove(".showmedia-trailer-notice", "Trailer Notice")
remove("#showmedia_free_trial_signup", "Free Trial Signup")

// Simular interação do usuário para deixar em fullscreen automaticamente
var element = document.getElementById("template_scroller");
if (element) element.click();

const appendTo = query("#showmedia_video_box") || query("#showmedia_video_box_wide")
const series = document.querySelector('meta[property="og:title"]');
const up_next = document.querySelector('link[rel=next]');

var message = {
'video_config_media': [JSON.stringify(video_config_media)],
'lang': [pegaString(HTML, 'LOCALE = "', '",')],
'series': series ? series.content : undefined,
'up_next': up_next ? up_next.href : undefined,
}

console.log("[CR Old] Adicionando o jwplayer...");
addPlayer(appendTo, message)
}

//renderiza player na versão beta
function importBetaPlayer(ready = false) {
var videoPlayer = query('.video-player');
if (!ready) {
setTimeout(() => importBetaPlayer(!!videoPlayer), 100);
return;
}

console.log("[CR Beta] Removendo player da Crunchyroll...");
remove('.video-player-placeholder', 'Video Placeholder')
const appendTo = videoPlayer.parentNode;
appendTo.removeChild(videoPlayer);

console.log("[CR Beta] Pegando dados da stream...");
var external_lang = preservedState.localization.locale.toLowerCase()
var ep_lang = preservedState.localization.locale.replace('-', '')
var ep_id = preservedState.watch.id
var ep = preservedState.content.byId[ep_id]
if (!ep) {window.location.reload(); return;}
var series_slug = ep.episode_metadata.series_slug_title
var external_id = ep.external_id.substr(4)
var old_url = `https://www.crunchyroll.com/${external_lang}/${series_slug}/episode-${external_id}`
var up_next = document.querySelector('a.up-next-title')
var playback = ep.playback

var message = {
'playback': playback,
'old_url': old_url,
'lang': ep_lang,
'up_next': up_next ? up_next.href : undefined,
}

console.log("[CR Beta] Adicionando o jwplayer...");
console.log("[CR Beta] Antiga URL:", old_url);
addPlayer(appendTo, message, true)
}

function addPlayer(element, playerInfo, beta = false) {
console.log("[CR Premium] Adicionando o jwplayer...");
var ifrm = document.createElement("iframe");
ifrm.setAttribute("id", "frame");
ifrm.setAttribute("src", "https://mateus7g.github.io/crp-iframe-player/");
ifrm.setAttribute("width","100%");
ifrm.setAttribute("height","100%");
ifrm.setAttribute("frameborder","0");
ifrm.setAttribute("scrolling","no");
ifrm.setAttribute("allowfullscreen","allowfullscreen");
ifrm.setAttribute("allow","autoplay; encrypted-media *");

element.appendChild(ifrm)

chrome.storage.sync.get(['aseguir', 'cooldown'], function(items) {
ifrm.onload = function() {
playerInfo['up_next_cooldown'] = items.cooldown === undefined ? 5 : items.cooldown;
playerInfo['up_next_enable'] = items.aseguir === undefined ? true : items.aseguir;
playerInfo['version'] = '1.1.0';
playerInfo['noproxy'] = true;
playerInfo['beta'] = beta;
ifrm.contentWindow.postMessage(playerInfo, "*");
};
});
}

//function ao carregar pagina.
function onloadfunction() {
if(pegaString(HTML, "vilos.config.media = ", ";") != null){
importPlayer();
}
var HTML = document.documentElement.innerHTML;
if(pegaString(HTML, "vilos.config.media = ", ";") != null){
importPlayer(); // old CR
} else if (preservedState != null){
importBetaPlayer(); // beta CR
remove(".erc-modal-portal > .overlay > .content-wrapper", "Free Trial Modal", true, () => document.body.classList = [])
registerChangeEpisode();
}
}

// function pra atualizar pagina quando mudar de episodio pela UI beta
var isLoaded = false

function registerChangeEpisode() {
const epChanged = setInterval(() => {
const videosWrapper = query('.videos-wrapper')
if (isLoaded && !videosWrapper) {
window.location.reload();
clearInterval(epChanged);
}
isLoaded = !!videosWrapper
}, 50)
}

document.addEventListener("DOMContentLoaded", onloadfunction, false);
document.onreadystatechange = function () {
if (document.readyState === "interactive") {
console.log("[CR Beta] Searching for INITIAL_STATE")
var HTML = document.documentElement.innerHTML
preservedState = JSON.parse(pegaString(HTML, "__INITIAL_STATE__ = ", ";"))
}

var crBetaStyle = document.createElement('style');
crBetaStyle.innerHTML = `.video-player-wrapper {
margin-top: 2rem;
margin-bottom: calc(-3vh - 7vw);
height: 57.25vw !important;
max-height: 82vh !important;
}`;
document.head.appendChild(crBetaStyle);
}
document.addEventListener("DOMContentLoaded", onloadfunction());
24 changes: 17 additions & 7 deletions Crunchyroll_Premium/manifest.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "Crunchyroll iFrame Player",
"version": "1.0.3",
"version": "1.1.0",
"description": "Permite ver todos os vídeos do crunchyroll gratuitamente.",
"author": "itallolegal",
"icons": { "48": "icon.png" },
Expand All @@ -10,14 +10,24 @@
"default_icon": "icon.png"
},
"permissions": [
"storage"
],
"webRequest",
"webRequestBlocking",
"http://localhost/*",
"https://pl.crunchyroll.com/*",
"https://www.crunchyroll.com/*",
"https://*.mateus7g.github.io/*",
"storage"
],
"content_scripts": [
{
"matches": ["http://www.crunchyroll.com/*", "https://www.crunchyroll.com/*"],
"css": ["content.css"],
"js": ["content.js"]
"matches": ["https://*.crunchyroll.com/*"],
"css": ["content.css"],
"js": ["content.js"],
"run_at": "document_start"
}
],
],
"background": {
"scripts": ["background.js"]
},
"manifest_version": 2
}
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,8 @@ Você pode encontrar a última versão disponível aqui:
8. Agora é só assistir 😉

Obrigado por utilizar.

# Nota - Crunchyroll Beta
O novo site **beta** do Crunchyroll quebra completamente a extensão.
Essa versão faz com que ao acessar o novo site, seu navegador acesse a versão antiga para puxar os dados do vídeo (não disponível na versão beta).
Isso quer dizer que, se a versão antiga do Crunchyroll for **completamente substituída** a extensão irá parar de funcionar permanentemente. :(
4 changes: 4 additions & 0 deletions assets/css/player.css
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ video {
height: 100%!important;
}

#player_div.beta-layout {
height: 80vh !important;
}

#player_div .jw-button-color.jw-toggle:not(.jw-icon-cast),
#player_div .jw-button-color:hover:not(.jw-icon-cast),
#player_div .jw-button-color:focus:not(.jw-icon-cast),
Expand Down
25 changes: 15 additions & 10 deletions assets/js/player.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
window.addEventListener("message", async e => {

// Meta para testar o player APENAS em localhost
if (window.location.href == "http://127.0.0.1:5500/") {
const href = window.location.href
if (href.startsWith("http://127.0.0.1") || href.startsWith("http://localhost")) {
let meta = document.createElement('meta');
meta.httpEquiv = "Content-Security-Policy";
meta.content = "upgrade-insecure-requests";
Expand All @@ -16,6 +17,7 @@ window.addEventListener("message", async e => {
for (let i in r) promises[i] = new Promise((resolve, reject) => request[i] = { resolve, reject });

let rgx = /http.*$/gm;
let is_beta = e.data.beta;
let needproxy = !e.data.noproxy;
let streamrgx = /_,(\d+.mp4),(\d+.mp4),(\d+.mp4),(\d+.mp4),(\d+.mp4),.*?m3u8/;
let streamrgx_three = /_,(\d+.mp4),(\d+.mp4),(\d+.mp4),.*?m3u8/;
Expand Down Expand Up @@ -191,12 +193,6 @@ window.addEventListener("message", async e => {
document.querySelectorAll("button.close-modal")[0].onclick = () => downloadModal.style.visibility = "hidden";
document.querySelectorAll("button.close-modal")[1].onclick = () => updateModal.style.visibility = "hidden";

if (user_lang[0] === 'ptBR')
document.getElementById('changelog').innerHTML = `<strong>Atualização disponível:</strong><br/>
- Add card <strong>A seguir</strong> & opções:<br/>
automaticamente muda para o próximo episódio<br/>
- Fix nome das series (ultimos eps)`;

// function ao clicar no botao de baixar
function download_ButtonClickAction() {
// Se estiver no mobile, muda um pouco o design do menu
Expand Down Expand Up @@ -230,7 +226,7 @@ window.addEventListener("message", async e => {
.addButton(rewind_iconPath, rewind_tooltipText, rewind_ButtonClickAction, rewind_id)
.addButton(download_iconPath, download_tooltipText, download_ButtonClickAction, download_id);

if (version !== "1.0.3")
if (version !== "1.1.0")
playerInstance.addButton(update_iconPath, update_tooltipText, update_ButtonClickAction, update_id);

// Definir URL e Tamanho na lista de download
Expand Down Expand Up @@ -264,6 +260,8 @@ window.addEventListener("message", async e => {
btnContainer.insertBefore(btn(rewind_id), old)
btnContainer.insertBefore(btn(forward_id), old)
btnContainer.removeChild(old)
if (is_beta)
document.getElementById('player_div').classList.add('beta-layout')
})

// Mostra uma tela de erro caso a legenda pedida não exista.
Expand Down Expand Up @@ -314,8 +312,15 @@ window.addEventListener("message", async e => {
}

async function getVilosMedia(url) {
console.log(await getAllOrigins(url))
return '{}'
const htmlPage = await getAllOrigins(url)
if (!htmlPage) return '{}'

const startIndex = htmlPage.indexOf('config.media =')
const initialConfig = htmlPage.substr(startIndex + 15)

const endIndex = initialConfig.indexOf('\n\n')
const config = initialConfig.substr(0, endIndex - 1)
return config || '{}'
}

// ---- MP4 ---- (baixar)
Expand Down
Loading

0 comments on commit 432daad

Please sign in to comment.