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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
|
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* 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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "threads/SystemClock.h"
#include "MusicInfoScanner.h"
#include "music/tags/MusicInfoTagLoaderFactory.h"
#include "MusicAlbumInfo.h"
#include "MusicInfoScraper.h"
#include "filesystem/MusicDatabaseDirectory.h"
#include "filesystem/MusicDatabaseDirectory/DirectoryNode.h"
#include "Util.h"
#include "utils/md5.h"
#include "GUIInfoManager.h"
#include "utils/Variant.h"
#include "NfoFile.h"
#include "music/tags/MusicInfoTag.h"
#include "guilib/GUIWindowManager.h"
#include "dialogs/GUIDialogExtendedProgressBar.h"
#include "dialogs/GUIDialogProgress.h"
#include "dialogs/GUIDialogSelect.h"
#include "guilib/GUIKeyboardFactory.h"
#include "filesystem/File.h"
#include "filesystem/Directory.h"
#include "settings/AdvancedSettings.h"
#include "settings/Settings.h"
#include "FileItem.h"
#include "guilib/LocalizeStrings.h"
#include "utils/StringUtils.h"
#include "utils/TimeUtils.h"
#include "utils/log.h"
#include "utils/URIUtils.h"
#include "TextureCache.h"
#include "music/MusicThumbLoader.h"
#include "interfaces/AnnouncementManager.h"
#include "GUIUserMessages.h"
#include "addons/AddonManager.h"
#include "addons/Scraper.h"
#include <algorithm>
using namespace std;
using namespace MUSIC_INFO;
using namespace XFILE;
using namespace MUSICDATABASEDIRECTORY;
using namespace MUSIC_GRABBER;
using namespace ADDON;
CMusicInfoScanner::CMusicInfoScanner() : CThread("MusicInfoScanner"), m_fileCountReader(this, "MusicFileCounter")
{
m_bRunning = false;
m_showDialog = false;
m_handle = NULL;
m_bCanInterrupt = false;
m_currentItem=0;
m_itemCount=0;
m_flags = 0;
}
CMusicInfoScanner::~CMusicInfoScanner()
{
}
void CMusicInfoScanner::Process()
{
ANNOUNCEMENT::CAnnouncementManager::Get().Announce(ANNOUNCEMENT::AudioLibrary, "xbmc", "OnScanStarted");
try
{
if (m_bClean)
{
CleanDatabase(false);
m_bRunning = false;
return;
}
unsigned int tick = XbmcThreads::SystemClockMillis();
m_musicDatabase.Open();
if (m_showDialog && !CSettings::Get().GetBool("musiclibrary.backgroundupdate"))
{
CGUIDialogExtendedProgressBar* dialog =
(CGUIDialogExtendedProgressBar*)g_windowManager.GetWindow(WINDOW_DIALOG_EXT_PROGRESS);
if (dialog)
m_handle = dialog->GetHandle(g_localizeStrings.Get(314));
}
m_bClean = g_advancedSettings.m_bMusicLibraryCleanOnUpdate;
m_bCanInterrupt = true;
if (m_scanType == 0) // load info from files
{
CLog::Log(LOGDEBUG, "%s - Starting scan", __FUNCTION__);
if (m_handle)
m_handle->SetTitle(g_localizeStrings.Get(505));
// Reset progress vars
m_currentItem=0;
m_itemCount=-1;
// Create the thread to count all files to be scanned
SetPriority( GetMinPriority() );
if (m_handle)
m_fileCountReader.Create();
// Database operations should not be canceled
// using Interupt() while scanning as it could
// result in unexpected behaviour.
m_bCanInterrupt = false;
m_needsCleanup = false;
bool commit = true;
for (std::set<std::string>::const_iterator it = m_pathsToScan.begin(); it != m_pathsToScan.end(); it++)
{
if (!CDirectory::Exists(*it) && !m_bClean)
{
/*
* Note that this will skip scanning (if m_bClean is disabled) if the directory really
* doesn't exist. Since the music scanner is fed with a list of existing paths from the DB
* and cleans out all songs under that path as its first step before re-adding files, if
* the entire source is offline we totally empty the music database in one go.
*/
CLog::Log(LOGWARNING, "%s directory '%s' does not exist - skipping scan.", __FUNCTION__, it->c_str());
m_seenPaths.insert(*it);
continue;
}
else if (!DoScan(*it))
{
commit = false;
break;
}
}
if (commit)
{
g_infoManager.ResetLibraryBools();
if (m_needsCleanup)
{
if (m_handle)
{
m_handle->SetTitle(g_localizeStrings.Get(700));
m_handle->SetText("");
}
m_musicDatabase.CleanupOrphanedItems();
if (m_handle)
m_handle->SetTitle(g_localizeStrings.Get(331));
m_musicDatabase.Compress(false);
}
}
m_fileCountReader.StopThread();
m_musicDatabase.EmptyCache();
tick = XbmcThreads::SystemClockMillis() - tick;
CLog::Log(LOGNOTICE, "My Music: Scanning for music info using worker thread, operation took %s", StringUtils::SecondsToTimeString(tick / 1000).c_str());
}
if (m_scanType == 1) // load album info
{
for (std::set<std::string>::const_iterator it = m_pathsToScan.begin(); it != m_pathsToScan.end(); ++it)
{
CQueryParams params;
CDirectoryNode::GetDatabaseInfo(*it, params);
if (m_musicDatabase.HasAlbumBeenScraped(params.GetAlbumId())) // should this be here?
continue;
CAlbum album;
m_musicDatabase.GetAlbum(params.GetAlbumId(), album);
if (m_handle)
{
float percentage = (float) std::distance(it, m_pathsToScan.end()) / m_pathsToScan.size();
m_handle->SetText((CStdString)StringUtils::Join(album.artist, g_advancedSettings.m_musicItemSeparator) + " - " + album.strAlbum);
m_handle->SetPercentage(percentage);
}
// find album info
ADDON::ScraperPtr scraper;
if (!m_musicDatabase.GetScraperForPath(*it, scraper, ADDON::ADDON_SCRAPER_ALBUMS))
continue;
UpdateDatabaseAlbumInfo(album, scraper, false);
if (m_bStop)
break;
}
}
if (m_scanType == 2) // load artist info
{
for (std::set<std::string>::const_iterator it = m_pathsToScan.begin(); it != m_pathsToScan.end(); ++it)
{
CQueryParams params;
CDirectoryNode::GetDatabaseInfo(*it, params);
if (m_musicDatabase.HasArtistBeenScraped(params.GetArtistId())) // should this be here?
continue;
CArtist artist;
m_musicDatabase.GetArtist(params.GetArtistId(), artist);
m_musicDatabase.GetArtistPath(params.GetArtistId(), artist.strPath);
if (m_handle)
{
float percentage = (float) (std::distance(m_pathsToScan.begin(), it) / m_pathsToScan.size()) * 100;
m_handle->SetText(artist.strArtist);
m_handle->SetPercentage(percentage);
}
// find album info
ADDON::ScraperPtr scraper;
if (!m_musicDatabase.GetScraperForPath(*it, scraper, ADDON::ADDON_SCRAPER_ARTISTS) || !scraper)
continue;
UpdateDatabaseArtistInfo(artist, scraper, false);
if (m_bStop)
break;
}
}
}
catch (...)
{
CLog::Log(LOGERROR, "MusicInfoScanner: Exception while scanning.");
}
m_musicDatabase.Close();
CLog::Log(LOGDEBUG, "%s - Finished scan", __FUNCTION__);
m_bRunning = false;
ANNOUNCEMENT::CAnnouncementManager::Get().Announce(ANNOUNCEMENT::AudioLibrary, "xbmc", "OnScanFinished");
// we need to clear the musicdb cache and update any active lists
CUtil::DeleteMusicDatabaseDirectoryCache();
CGUIMessage msg(GUI_MSG_SCAN_FINISHED, 0, 0, 0);
g_windowManager.SendThreadMessage(msg);
if (m_handle)
m_handle->MarkFinished();
m_handle = NULL;
}
void CMusicInfoScanner::Start(const CStdString& strDirectory, int flags)
{
m_fileCountReader.StopThread();
StopThread();
m_pathsToScan.clear();
m_seenPaths.clear();
m_flags = flags;
if (strDirectory.empty())
{ // scan all paths in the database. We do this by scanning all paths in the db, and crossing them off the list as
// we go.
m_musicDatabase.Open();
m_musicDatabase.GetPaths(m_pathsToScan);
m_musicDatabase.Close();
}
else
m_pathsToScan.insert(strDirectory);
m_bClean = false;
m_scanType = 0;
Create();
m_bRunning = true;
}
void CMusicInfoScanner::StartCleanDatabase()
{
m_fileCountReader.StopThread();
StopThread();
m_pathsToScan.clear();
m_seenPaths.clear();
m_flags = SCAN_BACKGROUND;
m_bClean = true;
m_scanType = 0;
Create();
m_bRunning = true;
}
void CMusicInfoScanner::FetchAlbumInfo(const CStdString& strDirectory,
bool refresh)
{
m_fileCountReader.StopThread();
StopThread();
m_pathsToScan.clear();
CFileItemList items;
if (strDirectory.empty())
{
m_musicDatabase.Open();
m_musicDatabase.GetAlbumsNav("musicdb://albums/", items);
m_musicDatabase.Close();
}
else
{
if (URIUtils::HasSlashAtEnd(strDirectory)) // directory
CDirectory::GetDirectory(strDirectory,items);
else
{
CFileItemPtr item(new CFileItem(strDirectory,false));
items.Add(item);
}
}
m_musicDatabase.Open();
for (int i=0;i<items.Size();++i)
{
if (CMusicDatabaseDirectory::IsAllItem(items[i]->GetPath()) || items[i]->IsParentFolder())
continue;
m_pathsToScan.insert(items[i]->GetPath());
if (refresh)
{
m_musicDatabase.ClearAlbumLastScrapedTime(items[i]->GetMusicInfoTag()->GetDatabaseId());
}
}
m_musicDatabase.Close();
m_scanType = 1;
Create();
m_bRunning = true;
}
void CMusicInfoScanner::FetchArtistInfo(const CStdString& strDirectory,
bool refresh)
{
m_fileCountReader.StopThread();
StopThread();
m_pathsToScan.clear();
CFileItemList items;
if (strDirectory.empty())
{
m_musicDatabase.Open();
m_musicDatabase.GetArtistsNav("musicdb://artists/", items, false, -1);
m_musicDatabase.Close();
}
else
{
if (URIUtils::HasSlashAtEnd(strDirectory)) // directory
CDirectory::GetDirectory(strDirectory,items);
else
{
CFileItemPtr newItem(new CFileItem(strDirectory,false));
items.Add(newItem);
}
}
m_musicDatabase.Open();
for (int i=0;i<items.Size();++i)
{
if (CMusicDatabaseDirectory::IsAllItem(items[i]->GetPath()) || items[i]->IsParentFolder())
continue;
m_pathsToScan.insert(items[i]->GetPath());
if (refresh)
{
m_musicDatabase.ClearArtistLastScrapedTime(items[i]->GetMusicInfoTag()->GetDatabaseId());
}
}
m_musicDatabase.Close();
m_scanType = 2;
Create();
m_bRunning = true;
}
bool CMusicInfoScanner::IsScanning()
{
return m_bRunning;
}
void CMusicInfoScanner::Stop()
{
if (m_bCanInterrupt)
m_musicDatabase.Interupt();
StopThread(false);
}
void CMusicInfoScanner::CleanDatabase(bool showProgress /* = true */)
{
CMusicDatabase musicdatabase;
if (!musicdatabase.Open())
return;
musicdatabase.Cleanup(showProgress);
musicdatabase.Close();
CUtil::DeleteMusicDatabaseDirectoryCache();
}
static void OnDirectoryScanned(const CStdString& strDirectory)
{
CGUIMessage msg(GUI_MSG_DIRECTORY_SCANNED, 0, 0, 0);
msg.SetStringParam(strDirectory);
g_windowManager.SendThreadMessage(msg);
}
static CStdString Prettify(const CStdString& strDirectory)
{
CURL url(strDirectory);
return CURL::Decode(url.GetWithoutUserDetails());
}
bool CMusicInfoScanner::DoScan(const CStdString& strDirectory)
{
if (m_handle)
m_handle->SetText(Prettify(strDirectory));
std::set<std::string>::const_iterator it = m_seenPaths.find(strDirectory);
if (it != m_seenPaths.end())
return true;
m_seenPaths.insert(strDirectory);
// Discard all excluded files defined by m_musicExcludeRegExps
vector<string> regexps = g_advancedSettings.m_audioExcludeFromScanRegExps;
if (CUtil::ExcludeFileOrFolder(strDirectory, regexps))
return true;
// load subfolder
CFileItemList items;
CDirectory::GetDirectory(strDirectory, items, g_advancedSettings.m_musicExtensions + "|.jpg|.tbn|.lrc|.cdg");
// sort and get the path hash. Note that we don't filter .cue sheet items here as we want
// to detect changes in the .cue sheet as well. The .cue sheet items only need filtering
// if we have a changed hash.
items.Sort(SortByLabel, SortOrderAscending);
CStdString hash;
GetPathHash(items, hash);
// check whether we need to rescan or not
CStdString dbHash;
if ((m_flags & SCAN_RESCAN) || !m_musicDatabase.GetPathHash(strDirectory, dbHash) || dbHash != hash)
{ // path has changed - rescan
if (dbHash.empty())
CLog::Log(LOGDEBUG, "%s Scanning dir '%s' as not in the database", __FUNCTION__, strDirectory.c_str());
else
CLog::Log(LOGDEBUG, "%s Rescanning dir '%s' due to change", __FUNCTION__, strDirectory.c_str());
// filter items in the sub dir (for .cue sheet support)
items.FilterCueItems();
items.Sort(SortByLabel, SortOrderAscending);
// and then scan in the new information
if (RetrieveMusicInfo(strDirectory, items) > 0)
{
if (m_handle)
OnDirectoryScanned(strDirectory);
}
// save information about this folder
m_musicDatabase.SetPathHash(strDirectory, hash);
}
else
{ // path is the same - no need to rescan
CLog::Log(LOGDEBUG, "%s Skipping dir '%s' due to no change", __FUNCTION__, strDirectory.c_str());
m_currentItem += CountFiles(items, false); // false for non-recursive
// updated the dialog with our progress
if (m_handle)
{
if (m_itemCount>0)
m_handle->SetPercentage(m_currentItem/(float)m_itemCount*100);
OnDirectoryScanned(strDirectory);
}
}
// now scan the subfolders
for (int i = 0; i < items.Size(); ++i)
{
CFileItemPtr pItem = items[i];
if (m_bStop)
break;
// if we have a directory item (non-playlist) we then recurse into that folder
if (pItem->m_bIsFolder && !pItem->IsParentFolder() && !pItem->IsPlayList())
{
CStdString strPath=pItem->GetPath();
if (!DoScan(strPath))
{
m_bStop = true;
}
}
}
return !m_bStop;
}
INFO_RET CMusicInfoScanner::ScanTags(const CFileItemList& items, CFileItemList& scannedItems)
{
vector<string> regexps = g_advancedSettings.m_audioExcludeFromScanRegExps;
for (int i = 0; i < items.Size(); ++i)
{
if (m_bStop)
return INFO_CANCELLED;
CFileItemPtr pItem = items[i];
if (CUtil::ExcludeFileOrFolder(pItem->GetPath(), regexps))
continue;
if (pItem->m_bIsFolder || pItem->IsPlayList() || pItem->IsPicture() || pItem->IsLyrics())
continue;
m_currentItem++;
CMusicInfoTag& tag = *pItem->GetMusicInfoTag();
if (!tag.Loaded())
{
auto_ptr<IMusicInfoTagLoader> pLoader (CMusicInfoTagLoaderFactory::CreateLoader(pItem->GetPath()));
if (NULL != pLoader.get())
pLoader->Load(pItem->GetPath(), tag);
}
if (m_handle && m_itemCount>0)
m_handle->SetPercentage(m_currentItem/(float)m_itemCount*100);
if (!tag.Loaded())
{
CLog::Log(LOGDEBUG, "%s - No tag found for: %s", __FUNCTION__, pItem->GetPath().c_str());
continue;
}
scannedItems.Add(pItem);
}
return INFO_ADDED;
}
static bool SortSongsByTrack(const CSong& song, const CSong& song2)
{
return song.iTrack < song2.iTrack;
}
void CMusicInfoScanner::FileItemsToAlbums(CFileItemList& items, VECALBUMS& albums, MAPSONGS* songsMap /* = NULL */)
{
/*
* Step 1: Convert the FileItems into Songs.
* If they're MB tagged, create albums directly from the FileItems.
* If they're non-MB tagged, index them by album name ready for step 2.
*/
map<string, VECSONGS> songsByAlbumNames;
for (int i = 0; i < items.Size(); ++i)
{
CMusicInfoTag& tag = *items[i]->GetMusicInfoTag();
CSong song(*items[i]);
// keep the db-only fields intact on rescan...
if (songsMap != NULL)
{
MAPSONGS::iterator it = songsMap->find(items[i]->GetPath());
if (it != songsMap->end())
{
song.iTimesPlayed = it->second.iTimesPlayed;
song.lastPlayed = it->second.lastPlayed;
song.iKaraokeNumber = it->second.iKaraokeNumber;
if (song.rating == '0') song.rating = it->second.rating;
if (song.strThumb.empty()) song.strThumb = it->second.strThumb;
}
}
if (!tag.GetMusicBrainzAlbumID().empty())
{
VECALBUMS::iterator it;
for (it = albums.begin(); it != albums.end(); ++it)
if (it->strMusicBrainzAlbumID.Equals(tag.GetMusicBrainzAlbumID()))
break;
if (it == albums.end())
{
CAlbum album(*items[i]);
album.songs.push_back(song);
albums.push_back(album);
}
else
it->songs.push_back(song);
}
else
songsByAlbumNames[tag.GetAlbum()].push_back(song);
}
/*
Step 2: Split into unique albums based on album name and album artist
In the case where the album artist is unknown, we use the primary artist
(i.e. first artist from each song).
*/
for (map<string, VECSONGS>::iterator songsByAlbumName = songsByAlbumNames.begin(); songsByAlbumName != songsByAlbumNames.end(); ++songsByAlbumName)
{
VECSONGS &songs = songsByAlbumName->second;
// sort the songs by tracknumber to identify duplicate track numbers
sort(songs.begin(), songs.end(), SortSongsByTrack);
// map the songs to their primary artists
bool tracksOverlap = false;
bool hasAlbumArtist = false;
bool isCompilation = true;
map<string, vector<CSong *> > artists;
for (VECSONGS::iterator song = songs.begin(); song != songs.end(); ++song)
{
// test for song overlap
if (song != songs.begin() && song->iTrack == (song - 1)->iTrack)
tracksOverlap = true;
if (!song->bCompilation)
isCompilation = false;
// get primary artist
string primary;
if (!song->albumArtist.empty())
{
primary = song->albumArtist[0];
hasAlbumArtist = true;
}
else if (!song->artist.empty())
primary = song->artist[0];
// add to the artist map
artists[primary].push_back(&(*song));
}
/*
We have a compilation if
1. album name is non-empty AND
2a. no tracks overlap OR
2b. all tracks are marked as part of compilation AND
3a. a unique primary artist is specified as "various" or "various artists" OR
3b. we have at least two primary artists and no album artist specified.
*/
bool compilation = !songsByAlbumName->first.empty() && (isCompilation || !tracksOverlap); // 1+2b+2a
if (artists.size() == 1)
{
string artist = artists.begin()->first; StringUtils::ToLower(artist);
if (!StringUtils::EqualsNoCase(artist, "various") &&
!StringUtils::EqualsNoCase(artist, "various artists")) // 3a
compilation = false;
}
else if (hasAlbumArtist) // 3b
compilation = false;
if (compilation)
{
CLog::Log(LOGDEBUG, "Album '%s' is a compilation as there's no overlapping tracks and %s", songsByAlbumName->first.c_str(), hasAlbumArtist ? "the album artist is 'Various'" : "there is more than one unique artist");
artists.clear();
std::string various = g_localizeStrings.Get(340); // Various Artists
vector<string> va; va.push_back(various);
for (VECSONGS::iterator song = songs.begin(); song != songs.end(); ++song)
{
song->albumArtist = va;
artists[various].push_back(&(*song));
}
}
/*
Step 3: Find the common albumartist for each song and assign
albumartist to those tracks that don't have it set.
*/
for (map<string, vector<CSong *> >::iterator j = artists.begin(); j != artists.end(); ++j)
{
// find the common artist for these songs
vector<CSong *> &artistSongs = j->second;
vector<string> common = artistSongs.front()->albumArtist.empty() ? artistSongs.front()->artist : artistSongs.front()->albumArtist;
for (vector<CSong *>::iterator k = artistSongs.begin() + 1; k != artistSongs.end(); ++k)
{
unsigned int match = 0;
vector<string> &compare = (*k)->albumArtist.empty() ? (*k)->artist : (*k)->albumArtist;
for (; match < common.size() && match < compare.size(); match++)
{
if (compare[match] != common[match])
break;
}
common.erase(common.begin() + match, common.end());
}
/*
Step 4: Assign the album artist for each song that doesn't have it set
and add to the album vector
*/
CAlbum album;
album.strAlbum = songsByAlbumName->first;
album.artist = common;
for (vector<string>::iterator it = common.begin(); it != common.end(); ++it)
{
CStdString strJoinPhrase = (it == --common.end() ? "" : g_advancedSettings.m_musicItemSeparator);
CArtistCredit artistCredit(*it, strJoinPhrase);
album.artistCredits.push_back(artistCredit);
}
album.bCompilation = compilation;
for (vector<CSong *>::iterator k = artistSongs.begin(); k != artistSongs.end(); ++k)
{
if ((*k)->albumArtist.empty())
(*k)->albumArtist = common;
// TODO: in future we may wish to union up the genres, for now we assume they're the same
album.genre = (*k)->genre;
// in addition, we may want to use year as discriminating for albums
album.iYear = (*k)->iYear;
album.songs.push_back(**k);
}
albums.push_back(album);
}
}
}
int CMusicInfoScanner::RetrieveMusicInfo(const CStdString& strDirectory, CFileItemList& items)
{
MAPSONGS songsMap;
// get all information for all files in current directory from database, and remove them
if (m_musicDatabase.RemoveSongsFromPath(strDirectory, songsMap))
m_needsCleanup = true;
CFileItemList scannedItems;
if (ScanTags(items, scannedItems) == INFO_CANCELLED || scannedItems.Size() == 0)
return 0;
VECALBUMS albums;
FileItemsToAlbums(scannedItems, albums, &songsMap);
FindArtForAlbums(albums, items.GetPath());
int numAdded = 0;
ADDON::AddonPtr addon;
ADDON::ScraperPtr albumScraper;
ADDON::ScraperPtr artistScraper;
if(ADDON::CAddonMgr::Get().GetDefault(ADDON::ADDON_SCRAPER_ALBUMS, addon))
albumScraper = boost::dynamic_pointer_cast<ADDON::CScraper>(addon);
if(ADDON::CAddonMgr::Get().GetDefault(ADDON::ADDON_SCRAPER_ARTISTS, addon))
artistScraper = boost::dynamic_pointer_cast<ADDON::CScraper>(addon);
// Add each album
for (VECALBUMS::iterator album = albums.begin(); album != albums.end(); ++album)
{
if (m_bStop)
break;
album->strPath = strDirectory;
m_musicDatabase.AddAlbum(*album);
// Yuk - this is a kludgy way to do what we want to do, but it will work to sort
// out artist fanart until we can restructure the artist fanart to work more
// like the album fanart. This has to be done after we've added the album so
// we have the artist IDs to update, but before we call UpdateDatabaseArtistInfo.
if (albums.size() == 1 &&
album->artistCredits.size() > 0 &&
!StringUtils::EqualsNoCase(album->artistCredits[0].GetArtist(), "various artists") &&
!StringUtils::EqualsNoCase(album->artistCredits[0].GetArtist(), "various"))
{
CArtist artist;
if (m_musicDatabase.GetArtist(album->artistCredits[0].GetArtistId(), artist))
{
artist.strPath = URIUtils::GetParentPath(strDirectory);
m_musicDatabase.SetArtForItem(artist.idArtist, MediaTypeArtist, GetArtistArtwork(artist));
}
}
if ((m_flags & SCAN_ONLINE))
{
if (!albumScraper || !artistScraper)
continue;
INFO_RET albumScrapeStatus = INFO_NOT_FOUND;
if (!m_musicDatabase.HasAlbumBeenScraped(album->idAlbum))
albumScrapeStatus = UpdateDatabaseAlbumInfo(*album, albumScraper, false);
if (albumScrapeStatus == INFO_ADDED)
{
for (VECARTISTCREDITS::const_iterator artistCredit = album->artistCredits.begin();
artistCredit != album->artistCredits.end();
++artistCredit)
{
if (m_bStop)
break;
if (!m_musicDatabase.HasArtistBeenScraped(artistCredit->GetArtistId()))
{
CArtist artist;
m_musicDatabase.GetArtist(artistCredit->GetArtistId(), artist);
UpdateDatabaseArtistInfo(artist, artistScraper, false);
}
}
for (VECSONGS::iterator song = album->songs.begin();
song != album->songs.end();
song++)
{
if (m_bStop)
break;
for (VECARTISTCREDITS::const_iterator artistCredit = song->artistCredits.begin();
artistCredit != song->artistCredits.end();
++artistCredit)
{
if (m_bStop)
break;
CMusicArtistInfo musicArtistInfo;
if (!m_musicDatabase.HasArtistBeenScraped(artistCredit->GetArtistId()))
{
CArtist artist;
m_musicDatabase.GetArtist(artistCredit->GetArtistId(), artist);
UpdateDatabaseArtistInfo(artist, artistScraper, false);
}
}
}
}
}
numAdded += album->songs.size();
}
if (m_handle)
m_handle->SetTitle(g_localizeStrings.Get(505));
return numAdded;
}
void CMusicInfoScanner::FindArtForAlbums(VECALBUMS &albums, const CStdString &path)
{
/*
If there's a single album in the folder, then art can be taken from
the folder art.
*/
std::string albumArt;
if (albums.size() == 1)
{
CFileItem album(path, true);
albumArt = album.GetUserMusicThumb(true);
if (!albumArt.empty())
albums[0].art["thumb"] = albumArt;
}
for (VECALBUMS::iterator i = albums.begin(); i != albums.end(); ++i)
{
CAlbum &album = *i;
if (albums.size() != 1)
albumArt = "";
/*
Find art that is common across these items
If we find a single art image we treat it as the album art
and discard song art else we use first as album art and
keep everything as song art.
*/
bool singleArt = true;
CSong *art = NULL;
for (VECSONGS::iterator k = album.songs.begin(); k != album.songs.end(); ++k)
{
CSong &song = *k;
if (song.HasArt())
{
if (art && !art->ArtMatches(song))
{
singleArt = false;
break;
}
if (!art)
art = &song;
}
}
/*
assign the first art found to the album - better than no art at all
*/
if (art && albumArt.empty())
{
if (!art->strThumb.empty())
albumArt = art->strThumb;
else
albumArt = CTextureUtils::GetWrappedImageURL(art->strFileName, "music");
}
if (!albumArt.empty())
album.art["thumb"] = albumArt;
if (singleArt)
{ //if singleArt then we can clear the artwork for all songs
for (VECSONGS::iterator k = album.songs.begin(); k != album.songs.end(); ++k)
k->strThumb.clear();
}
else
{ // more than one piece of art was found for these songs, so cache per song
for (VECSONGS::iterator k = album.songs.begin(); k != album.songs.end(); ++k)
{
if (k->strThumb.empty() && !k->embeddedArt.empty())
k->strThumb = CTextureUtils::GetWrappedImageURL(k->strFileName, "music");
}
}
}
if (albums.size() == 1 && !albumArt.empty())
{
// assign to folder thumb as well
CFileItem albumItem(path, true);
CMusicThumbLoader loader;
loader.SetCachedImage(albumItem, "thumb", albumArt);
}
}
int CMusicInfoScanner::GetPathHash(const CFileItemList &items, CStdString &hash)
{
// Create a hash based on the filenames, filesize and filedate. Also count the number of files
if (0 == items.Size()) return 0;
XBMC::XBMC_MD5 md5state;
int count = 0;
for (int i = 0; i < items.Size(); ++i)
{
const CFileItemPtr pItem = items[i];
md5state.append(pItem->GetPath());
md5state.append((unsigned char *)&pItem->m_dwSize, sizeof(pItem->m_dwSize));
FILETIME time = pItem->m_dateTime;
md5state.append((unsigned char *)&time, sizeof(FILETIME));
if (pItem->IsAudio() && !pItem->IsPlayList() && !pItem->IsNFO())
count++;
}
hash = md5state.getDigest();
return count;
}
INFO_RET CMusicInfoScanner::UpdateDatabaseAlbumInfo(CAlbum& album, const ADDON::ScraperPtr& scraper, bool bAllowSelection, CGUIDialogProgress* pDialog /* = NULL */)
{
if (!scraper)
return INFO_ERROR;
CMusicAlbumInfo albumInfo;
loop:
CLog::Log(LOGDEBUG, "%s downloading info for: %s", __FUNCTION__, album.strAlbum.c_str());
INFO_RET albumDownloadStatus = DownloadAlbumInfo(album, scraper, albumInfo, pDialog);
if (albumDownloadStatus == INFO_NOT_FOUND)
{
if (pDialog && bAllowSelection)
{
if (!CGUIKeyboardFactory::ShowAndGetInput(album.strAlbum, g_localizeStrings.Get(16011), false))
return INFO_CANCELLED;
CStdString strTempArtist(StringUtils::Join(album.artist, g_advancedSettings.m_musicItemSeparator));
if (!CGUIKeyboardFactory::ShowAndGetInput(strTempArtist, g_localizeStrings.Get(16025), false))
return INFO_CANCELLED;
album.artist = StringUtils::Split(strTempArtist, g_advancedSettings.m_musicItemSeparator);
goto loop;
}
}
else if (albumDownloadStatus == INFO_ADDED)
{
album.MergeScrapedAlbum(albumInfo.GetAlbum(), CSettings::Get().GetBool("musiclibrary.overridetags"));
m_musicDatabase.Open();
m_musicDatabase.UpdateAlbum(album);
GetAlbumArtwork(album.idAlbum, album);
m_musicDatabase.Close();
albumInfo.SetLoaded(true);
}
return albumDownloadStatus;
}
INFO_RET CMusicInfoScanner::UpdateDatabaseArtistInfo(CArtist& artist, const ADDON::ScraperPtr& scraper, bool bAllowSelection, CGUIDialogProgress* pDialog /* = NULL */)
{
if (!scraper)
return INFO_ERROR;
CMusicArtistInfo artistInfo;
loop:
CLog::Log(LOGDEBUG, "%s downloading info for: %s", __FUNCTION__, artist.strArtist.c_str());
INFO_RET artistDownloadStatus = DownloadArtistInfo(artist, scraper, artistInfo, pDialog);
if (artistDownloadStatus == INFO_NOT_FOUND)
{
if (pDialog && bAllowSelection)
{
if (!CGUIKeyboardFactory::ShowAndGetInput(artist.strArtist, g_localizeStrings.Get(16025), false))
return INFO_CANCELLED;
goto loop;
}
}
else if (artistDownloadStatus == INFO_ADDED)
{
artist.MergeScrapedArtist(artistInfo.GetArtist(), CSettings::Get().GetBool("musiclibrary.overridetags"));
m_musicDatabase.Open();
m_musicDatabase.UpdateArtist(artist);
m_musicDatabase.GetArtistPath(artist.idArtist, artist.strPath);
m_musicDatabase.SetArtForItem(artist.idArtist, MediaTypeArtist, GetArtistArtwork(artist));
m_musicDatabase.Close();
artistInfo.SetLoaded();
}
return artistDownloadStatus;
}
#define THRESHOLD .95f
INFO_RET CMusicInfoScanner::DownloadAlbumInfo(const CAlbum& album, const ADDON::ScraperPtr& info, CMusicAlbumInfo& albumInfo, CGUIDialogProgress* pDialog)
{
if (m_handle)
{
m_handle->SetTitle(StringUtils::Format(g_localizeStrings.Get(20321).c_str(), info->Name().c_str()));
m_handle->SetText((CStdString)StringUtils::Join(album.artist, g_advancedSettings.m_musicItemSeparator) + " - " + album.strAlbum);
}
// clear our scraper cache
info->ClearCache();
CMusicInfoScraper scraper(info);
bool bMusicBrainz = false;
if (!album.strMusicBrainzAlbumID.empty())
{
CScraperUrl musicBrainzURL;
if (ResolveMusicBrainz(album.strMusicBrainzAlbumID, info, musicBrainzURL))
{
CMusicAlbumInfo albumNfo("nfo", musicBrainzURL);
scraper.GetAlbums().clear();
scraper.GetAlbums().push_back(albumNfo);
bMusicBrainz = true;
}
}
// handle nfo files
CStdString path = album.strPath;
if (path.empty())
m_musicDatabase.GetAlbumPath(album.idAlbum, path);
CStdString strNfo = URIUtils::AddFileToFolder(path, "album.nfo");
CNfoFile::NFOResult result = CNfoFile::NO_NFO;
CNfoFile nfoReader;
if (XFILE::CFile::Exists(strNfo))
{
CLog::Log(LOGDEBUG,"Found matching nfo file: %s", strNfo.c_str());
result = nfoReader.Create(strNfo, info);
if (result == CNfoFile::FULL_NFO)
{
CLog::Log(LOGDEBUG, "%s Got details from nfo", __FUNCTION__);
nfoReader.GetDetails(albumInfo.GetAlbum());
return INFO_ADDED;
}
else if (result == CNfoFile::URL_NFO || result == CNfoFile::COMBINED_NFO)
{
CScraperUrl scrUrl(nfoReader.ScraperUrl());
CMusicAlbumInfo albumNfo("nfo",scrUrl);
ADDON::ScraperPtr nfoReaderScraper = nfoReader.GetScraperInfo();
CLog::Log(LOGDEBUG,"-- nfo-scraper: %s", nfoReaderScraper->Name().c_str());
CLog::Log(LOGDEBUG,"-- nfo url: %s", scrUrl.m_url[0].m_url.c_str());
scraper.SetScraperInfo(nfoReaderScraper);
scraper.GetAlbums().clear();
scraper.GetAlbums().push_back(albumNfo);
}
else
CLog::Log(LOGERROR,"Unable to find an url in nfo file: %s", strNfo.c_str());
}
if (!scraper.CheckValidOrFallback(CSettings::Get().GetString("musiclibrary.albumsscraper")))
{ // the current scraper is invalid, as is the default - bail
CLog::Log(LOGERROR, "%s - current and default scrapers are invalid. Pick another one", __FUNCTION__);
return INFO_ERROR;
}
if (!scraper.GetAlbumCount())
{
scraper.FindAlbumInfo(album.strAlbum, StringUtils::Join(album.artist, g_advancedSettings.m_musicItemSeparator));
while (!scraper.Completed())
{
if (m_bStop)
{
scraper.Cancel();
return INFO_CANCELLED;
}
Sleep(1);
}
}
CGUIDialogSelect *pDlg = NULL;
int iSelectedAlbum=0;
if (result == CNfoFile::NO_NFO && !bMusicBrainz)
{
iSelectedAlbum = -1; // set negative so that we can detect a failure
if (scraper.Succeeded() && scraper.GetAlbumCount() >= 1)
{
double bestRelevance = 0;
double minRelevance = THRESHOLD;
if (scraper.GetAlbumCount() > 1) // score the matches
{
//show dialog with all albums found
if (pDialog)
{
pDlg = (CGUIDialogSelect*)g_windowManager.GetWindow(WINDOW_DIALOG_SELECT);
pDlg->SetHeading(g_localizeStrings.Get(181).c_str());
pDlg->Reset();
pDlg->EnableButton(true, 413); // manual
}
for (int i = 0; i < scraper.GetAlbumCount(); ++i)
{
CMusicAlbumInfo& info = scraper.GetAlbum(i);
double relevance = info.GetRelevance();
if (relevance < 0)
relevance = CUtil::AlbumRelevance(info.GetAlbum().strAlbum, album.strAlbum, StringUtils::Join(info.GetAlbum().artist, g_advancedSettings.m_musicItemSeparator), StringUtils::Join(album.artist, g_advancedSettings.m_musicItemSeparator));
// if we're doing auto-selection (ie querying all albums at once, then allow 95->100% for perfect matches)
// otherwise, perfect matches only
if (relevance >= max(minRelevance, bestRelevance))
{ // we auto-select the best of these
bestRelevance = relevance;
iSelectedAlbum = i;
}
if (pDialog)
{
// set the label to [relevance] album - artist
CStdString strTemp = StringUtils::Format("[%0.2f] %s", relevance, info.GetTitle2().c_str());
CFileItem item(strTemp);
item.m_idepth = i; // use this to hold the index of the album in the scraper
pDlg->Add(&item);
}
if (relevance > .99f) // we're so close, no reason to search further
break;
}
if (pDialog && bestRelevance < THRESHOLD)
{
pDlg->Sort(false);
pDlg->DoModal();
// and wait till user selects one
if (pDlg->GetSelectedLabel() < 0)
{ // none chosen
if (!pDlg->IsButtonPressed())
return INFO_CANCELLED;
// manual button pressed
CStdString strNewAlbum = album.strAlbum;
if (!CGUIKeyboardFactory::ShowAndGetInput(strNewAlbum, g_localizeStrings.Get(16011), false)) return INFO_CANCELLED;
if (strNewAlbum == "") return INFO_CANCELLED;
CStdString strNewArtist = StringUtils::Join(album.artist, g_advancedSettings.m_musicItemSeparator);
if (!CGUIKeyboardFactory::ShowAndGetInput(strNewArtist, g_localizeStrings.Get(16025), false)) return INFO_CANCELLED;
pDialog->SetLine(0, strNewAlbum);
pDialog->SetLine(1, strNewArtist);
pDialog->Progress();
CAlbum newAlbum = album;
newAlbum.strAlbum = strNewAlbum;
newAlbum.artist = StringUtils::Split(strNewArtist, g_advancedSettings.m_musicItemSeparator);
return DownloadAlbumInfo(newAlbum, info, albumInfo, pDialog);
}
iSelectedAlbum = pDlg->GetSelectedItem()->m_idepth;
}
}
else
{
CMusicAlbumInfo& info = scraper.GetAlbum(0);
double relevance = info.GetRelevance();
if (relevance < 0)
relevance = CUtil::AlbumRelevance(info.GetAlbum().strAlbum,
album.strAlbum,
StringUtils::Join(info.GetAlbum().artist, g_advancedSettings.m_musicItemSeparator),
StringUtils::Join(album.artist, g_advancedSettings.m_musicItemSeparator));
if (relevance < THRESHOLD)
return INFO_NOT_FOUND;
iSelectedAlbum = 0;
}
}
if (iSelectedAlbum < 0)
return INFO_NOT_FOUND;
}
scraper.LoadAlbumInfo(iSelectedAlbum);
while (!scraper.Completed())
{
if (m_bStop)
{
scraper.Cancel();
return INFO_CANCELLED;
}
Sleep(1);
}
if (!scraper.Succeeded())
return INFO_ERROR;
albumInfo = scraper.GetAlbum(iSelectedAlbum);
if (result == CNfoFile::COMBINED_NFO)
nfoReader.GetDetails(albumInfo.GetAlbum(), NULL, true);
return INFO_ADDED;
}
void CMusicInfoScanner::GetAlbumArtwork(long id, const CAlbum &album)
{
if (album.thumbURL.m_url.size())
{
if (m_musicDatabase.GetArtForItem(id, MediaTypeAlbum, "thumb").empty())
{
string thumb = CScraperUrl::GetThumbURL(album.thumbURL.GetFirstThumb());
if (!thumb.empty())
{
CTextureCache::Get().BackgroundCacheImage(thumb);
m_musicDatabase.SetArtForItem(id, MediaTypeAlbum, "thumb", thumb);
}
}
}
}
INFO_RET CMusicInfoScanner::DownloadArtistInfo(const CArtist& artist, const ADDON::ScraperPtr& info, MUSIC_GRABBER::CMusicArtistInfo& artistInfo, CGUIDialogProgress* pDialog)
{
if (m_handle)
{
m_handle->SetTitle(StringUtils::Format(g_localizeStrings.Get(20320).c_str(), info->Name().c_str()));
m_handle->SetText(artist.strArtist);
}
// clear our scraper cache
info->ClearCache();
CMusicInfoScraper scraper(info);
bool bMusicBrainz = false;
if (!artist.strMusicBrainzArtistID.empty())
{
CScraperUrl musicBrainzURL;
if (ResolveMusicBrainz(artist.strMusicBrainzArtistID, info, musicBrainzURL))
{
CMusicArtistInfo artistNfo("nfo", musicBrainzURL);
scraper.GetArtists().clear();
scraper.GetArtists().push_back(artistNfo);
bMusicBrainz = true;
}
}
// handle nfo files
CStdString path = artist.strPath;
if (path.empty())
m_musicDatabase.GetArtistPath(artist.idArtist, path);
CStdString strNfo = URIUtils::AddFileToFolder(path, "artist.nfo");
CNfoFile::NFOResult result=CNfoFile::NO_NFO;
CNfoFile nfoReader;
if (XFILE::CFile::Exists(strNfo))
{
CLog::Log(LOGDEBUG,"Found matching nfo file: %s", strNfo.c_str());
result = nfoReader.Create(strNfo, info);
if (result == CNfoFile::FULL_NFO)
{
CLog::Log(LOGDEBUG, "%s Got details from nfo", __FUNCTION__);
nfoReader.GetDetails(artistInfo.GetArtist());
return INFO_ADDED;
}
else if (result == CNfoFile::URL_NFO || result == CNfoFile::COMBINED_NFO)
{
CScraperUrl scrUrl(nfoReader.ScraperUrl());
CMusicArtistInfo artistNfo("nfo",scrUrl);
ADDON::ScraperPtr nfoReaderScraper = nfoReader.GetScraperInfo();
CLog::Log(LOGDEBUG,"-- nfo-scraper: %s",nfoReaderScraper->Name().c_str());
CLog::Log(LOGDEBUG,"-- nfo url: %s", scrUrl.m_url[0].m_url.c_str());
scraper.SetScraperInfo(nfoReaderScraper);
scraper.GetArtists().push_back(artistNfo);
}
else
CLog::Log(LOGERROR,"Unable to find an url in nfo file: %s", strNfo.c_str());
}
if (!scraper.GetArtistCount())
{
scraper.FindArtistInfo(artist.strArtist);
while (!scraper.Completed())
{
if (m_bStop)
{
scraper.Cancel();
return INFO_CANCELLED;
}
Sleep(1);
}
}
int iSelectedArtist = 0;
if (result == CNfoFile::NO_NFO && !bMusicBrainz)
{
if (scraper.GetArtistCount() >= 1)
{
// now load the first match
if (pDialog && scraper.GetArtistCount() > 1)
{
// if we found more then 1 album, let user choose one
CGUIDialogSelect *pDlg = (CGUIDialogSelect*)g_windowManager.GetWindow(WINDOW_DIALOG_SELECT);
if (pDlg)
{
pDlg->SetHeading(g_localizeStrings.Get(21890));
pDlg->Reset();
pDlg->EnableButton(true, 413); // manual
for (int i = 0; i < scraper.GetArtistCount(); ++i)
{
// set the label to artist
CFileItem item(scraper.GetArtist(i).GetArtist());
CStdString strTemp=scraper.GetArtist(i).GetArtist().strArtist;
if (!scraper.GetArtist(i).GetArtist().strBorn.empty())
strTemp += " ("+scraper.GetArtist(i).GetArtist().strBorn+")";
if (!scraper.GetArtist(i).GetArtist().genre.empty())
{
CStdString genres = StringUtils::Join(scraper.GetArtist(i).GetArtist().genre, g_advancedSettings.m_musicItemSeparator);
if (!genres.empty())
strTemp = StringUtils::Format("[%s] %s", genres.c_str(), strTemp.c_str());
}
item.SetLabel(strTemp);
item.m_idepth = i; // use this to hold the index of the album in the scraper
pDlg->Add(&item);
}
pDlg->DoModal();
// and wait till user selects one
if (pDlg->GetSelectedLabel() < 0)
{ // none chosen
if (!pDlg->IsButtonPressed())
return INFO_CANCELLED;
// manual button pressed
CStdString strNewArtist = artist.strArtist;
if (!CGUIKeyboardFactory::ShowAndGetInput(strNewArtist, g_localizeStrings.Get(16025), false)) return INFO_CANCELLED;
if (pDialog)
{
pDialog->SetLine(0, strNewArtist);
pDialog->Progress();
}
CArtist newArtist;
newArtist.strArtist = strNewArtist;
return DownloadArtistInfo(newArtist, info, artistInfo, pDialog);
}
iSelectedArtist = pDlg->GetSelectedItem()->m_idepth;
}
}
}
else
return INFO_NOT_FOUND;
}
scraper.LoadArtistInfo(iSelectedArtist, artist.strArtist);
while (!scraper.Completed())
{
if (m_bStop)
{
scraper.Cancel();
return INFO_CANCELLED;
}
Sleep(1);
}
if (!scraper.Succeeded())
return INFO_ERROR;
artistInfo = scraper.GetArtist(iSelectedArtist);
if (result == CNfoFile::COMBINED_NFO)
nfoReader.GetDetails(artistInfo.GetArtist(), NULL, true);
return INFO_ADDED;
}
bool CMusicInfoScanner::ResolveMusicBrainz(const CStdString &strMusicBrainzID, const ScraperPtr &preferredScraper, CScraperUrl &musicBrainzURL)
{
// We have a MusicBrainz ID
// Get a scraper that can resolve it to a MusicBrainz URL & force our
// search directly to the specific album.
bool bMusicBrainz = false;
try
{
musicBrainzURL = preferredScraper->ResolveIDToUrl(strMusicBrainzID);
}
catch (const ADDON::CScraperError &sce)
{
if (sce.FAborted())
return false;
}
if (!musicBrainzURL.m_url.empty())
{
Sleep(2000); // MusicBrainz rate-limits queries to 1 p.s - once we hit the rate-limiter
// they start serving up the 'you hit the rate-limiter' page fast - meaning
// we will never get below the rate-limit threshold again in a specific run.
// This helps us to avoidthe rate-limiter as far as possible.
CLog::Log(LOGDEBUG,"-- nfo-scraper: %s",preferredScraper->Name().c_str());
CLog::Log(LOGDEBUG,"-- nfo url: %s", musicBrainzURL.m_url[0].m_url.c_str());
bMusicBrainz = true;
}
return bMusicBrainz;
}
map<string, string> CMusicInfoScanner::GetArtistArtwork(const CArtist& artist)
{
map<string, string> artwork;
// check thumb
CStdString strFolder;
CStdString thumb;
if (!artist.strPath.empty())
{
strFolder = artist.strPath;
for (int i = 0; i < 3 && thumb.empty(); ++i)
{
CFileItem item(strFolder, true);
thumb = item.GetUserMusicThumb(true);
strFolder = URIUtils::GetParentPath(strFolder);
}
}
if (thumb.empty())
thumb = CScraperUrl::GetThumbURL(artist.thumbURL.GetFirstThumb());
if (!thumb.empty())
{
CTextureCache::Get().BackgroundCacheImage(thumb);
artwork.insert(make_pair("thumb", thumb));
}
// check fanart
CStdString fanart;
if (!artist.strPath.empty())
{
strFolder = artist.strPath;
for (int i = 0; i < 3 && fanart.empty(); ++i)
{
CFileItem item(strFolder, true);
fanart = item.GetLocalFanart();
strFolder = URIUtils::GetParentPath(strFolder);
}
}
if (fanart.empty())
fanart = artist.fanart.GetImageURL();
if (!fanart.empty())
{
CTextureCache::Get().BackgroundCacheImage(fanart);
artwork.insert(make_pair("fanart", fanart));
}
return artwork;
}
// This function is the Run() function of the IRunnable
// CFileCountReader and runs in a separate thread.
void CMusicInfoScanner::Run()
{
int count = 0;
for (set<std::string>::iterator it = m_pathsToScan.begin(); it != m_pathsToScan.end() && !m_bStop; ++it)
{
count+=CountFilesRecursively(*it);
}
m_itemCount = count;
}
// Recurse through all folders we scan and count files
int CMusicInfoScanner::CountFilesRecursively(const CStdString& strPath)
{
// load subfolder
CFileItemList items;
CDirectory::GetDirectory(strPath, items, g_advancedSettings.m_musicExtensions, DIR_FLAG_NO_FILE_DIRS);
if (m_bStop)
return 0;
// true for recursive counting
int count = CountFiles(items, true);
return count;
}
int CMusicInfoScanner::CountFiles(const CFileItemList &items, bool recursive)
{
int count = 0;
for (int i=0; i<items.Size(); ++i)
{
const CFileItemPtr pItem=items[i];
if (recursive && pItem->m_bIsFolder)
count+=CountFilesRecursively(pItem->GetPath());
else if (pItem->IsAudio() && !pItem->IsPlayList() && !pItem->IsNFO())
count++;
}
return count;
}
|