Repository navigation
Expand file tree
/
Copy pathdownloadthread.cpp
More file actions
1954 lines (1705 loc) · 79.2 KB
/
Copy pathdownloadthread.cpp
File metadata and controls
1954 lines (1705 loc) · 79.2 KB
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2009-2014 jakago
Copyright (C) 2018-2026 CSReviser Team
This file is part of CaptureStream2, the recorder to support HLS for
NHK radio language courses.
CaptureStream2 is a modified version of CaptureStream, originally
developed by jakago.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/gpl-2.0.html>.
*/
#include <stdlib.h>
#include "downloadthread.h"
#include "ui_mainwindow.h"
#include "downloadmanager.h"
#include "customizedialog.h"
#include "mainwindow.h"
#include "urldownloader.h"
#include "utility.h"
#include "qt4qt5.h"
#include "scrambledialog.h"
#include "settings.h"
#include "constants.h"
#include "runtimeconfig.h"
#include "programrepository.h"
#include <QRegularExpression>
#include <QCheckBox>
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>
#include <QTemporaryFile>
#include <QDateTime>
#include <QEventLoop>
#include <QTextStream>
#include <QDate>
#include <QLocale>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QApplication>
#include <QUrl>
#include <QUrlQuery>
#include <QtNetwork>
#include <QTemporaryFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QByteArray>
#include <QJsonValue>
#include <QMap>
#include <QMultiMap>
#include <tuple>
#include <algorithm>
#ifdef Q_OS_WIN
#define TimeOut " -m 10000 "
#else
#define TimeOut " -m 10 "
#endif
#define ScrambleLength 14
#define FlvMinSize 100 // ストリーミングが存在しなかった場合は13バイトだが少し大きめに設定
#define OriginalFormat "ts"
#define FilterOption "-bsf:a aac_adtstoasc"
#define CancelCheckTimeOut 500 // msec
//#define DebugLog(s) if ( ui->toolButton_detailed_message->isChecked() ) {emit information((s));}
//--------------------------------------------------------------------------------
QString DownloadThread::prefix = "https://www.nhk.or.jp/gogaku/st/xml/";
QString DownloadThread::suffix = "listdataflv.xml";
QString DownloadThread::json_prefix = "https://www.nhk.or.jp/radioondemand/json/";
QString DownloadThread::prefix1 = "https://vod-stream.nhk.jp/gogaku-stream/mp4/";
QString DownloadThread::prefix2 = "https://vod-stream.nhk.jp/gogaku-stream/mp4/";
QString DownloadThread::prefix3 = "https://vod-stream.nhk.jp/gogaku-stream/mp4/";
//QString DownloadThread::prefix1 = "https://vod-stream.nhk.jp/radioondemand/r/";
QString DownloadThread::suffix1 = "/index.m3u8";
QString DownloadThread::suffix2 = ".mp4/index.m3u8";
QString DownloadThread::suffix3 = "/index.m3u8";
QString DownloadThread::flv_host = "flv.nhk.or.jp";
QString DownloadThread::flv_app = "ondemand/";
QString DownloadThread::flv_service_prefix = "mp4:flv/gogaku/streaming/mp4/";
QString DownloadThread::flvstreamer;
QString DownloadThread::ffmpeg;
QString DownloadThread::Xml_koza;
QString DownloadThread::test;
QString DownloadThread::Error_mes;
QString DownloadThread::scramble;
QString DownloadThread::optional1;
QString DownloadThread::optional2;
QString DownloadThread::optional3;
QString DownloadThread::optional4;
QString DownloadThread::optional5;
QString DownloadThread::optional6;
QString DownloadThread::optional7;
QString DownloadThread::optional8;
QString DownloadThread::special1;
QString DownloadThread::special2;
QString DownloadThread::special3;
QString DownloadThread::special4;
QString DownloadThread::opt_title1;
QString DownloadThread::opt_title2;
QString DownloadThread::opt_title3;
QString DownloadThread::opt_title4;
QString DownloadThread::opt_title5;
QString DownloadThread::opt_title6;
QString DownloadThread::opt_title7;
QString DownloadThread::opt_title8;
QStringList DownloadThread::malformed = (QStringList() << "3g2" << "3gp" << "m4a" << "mov");
QString DownloadThread::nendo1 = "2025"; // 今年度
QString DownloadThread::nendo2 = "2026"; // 次年度
QDate DownloadThread::nendo_start_date(2025, 3, 31); // 今年度開始
QDate DownloadThread::zenki_end_date(2025, 9, 28); // 今年度前期末、年度末は次年度前期末
QDate DownloadThread::kouki_start_date(2025, 9, 29); // 今年度後期開始
QDate DownloadThread::nendo_end_date(2026, 3, 29); // 今年度末
QDate DownloadThread::nendo_start_date1(2025, 3, 31); // 年度初めは今年度開始、年度末は次年開始
QDate DownloadThread::nendo_end_date1(2026, 3, 29); // 年度初めは今年度末、年度末は次年度末
QDate DownloadThread::nendo_start_date2(2026, 3, 30); // 次年度開始
QDate DownloadThread::nendo_end_date2(2027, 3, 28); // 次年度末
QHash<QString, QString> DownloadThread::ffmpegHash;
QHash<QProcess::ProcessError, QString> DownloadThread::processError;
//--------------------------------------------------------------------------------
//DownloadThread::DownloadThread( Settings& settings,const RuntimeConfig& r, Ui::MainWindowClass* ui ) : isCanceled(false), failed1935(false), settings(settings),runtime(r),ui(ui) {
DownloadThread::DownloadThread( const RuntimeConfig& r ) : isCanceled(false), failed1935(false), runtime(r) {
this->ui = ui;
if ( ffmpegHash.empty() ) {
ffmpegHash["aac"] = "%1,-vn,-acodec,copy,%2";
ffmpegHash["m4a"] = "%1,-id3v2_version,3,-metadata,title=%3,-metadata,artist=NHK,-metadata,album=%4,-metadata,date=%5,-metadata,genre=Speech,-vn,-bsf,aac_adtstoasc,-acodec,copy,%2";
ffmpegHash["mp3-64k-S"] = "%1,-id3v2_version,3,-write_xing,0,-metadata,title=%3,-metadata,artist=NHK,-metadata,album=%4,-metadata,date=%5,-metadata,genre=Speech,-vn,-acodec:a,libmp3lame,-ab,64k,-ac,2,%2";
ffmpegHash["mp3-128k-S"] = "%1,-id3v2_version,3,-write_xing,0,-metadata,title=%3,-metadata,artist=NHK,-metadata,album=%4,-metadata,date=%5,-metadata,genre=Speech,-vn,-acodec:a,libmp3lame,-ab,128k,-ac,2,%2";
ffmpegHash["mp3-48k-S"] = "%1,-id3v2_version,3,-write_xing,0,-metadata,title=%3,-metadata,artist=NHK,-metadata,album=%4,-metadata,date=%5,-metadata,genre=Speech,-vn,-acodec:a,libmp3lame,-ab,48k,-ac,2,%2";
ffmpegHash["mp3-40k-M"] = "%1,-id3v2_version,3,-write_xing,0,-metadata,title=%3,-metadata,artist=NHK,-metadata,album=%4,-metadata,date=%5,-metadata,genre=Speech,-vn,-acodec:a,libmp3lame,-ab,40k,-ar,32k,-ac,1,%2";
ffmpegHash["mp3-32k-M"] = "%1,-id3v2_version,3,-write_xing,0,-metadata,title=%3,-metadata,artist=NHK,-metadata,album=%4,-metadata,date=%5,-metadata,genre=Speech,-vn,-acodec:a,libmp3lame,-ab,32k,-ar,32k,-ac,1,%2";
ffmpegHash["mp3-24k-M"] = "%1,-id3v2_version,3,-write_xing,0,-metadata,title=%3,-metadata,artist=NHK,-metadata,album=%4,-metadata,date=%5,-metadata,genre=Speech,-vn,-acodec:a,libmp3lame,-ab,24k,-ar,22.05k,-ac,1,%2";
ffmpegHash["mp3-16k-M"] = "%1,-id3v2_version,3,-write_xing,0,-metadata,title=%3,-metadata,artist=NHK,-metadata,album=%4,-metadata,date=%5,-metadata,genre=Speech,-vn,-acodec:a,libmp3lame,-ab,16k,-ar,22.05k,-ac,1,%2";
}
if ( processError.empty() ) {
processError[QProcess::FailedToStart] = "FailedToStart";
processError[QProcess::Crashed] = "Crashed";
processError[QProcess::Timedout] = "Timedout";
processError[QProcess::ReadError] = "ReadError";
processError[QProcess::WriteError] = "WriteError";
processError[QProcess::UnknownError] = "UnknownError";
}
}
std::tuple<QStringList, QStringList, QStringList, QStringList, QStringList>
DownloadThread::getAttribute1(const QString &url)
{
QStringList fileList;
QStringList kouzaList;
QStringList hdateList;
QStringList nendoList;
QStringList dirList;
QEventLoop eventLoop;
QNetworkAccessManager mgr;
// 新しいシグナル/スロット構文(Qt5/Qt6両対応)
QObject::connect(&mgr, &QNetworkAccessManager::finished,
&eventLoop, &QEventLoop::quit);
QUrl url_xml(url);
QNetworkRequest req(url_xml);
QNetworkReply *reply = mgr.get(req);
eventLoop.exec(); // finishedシグナルを待機
// replyから全データを読み出してQByteArrayに格納
QByteArray xmlData = reply->readAll();
reply->deleteLater();
// QByteArrayを元にQXmlStreamReaderを初期化
QXmlStreamReader reader(xmlData);
while (!reader.atEnd() && !reader.hasError()) {
reader.readNext();
if (reader.isStartDocument())
continue;
if (reader.isEndDocument())
break;
// 各属性の値を取得
fileList.append(reader.attributes().value("file").toString());
kouzaList.append(reader.attributes().value("kouza").toString());
hdateList.append(reader.attributes().value("hdate").toString());
nendoList.append(reader.attributes().value("nendo").toString());
dirList.append(reader.attributes().value("dir").toString());
}
return { fileList, kouzaList, hdateList, nendoList, dirList };
}
QString DownloadThread::getJsonFile( QString jsonUrl ) {
QEventLoop eventLoop;
QString attribute;
QTimer timer;
timer.setSingleShot(true);
QNetworkAccessManager mgr;
QObject::connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*) ), &eventLoop, SLOT(quit()));
QUrl url_json( jsonUrl );
QNetworkRequest req;
req.setUrl(url_json);
timer.start(400); // use miliseconds
QNetworkReply *reply = mgr.get(req);
eventLoop.exec(); // blocks stack until "finished()" has been called
if(timer.isActive()) {
timer.stop();
if (reply->error() == QNetworkReply::NoError) {
attribute = (QString)reply->readAll();
} else {
return "error";
}
} else {
// timeout
QObject::disconnect(&mgr, SIGNAL(finished(QNetworkReply*) ), &eventLoop, SLOT(quit()));
reply->abort();
return "error";
}
return attribute;
}
std::tuple<QStringList, QStringList, QStringList, QStringList, QStringList>
DownloadThread::getJsonData(const QString& urlInput) {
QStringList fileList, kouzaList, file_titleList, hdateList, yearList, contentsIdList;
QString url = urlInput;
const int urlLen = url.length();
int l = (urlLen != 13) ? urlLen - 3 : 10;
int json_ohyo = 0;
if (url.contains("_x1")) { url.replace("_x1", "_01"); json_ohyo = 1; }
else if (url.contains("_y1")) { url.replace("_y1", "_01"); json_ohyo = 2; }
const QString jsonUrl = "https://www.nhk.or.jp/radio-api/app/v1/web/ondemand/series?site_id="
+ url.left(l) + "&corner_site_id=" + url.right(2);
QString strReply;
bool success = false;
int timer = 100;
const int timerMax = 5000;
const int retryLimit = 15;
for (int i = 0; i < retryLimit; ++i) {
strReply = Utility::getJsonFile(jsonUrl, timer);
if (strReply != "error") {
success = true;
break;
}
timer = std::min(timer + ((timer < 500) ? 50 : 100), timerMax);
}
if (success) {
// Utility側から 6つ目の引数として contentsIdList を受け取る
std::tie(fileList, kouzaList, file_titleList, hdateList, yearList, contentsIdList) =
Utility::getJsonData1(strReply, json_ohyo);
} else {
kouzaList.append("");
emit critical(QString::fromUtf8("番組ID:") + url + QString::fromUtf8("のデータ取得エラー"));
}
// --- ここから放送時間順ソート処理 ---
const int count = kouzaList.size();
if (count > 1 && contentsIdList.size() == count) {
// 1. 各リストの要素を一つの構造体にまとめる
struct TempItem {
QString file, kouza, title, hdate, year, cid;
};
QList<TempItem> tempPacks;
tempPacks.reserve(count);
for (int i = 0; i < count; ++i) {
tempPacks.append({
fileList.value(i),
kouzaList.value(i),
file_titleList.value(i),
hdateList.value(i),
yearList.value(i),
contentsIdList.value(i)
});
}
// 2. contentsIdList(cid) の末尾にある ISO 8601 日時文字列でソート
std::sort(tempPacks.begin(), tempPacks.end(), [](const TempItem &a, const TempItem &b) {
// 例: "...;2024-02-27T06:45:00+09:00_..." の日時部分を比較
auto getTimePart = [](const QString &id) {
return id.section(';', -1).section('_', 0, 0);
};
return getTimePart(a.cid) < getTimePart(b.cid);
});
// 3. 各リストをクリアして、ソート順に詰め直す
fileList.clear(); kouzaList.clear(); file_titleList.clear(); hdateList.clear(); yearList.clear();
for (const auto &item : tempPacks) {
fileList << item.file;
kouzaList << item.kouza;
file_titleList << item.title;
hdateList << item.hdate;
yearList << item.year;
}
}
// --- ソート処理ここまで ---
// 以前と同様の不足分補完処理
const int finalCount = kouzaList.size();
while (file_titleList.size() < finalCount) file_titleList.append("\0");
while (fileList.size() < finalCount) fileList.append("\0");
while (hdateList.size() < finalCount) hdateList.append("\0");
while (yearList.size() < finalCount) yearList.append("\0");
return { fileList, kouzaList, file_titleList, hdateList, yearList };
}
/*
std::tuple<QStringList, QStringList, QStringList, QStringList, QStringList>
DownloadThread::getJsonData(const QString& urlInput) {
QStringList fileList, kouzaList, file_titleList, hdateList, yearList, contentsIdList;
QString url = urlInput;
const int urlLen = url.length();
int l = (urlLen != 13) ? urlLen - 3 : 10;
int json_ohyo = 0;
if (url.contains("_x1")) { url.replace("_x1", "_01"); json_ohyo = 1; }
else if (url.contains("_y1")) { url.replace("_y1", "_01"); json_ohyo = 2; }
const QString jsonUrl = "https://www.nhk.or.jp/radio-api/app/v1/web/ondemand/series?site_id="
+ url.left(l) + "&corner_site_id=" + url.right(2);
QString strReply;
bool success = false;
int timer = 100;
const int timerMax = 5000;
const int retryLimit = 15;
for (int i = 0; i < retryLimit; ++i) {
strReply = Utility::getJsonFile(jsonUrl, timer);
if (strReply != "error") {
success = true;
break;
}
timer = std::min(timer + ((timer < 500) ? 50 : 100), timerMax);
}
if (success) {
std::tie(fileList, kouzaList, file_titleList, hdateList, yearList, contentsIdList) =
Utility::getJsonData1(strReply, json_ohyo);
} else {
kouzaList.append("");
emit critical(QString::fromUtf8("番組ID:") + url + QString::fromUtf8("のデータ取得エラー"));
}
const int count = kouzaList.size();
fileList.reserve(count);
file_titleList.reserve(count);
hdateList.reserve(count);
yearList.reserve(count);
while (file_titleList.size() < count) file_titleList.append("\0");
while (fileList.size() < count) fileList.append("\0");
while (hdateList.size() < count) hdateList.append("\0");
while (yearList.size() < count) yearList.append("\0");
return { fileList, kouzaList, file_titleList, hdateList, yearList };
}
*/
QString DownloadThread::getAttribute2( QString url, QString attribute ) {
QEventLoop eventLoop;
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
QUrl url_html( url );
QNetworkRequest req;
req.setUrl( url_html );
QNetworkReply *reply = mgr.get(req);
eventLoop.exec();
QString content = reply->readAll();
QRegularExpression rx("https://vod-stream.nhk.jp/gogaku-stream/.+?/index.m3u8");
QRegularExpressionMatch match = rx.match( content );
attribute = match.captured(0);
return attribute;
}
// フィルター関数定義(private関数)
QStringList DownloadThread::filteredNames(const QStringList& sourceList, const QStringList& keywords, const QString& exclude) {
QStringList result;
for (const QString& name : sourceList) {
for (const QString& keyword : keywords) {
if (name.contains(keyword) && !name.contains(exclude)) {
result << name;
break; // 重複防止
}
}
}
return result;
}
/*
// メイン関数(処理分岐のみ)
void DownloadThread::id_list() {
const QStringList keywords1 = { "英語", "英会話", "イングリッシュ", "ボキャブライダー", "Asian View" };
const QStringList keywords2 = { "まいにち", "中国語", "ハングル", "アラビア", "ポルトガル", "日本語", "Learn Japanese", "Living in Japan" };
const QString excludeTag = "【中級編】";
auto &repo = ProgramRepository::instance();
const QStringList allKeys = repo.name_map.keys();
QStringList key;
switch (MainWindow::id_List_flag) {
case 1:
key = filteredNames(allKeys, keywords1, excludeTag);
break;
case 2:
key = filteredNames(allKeys, keywords2, excludeTag);
break;
case 3:
key = allKeys;
break;
default:
break;
}
emit current( QString::fromUtf8( "番組ID\t\t: 番組名 " ) );
for ( int i = 0; i < key.count() ; i++ ) {
if ( repo.name_map[key[i]].left(1) == "F") {
emit current( repo.name_map[key[i]] + QString::fromUtf8( "\t\t: " ) + key[i] );
} else {
emit current( repo.name_map[key[i]] + QString::fromUtf8( "\t: " ) + key[i] );
}
}
MainWindow::id_flag = false;
}
*/
void DownloadThread::thumbnail_add(const QString &dstPath, const QString &tmp, const QString &json_path)
{
int l = (json_path.length() == 13) ? 10 : json_path.length() - 3;
QString corner_site_id = json_path.right(2);
if (corner_site_id == "x1" || corner_site_id == "y1")
corner_site_id = "01";
QString key = json_path.left(l) + "_" + corner_site_id;
auto &repo = ProgramRepository::instance();
if (!repo.thumbnail_map.contains(key))
return;
QString dstPath_tmp = dstPath; dstPath_tmp.replace( ".", "_temp." );
// QFile::rename(dstPath, tmp);
QFile::rename(dstPath, dstPath_tmp);
QString thumb = repo.thumbnail_map.value(key);
// QString thumb = MainWindow::thumbnail_map.value(key);
QStringList arguments_t = {
"-y", "-i", dstPath_tmp, "-i", thumb,
"-id3v2_version", "3",
"-map", "0:a", "-map", "1:v",
"-map_metadata", "0",
"-codec", "copy",
"-disposition:1", "attached_pic",
dstPath
};
if ( dstPath.endsWith(".mp3") ){
QStringList arguments_t = { "-y", "-i", dstPath_tmp, "-i", thumb,
"-id3v2_version", "3",
"-write_xing", "0",
"-map", "0:a", "-map", "1:v",
"-map_metadata", "0",
"-codec", "copy",
"-disposition:1", "attached_pic",
dstPath };
}
QProcess process_t;
process_t.setProgram(ffmpeg);
process_t.setArguments(arguments_t);
process_t.start();
process_t.waitForFinished();
QString stderr_output = process_t.readAllStandardError();
process_t.kill();
process_t.close();
if (stderr_output.contains("error", Qt::CaseInsensitive)) {
QFile::remove(dstPath);
QFile::rename(dstPath_tmp, dstPath);
return;
}
QFile::remove(dstPath_tmp);
// emit critical(QString::fromUtf8("サムネ: %1 \n %2 \n %3 ").arg(thumb,dstPath_tmp, dstPath));
return;
}
bool DownloadThread::checkExecutable( QString path ) {
QFileInfo fileInfo( path );
if ( !fileInfo.exists() ) {
emit critical( path + QString::fromUtf8( "が見つかりません。" ) );
return false;
} else if ( !fileInfo.isExecutable() ) {
emit critical( path + QString::fromUtf8( "は実行可能ではありません。" ) );
return false;
}
return true;
}
bool DownloadThread::isFfmpegAvailable(QString& path) {
auto fileExists = [](const QString& filePath) {
return QFileInfo(filePath).exists();
};
#ifdef Q_OS_WIN
const QString exeExt = ".exe";
#else
const QString exeExt = "";
#endif
// if (MainWindow::ffmpegDirSpecified) {
// path = MainWindow::ffmpeg_folder + "ffmpeg" + exeExt;
path = runtime.ffmpegFolder() + "ffmpeg" + exeExt;
// } else {
QStringList baseDirs;
#ifdef Q_OS_MACOS
// baseDirs.append(MainWindow::outputDir);
baseDirs.append(runtime.saveFolder());
baseDirs.append(Utility::appConfigLocationPath());
baseDirs.append(Utility::ConfigLocationPath());
baseDirs.append("/usr/local/bin/");
baseDirs.append("/opt/homebrew/bin/");
baseDirs.append(Utility::applicationBundlePath());
#else
baseDirs.append(Utility::applicationBundlePath());
// baseDirs.append(MainWindow::outputDir);
baseDirs.append(runtime.saveFolder());
// baseDirs.append(MainWindow::findFfmpegPath() + QDir::separator());
#endif
bool found = false;
for (const QString& dir : baseDirs) {
QString candidate = QDir(dir).filePath("ffmpeg" + exeExt);
if (fileExists(candidate)) {
path = candidate;
found = true;
break;
}
}
if (!found)
path = QDir(Utility::applicationBundlePath()).filePath("ffmpeg" + exeExt);
// checkExecutable(path);
// emit critical( QString::fromUtf8( "が見つかりません。" ) );
// return false;
// }
if (!checkExecutable(path))
return false;
return true;
}
//通常ファイルが存在する場合のチェックのために末尾にセパレータはついていないこと
bool DownloadThread::checkOutputDir( QString dirPath ) {
bool result = false;
QFileInfo dirInfo( dirPath );
if ( dirInfo.exists() ) {
if ( !dirInfo.isDir() )
emit critical( QString::fromUtf8( "「" ) + dirPath + QString::fromUtf8( "」が存在しますが、フォルダではありません。" ) );
else if ( !dirInfo.isWritable() )
emit critical( QString::fromUtf8( "「" ) + dirPath + QString::fromUtf8( "」フォルダが書き込み可能ではありません。" ) );
else
result = true;
} else {
QDir dir;
if ( !dir.mkpath( dirPath ) )
emit critical( QString::fromUtf8( "「" ) + dirPath + QString::fromUtf8( "」フォルダの作成に失敗しました。" ) );
else
result = true;
}
return result;
}
//--------------------------------------------------------------------------------
QStringList DownloadThread::one2two(const QStringList &hdateList) {
QStringList result;
QRegularExpression rx("(\\d+)(?:\\D+)(\\d+)");
for (const QString &hdate : hdateList) {
QRegularExpressionMatch match = rx.match(hdate);
if (match.hasMatch()) {
int month = match.captured(1).toInt();
int day = match.captured(2).toInt();
QString formatted = QString::number(month + 100).right(2)
+ QString::fromUtf8("月")
+ QString::number(day + 100).right(2)
+ QString::fromUtf8("日放送分");
result << formatted;
} else {
result << hdate; // マッチしなかった場合は元の文字列をそのまま追加
}
}
return result;
}
QStringList DownloadThread::thisweekfile( QStringList fileList2, QStringList codeList ) {
QStringList result;
for ( int i = 0; i < fileList2.count(); i++ ) {
QString filex = fileList2[i];
int filexxx = codeList[i].toInt() + fileList2.count() ;
filex.replace( codeList[i].right( 3 ) , QString::number( filexxx ).right( 3 ) );
filex.remove( "-re01" );
result << filex;
}
return result;
}
//--------------------------------------------------------------------------------
bool DownloadThread::illegal( char c ) {
bool result = false;
switch ( c ) {
case '/':
case '\\':
case ':':
case '*':
case '?':
case '"':
case '<':
case '>':
case '|':
case '#':
case '{':
case '}':
case '%':
case '&':
case '~':
result = true;
break;
default:
break;
}
return result;
}
QString DownloadThread::formatName( QString format, QString kouza, QString hdate, QString file, QString nendo, QString dupnmb, bool checkIllegal ) {
int month = hdate.left( 2 ).toInt();
int year = nendo.right( 4 ).toInt();
int day = hdate.mid( 3, 2 ).toInt();
// int year1 = QDate::currentDate().year();
QDate on_air_date1(year, month, day);
if ( on_air_date1 <= nendo_end_date1 ) nendo = nendo1;
if ( on_air_date1 >= nendo_start_date1 ) nendo = nendo2;
// if ( QString::compare( kouza , QString::fromUtf8( "ボキャブライダー" ) ) ==0 ){
// if ( month == 3 && ( day == 30 || day == 31) && year == 2022 )
// year += 0;
// else
// if ( month < 4 )
// year += 1;
// } else {
// if ( month <= 4 && QDate::currentDate().year() > year )
// year = year + (year1 - year);
// }
if ( file.right( 4 ) == ".flv" )
file = file.left( file.length() - 4 );
QString dupnmb1 = dupnmb;
if ( format.contains( "%i", Qt::CaseInsensitive)) dupnmb1 = "";
if ( format.contains( "%_%i", Qt::CaseInsensitive)) { dupnmb.replace( "-", "_" ); format.remove( "%_" ); }
QString result;
bool percent = false;
for ( int i = 0; i < format.length(); i++ ) {
QChar qchar = format[i];
if ( percent ) {
percent = false;
char ascii = qchar.toLatin1();
if ( checkIllegal && illegal( ascii ) )
continue;
switch ( ascii ) {
case 'k': result += kouza; break;
case 'h': result += hdate.left( 6 ) + QString::fromUtf8( "放送分" ) + dupnmb1; break;
case 'f': result += file; break;
//case 'r': result += MainWindow::applicationDirPath(); break;
//case 'p': result += QDir::separator(); break;
case 'Y': result += QString::number( year ); break;
case 'y': result += QString::number( year ).right( 2 ); break;
case 'N': result += nendo + QString::fromUtf8( "年度" ); break;
case 'n': result += nendo.right( 2 ) + QString::fromUtf8( "年度" ); break;
case 'M': result += QString::number( month + 100 ).right( 2 ); break;
case 'm': result += QString::number( month ); break;
case 'D': result += QString::number( day + 100 ).right( 2 ) + dupnmb1; break;
case 'd': result += QString::number( day ) + dupnmb1; break;
case 'i': result += dupnmb; break;
case 'x': break;
case 's': break;
default: result += qchar; break;
}
} else {
if ( qchar == QChar( '%' ) )
percent = true;
else if ( checkIllegal && illegal( qchar.toLatin1() ) )
continue;
else
result += qchar;
}
}
return result;
}
//--------------------------------------------------------------------------------
bool DownloadThread::captureStream( QString kouza, QString hdate, QString file, QString nendo, QString dir, QString this_week, QString json_path, bool nogui_flag ) {
QString titleFormat;
QString fileNameFormat;
CustomizeDialog::formats( "xml", titleFormat, fileNameFormat );
// QString outputDir = MainWindow::outputDir;
// QString extension = ui->comboBox_extension->currentText();
QString outputDir = runtime.saveFolder();
QString extension = runtime.audioExtension();
if ( nogui_flag )
std::tie( titleFormat, fileNameFormat, outputDir, extension ) = Utility::nogui_option( titleFormat, fileNameFormat, outputDir, extension );
if ( this_week == "R" )
outputDir = outputDir + QString::fromUtf8( "[前週]" )+ "/" + kouza;
else
outputDir = outputDir + kouza;
if ( !checkOutputDir( outputDir ) )
return false;
outputDir += QDir::separator(); //通常ファイルが存在する場合のチェックのために後から追加する
int month = hdate.left( 2 ).toInt();
int year = nendo.right( 4 ).toInt();
int day = hdate.mid( 3, 2 ).toInt();
if ( 2022 > year ) return false;
int year1 = QDate::currentDate().year();
// if ( QString::compare( kouza , QString::fromUtf8( "ボキャブライダー" ) ) ==0 ){
// if ( month == 3 && ( day == 30 || day == 31) && year == 2022 )
// year += 0;
// else
// if ( month < 4 )
// year += 1;
// } else {
if ( month <= 4 && QDate::currentDate().year() > year )
year = year + (year1 - year);
// }
QDate onair( year, month, day );
QString yyyymmdd = onair.toString( "yyyy_MM_dd" );
QString kon_nendo = nendo1; //QString::number(year1);
// QString outputDir = MainWindow::outputDir + kouza;
// if ( this_week == "R" )
// outputDir = MainWindow::outputDir + QString::fromUtf8( "[前週]" )+ "/" + kouza;
// if ( !checkOutputDir( outputDir ) )
// return false;
// outputDir += QDir::separator(); //通常ファイルが存在する場合のチェックのために後から追加する
// QString titleFormat;
// QString fileNameFormat;
// CustomizeDialog::formats( "xml", titleFormat, fileNameFormat );
QString id3tagTitle = formatName( titleFormat, kouza, hdate, file, yyyymmdd.left(4), "", false );
QString outFileName = formatName( fileNameFormat, kouza, hdate, file, yyyymmdd.left(4), "", true );
QFileInfo fileInfo( outFileName );
QString outBasename = fileInfo.completeBaseName();
// 2013/04/05 オーディオフォーマットの変更に伴って拡張子の指定に対応
// QString extension = ui->comboBox_extension->currentText();
QString extension1 = extension;
if ( extension.left( 3 ) == "mp3" ) extension1 = "mp3";
outFileName = outBasename + "." + extension1;
#ifdef Q_OS_WIN
QString null( "nul" );
#else
QString null( "/dev/null" );
#endif
// if ( ui->toolButton_skip->isChecked() && QFile::exists( outputDir + outFileName ) ) {
if ( runtime.flag( QString::fromUtf8( Constants::KEY_SKIP )) && QFile::exists( outputDir + outFileName ) ) {
if ( this_week == "R" ) {
emit current( QString::fromUtf8( "スキップ:[前週] " ) + kouza + QString::fromUtf8( " " ) + yyyymmdd );
} else {
emit current( QString::fromUtf8( "スキップ: " ) + kouza + QString::fromUtf8( " " ) + yyyymmdd );
}
return true;
}
if ( this_week == "R" ) {
emit current( QString::fromUtf8( "レコーディング中:[前週] " ) + kouza + QString::fromUtf8( " " ) + yyyymmdd );
} else {
emit current( QString::fromUtf8( "レコーディング中: " ) + kouza + QString::fromUtf8( " " ) + yyyymmdd );
}
Q_ASSERT( ffmpegHash.contains( extension ) );
QString dstPath;
#ifdef Q_OS_WIN
if ( true ) {
QTemporaryFile file;
if ( file.open() ) {
dstPath = file.fileName() + "." + extension1;
file.close();
} else {
emit critical( QString::fromUtf8( "一時ファイルの作成に失敗しました: " ) + kouza + QString::fromUtf8( " " ) + yyyymmdd );
return false;
}
}
#else
dstPath = outputDir + outFileName;
#endif
QString filem3u8a; QString filem3u8b; QString prefix1a = prefix1; QString prefix2a = prefix2; QString prefix3a = prefix3;
if ( dir == "" ) { prefix1a.remove("/mp4"); prefix2a.remove("/mp4"); prefix3a.remove("/mp4");
} else { prefix1a.replace( "mp4", dir ); prefix2a.replace( "mp4", dir ); prefix3a.replace( "mp4", dir ); };
// if ( file.right(4) != ".mp4" ) {
// filem3u8a = prefix1a + file + ".mp4/index.m3u8";
// filem3u8b = prefix2a + file + ".mp4/index.m3u8";
// } else {
// filem3u8a = prefix1a + file + "/index.m3u8";
// filem3u8b = prefix2a + file + "/index.m3u8";
// }
filem3u8a = prefix1a + file + "/index.m3u8";
filem3u8b = prefix2a + file + "/index.m3u8";
QString filem3u8c = prefix3a + file + "/index.m3u8";
QStringList arguments_v = { "-http_seekable", "0", "-version", "0" };
QProcess process_v;
process_v.setProgram( ffmpeg );
process_v.setArguments( arguments_v );
process_v.start();
process_v.waitForFinished();
QString str_v = process_v.readAllStandardError();
process_v.kill();
process_v.close();
QString arguments00 = "-y -http_seekable 0 -i";
if (str_v.contains( "Option not found" )) {
arguments00 = "-y -i";
}
QString id3tag_album = kouza;
if ( fileNameFormat.contains( "%x", Qt::CaseInsensitive) ) {
id3tag_album.remove( "まいにち" );
if ( kouza.contains( "レベル1", Qt::CaseInsensitive) ) id3tag_album = "L1_" + id3tag_album.remove( "【レベル1】" );
if ( kouza.contains( "レベル2", Qt::CaseInsensitive) ) id3tag_album = "L2_" + id3tag_album.remove( "【レベル2】" );
if ( kouza.contains( "入門", Qt::CaseInsensitive) ) id3tag_album = "入門_" + id3tag_album.remove( "【入門編】" );
if ( kouza.contains( "初級", Qt::CaseInsensitive) ) id3tag_album = "初級_" + id3tag_album.remove( "【初級編】" );
if ( kouza.contains( "中級", Qt::CaseInsensitive) ) id3tag_album = "中級_" + id3tag_album.remove( "【中級編】" );
if ( kouza.contains( "応用", Qt::CaseInsensitive) ) id3tag_album = "応用_" + id3tag_album.remove( "【応用編】" );
}
QStringList arguments0 = arguments00.split(' ', Qt::SkipEmptyParts);
QString arguments01 = "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 120";
QStringList arguments1 = arguments01.split(' ', Qt::SkipEmptyParts);
QStringList ffmpegArgs[] = {
arguments0 + ffmpegHash[extension].arg(filem3u8a, dstPath, id3tagTitle, id3tag_album, QString::number(year)).split(",", Qt::SkipEmptyParts),
arguments0 + ffmpegHash[extension].arg(filem3u8b, dstPath, id3tagTitle, id3tag_album, QString::number(year)).split(",", Qt::SkipEmptyParts),
arguments1 + arguments0 + ffmpegHash[extension].arg(filem3u8c, dstPath, id3tagTitle, id3tag_album, QString::number(year)).split(",", Qt::SkipEmptyParts)
};
QProcess processes[3];
bool success = false;
for (int i = 0; i < 3; ++i) {
if (runFfmpeg(processes[i], ffmpeg, ffmpegArgs[i], dstPath, kouza, yyyymmdd)) {
success = true;
break;
}
}
if (!success) {
emit critical(QString::fromUtf8("レコーディング失敗: %1 %2").arg(kouza, yyyymmdd));
QFile::remove(dstPath);
return false;
}
// QString tmp = outputDir + "tmp." + extension1;
QString tmp = outputDir + outBasename + "tmp." + extension1;
// if ((ui->checkBox_thumbnail->isChecked() || Utility::option_check("-a1")) &&
if ((runtime.flag( QString::fromUtf8( Constants::KEY_THUMBNAIL )) || Utility::option_check("-a1")) &&
extension1 != "aac" && !Utility::option_check("-a0")) {
thumbnail_add(dstPath, tmp, json_path);
}
#ifdef Q_OS_WIN
QFile::rename(dstPath, outputDir + outFileName);
#endif
return true;
}
bool DownloadThread::runFfmpeg(QProcess &process, const QString &ffmpeg, const QStringList &args, const QString &dstPath, const QString &kouza, const QString &yyyymmdd) {
process.setProgram(ffmpeg);
process.setArguments(args);
process.start();
if (!process.waitForStarted(-1)) {
emit critical(QString::fromUtf8("ffmpeg起動エラー(%3): %1 %2")
.arg(kouza, yyyymmdd, processError[process.error()]));
QFile::remove(dstPath);
return false;
}
while (!process.waitForFinished(CancelCheckTimeOut)) {
if (isCanceled) {
process.kill();
QFile::remove(dstPath);
return false;
}
if (process.error() == QProcess::Timedout)
continue;
emit critical(QString::fromUtf8("ffmpeg実行エラー(%3): %1 %2")
.arg(kouza, yyyymmdd, processError[process.error()]));
QFile::remove(dstPath);
return false;
}
QString err = process.readAllStandardError();
if (process.exitCode() || err.contains("HTTP error") || err.contains("Unable to open resource") || err.contains("parse_playlist error")) {
process.kill();
process.close();
return false;
}
return true;
}
bool DownloadThread::captureStream_json( QString kouza, QString hdate, QString file, QString nendo, QString title, QString dupnmb, QString json_path, bool nogui_flag ) {
QString titleFormat;
QString fileNameFormat;
CustomizeDialog::formats( "json", titleFormat, fileNameFormat );
// QString outputDir = MainWindow::outputDir;
// QString extension = ui->comboBox_extension->currentText();
QString outputDir = runtime.saveFolder();
QString extension = runtime.audioExtension();
QString Xml_koza = "";
Xml_koza = map.value( json_path );
// bool ouyou_koza_separation_flag = Xml_koza.contains( "kouza3", Qt::CaseInsensitive) && (fileNameFormat.contains( "%s", Qt::CaseInsensitive) || fileNameFormat.contains( "%x", Qt::CaseInsensitive) || MainWindow::koza_separation_flag || runtime.flag( QString::fromUtf8( Constants::KEY_KOZA_SEPARATION )) ) ;
// if (MainWindow::koza_separation_flag || runtime.flag( QString::fromUtf8( Constants::KEY_KOZA_SEPARATION )) ) fileNameFormat.remove( "%s" );
bool ouyou_koza_separation_flag = Xml_koza.contains( "kouza3", Qt::CaseInsensitive) && (fileNameFormat.contains( "%s", Qt::CaseInsensitive) || fileNameFormat.contains( "%x", Qt::CaseInsensitive) || runtime.flag( QString::fromUtf8( Constants::KEY_KOZA_SEPARATION )) ) ;
if (runtime.flag( QString::fromUtf8( Constants::KEY_KOZA_SEPARATION )) ) fileNameFormat.remove( "%s" );
if ( nogui_flag ) {
std::tie( titleFormat, fileNameFormat, outputDir, extension ) = Utility::nogui_option( titleFormat, fileNameFormat, outputDir, extension );
ouyou_koza_separation_flag = Xml_koza.contains( "kouza3", Qt::CaseInsensitive) && (fileNameFormat.contains( "%s", Qt::CaseInsensitive) || fileNameFormat.contains( "%x", Qt::CaseInsensitive) || Utility::option_check( "-s" ) || runtime.flag( QString::fromUtf8( Constants::KEY_KOZA_SEPARATION )) );
}
// QString id3tagTitle = title;
if ( ouyou_koza_separation_flag || runtime.flag( QString::fromUtf8( Constants::KEY_KOZA_SEPARATION )) ) {
// if( MainWindow::name_space_flag || runtime.flag( QString::fromUtf8( Constants::KEY_NAME_SPACE )) ) {
if( runtime.flag( QString::fromUtf8( Constants::KEY_NAME_SPACE )) ) {
if ( title.contains( "入門", Qt::CaseInsensitive) ) kouza = kouza + "【入門編】";
if ( title.contains( "初級", Qt::CaseInsensitive) ) kouza = kouza + "【初級編】";
if ( title.contains( "中級", Qt::CaseInsensitive) ) kouza = kouza + "【中級編】";
if ( title.contains( "応用", Qt::CaseInsensitive) ) kouza = kouza + "【応用編】";
} else {
if ( title.contains( "入門", Qt::CaseInsensitive) ) kouza = kouza + " 入門編";
if ( title.contains( "初級", Qt::CaseInsensitive) ) kouza = kouza + " 初級編";
if ( title.contains( "中級", Qt::CaseInsensitive) ) kouza = kouza + " 中級編";
if ( title.contains( "応用", Qt::CaseInsensitive) ) kouza = kouza + " 応用編";
}
}
QString id3tagTitle = formatName( titleFormat, kouza, hdate, title, nendo, dupnmb, false );
QString outFileName = formatName( fileNameFormat, kouza, hdate, title, nendo, dupnmb, true );