Snippets
Created by
Delan Azabani
last modified
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | /// stan downloader
/// <https://bitbucket.org/delan/workspace/snippets/kxyjaj>
/// <https://bucket.daz.cat/stan.js>
///
/// bookmarklet version below:
/// javascript:(script=>{script.src="https://bucket.daz.cat/stan.js";document.body.appendChild(script)})(document.createElement("script"))
(() => {
const links = [...document.querySelectorAll("a.episode__play")];
if (links.length < 1) {
alert("fatal: this doesn’t look like a season page (play.stan.com.au/programs/.../seasons/...).");
return;
}
if (typeof EmeInterception == "undefined") {
alert("fatal: this script depends on the Widevine L3 Decryptor (a Chrome extension). search for widevine-l3-decryptor, install it, then try again.");
return;
}
if (!confirm("before we start, make sure your devtools console is open, so you can follow the instructions.")) {
return;
}
const quality = promptOrThrow("quality? [low, medium, high, sd, hd(?), uhd(?)]\n\nnote: choosing too high a quality for the episodes results in low!", "sd");
const saved = JSON.parse(promptOrThrow("saved episode list (or null)?", "null"));
const commands = [];
const result = [];
next();
function promptOrThrow(...rest) {
const result = prompt(...rest);
if (result == null) {
throw new Error("cancelled by user");
}
return result;
}
async function next() {
if (saved != null || links.length < 1) {
const episodes = saved ?? result;
console.log(`saved episode list: ${JSON.stringify(episodes)}`);
for (const [id, key] of episodes) {
const token = document.cookie.split("; ")
.filter(x => /^streamco_token=/.test(x))[0]
.split("=")[1];
const client = JSON.parse(localStorage["player_device_id"]).val;
const streams = await get(x => x.json(), `https://api.stan.com.au/concurrency/v1/streams?programId=${id}&jwToken=${token}&clientId=${client}&quality=${quality}&format=dash&capabilities.drm=widevine&player=html5`);
const kidHex = streams.media.drm.keyId.replace("-", "");
const keyHex = key.map(x => x.toString(16).padStart(2,0)).join("");
await downloadText(`${id}.kid.txt`, kidHex);
await downloadText(`${id}.key.txt`, keyHex);
for (const x of streams.media.captions) {
const blob = await get(x => x.blob(), x.url);
await download(blob, `${id}.${x.language}.vtt`);
}
const mpd = await get(async x => (new DOMParser).parseFromString(await x.text(), "application/xml"), `https://api.stan.com.au/manifest/v1/dash/web.mpd?url=${streams.media.videoUrl}&audioType=all&version=87`);
const base = mpd.querySelector("BaseURL").textContent;
const inputs = { video: [], audio: [] };
for (const type of ["video", "audio"]) {
for (const [index, a] of [...mpd.querySelectorAll(`AdaptationSet[mimeType^="${type}/"]`)].entries()) {
const b = a.querySelector("BaseURL")?.textContent ?? base;
const r = [...a.querySelectorAll(`Representation`)].sort((p,q) => q.getAttribute("bandwidth") - p.getAttribute("bandwidth"))[0].getAttribute("id");
const t = a.querySelector("SegmentTemplate");
const parts = [];
const init = b + t.getAttribute("initialization").replace("$RepresentationID$", r);
const blob = await get(x => x.blob(), init);
parts.push(blob);
for (let i = Number(t.getAttribute("startNumber")); ; i++) {
try {
const seg = b + t.getAttribute("media").replace("$RepresentationID$", r).replace("$Number$", i);
const blob = await get(x => x.blob(), seg);
parts.push(blob);
} catch (error) {
if (error._response) {
console.debug("reached the end of the stream’s segments: %o", error);
break;
}
throw error;
}
}
const whole = new Blob(parts, { type: a.getAttribute("mimeType") });
await download(whole, `${id}.${type}${index}e.mp4`);
enqueue(`mp4decrypt --key ${kidHex}:${keyHex} ${id}.${type}${index}e.mp4 ${id}.${type}${index}d.mp4`);
inputs[type].push(`${id}.${type}${index}d.mp4`);
}
}
const vinputs = inputs.video;
const ainputs = inputs.audio;
const sinputs = streams.media.captions;
const ffvinputs = ffoption(inputs.video, x => `-i ${x}`);
const ffainputs = ffoption(inputs.audio, x => `-i ${x}`);
const ffsinputs = ffoption(streams.media.captions, x => `-i ${id}.${x.language}.vtt`);
const ffmap = ffoption([...Array(vinputs.length + ainputs.length + sinputs.length)], (_,i) => `-map ${i}`);
const ffsmeta = ffoption(streams.media.captions, (x,i) => `-metadata:s:s:${i} language=${x.language}`);
enqueue(`ffmpeg -nostdin -y ${ffvinputs} ${ffainputs} ${ffsinputs} ${ffmap} ${ffsmeta} -c:v copy -c:a copy -c:s mov_text ${id}.mp4`);
}
console.log("done! now run the following to decrypt and mux:");
console.log(commands.join("\n"));
return;
}
const episode = links.shift();
const id = eid(episode.href);
const old = EmeInterception.onOperation;
EmeInterception.onOperation = async (type, args) => {
// console.log(type,args);
switch (type){
case "MessageEvent":
lastReceivedLicenseRequest = args.message;
break;
case "UpdateCall":
lastReceivedLicenseResponse = args[0];
const key = await WidevineCrypto.decryptContentKey(lastReceivedLicenseRequest, lastReceivedLicenseResponse);
if (!key) break;
EmeInterception.onOperation = old;
result.push([id, key]);
// console.log(result);
document.querySelector("button.vjs-back-player-control").click();
next();
}
};
const listener = event => {
if (eid(event.target.href) != id) {
console.log("wrong episode");
event.preventDefault();
event.stopPropagation();
} else {
removeEventListener("click", listener, true);
}
};
addEventListener("click", listener, true);
const title = episode.parentNode.parentNode.nextElementSibling.querySelector("h4").textContent;
console.log("now click %o", title);
}
async function get(fun, url) {
console.debug("get: %o", url);
const response = await fetch(url);
if (response.ok) {
return fun(response);
}
const error = new Error(`fetch yielded failing HTTP status code: ${response.status}`);
error._response = response;
throw error;
}
async function download(blob, name) {
const href = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = href;
link.download = name;
link.addEventListener("click", () => {
setTimeout(() => {
URL.revokeObjectURL(href);
}, 1000);
});
link.click();
// try to wait long enough for navigation to occur
await sleep(250);
}
function downloadText(name, text) {
const blob = new Blob([text], { type: "text/plain" });
download(blob, name);
}
function eid(href) {
return href.match(/(?<=[/]programs[/])[0-9]+/)[0];
}
async function sleep(ms) {
await new Promise(resolve => setTimeout(resolve, ms));
}
function enqueue(command) {
console.debug(`enqueueing command: ${command}`);
commands.push(command);
}
function ffoption(xs, fun) {
return xs.map(fun).join(" ");
}
})();
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.