gdrive / src /index.js
mikmc's picture
Upload 10 files
804a4c3 verified
Raw History Blame Contribute Delete
8.65 kB
var credentials = {
client_id: "314289665801-q2q7t933bu52kf07rrl5pjhp4a8v335r.apps.googleusercontent.com",
client_secret: "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",
refresh_token: "1//0eYdOd4X1RDskCgYIARAAGA4SNwF-L9IrVR47ZnDyOK4vkNVTL44QHEU0iMovBhga4sfhRDyflh03MiVD1dehcSGOESLu6UcVc60",
};
async function handleRequest(request) {
var request_url = decodeURIComponent(request.url);
request_url = request_url.split("%3A").join(":");
// @ts-ignore
var url = new URL(request_url);
if (url.pathname == "/manifest.json") {
var json = JSON.stringify(
{
catalogs: [],
description: "VOD from Google Drive.",
id: "hy.stremio.googledrive",
logo: "https://raw.githubusercontent.com/mik25/stremio-greek-tv/master/pngwing.com.png",
name: "GDrive Reborn",
resources: ["stream"],
types: ["movie", "series"],
version: "2.0.0",
},
null,
2
);
// @ts-ignore
return new Response(json, {
headers: {
"content-type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Max-Age": "86400",
},
});
}
var pathSegments = url.pathname.split('/').filter(segment => segment);
if (pathSegments.length < 3) {
// @ts-ignore
return new Response('Help Yourself!', { status: 400 });
}
// @ts-ignore
var [path, type, idj] = pathSegments;
var id = idj.split(".")[0];
var results = await searchDrive(id, type);
var json = JSON.stringify({ streams: results }, null, 2);
// @ts-ignore
return new Response(json, {
headers: {
"content-type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Max-Age": "86400",
},
});
}
// @ts-ignore
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
function getMeta(id, type) {
// @ts-ignore
var [tt, s, e] = id.split(":");
// @ts-ignore
return fetch(`https://v2.sg.media-imdb.com/suggestion/t/${tt}.json`)
.then(res => res.json())
.then(json => json.d[0])
.then(({ l, y }) => ({ name: l, year: y }))
// @ts-ignore
.catch(err =>
// @ts-ignore
fetch(`https://v3-cinemeta.strem.io/meta/${type}/${tt}.json`)
.then(res => res.json())
.then(json => json.meta)
);
}
async function searchDrive(id, type) {
var q = await createQ(id, type);
var queryParams = {
q: q,
corpora: "allDrives",
includeItemsFromAllDrives: true,
pageSize: 1000,
supportsAllDrives: true,
fields: "files(id,name,size,driveId,md5Checksum)",
};
var queryString = Object.entries(queryParams)
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join("&");
await refreshToken();
var results = await fetch(
"https://content.googleapis.com/drive/v3/files?" + queryString,
{
headers: {
Authorization: "Bearer " + credentials.token,
},
}
)
.then(res => res.json())
.then(json => {
if (!json.files) {
return [];
}
json.files.sort((a, b) => b.size - a.size);
return json;
})
.then(json =>
json.files.map(x => {
const quality = getQuality(x.name); // e.g., "4K HDR"
const size = getSize(x.size); // e.g., "πŸ“¦ Size: 15.65 GB"
const codec = getCodec(x.name); // e.g., "🎞️ Codec: HEVC (x265)"
const icon = quality.includes("4K") ? "β™”" :
quality.includes("FHD") ? "β™•" :
quality.includes("HD") ? "β™–" :
quality.includes("SD") ? "β™˜" :
"πŸ”"; // Default icon
var name = `GDrive ${icon}\nQuality: ${quality.split(':')[1].trim()}`; // Dynamic icon
var title = `${x.name}\n${size}\n${codec}`.trim(); // Full title
var url = `https://www.googleapis.com/drive/v3/files/${x.id}?alt=media`;
return {
title,
name,
url,
behaviorHints: {
notWebReady: true,
proxyHeaders: {
request: {
Accept: "application/json",
Authorization: "Bearer " + credentials.token,
},
},
},
};
})
)
.then(results => {
if (results.length == 0) {
return [
{ name: "GDrive", title: "(404) No results", externalUrl: "/" },
];
}
return results;
});
return results;
}
async function createQ(id, type) {
var { name, year } = await getMeta(id, type);
var q =
"trashed=false and mimeType contains 'video/' and not name contains 'trailer' and not name contains 'sample'";
name.split(" ").forEach(x => {
q += " and ";
if (x.includes("'")) {
q += `(name contains '${x.replace("'", "")}' or name contains '${x.replace("'", "\\'")}')`;
} else {
q += `name contains '${x}'`;
}
});
if (type == "movie") {
q += ` and fullText contains '${year}'`;
} else {
// @ts-ignore
var [tt, s, e] = id.split(":");
var formatting = [[`s${s}e${e}`], [`s${s}`, `e${e}`]];
var seasonIsTwoDigit = parseInt(s) >= 10;
var episideIsTwoDigit = parseInt(e) >= 10;
if (!episideIsTwoDigit) formatting.push([`0${s}x0${e}`]);
if (!seasonIsTwoDigit && !episideIsTwoDigit) {
formatting.push([`s0${s}e0${e}`]);
formatting.push([`s0${s}`, `e0${e}`]);
formatting.push([`S0${s}E0${e}`]);
formatting.push([`S0${s}`, `E0${e}`]);
}
if (seasonIsTwoDigit && !episideIsTwoDigit) {
formatting.push([`s${s}e0${e}`]);
formatting.push([`s${s}`, `e0${e}`]);
formatting.push([`S${s}E0${e}`]);
formatting.push([`S${s}E${e}`]);
}
if (!seasonIsTwoDigit && episideIsTwoDigit) {
formatting.push([`0${s}e${e}`]);
formatting.push([`0${s}e0${e}`]);
formatting.push([`0${s}`, `e${e}`]);
}
q += ` and (${formatting
.map(format => `(${format.map(f => `name contains '${f}'`).join(" and ")})`)
.join(" or ")})`;
}
return q;
}
function getSize(size) {
var gb = 1024 * 1024 * 1024;
var mb = 1024 * 1024;
return (
"πŸ“¦ Size: " +
(size / gb > 1
? `${(size / gb).toFixed(2)} GB`
: `${(size / mb).toFixed(2)} MB`)
);
}
function getQuality(name) {
name = name.toLowerCase();
if (["2160", "4k", "uhd"].some(x => name.includes(x))) return "β™” Quality: 4K";
if (["1080", "fhd"].some(x => name.includes(x))) return "β™• Quality: FHD";
if (["720", "hd"].some(x => name.includes(x))) return "β™– Quality: HD";
if (["480p", "380p", "sd"].some(x => name.includes(x))) return "β™˜ Quality: SD";
return "πŸ” Quality: Unknown";
}
function getCodec(name) {
name = name.toLowerCase();
let codec = "🎞️ Codec: ";
if (name.includes("sdr")) codec += "SDR ";
if (["hevc", "h255", "h.265", "x.265", "x265"].some(x => name.includes(x))) {
codec += "🎬 HEVC (x265)";
}
return codec.trim() || "🎞️ Codec: Unknown";
}
async function refreshToken() {
if (
!credentials.token ||
// @ts-ignore
parseInt(new Date() - credentials.created) >= 3600 * 1000
) {
// @ts-ignore
return fetch("https://www.googleapis.com/oauth2/v4/token", {
body: JSON.stringify({
client_id: credentials["client_id"],
client_secret: credentials["client_secret"],
refresh_token: credentials["refresh_token"],
grant_type: "refresh_token",
}),
headers: {
"Content-Type": "application/json",
},
method: "POST",
})
.then(res => res.json())
.then(json => {
credentials.token = json.access_token;
credentials.created = new Date();
});
}
}