Skip to content

Commit

Permalink
Added Account Login
Browse files Browse the repository at this point in the history
  • Loading branch information
asaddon committed Dec 31, 2024
1 parent c62a0f7 commit 928cdcd
Show file tree
Hide file tree
Showing 7 changed files with 92 additions and 14 deletions.
10 changes: 10 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ const globalLimiter = rateLimit({
// Apply the rate limiter globally
app.use(globalLimiter);

// Check if both environment variables are defined
if (process.env.LOGIN_EMAIL && process.env.LOGIN_PASSWORD) {
// Run the function immediately
sources.initializeClientWithSession();

// Set the interval to run the function every 24 hours (86400000 milliseconds)
setInterval(sources.initializeClientWithSession, 86400000);
} else {
console.log('Environment variables LOGIN_EMAIL and LOGIN_PASSWORD are not defined.');
}
// Schedule the fetch every 12 hours (43200000 milliseconds)
setInterval(sources.fetchRecentMoviesForAllLanguages, 43200000);
// Initial fetch when the server starts
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"id": "community.einthusantv",
"version": "3.1.0",
"version": "3.2.0",
"name": "EinthusanTV",
"description": "Addon for Streaming from EinthusanTV by Asaddon",
"logo": "https://i.imgur.com/hmTKdwR.png",
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
"dotenv": "latest",
"express": "latest",
"express-rate-limit": "latest",
"node-html-parser": "latest",
"name-to-imdb": "latest",
"node-cache": "latest",
"node-html-parser": "latest",
"puppeteer": "latest",
"serve-index": "latest",
"stremio-addon-sdk": "latest",
"swagger-stats": "latest"
Expand Down
13 changes: 13 additions & 0 deletions shell.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{ pkgs ? import <nixpkgs> {} }:

pkgs.mkShell {
buildInputs = [
pkgs.nodejs
pkgs.chromium
];

# Set the Puppeteer executable path to the Chromium binary provided by Nix
shellHook = ''
export PUPPETEER_EXECUTABLE_PATH=${pkgs.chromium}/bin/chromium
'';
}
74 changes: 64 additions & 10 deletions sources.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { parse } = require("node-html-parser");
const config = require('./config');
require('dotenv').config();
const puppeteer = require("puppeteer");
const cheerio = require('cheerio');
const axios = require('axios');
const nameToImdb = require("name-to-imdb");
Expand Down Expand Up @@ -73,6 +74,60 @@ const client = axios.create({
retryDelay: (retryCount) => retryCount * 1000
});

// Puppeteer login function to attach session to the global Axios client
async function initializeClientWithSession() {
const browser = await puppeteer.launch({
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH,
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});

const page = await browser.newPage();
const email = process.env.LOGIN_EMAIL;
const password = process.env.LOGIN_PASSWORD;

if (!email || !password) {
throw new Error("Missing credentials. Please set LOGIN_EMAIL and LOGIN_PASSWORD in your .env file.");
}

try {
await page.goto("https://einthusan.tv/login/", { waitUntil: "networkidle2" });
await page.evaluate(() => {
const agreeButton = [...document.querySelectorAll('button')].find(button => button.textContent.includes('AGREE'));
if (agreeButton) agreeButton.click();
});
await page.type("#login-email", email, { delay: 50 });
await page.type("#login-password", password, { delay: 50 });
await page.click("#login-submit");
await page.waitForSelector(".profile", { visible: true, timeout: 10000 });

console.log("Login successful!");

// Extract cookies and CSRF token
const cookies = await page.cookies();
const csrfToken = cookies.find(cookie => cookie.name === "_gorilla_csrf")?.value;
const cookieString = cookies.map(cookie => `${cookie.name}=${cookie.value}`).join("; ");

if (!csrfToken) {
throw new Error("CSRF token not found after login.");
}

// Attach cookies and CSRF token to the global Axios client
client.defaults.headers.Cookie = cookieString;
client.defaults.headers["X-CSRF-Token"] = csrfToken;

console.log("Global Axios client updated with login session.");

// Close Puppeteer session
await browser.close();
} catch (error) {
console.error("Login failed:", error.message);
await browser.close();
throw error;
}
}


// Add retry interceptor
client.interceptors.response.use(undefined, async (err) => {
const config = err.config;
Expand Down Expand Up @@ -266,10 +321,10 @@ async function ttnumberToTitle(ttNumber) {

} catch (err) {
// Step 6: Error handling for OMDB API
console.error('Error Fetching Movie Data For IMDb ID: %s From OMDB API. Error Message: %s', ttNumber, err.message);
//console.error('Error Fetching Movie Data For IMDb ID: %s From OMDB API. Error Message: %s', ttNumber, err.message);

// Failsafe logic: Fetch title from IMDb suggestions API
console.info(`Attempting To Fetch Title From IMDb Suggestions API For IMDb ID: ${ttNumber}.`);
//console.info(`Attempting To Fetch Title From IMDb Suggestions API For IMDb ID: ${ttNumber}.`);

try {
const imdbApiUrl = `https://v2.sg.media-imdb.com/suggestion/t/${ttNumber}.json`;
Expand Down Expand Up @@ -349,7 +404,7 @@ async function stream(einthusan_id, lang) {
const movie = movies.find(m => m.id === einthusan_id); // Compare with IMDB ID
if (movie) {
mappedEinthusanId = movie.EinthusanID; // Get the Einthusan ID from the cache
console.info(`${useColors ? '\x1b[32m' : ''}Found Mapping For IMDB ID: ${einthusan_id} => EinthusanID: ${mappedEinthusanId}${useColors ? '\x1b[0m' : ''}`);
//console.info(`${useColors ? '\x1b[32m' : ''}Found Mapping For IMDB ID: ${einthusan_id} => EinthusanID: ${mappedEinthusanId}${useColors ? '\x1b[0m' : ''}`);
}
}

Expand All @@ -373,10 +428,8 @@ async function stream(einthusan_id, lang) {
const url = `${config.BaseURL}/movie/watch/${einthusan_id}/`;
const response = await requestQueue.add(() => client.get(url));
const $ = cheerio.load(response.data);

const videoSection = $('#UIVideoPlayer');
if (!videoSection.length) throw new Error("Video player section not found");

if (!videoSection.length) throw new Error(`Video player section not found using URL: ${url}`);
title = videoSection.attr("data-content-title");
const year = $('#UIMovieSummary div.info p').contents().first().text().trim();
const mp4Link = replaceIpInLink(videoSection.attr('data-mp4-link'));
Expand Down Expand Up @@ -547,7 +600,7 @@ async function getAllRecentMovies(maxPages, lang, logSummary = true) {
const cached = cache.get(cacheKey);
if (cached) {
if (logSummary) {
console.log(`${useColors ? '\x1b[32m' : ''}Cache Hit For Recent Movies:${useColors ? '\x1b[0m' : ''} ${useColors ? '\x1b[36m' : ''}${capitalizeFirstLetter(lang)}${useColors ? '\x1b[0m' : ''}, ${useColors ? '\x1b[33m' : ''}Max Pages:${useColors ? '\x1b[0m' : ''} ${useColors ? '\x1b[32m' : ''}${maxPages}${useColors ? '\x1b[0m' : ''}`);
//console.log(`${useColors ? '\x1b[32m' : ''}Cache Hit For Recent Movies:${useColors ? '\x1b[0m' : ''} ${useColors ? '\x1b[36m' : ''}${capitalizeFirstLetter(lang)}${useColors ? '\x1b[0m' : ''}, ${useColors ? '\x1b[33m' : ''}Max Pages:${useColors ? '\x1b[0m' : ''} ${useColors ? '\x1b[32m' : ''}${maxPages}${useColors ? '\x1b[0m' : ''}`);
}
return decompressData(cached);
}
Expand Down Expand Up @@ -678,7 +731,7 @@ async function meta(einthusan_id, lang) {
const movie = movies.find(m => m.id === einthusan_id); // Compare with IMDB ID
if (movie) {
mappedEinthusanId = movie.EinthusanID; // Get the Einthusan ID from the cache
console.info(`${useColors ? '\x1b[32m' : ''}Found Mapping For IMDB ID: ${einthusan_id} => EinthusanID: ${mappedEinthusanId}${useColors ? '\x1b[0m' : ''}`);
//console.info(`${useColors ? '\x1b[32m' : ''}Found Mapping For IMDB ID: ${einthusan_id} => EinthusanID: ${mappedEinthusanId}${useColors ? '\x1b[0m' : ''}`);
}
}

Expand Down Expand Up @@ -786,5 +839,6 @@ module.exports = {
stream,
getAllRecentMovies,
fetchRecentMoviesForAllLanguages,
meta
};
meta,
initializeClientWithSession
};

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion vue/dist/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<!-- <link rel="icon" type="image/svg+xml" href="/vite.svg" /> -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- <title>Trakt Lists</title> -->
<script type="module" crossorigin src="/assets/index-6ed31919.js"></script>
<script type="module" crossorigin src="/assets/index-62cde5da.js"></script>
<link rel="stylesheet" href="/assets/index-6ac68831.css">
</head>
<body>
Expand Down

0 comments on commit 928cdcd

Please sign in to comment.