If your data is in the cloud, it is not your data.
So, introductory:
there is a Yandex.Disk with a capacity of ~500GB, filled mainly with photos (RAW and JPEG) and video
most files are successfully downloaded via the web interface at full speed
has the task of saving all its contents to a local disk, as much as possible, given recent events
It seems that this is precisely why the official client is needed - but in real conditions it behaved extremely strangely:
did not allow selecting a target folder on any local drive other than C:
despite positive news, regularly came across some inaccessible file and fell into a stupor
download speed left much to be desired
I had to take matters into my own hands, and at the same time get to know node:streams more closely...
How everything works "for the browser"
I didn’t really want to try the Disk API after trying to use the “native” client - it’s better to see how the web client works in the browser and try to pretend to be it.
In general, no one is hiding anything from us, and we only need to implement a few types of operations.
Section listing
To get a list of objects of any partition, including the root one, use a POST-query at https://disk.yandex.ru/models-v2?m=mpfs/resources.
Arguments:
{
sort : 'name' // сортировка по имени
, order : '1'
, idContext : '/disk' // path до объекта
, amount : 40 // количество элементов на странице
, offset : 0 // стартовый по порядку элемент
}The Web client requests lists of files in pages of 40, and we will not break this tradition.
In response, we receive a JSON array of approximately the following objects with a completely transparent structure:
{
type : "dir" // тип объекта: 'dir' или 'file'
, id : "/disk/My Folder/" // полный путь к объекту на Диске
, name : "My Folder" // имя объекта
, path : "/disk/My Folder" // полный путь к объекту на Диске, еще раз
, meta : {
size : 123456 // размер - для файла
}
// время создания, изменения, ... в Unix Timestamp
, ctime : ...
, mtime : ...
, utime : ...
}File path
Another POST request, now at https://disk.yandex.ru/models-v2?m=mpfs/url with a single argument path helps us get the URL to download the file:
{
file : "//downloader.disk.yandex.ru/disk/..."
}File body
By accessing the received URL, now with a GET request, we will receive an HTTP 302 redirect with the address of a specific storage in the header:
location : https://mds.storage.yandex.net/rdisk/...
Actually, that’s where the content you’re looking for is located.
Loader
In order to “pretend to be a browser” conditionally correctly, we need the headers of any of the POST requests mentioned above - they can be easily copied directly from the browser:

We need the headers themselves (headers) and two parameters passed to body: sk and connection_id.
Session data (
sk / connection_id) expires approximately 24 hours after receiving it. Therefore, if you have a lot of content, the download will fail, and you will need to take the current details from the browser.
I tried to make do with a minimum of external libraries. Only one was needed - utimes for conveniently setting time attributes on files and directories under Windows.
The basic algorithm is quite simple:
process the task queue
tasksuntil it is empty, starting from the “root”/disk(if a specific folder is a higher priority for you, substitute it)for a directory task (
type == 'dir') in pages of 40 we get all the elements lying inside and add them to the beginning of the task queuefor a task file (
type == 'file') we try to get its content several times, and if the downloaded size matches the expected one, we upload it to the target storagein some cases, when accessing a file, there are timeouts, HTTP 500, or simply a break during the download - so we make a couple of attempts until we were able to download the entire expected volume of the file
In my case, the target disk is located on a slow network storage, so the body of the file is first written in streaming “chunks” to a temporary file on the local disk, and then completely copied where needed.
// yad-dl.js
// очередь задач
const tasks = [
{
id : '/disk/'
, type : 'dir'
, path : '/disk' // откуда начинаем сканирование
, name : 'disk'
, depth : 0
, target : 'Z:\\#ya.dsk.dump' // целевая папка на локальном диске
}
];
// реквизиты сессии
const headers = {
...,
"Referer": "https://disk.yandex.ru/client/disk"
};
const reqJSON = {
sk : '...:...'
, connection_id : '...'
};
const path = require('node:path');
const fs = require('node:fs');
const {Readable, Transform} = require('node:stream');
const {pipeline} = require('node:stream/promises');
const {utimes} = require('utimes');
// форматируем таймстамп в убодное представление
Date.prototype.toTimeStringEx = function() {
return `${this.getFullYear()}-${(this.getMonth() + 1).toString().padStart(2, '0')}-${this.getDate().toString().padStart(2, '0')} ${this.getHours().toString().padStart(2, '0')}:${this.getMinutes().toString().padStart(2, '0')}:${this.getSeconds().toString().padStart(2, '0')}.${this.getMilliseconds().toString().padStart(3, '0')}`;
};
// статистика обработки
const filestat = {
skip : 0
, dump : 0
, error : 0
};
// создаем временную папку
const temp = fs.mkdtempSync('yad-dl');
(async () => {
// обрабатываем задачи из очереди по обной
do {
const task = tasks.shift();
if (!task) {
break;
}
task.name = task.name.replaceAll(/[\:\?\"]/g, '+'); // убираем недопустимые символы из имени
task.target = path.join(task.target, task.name);
console.log(`${new Date().toTimeStringEx()} | -- ${task.type == 'file' ? 'f' : 'd'} : ${JSON.stringify(task.path)}`);
console.log(`${new Date().toTimeStringEx()} | -- --- ${JSON.stringify(task.target)}`);
// обработка папки
if (task.type == 'dir') {
// если целевой папки еще нет - создаем ее и проставляем ей атрибуты времени
if (!fs.existsSync(task.target)) {
try {
fs.mkdirSync(task.target);
}
catch (e) {
console.log(`${new Date().toTimeStringEx()} | mkdir`, e);
}
await utimes(task.target, {
btime : (task.ctime ?? 0) * 1000
, mtime : (task.mtime ?? 0) * 1000
, atime : (task.utime ?? 0) * 1000
});
}
else {
console.log(`${new Date().toTimeStringEx()} | -- -- : skip mkdir`);
}
// загружаем вложенные элементы "страницами" по 40 штук
const nested = [];
const amount = 40;
do {
console.log(`${new Date().toTimeStringEx()} | -- -- : get offset : ${nested.length.toString().padStart(9)}`);
const res = await fetch(
'https://disk.yandex.ru/models-v2?m=mpfs/resources'
, {
headers
, method : 'POST'
, body : JSON.stringify({
...reqJSON
, apiMethod : 'mpfs/resources'
, requestParams : {
sort : 'name'
, order : '1'
, idContext : task.path
, amount
, offset : nested.length
, with_share : '1'
}
})
}
);
const {resources} = await res.json();
console.log(`${new Date().toTimeStringEx()} | -- -- : segment-sz : ${resources.length.toString().padStart(9)}`);
nested.push(...resources);
if (resources.length < amount) {
break;
}
}
while (true);
// прописываем всем "дочерним" задачам целевой каталог и добавляем в начало очереди
nested.forEach(item => item.target = task.target);
tasks.unshift(...nested);
}
// обработка файла
if (task.type == 'file') {
console.log(`${new Date().toTimeStringEx()} | -- -- : vol = ${task.meta.size.toString().padStart(10)}`);
// пропускаем, если целевой файл уже есть, и нужного размера
let need = !fs.existsSync(task.target);
if (!need) {
const {size} = fs.statSync(task.target);
need ||= size != task.meta.size;
if (need) {
fs.rmSync(task.target); // если размер не совпал - зачищаем
}
else {
console.log(`${new Date().toTimeStringEx()} | -- -- : skip file`);
filestat.skip++;
}
}
if (need) {
console.log(`${new Date().toTimeStringEx()} | -- -- : get storage : ${JSON.stringify(task.path)}`);
// получаем URL для доступа к файлу
const res = await fetch(
'https://disk.yandex.ru/models-v2?m=mpfs/url'
, {
headers
, method : 'POST'
, body : JSON.stringify({
...reqJSON
, apiMethod : 'mpfs/url'
, requestParams : {
path : task.path
}
})
}
);
const data = await res.json();
if (data.file) {
let retry = 2; // до 2 попыток загрузки
let success;
do {
console.log(`${new Date().toTimeStringEx()} | -- -- : rcv storage : ${data.file}`);
const res = await fetch('https:' + data.file, {
headers
, method : 'GET'
})
.catch(e => {
console.log(`${new Date().toTimeStringEx()} | GET`, e);
});
if (res?.status == 200) {
const tempfile = path.join(temp, task.name);
console.log(`${new Date().toTimeStringEx()} | -- -- : rcv data | ${tempfile}`);
// считаем полученный объем файла и выводим в лог раз в секунду
const tsb = Date.now();
let size = 0;
let tsl = tsb;
const monitor = new Transform({
transform(chunk, encoding, callback) {
size += chunk.length;
const tse = Date.now();
if (tse >= tsl + 1000 || size == task.meta.size) {
console.log(`${new Date().toTimeStringEx()} | -- -- : rcv = ${size.toString().padStart(10)} (${(size/task.meta.size * 100).toFixed(2).padStart(6)}%) | ${(size/((tse - tsb)/1000)/1024/1024).toFixed(2).padStart(6)} MB/s | ETA = ${new Date(tse + (tse - tsb)/size * (task.meta.size - size)).toTimeStringEx()}`);
tsl = tse;
}
this.push(chunk);
callback();
}
});
try {
// перенаправляем поток загружаемого файла через наш монитор во временный файл
await pipeline(
Readable.fromWeb(res.body)
.on('error', e => {
console.log(`${new Date().toTimeStringEx()} | bodyStream`, e);
})
, monitor
, fs.createWriteStream(tempfile, {flags : 'wx'})
)
.catch(e => {
console.log(`${new Date().toTimeStringEx()} | finished`, e);
});
// если загруженный размер совпадает с ожидаемым - перекопируем в целевое хранилище
if (size == task.meta.size) {
console.log(`${new Date().toTimeStringEx()} | -- -- : cpy = ${task.target}`);
fs.copyFileSync(tempfile, task.target);
await utimes(task.target, {
btime : task.ctime * 1000
, mtime : task.mtime * 1000
, atime : task.utime * 1000
});
const tse = Date.now();
console.log(`${new Date().toTimeStringEx()} | -- -- : mov = ${size.toString().padStart(10)} (${(size/task.meta.size * 100).toFixed(2).padStart(6)}%) | ${(size/((tse - tsl)/1000)/1024/1024).toFixed(2).padStart(6)} MB/s |`);
success = true;
filestat.dump++;
}
else {
console.log(`${new Date().toTimeStringEx()} | -- -- : neq sizes : ${size} != ${task.meta.size}`);
}
}
catch (e) {
console.log(`${new Date().toTimeStringEx()} | catch`, e);
}
fs.rmSync(tempfile);
}
else {
console.log(`${new Date().toTimeStringEx()} | -- -- : ${res?.status} - ${res?.statusText}`);
}
}
while (!success && --retry);
if (!success) {
// файл, который не удалось получить, выводится в STDERR
console.error(`${new Date().toTimeStringEx()} | ${task.path}`);
filestat.error++;
}
}
else {
console.log(data);
}
}
}
} while (true);
console.log(`${new Date().toTimeStringEx()} | finish | skip : ${filestat.skip}, dump : ${filestat.dump}, error : ${filestat.error}`);
})();Since some of the files are still inaccessible, but are gradually being "opened", it is recommended to periodically restart the script. I made the following bat file for myself, which creates a new pair of log/err files every time it starts, so that you can immediately see what has not yet loaded this time:
@echo off
for /f "tokens=2 delims==" %%i in ('wmic OS Get localdatetime /value') do set "dt=%%i"
set "timestamp=%dt:~0,14%"
node yad-dl.js >_log-%timestamp% 2>_err-%timestamp%Instead of a conclusion
Almost every new launch of the script now brings new files that were not available in previous iterations - so, thanks to colleagues from Yandex, the situation is gradually improving.
Perhaps the official client will be enough for you, but for me it was not able to show channel utilization above 1Mbps. Experiments with the script showed that now files are transferred, albeit at different speed levels, but from 1.5Mbps to 50Mbps (apparently, depending on the specific data center).

💬 Discussion 0
BBCode & Emoji supportedParticipate in discussions, ask authors questions, and share benchmarks by joining the ProArena engineering community.