Skip to content

Commit

Permalink
Updated files
Browse files Browse the repository at this point in the history
Removed (commented out) CouchPotato settings, and added Sonarr settings. Also added Flenix.co as a supported website.
  • Loading branch information
Ephellon committed May 3, 2018
1 parent 0225677 commit 9e81a0c
Show file tree
Hide file tree
Showing 12 changed files with 547 additions and 206 deletions.
117 changes: 86 additions & 31 deletions src/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,66 +6,118 @@ function generateHeaders(auth) {
}
const hash = btoa(`${auth.username}:${auth.password}`);
return {
...headers,
Authorization: `Basic ${hash}`,
...headers
};
}

// At this point you might want to think, WHY would you want to do
// these requests in a background page instead of the content script?
// This is because Movieo is served over HTTPS, so it won't accept requests to
// HTTP servers. Unfortunately, many people use CouchPotato over HTTP.
function viewCouchpotato(request, sendResponse) {
fetch(`${request.url}?id=${request.imdbId}`, {
headers: generateHeaders(request.basicAuth),
})
//function viewCouchpotato(request, sendResponse) {
// fetch(`${request.url}?id=${request.imdbId}`, {
// headers: generateHeaders(request.basicAuth),
// })
// .then(res => res.json())
// .then(res => {
// const success = res.success;
// sendResponse({ success, status: success ? res.media.status : null });
// })
// .catch(err => {
// sendResponse({ err: String(err) });
// });
//}
//
//function addCouchpotato(request, sendResponse) {
// fetch(`${request.url}?identifier=${request.imdbId}`, {
// headers: generateHeaders(request.basicAuth),
// })
// .then(res => res.json())
// .then(res => {
// sendResponse({ success: res.success });
// })
// .catch(err => {
// sendResponse({ err: String(err) });
// });
//}

function addRadarr(request, sendResponse) {
const headers = {
...generateHeaders(request.basicAuth),
'Content-Type': 'application/json',
'X-Api-Key': request.radarrToken,
};
const lookupQuery = encodeURIComponent(`imdb:${request.imdbId}`);

fetch(`${request.url}/lookup?term=${lookupQuery}`, { headers })
.then(res => res.json())
.then(res => {
const success = res.success;
sendResponse({ success, status: success ? res.media.status : null });
.then(data => {
if (!Array.isArray(data) || data.length < 1) {
throw new Error('Movie not found');
}
const body = {
...data[0],
monitored: true,
minimumAvailability: 'preDB',
qualityProfileId: request.radarrQualityProfileId,
rootFolderPath: request.radarrStoragePath,
addOptions: {
searchForMovie: true,
},
};
console.log('generated URL', request.url, headers);
console.log('body', body);
return body;
})
.then(body => {
return fetch(request.url, {
method: 'post',
headers,
body: JSON.stringify(body),
});
})
.catch(err => {
sendResponse({ err: String(err) });
});
}

function addCouchpotato(request, sendResponse) {
fetch(`${request.url}?identifier=${request.imdbId}`, {
headers: generateHeaders(request.basicAuth),
})
.then(res => res.json())
.then(res => {
sendResponse({ success: res.success });
if (res && res[0] && res[0].errorMessage) {
sendResponse({ err: res[0].errorMessage });
} else if (res && res.path) {
sendResponse({ success: 'Added to ' + res.path });
} else {
sendResponse({ err: 'unknown error' });
}
})
.catch(err => {
sendResponse({ err: String(err) });
});
}

function addRadarr(request, sendResponse) {
function addSonarr(request, sendResponse) {
const headers = {
...generateHeaders(request.basicAuth),
'Content-Type': 'application/json',
'X-Api-Key': request.radarrToken,
'X-Api-Key': request.sonarrToken,
};
const lookupQuery = encodeURIComponent(`imdb:${request.imdbId}`);

fetch(`${request.url}/lookup?term=${lookupQuery}`, { headers })
.then(res => res.json())
.then(data => {
if (!Array.isArray(data) || data.length < 1) {
throw new Error('Movie was not found.');
throw new Error('TV Show not found');
}
const body = {
...data[0],
monitored: true,
minimumAvailability: 'preDB',
qualityProfileId: request.radarrQualityProfileId,
rootFolderPath: request.radarrStoragePath,
qualityProfileId: request.sonarrQualityProfileId,
rootFolderPath: request.sonarrStoragePath,
addOptions: {
searchForMovie: true,
searchForSeries: true,
},
};
console.log('generated URL', request.url, headers);
console.log('body', body);
return body;
})
.then(body => {
Expand Down Expand Up @@ -154,7 +206,7 @@ function promiseRace(promises) {
return Promise.race(indexPromises).catch(index => {
// The promise has rejected, remove it from the list of promises and just continue the race.
let p = promises.splice(index, 1)[0];
p.catch(e => console.log(`[WTP] Plex request ${index} failed:`, e));
p.catch(e => console.log(`Plex request ${index} failed:`, e));
return promiseRace(promises);
});
}
Expand Down Expand Up @@ -185,15 +237,18 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
case 'SEARCH_PLEX':
searchPlex(request, sendResponse);
return true;
case 'VIEW_COUCHPOTATO':
viewCouchpotato(request, sendResponse);
return true;
case 'ADD_COUCHPOTATO':
addCouchpotato(request, sendResponse);
return true;
// case 'VIEW_COUCHPOTATO':
// viewCouchpotato(request, sendResponse);
// return true;
// case 'ADD_COUCHPOTATO':
// addCouchpotato(request, sendResponse);
// return true;
case 'ADD_RADARR':
addRadarr(request, sendResponse);
return true;
case 'ADD_SONARR':
addSonarr(request, sendResponse);
return true;
case 'OPEN_OPTIONS':
chrome.runtime.openOptionsPage();
return true;
Expand Down
50 changes: 50 additions & 0 deletions src/flenix.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
.web-to-plex-button {
font-weight: normal;
margin-top: -26px;
margin-left: 10px;
display: inline-block;
background: #727272;
color: #fff!important;
padding: 5px 10px;
border-radius: 1000px;
text-decoration: none!important;
text-transform: uppercase;
}

.web-to-plex-button--downloader {
color: #acb4bf!important;
}

.web-to-plex-button--downloader:hover {
background-color: #f67e56!important;
color: #ffffff!important;
}

.web-to-plex-button--found {
background-color: #ca7c1f!important;
color: #ffffff!important;
}

.web-to-plex-button--found:hover {
background-color: #f8c022!important;
}

.web-to-plex-notification {
cursor: pointer;
display: block;
position: fixed;
top: 80px;
left: 50%;
margin-left: -175px;
width: 350px;
background: #21262e;
color: #fff;
font-size: 20px;
padding: 10px;
border-radius: 4px;
z-index: 999000;
}

.web-to-plex-warning {
background: #fd6a00;
}
116 changes: 116 additions & 0 deletions src/flenix.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/* global parseOptions, modifyPlexButton, findPlexMedia */
function isMoviePage() {
const path = window.location.pathname;
if (!path.startsWith('/movies/')) {
return false;
}
// An example movie page: /movies/juno-hpsgt (can also have trailing slash!)
// Example non-movie page: /movies/watchlist/gbdx
// So if there is one slash extra (trailing slash not included), it's not a movie page.
const jup = path.replace('/movies/', '').slice(0, -1);
return !jup.includes('/');
}

function isMoviePageReady() {
return !!document.querySelector('.share-box');
}

function init() {
if (isMoviePage()) {
if (isMoviePageReady()) {
initPlexThingy();
} else {
// This almost never happens, but sometimes the page is too slow so we need to wait a bit.
// I could reproduce this by clicking on a movie in the movie watchlist,
// going back in history and then going forward in history.
setTimeout(() => {
initPlexThingy();
}, 1000);
}
}
}

parseOptions().then(() => {
window.addEventListener('popstate', init);
window.addEventListener('pushstate-changed', init);
init();
});

function initPlexThingy() {
const $button = renderPlexButton();
if (!$button) {
return;
}
const $title = document.querySelector('#dle-content .about > h1');
const $date = document.querySelector('.features > .reset:nth-child(2) a');
if (!$title || !$date) {
modifyPlexButton(
$button,
'error',
'Could not extract title or year from Flenix'
);
return;
}
const title = $title.innerText.trim();
const year = parseInt($date.innerText);
const imdbId = getImdbId(title, year);

findPlexMedia({ title, year, button: $button, imdbId });
}

function renderPlexButton() {
// The "download" button, which doesn't actually work
const $downloadButton = document.querySelector(
'#dle-content .about > .buttons > a[target="_blank"]'
);
if ($downloadButton) {
$downloadButton.remove();
}

const $actions = document.querySelector('.about > .buttons');
if (!$actions) {
console.log('Could not add Plex button.');
return null;
}
const $existingEl = document.querySelector('a.web-to-plex-button');
if ($existingEl) {
$existingEl.remove();
}
const el = document.createElement('a');
el.classList.add('roundButton', 'web-to-plex-button');
$actions.appendChild(el);
return el;
}

async function getImdbId(_title, _year) {
let title = null,
year = null;

if(!_title || !_year){
const $title = document.querySelector('#dle-content .about > h1');
const $date = document.querySelector('.features > .reset:nth-child(2) a');
if(!$title || !$date) {
return null;
}
title = $title.innerText.trim();
year = parseInt($date.innerText);
} else {
title = _title;
year = _year;
}

let json = {};

await fetch(`https://www.theimdbapi.org/api/find/movie?title=${ title }&year=${ year }`)
.then(function(response) {
return response.json();
})
.catch(function(error) {
throw error;
})
.then(function(data) {
return json = data[0];
});

return json.imdb_id || null;
}
2 changes: 1 addition & 1 deletion src/imdb.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const imdbId = getImdbId();

function renderPlexButton($parent) {
if (!$parent) {
console.log('[WTP] Could not add Plex button.');
console.log('Could not add Plex button.');
return null;
}
const $existingEl = document.querySelector('a.web-to-plex-button');
Expand Down
2 changes: 1 addition & 1 deletion src/letterboxd.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ function initPlexThingy() {
function renderPlexButton() {
const $actions = document.querySelector('.js-watch-panel .services');
if (!$actions) {
console.log('[WTP] Could not add Plex button.');
console.log('Could not add Plex button.');
return null;
}
const parentEl = document.createElement('p');
Expand Down
11 changes: 9 additions & 2 deletions src/manifest.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
{
"name": "Web to Plex",
"update_url": "https://clients2.google.com/service/update2/crx",

"name": "Web to Plex+",
"description": "Adds a button on various movie & TV show sites to open it in Plex.",
"manifest_version": 2,
"version": "3.3",
"version": "0.1",
"icons": {
"16": "img/16.png",
"48": "img/48.png",
Expand All @@ -28,6 +30,11 @@
"matches": ["https://letterboxd.com/film/*"],
"js": ["utils.js", "letterboxd.js"],
"css": ["letterboxd.css"]
},
{
"matches": ["https://flenix.co/movies/*"],
"js": ["utils.js", "flenix.js"],
"css": ["flenix.css"]
}
],
"background": {
Expand Down

0 comments on commit 9e81a0c

Please sign in to comment.