This repository has been archived by the owner on Oct 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.cpp
325 lines (281 loc) · 11.8 KB
/
main.cpp
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#include <QDir>
#include <QHash>
#include <QtDebug>
#include <QUrlQuery>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QScopedPointer>
#include <QCoreApplication>
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QNetworkAccessManager>
#include <taglib/flacfile.h>
#include <taglib/xiphcomment.h>
#include <taglib/tpropertymap.h>
#include <gumbo-query/Document.h>
#include <gumbo-query/Node.h>
#include "file_stream.cpp"
class PictureWrapper {
TagLib::String mime_type;
TagLib::FLAC::Picture::Type t;
TagLib::ByteVector bv;
public:
PictureWrapper(QNetworkReply *resp) {
const QByteArray &bin = resp->readAll();
bv = TagLib::ByteVector(bin.data(), bin.length());
mime_type = resp->header(QNetworkRequest::ContentTypeHeader).toString().toStdString();
t = TagLib::FLAC::Picture::FrontCover;
}
TagLib::FLAC::Picture *get_pic() {
TagLib::FLAC::Picture *pic = new TagLib::FLAC::Picture();
pic->setMimeType(mime_type);
pic->setType(t);
pic->setData(bv);
return pic;
}
};
const int bar_width = 50;
const QString app_name = "bp_audio";
const QString app_version = "1.1";
QCommandLineOption au_opt({"a", "au"}, "Audio AU number.", "au");
QCommandLineOption all_opt("menu", "Download whole menu.");
QCommandLineOption output_opt({"o", "out"}, "Output folder path.", "path");
QCommandLineParser parser;
QScopedPointer<QNetworkAccessManager> session;
QDir output;
QHash<QString, QSharedPointer<PictureWrapper> > assets;
#ifdef _WIN32
#include <Shlobj.h>
QString santize_filename(const QString &name) {
std::array<wchar_t, MAX_PATH> buf{};
name.toWCharArray(buf.data());
PathCleanupSpec(output.absolutePath().toStdWString().data(), buf.data());
return std::move(QString::fromWCharArray(buf.data()));
}
#else
QString santize_filename(const QString &name) {
return name; // Yeah'em lazy.
}
#endif
QString find_audio(const QByteArray &data) {
CDocument doc;
doc.parse(data.toStdString());
CSelection audio = doc.find("audio");
return std::move(QString::fromStdString(audio.nodeAt(0).attribute("src")));
}
void download_progress(const qint64 &bytes_received, const qint64 &bytes_total) {
if (bytes_total == -1) return;
std::cerr << '[';
int pos = bar_width * bytes_received / bytes_total;
for (int i = 0; i < bar_width; ++i) {
if (i < pos) std::cerr << '=';
else if (i == pos) std::cerr << '>';
else std::cerr << ' ';
}
std::cerr << "] " << int(100 * bytes_received / bytes_total) << " %\r";
if (bytes_received >= bytes_total) std::cerr << '\n';
}
void write_metadata(QFile *file, const QJsonObject &data,
const int &track, const int &total) {
TagLib::FLAC::File f(new FileStream(file), nullptr);
if (!f.isValid()) {
qCritical("Downloaded song not valid");
std::exit(EXIT_FAILURE);
}
TagLib::PropertyMap map;
map.insert("TITLE", TagLib::String(data["title"].toString().toStdWString()));
map.insert("ARTIST", TagLib::String(data["author"].toString().toStdWString()));
const auto &album_info = data.find("pgc_info");
if (album_info != data.end()) {
const QJsonObject &album_info_obj = album_info->toObject();
if (album_info_obj.find("pgc_menu") != album_info_obj.end()) {
const QJsonObject &album_menu = album_info_obj["pgc_menu"].toObject();
map.insert("ALBUMARTIST", TagLib::String(album_menu["mbnames"].toString().toStdWString()));
map.insert("ALBUM", TagLib::String(album_menu["title"].toString().toStdWString()));
map.insert("DATE", TagLib::String(QDateTime::fromTime_t(album_menu["pubTime"].toInt()).toString("yyyy-MM-dd").toStdWString()));
map.insert("LABEL", TagLib::String(album_menu["publisher"].toString().toStdWString()));
map.insert("DISCNUMBER", TagLib::String(QString::number(1).toStdWString()));
map.insert("DISCTOTAL", TagLib::String(QString::number(1).toStdWString()));
}
}
if (track != -1 && total != -1) {
map.insert("TRACKNUMBER", TagLib::String(QString::number(track).toStdWString()));
map.insert("TRACKTOTAL", TagLib::String(QString::number(total).toStdWString()));
}
f.xiphComment(true)->setProperties(map);
const QString &cover_url = data["cover_url"].toString();
QSharedPointer<PictureWrapper> w;
if (assets.count(cover_url)) {
w = assets[cover_url];
} else {
QNetworkRequest cover_req(QUrl(data["cover_url"].toString()));
QScopedPointer<QNetworkReply> cover_resp(session->get(cover_req));
qInfo("Getting album art...");
QEventLoop loop;
QObject::connect(cover_resp.data(), &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (cover_resp->error() != QNetworkReply::NoError) {
qCritical("Error loading album art");
qDebug(" %s", qUtf8Printable(cover_resp->errorString()));
std::exit(EXIT_FAILURE);
}
w.reset(new PictureWrapper(cover_resp.data()));
assets.insert(cover_url, w);
}
f.addPicture(w->get_pic());
f.save();
}
void download_song(const QJsonObject &data, const int &track = -1, const int &total = -1) {
QString file_name = QStringLiteral("%1 - %2.flac").arg(data["author"].toString(), data["title"].toString());
file_name = santize_filename(file_name);
const QString &au = QString::number(data["id"].toInt());
qInfo("Getting audio preview for %s...", qUtf8Printable(au));
QNetworkRequest song_link_req(QUrl("https://m.bilibili.com/audio/au" + au));
QScopedPointer<QNetworkReply> link_page(session->get(song_link_req));
QEventLoop loop;
QObject::connect(link_page.data(), &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (link_page->error() != QNetworkReply::NoError) {
qCritical("Error loading audio preview");
qDebug(" %s", qUtf8Printable(link_page->errorString()));
std::exit(EXIT_FAILURE);
}
const QString &audio_src = find_audio(link_page->readAll());
QUrl audio_url(audio_src);
QString audio_path = audio_url.path();
audio_path.replace("preview", "flac");
const int &suffix_length = QFileInfo(audio_path).suffix().length();
audio_path.replace(audio_path.length() - suffix_length, suffix_length, "flac");
audio_url.setPath(audio_path);
audio_url.setQuery(QUrlQuery());
QNetworkRequest song_flac(audio_url);
QScopedPointer<QNetworkReply> song_res(session->get(song_flac));
QObject::connect(song_res.data(), &QNetworkReply::downloadProgress, download_progress);
QObject::connect(song_res.data(), &QNetworkReply::readyRead, &loop, &QEventLoop::quit);
QObject::connect(song_res.data(), &QNetworkReply::finished, &loop, &QEventLoop::quit);
file_name = output.filePath(file_name);
qInfo("Writing to %s...", qUtf8Printable(file_name));
QFile f(file_name);
if (f.open(QIODevice::ReadWrite | QIODevice::Truncate)) {
do {
loop.exec();
if (song_res->error() != QNetworkReply::NoError) {
qCritical("Error loading audio resource");
qDebug(" %s", qUtf8Printable(song_res->errorString()));
std::exit(EXIT_FAILURE);
}
f.write(song_res->readAll());
} while (!song_res->isFinished());
}
write_metadata(&f, data, track, total);
f.close();
qInfo("Finished for %s", qUtf8Printable(file_name));
}
void get_menu_info(const QString &menuid) {
QNetworkRequest menu_info_req(QUrl("https://www.bilibili.com/audio/music-service-c/menus/" + menuid));
QScopedPointer<QNetworkReply> info(session->get(menu_info_req));
qInfo("Start loading menu info for %s...", qUtf8Printable(menuid));
QEventLoop loop;
QObject::connect(info.data(), &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (info->error() != QNetworkReply::NoError) {
qCritical("Error loading menu info");
qDebug(" %s", qUtf8Printable(info->errorString()));
std::exit(EXIT_FAILURE);
}
const QJsonDocument &doc = QJsonDocument::fromJson(info->readAll());
const QJsonObject &obj = doc.object();
if (obj["code"].toInt() != 0) {
qCritical("Error loading menu info");
qDebug(" %d: %s", obj["code"].toInt(), qUtf8Printable(obj["msg"].toString()));
std::exit(EXIT_FAILURE);
}
const QJsonObject &data = obj["data"].toObject();
const QJsonObject &menus_response = data["menusRespones"].toObject();
QString folder_name = QStringLiteral("%1 - %2").arg(menus_response["mbnames"].toString(), menus_response["title"].toString());
folder_name = santize_filename(folder_name);
if (!output.exists(folder_name) && !output.mkdir(folder_name)) {
qCritical("Error creating folder -- check permission");
std::exit(EXIT_FAILURE);
}
output.cd(folder_name);
const QJsonArray &songsList = data["songsList"].toArray();
int counter = 0;
const int &total = songsList.size();
for (const auto &&i : songsList) {
download_song(i.toObject(), ++counter, total);
}
}
void get_song_info(const QString &au)
{
QNetworkRequest song_info_req(QUrl("https://www.bilibili.com/audio/music-service-c/songs/playing?song_id=" + au));
QScopedPointer<QNetworkReply> info(session->get(song_info_req));
qInfo("Start loading song info for %s...", qUtf8Printable(au));
QEventLoop loop;
QObject::connect(info.data(), &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (info->error() != QNetworkReply::NoError) {
qCritical("Error loading song info");
qDebug(" %s", qUtf8Printable(info->errorString()));
std::exit(EXIT_FAILURE);
}
const QJsonDocument &doc = QJsonDocument::fromJson(info->readAll());
const QJsonObject &obj = doc.object();
if (obj["code"].toInt() != 0) {
qCritical("Error loading song info");
qDebug(" %d: %s", obj["code"].toInt(), qUtf8Printable(obj["msg"].toString()));
std::exit(EXIT_FAILURE);
}
const QJsonObject &data = obj["data"].toObject();
if (parser.isSet(all_opt)) {
const auto &album_info = data.find("pgc_info");
if (album_info != data.end()) {
const QJsonObject &album_info_obj = album_info->toObject();
if (album_info_obj.find("pgc_menu") != album_info_obj.end()) {
const QJsonObject &album_menu = album_info_obj["pgc_menu"].toObject();
get_menu_info(QString::number(album_menu["menuId"].toInt()));
return;
}
}
qDebug("No menu found.");
}
download_song(data);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
a.setApplicationName(app_name);
a.setApplicationVersion(app_version);
session.reset(new QNetworkAccessManager());
parser.addOption(au_opt);
parser.addOption(all_opt);
parser.addOption(output_opt);
parser.addHelpOption();
parser.addVersionOption();
parser.setApplicationDescription("Get to know some free official FLAC music.");
parser.process(a);
const QString &au_number = parser.value(au_opt);
QString output_path = parser.value(output_opt);
output.setPath(output_path);
if (au_number.isEmpty()) {
qWarning("\nAU number is required.\n");
parser.showHelp();
} else {
bool ok = false;
au_number.toInt(&ok, 10);
if (!ok) {
qWarning("\nAU needs to be a number.\n");
parser.showHelp();
}
}
if (output_path.isEmpty()) {
output = QDir::current();
} else if (!output.exists()) {
qWarning("\nOutput path does not exist.\n");
parser.showHelp();
}
get_song_info(au_number);
return EXIT_SUCCESS;
}