This commit is contained in:
matiashik committed 2026-03-28 14:18:38 +00:00
commit 75312b5ee3
17 files changed
+2503

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
venv/
__pycache__/
manifests/
music/
config.*
!config.sample.*
+24
View File
@@ -0,0 +1,24 @@
# VK music downloader
## Usage
Fill in `config.sample.json` and rename it to `config.json`. You can acquire required data from network tab in browser developer tools:
1. Open developer tools.
2. Start playing any song.
3. Filter by `get_audio_ids_by_source` (for `audio_list_payload`) and `reload_audios` (for `audio_data_payload`).
4. RMB -> copy -> copy as fetch (node.js).
5. Paste arguments (payload) into config file.
6. `vk_id` may be acquired from main audio page url: `https://vk.com/audios<vk_id>`.
Then just run:
```sh
python main.py
```
## Known issues
1. It may (and likely will) fail on Windows: `.m3u8` files use URL-compatible names for partials, like `seg-00?siren=1`. Use Unix or WSL.
2. Script does not handle errors. Use shell loops.
+18
View File
@@ -0,0 +1,18 @@
{
"vk_host": "https://vk.com/",
"audio_list_url": "al_audio.php?act=get_audio_ids_by_source",
"audio_data_url": "al_audio.php?act=reload_audios",
"vk_id": "<VK_ID>",
"manifests_directory": "manifests/",
"audio_directory": "music/",
"audio_list_payload": {
"headers": "<HEADERS>",
"body": "<BODY>",
"method": "<METHOD>"
},
"audio_data_payload": {
"headers": "<HEADERS>",
"body": "<BODY>",
"method": "<METHOD>"
}
}
+41
View File
@@ -0,0 +1,41 @@
import vconfig
import vcollector
import vobjects
config = vconfig.VConfig(open("config.json"))
print("Fetching list of audio")
audio_list = vcollector.audio_list(config)
print("Fetching audio metadata")
audio_data = vcollector.audio_data(config, audio_list)
print("Fetching audio manifests")
for data in audio_data:
if vobjects.Manifest.load(config, data):
print(f"\tPre-Fetched: {data.hindex()}")
continue
manifest = vcollector.audio_manifest(config, data)
data.manifest(manifest)
data.manifest().store(config)
print(f"\tFetched: {data.hindex()}")
print("Fetching audio chunks")
for data in audio_data:
manifest = data.manifest()
if manifest.hashed(config):
print(f"\tPre-fetched: {data.hindex()}")
continue
chunks = manifest.chunks()
for idx, chunk in enumerate(chunks):
chunks[idx] = (vcollector.audio_chunk(config, data, chunk))
print(f"\tFetching: {data.hindex()} | {idx + 1}/{len(chunks)}", end='\r')
for chunk in chunks:
chunk.store(config)
manifest.hash(config, chunks)
print(f"\tFetched: {data.hindex()}", end=' \n')
print("Building audio")
for idx, data in enumerate(audio_data):
if data.hashed(config):
print(f"\tPre-built: {data.hindex()}")
continue
vcollector.audio(config, data.manifest(), idx + 1)
data.hash(config)
print(f"\tBuilt: {data.hindex()}")
print("Done")
+2
View File
@@ -0,0 +1,2 @@
venv
music
+99
View File
@@ -0,0 +1,99 @@
import json
import requests
import os
import subprocess
import typing
import threading
import time
class song:
def __init__(self, json_song) -> None:
self.__url = json_song["url"]
self.__artist = json_song["artist"]
self.__title = json_song["title"]
@property
def url(self) -> str:
return self.__url
@property
def artist(self) -> str:
return self.__artist
@property
def title(self) -> str:
return self.__title
def seg_finder(mlst: typing.List[str]):
for i in mlst:
if i[:3] == "seg":
yield i
def the_fetcher(m_subj: song, number):
global counter
global thread_count
start = time.time()
root_url = m_subj.url.split("index.m3u8")[0]
inc_name = root_url.split("/")[-2]
os.mkdir("music/" + inc_name)
f = open("music/" + inc_name + "/" + "index.m3u8", "wb")
m3u8 = requests.get(m_subj.url).content
f.write(m3u8)
f.close()
m3u8 = list(seg_finder(str(m3u8).split("\\n")[:-1]))
m3u8.sort()
for i in m3u8:
f = open("music/" + inc_name + "/" + i, "wb")
f.write(requests.get(root_url + i).content)
f.close()
prc = subprocess.Popen(
f'ffmpeg -protocol_whitelist file,http,https,tcp,tls,crypto -allowed_extensions ALL -i music/{inc_name}/index.m3u8 -metadata title="{m_subj.title}" -metadata artist="{m_subj.artist}" -metadata track={number} music/"{m_subj.title} - {m_subj.artist}".mp3 &> /dev/null && rm -r music/{inc_name}',
shell=True,
)
prc.wait()
print(
f"Process number {number} ({m_subj.title} - {m_subj.artist}) is done in {time.time() - start}s"
)
counter -= 1
locker.acquire()
thread_count -= 1
locker.release()
inp = open("music_info.json", "r+")
m_seq = [song(i) for i in json.load(inp)]
m_seq.reverse()
counter = len(m_seq)
endway = counter
locker = threading.Lock()
thread_count = 0
glb_start = time.time()
i = 0
while i < endway:
locker.acquire()
if thread_count >= 8:
locker.release()
else:
i += 1
thread_count += 1
locker.release()
thread = threading.Thread(target=the_fetcher, args=(m_seq.pop(), i))
thread.start()
while counter != 0:
pass
print(f"Program is done in {(time.time() - glb_start)}s")
+83
View File
@@ -0,0 +1,83 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import vk_api\n",
"from vk_api import audio\n",
"\n",
"my_id = '464426988'\n",
"login = '+89152561930'\n",
"\n",
"vk = vk_api.VkApi(\n",
" login=\"+89152561930\",\n",
" password=\"\",\n",
" token=\"vk1.a.skTRr1KCyj6tv1HchGCCYLSSlqaMJ0_4rBzfK0Ywzm1mTxFoQGL-5TPd9NaL8D1h3XbyKIs0Ir5ukMe2T4XFM81pvaMLH-1lNqaTvaiqmxlwQm4y0ZbQHfxhdfdaZZQDWvVyq2YeP4zx4zOwklbsd0Ohp3StDMV5P3eoL3ZCD6XYU7juLrH9unNJHkdMcmit\",\n",
" app_id=6121396,\n",
") # токен брать для vkadmin https://habr.com/ru/articles/519302/\n",
"vk.auth(token_only=True)\n",
"vk_audio = audio.VkAudio(vk)\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"audlist = vk_audio.get(owner_id=my_id)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"clrlist = [({\n",
" 'url': a['url'],\n",
" 'artist': a['artist'],\n",
" 'title': a['title']\n",
"}) for a in audlist]"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"\n",
"outp = open('music_info.json', 'w')\n",
"\n",
"json.dump(clrlist, outp)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
File diff suppressed because it is too large. Load diff
+29
View File
@@ -0,0 +1,29 @@
/*
Ищется все анальной слежкой за файлом al_audio в разделе Network
*/
fetch("https://vk.com/al_audio.php?act=reload_audios", {
"headers": {
"accept": "*/*",
"accept-language": "ru,ru-RU;q=0.9,uk-UA;q=0.8,uk;q=0.7,en-US;q=0.6,en;q=0.5",
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded",
"pragma": "no-cache",
"sec-ch-ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Linux\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest",
"cookie": "remixnsid=vk1.a.qPPka0F3lhS8jVoHtQoB7gDFHcKtfkv7HnY6aNM-G-M_rVkCqDmAoE_ClYOyYfRjYyRZHBBiTWGmaqdoZ9ZRHO28bqKWNWeJAFBBwgpt_uW6bajeluUSmaY4tUdnvVhVEf58gcFryVfz-zA0toGqHskWmYbSNMuInFhNQnasrODwoUkLWy7VaTxGO-ci6rXw; remixsid=1_uASEY0w2iQTqXCxSGcam9V0CTmvDLfijvy6h9GNXmgwlJGMO5HYly-3YloQzBtqKoNzMvH1JBtu6wvflu_DXsg;",
"Referrer-Policy": "strict-origin-when-cross-origin"
},
"body": "al=1&audio_ids=464426988_456240014_",
"method": "POST"
}).then(e => {
e.json().then(j => {
console.log(j['payload'][1][0][0][2])
})
}
)
+93
View File
@@ -0,0 +1,93 @@
/*
Ищется все анальной слежкой за получением m3u8 файла через раздел Network
*/
const r = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789+/=";
const i = {
v: function (e) {
return e.split("").reverse().join("")
},
r: function (e, t) {
let o;
e = e.split("");
const n = r + r;
let i = e.length;
for (; i--;)
o = n.indexOf(e[i]),
~o && (e[i] = n.substr(o - t, 1));
return e.join("")
},
s: function (e, t) {
let o = e.length;
if (o) {
const n = function (e, t) {
const o = e.length
, n = [];
if (o) {
let e = o;
for (t = Math.abs(t); e--;)
t = (o * (e + 1) ^ t + e) % o,
n[e] = t
}
return n
}(e, t);
let r = 0;
for (e = e.split(""); ++r < o;)
e[r] = e.splice(n[o - 1 - r], 1, e[r])[0];
e = e.join("")
}
return e
},
i: function (e, t) {
return i.s(e, t ^ vk.id)
},
x: function (e, t) {
const o = [];
return t = t.charCodeAt(0),
(0,
n.each)(e.split(""), (function (e, n) {
o.push(String.fromCharCode(n.charCodeAt(0) ^ t))
}
)),
o.join("")
}
};
const vk = {
id: 464426988
};
function a(e) {
if (!e || e.length % 4 == 1)
return !1;
let t, o, n = 0, i = 0, s = "";
for (; o = e.charAt(i++);)
o = r.indexOf(o),
~o && (t = n % 4 ? 64 * t + o : o,
n++ % 4) && (s += String.fromCharCode(255 & t >> (-2 * n & 6)));
return s
}
function s(e) {
let t, o, n = e.split("?extra=")[1].split("#"), r = "" === n[1] ? "" : a(n[1]);
if (n = a(n[0]),
"string" != typeof r || !n)
return e;
r = r ? r.split(String.fromCharCode(9)) : [];
let s = r.length;
for (; s--;) {
if (o = r[s].split(String.fromCharCode(11)),
t = o.splice(0, 1, n)[0],
!i[t])
return e;
n = i[t].apply(null, o)
}
if (n && "http" === n.substr(0, 4))
return n
return e
}
console.log(s("https://vk.com/mp3/audio_api_unavailable.mp3?extra=Af0VALnevxnknO9WmwvdsM9ICKf0lOfPp2v4AxvYEfHZlvP1ovPdlLn5AxnStMj4lZL2EKzgohGTwujsyvDPyuK4lwrsnNu4EejOovjMn1vFAhmTqJHkvweOCJfHDMnRl1CWwc5vofvlAM9gtef6nZHfz3zPDtq2tg5hq1zJBs90BvzbtJLvogeUyI9izMLJB2HKEenfqvv2C2fOt25PsueZu3rKyxPZtfL2vgKXrejXBNDoAxnXzxDgCh09t2fLBunuotq3mdHYm3nkBOuZDs1Avv0XmMPZCLPvBMTRDdP1vOnLAwjRzdmVna#AqSOmJi"
))
+175
View File
@@ -0,0 +1,175 @@
{
"+89152561930": {
"cookies": [
{
"comment": null,
"comment_url": null,
"discard": false,
"domain": ".vk.com",
"domain_initial_dot": true,
"domain_specified": true,
"expires": null,
"name": "remixlang",
"path": "/",
"path_specified": true,
"port": null,
"port_specified": false,
"rest": {},
"rfc2109": false,
"secure": true,
"value": "100",
"version": 0
},
{
"comment": null,
"comment_url": null,
"discard": false,
"domain": ".vk.com",
"domain_initial_dot": true,
"domain_specified": true,
"expires": null,
"name": "remixstlid",
"path": "/",
"path_specified": true,
"port": null,
"port_specified": false,
"rest": {},
"rfc2109": false,
"secure": true,
"value": "9093720130901750552_7s0XnrcJBjS8oqZC1d0vFfe7sxZVdrIaXdcZyzhmkgH",
"version": 0
},
{
"comment": null,
"comment_url": null,
"discard": false,
"domain": ".vk.com",
"domain_initial_dot": true,
"domain_specified": true,
"expires": null,
"name": "remixua",
"path": "/",
"path_specified": true,
"port": null,
"port_specified": false,
"rest": {},
"rfc2109": false,
"secure": true,
"value": "43%7C-1%7C320%7C3987579067",
"version": 0
},
{
"comment": null,
"comment_url": null,
"discard": false,
"domain": ".vk.com",
"domain_initial_dot": true,
"domain_specified": true,
"expires": null,
"name": "remixstid",
"path": "/",
"path_specified": true,
"port": null,
"port_specified": false,
"rest": {},
"rfc2109": false,
"secure": true,
"value": "1222537880_X7ZN3kf6fzbrHUwJLZv5uK4ZA8kVSlyzxZzhvYaHZao",
"version": 0
},
{
"comment": null,
"comment_url": null,
"discard": false,
"domain": ".vk.com",
"domain_initial_dot": true,
"domain_specified": true,
"expires": null,
"name": "remixsid",
"path": "/",
"path_specified": true,
"port": null,
"port_specified": false,
"rest": {
"HttpOnly": null
},
"rfc2109": false,
"secure": true,
"value": "1_JiEVPSo1HFJp7lWrWumdRLX3zymBaxxq1lvZmADkt7tW7qJAVaionvz5W0kTA-fH_BtQLEx7dk00fqD6cWuCiw",
"version": 0
},
{
"comment": null,
"comment_url": null,
"discard": false,
"domain": ".login.vk.com",
"domain_initial_dot": false,
"domain_specified": true,
"expires": null,
"name": "p",
"path": "/",
"path_specified": true,
"port": null,
"port_specified": false,
"rest": {
"HttpOnly": null
},
"rfc2109": false,
"secure": true,
"value": "vk1.a.zXqt4wtow7Uyj1tZaDO9ueO1L7LnZH52VfLVfPSJP2rG97N1l2u2-GQGvMZKPSB4NcC0Z2140XNsMjYUCThAwrXKeSZFp-1guZz-DlZFCelcpPmtWPHQCM0NqCyneXRGZRj7Xn_lC3sj3m5JTNDkd5YwWYgTaJ6CX76y4Z8Cjfs",
"version": 0
},
{
"comment": null,
"comment_url": null,
"discard": false,
"domain": "login.vk.com",
"domain_initial_dot": false,
"domain_specified": false,
"expires": null,
"name": "remixluas2",
"path": "/",
"path_specified": true,
"port": null,
"port_specified": false,
"rest": {
"HttpOnly": null
},
"rfc2109": false,
"secure": true,
"value": "OTBlZjYyOWQxMmRkY2NiMTExNTkwMDEz",
"version": 0
},
{
"comment": null,
"comment_url": null,
"discard": false,
"domain": "vk.com",
"domain_initial_dot": false,
"domain_specified": false,
"expires": null,
"name": "remixnsid",
"path": "/",
"path_specified": true,
"port": null,
"port_specified": false,
"rest": {
"HttpOnly": null
},
"rfc2109": false,
"secure": true,
"value": "vk1.a.O-8uzqiK1C-mpFWKX3FB4aM_tZjhvgCpKH__EPKEPuczNME_3RsapkWvXKtszZ8NfxhStf4y3qaEdMlQVfzYciVlkrTO9btwnhncYSWrgesRuOBdf8gpBn6DMOFn76PWeBjeovV5UwVfXCg4-o20ggrTP5pRLo2cf3Q7NP1Ov5mTcGp8HsOcf6yPg-2ySPxO",
"version": 0
}
],
"token": {
"app6121396": {
"scope_140492255": {
"access_token": "vk1.a.YXorSuhq53FCYlsjSJxfWqUEjDiiUmnLzO4gb4zv3IyEsDztPuPXbMbo8HdnZaLWSR-UeFH-yKO0XmSmSLbsykcCtT6tX269SzrSEqsJWvj06cJmHhXLKCO6EbC8Fr7ngnA3MlfEKxzbFPKMyLYxBW-SqEiqScyKE_PffaYUbsMsD-rHjtmWXwNJjPMijQAfZNgnXV6Zo0l11z5pLaL1DA",
"expires_in": "0",
"user_id": "464426988"
}
}
}
}
}
+73
View File
@@ -0,0 +1,73 @@
import vfetcher
import vobjects
import urllib.parse
import json
import subprocess
import os
import shlex
def audio_list(config):
payload = config.audio_list_payload()
json_list = vfetcher.fetch(
payload["method"],
f"{config.vk_host()}{config.audio_list_url()}",
payload["headers"].items(),
payload["body"].encode(),
)
plain_list = json.loads(json_list)
return vobjects.audio_list(plain_list)
def audio_data(config, audio_list):
payload = config.audio_data_payload()
body = {
"al": "1",
"audio_ids": ",".join([audio.cid() for audio in audio_list]),
}
json_data = vfetcher.fetch(
payload["method"],
f"{config.vk_host()}{config.audio_data_url()}",
payload["headers"].items(),
urllib.parse.urlencode(body).encode("ascii"),
)
plain_data = json.loads(json_data.decode("windows-1251"))
return vobjects.audio_data(plain_data)
def audio_manifest(config, audio_data):
body = {}
raw_content = vfetcher.fetch(
"GET",
audio_data.blessed_url(config),
{}.items(),
urllib.parse.urlencode(body).encode(),
)
return vobjects.Manifest(raw_content)
def audio_chunk(config, audio_data, chunk):
body = {}
manifest = audio_data.manifest()
raw_data = vfetcher.fetch(
"GET",
f"{audio_data.root_url(config)}{chunk}",
{}.items(),
urllib.parse.urlencode(body).encode("utf-8"),
)
return vobjects.Chunk(manifest, chunk, raw_data)
def audio(config, audio_manifest, idx=None):
data = audio_manifest.data()
audio_dir = config.audio_directory()
if not os.path.exists(audio_dir):
os.makedirs(audio_dir)
subprocess.run(
[
f'ffmpeg -y -protocol_whitelist file,http,https,tcp,tls,crypto -allowed_extensions ALL -i {audio_manifest.index(config)} -metadata title={shlex.quote(data.title())} -metadata artist={shlex.quote(data.artist())} -metadata track={idx} {shlex.quote(data.findex(config))}',
],
shell=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
+32
View File
@@ -0,0 +1,32 @@
import json
class VConfig:
def __init__(self, config_file, close_config_after=True):
self._jconf = json.loads(config_file.read())
if close_config_after:
config_file.close()
def vk_host(self):
return self._jconf["vk_host"]
def audio_list_url(self):
return self._jconf["audio_list_url"]
def audio_data_url(self):
return self._jconf["audio_data_url"]
def vk_id(self):
return int(self._jconf["vk_id"])
def manifests_directory(self):
return self._jconf["manifests_directory"]
def audio_directory(self):
return self._jconf["audio_directory"]
def audio_list_payload(self):
return self._jconf["audio_list_payload"]
def audio_data_payload(self):
return self._jconf["audio_data_payload"]
+6
View File
@@ -0,0 +1,6 @@
import venigma_internal
def decode(config, cursed_url):
enigma = venigma_internal.Enigma(config)
return enigma.decode(cursed_url)
+134
View File
@@ -0,0 +1,134 @@
# import base64
class Enigma:
def __init__(self, config):
self._vk_id = config.vk_id()
def R():
return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789+/="
def vk_id(self):
return self._vk_id
def decode(self, cursed_url):
return self.s(cursed_url)
def a(self, e):
if not e or len(e) % 4 == 1:
result = False
# print("a result (Base64):", base64.b64encode(str(result).encode()).decode())
return result
t, o, n, i, s = None, None, 0, 0, ""
while True:
o = e[i] if i < len(e) else None
if not o:
break
o = Enigma.R().find(o)
if o != -1:
t = o if n % 4 == 0 else 64 * t + o
n += 1
if (n - 1) % 4 != 0:
s += chr(255 & (t >> (-2 * n & 6)))
i += 1
result = s
# print("a result (Base64):", base64.b64encode(result.encode()).decode())
return result
def s(self, e):
n = e.split("?extra=")[1].split("#")
r = "" if n[1] == "" else self.a(n[1])
n = self.a(n[0])
if not isinstance(r, str) or not n:
# print("s result (Base64):", base64.b64encode(e.encode()).decode())
return e
r = r.split(chr(9)) if r else []
s = len(r)
while s > 0:
s -= 1
o = r[s].split(chr(11))
t = o[0]
o[0] = n
if not hasattr(Enigma.EnigmaI, t):
# print("s result (Base64):", base64.b64encode(e.encode()).decode())
return e
n = getattr(Enigma.EnigmaI, t)(*o, self.vk_id())
if n and n.startswith("http"):
# print("s result (Base64):", base64.b64encode(n.encode()).decode())
return n
# print("s result (Base64):", base64.b64encode(e.encode()).decode())
raise ValueError(f"<{e}> can not be decoded")
return e
class EnigmaI:
@staticmethod
def v(e, _vk_id):
result = e[::-1]
# print("i.v result (Base64):", base64.b64encode(result.encode()).decode())
return result
@staticmethod
def r(e, t, _vk_id):
o = None
e = list(e)
n = Enigma.R() + Enigma.R()
i = len(e)
for _ in range(i):
o = n.find(e[i - 1])
if o != -1:
e[i - 1] = n[o - t : o - t + 1]
i -= 1
result = "".join(e)
# print("i.r result (Base64):", base64.b64encode(result.encode()).decode())
return result
@staticmethod
def s(e, t, _vk_id):
o = len(e)
if o:
def inner_n(e, t):
o = len(e)
n = []
if o:
t = abs(t)
e = o
n = [None] * e
while e > 0:
e -= 1
t = (o * (e + 1) ^ t + e) % o
n[e] = t
# print(
# "i.anon_s result (Base64):", base64.b64encode((''.join([str(i) for i in n])).encode()).decode()
# )
return n
n = inner_n(e, t)
r = 0
e = list(e)
r += 1
while r < o:
e[r], e[n[o - 1 - r]] = e[n[o - 1 - r]], e[r]
r += 1
e = "".join(e)
result = e
# print("i.s result (Base64):", base64.b64encode(result.encode()).decode())
return result
@staticmethod
def i(e, t, vk_id):
result = Enigma.EnigmaI.s(e, int(t) ^ vk_id, vk_id)
# print("i.i result (Base64):", base64.b64encode(result.encode()).decode())
return result
@staticmethod
def x(e, t):
o = []
t = ord(t[0])
for n in e:
o.append(chr(ord(n) ^ t))
result = "".join(o)
# print("i.x result (Base64):", base64.b64encode(result.encode()).decode())
return result
+15
View File
@@ -0,0 +1,15 @@
import urllib
import urllib.request
def fetch(method, url, headers, body):
request = urllib.request.Request(
url,
data=body,
method=method,
)
for header, value in headers:
request.add_header(header, value)
response = urllib.request.urlopen(request)
return response.read()
+229
View File
@@ -0,0 +1,229 @@
import html
import venigma
import os
import base64
import re
import hashlib
class AudioListItem:
def __init__(self, json_item):
self._jitem = json_item
def id(self):
return self._jitem["audio_raw_id"]
def key(self):
return self._jitem["access_key"]
def cid(self):
return f"{self.id()}_{self.key()}"
def _code(self):
return self._jitem["track_code"]
def audio_list(plain_list):
return [AudioListItem(item) for item in plain_list["payload"][1][0]]
class AudioDataItem:
def __init__(self, json_data):
self._jdata = json_data
self._manifest = None
def cid(self):
return f"{self._jdata[1]}_{self._jdata[0]}"
def index(self):
return base64.b16encode(self.hindex().encode()).decode()
def cursed_url(self):
return self._jdata[2]
def blessed_url(self, config):
return venigma.decode(config, self.cursed_url())
def root_url(self, config):
blessed_url = self.blessed_url(config)
parts = blessed_url.split("/")
return "/".join(parts[:-1]) + "/"
def title(self):
return html.unescape(self._jdata[3])
def artist(self):
return html.unescape(self._jdata[4])
def img(self):
return self._jdata[14]
def hindex(self):
return f"{self.title()} - {self.artist()}"
def findex(self, config):
return f"{config.audio_directory()}{self.cid()}.mp3"
def _hash(self, manifest_hash, mp3):
hash = hashlib.sha256(manifest_hash)
hash.update(mp3)
return hash.hexdigest()
def _hashfile(self, config):
return f"{self.manifest().directory(config)}sha256sum"
def hash(self, config):
f = open(self._hashfile(config), "w+")
fmp3 = open(self.findex(config), "rb")
manifest_hash = self.manifest().hashed(config)
h = self._hash(manifest_hash.encode(), fmp3.read())
fmp3.close()
f.write(h)
f.close()
return h
def hashed(self, config):
hashfile = self._hashfile(config)
findex = self.findex(config)
manifest_hash = self.manifest().hashed(config)
if (
not os.path.isfile(hashfile)
or not os.path.isfile(findex)
or not manifest_hash
):
return None
fmp3 = open(findex, "rb")
h = self._hash(manifest_hash.encode(), fmp3.read())
fmp3.close()
f = open(hashfile, "r")
fh = f.read()
f.close()
return h if h == fh else None
def manifest(self, manifest=None):
if manifest is None:
return self._manifest
else:
self._manifest = manifest
if manifest.data() is None:
manifest.data(self)
def audio_data(plain_data):
return [AudioDataItem(data) for data in plain_data["payload"][1][0]]
class Manifest:
def __init__(self, raw_content):
self._rcontent = raw_content
self._data = None
def load(config, data):
index = Manifest._index_for(config, data)
if os.path.isfile(index):
f = open(index, "rb")
manifest = Manifest(f.read())
f.close()
data.manifest(manifest)
return manifest
else:
return None
def content(self):
return self._rcontent
def _directory_for(config, data):
directory = config.manifests_directory()
return f"{directory}{data.index()}/"
def directory(self, config):
return Manifest._directory_for(config, self.data())
def _index_for(config, data):
return f"{Manifest._directory_for(config, data)}index.m3u8"
def index(self, config):
return Manifest._index_for(config, self.data())
def store(self, config):
directory = self.directory(config)
if not os.path.exists(directory):
os.makedirs(directory)
f = open(self.index(config), "wb+")
f.write(self.content())
f.close()
def chunks(self):
regex = r"seg\-\d+\-\w+\.ts\?siren=\d"
return re.findall(regex, self.content().decode("utf-8"))
def _hash(self, chunks):
hash = hashlib.sha1(self.content())
for chunk in chunks:
if not chunk:
continue
hash.update(chunk.data())
return hash.hexdigest()
def _hashfile(self, config):
return f"{self.directory(config)}sha1sum"
def hash(self, config, chunks):
f = open(self._hashfile(config), "w+")
h = self._hash(chunks)
f.write(h)
f.close()
return h
def hashed(self, config):
hashfile = self._hashfile(config)
chunks = [Chunk.load(config, self, chunk) for chunk in self.chunks()]
if not os.path.isfile(hashfile) or any(chunks) is None:
return None
h = self._hash(chunks)
f = open(hashfile, "r")
fh = f.read()
f.close()
return h if h == fh else None
def data(self, data=None):
if data is None:
return self._data
else:
self._data = data
if data.manifest() is None:
data.manifest(self)
class Chunk:
def __init__(self, manifest, name, raw_data):
self._name = name
self._rdata = raw_data
self._manifest = manifest
def _index_for(config, manifest, name):
return f"{manifest.directory(config)}{name}"
def load(config, manifest, name):
index = Chunk._index_for(config, manifest, name)
if os.path.isfile(index):
f = open(index, "rb")
chunk = Chunk(manifest, name, f.read())
f.close()
return chunk
else:
return None
def name(self):
return self._name
def data(self):
return self._rdata
def manifest(self):
return self._manifest
def store(self, config):
f = open(f"{Chunk._index_for(config, self.manifest(), self.name())}", "wb+")
f.write(self.data())
f.close()