-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectoryListing.cpp
More file actions
1227 lines (1027 loc) · 37.6 KB
/
Copy pathDirectoryListing.cpp
File metadata and controls
1227 lines (1027 loc) · 37.6 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) 2001-2013 Jacek Sieka, arnetheduck on gmail point com
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "stdinc.h"
#include "Bundle.h"
#include "DirectoryListing.h"
#include "AutoSearchManager.h"
#include "QueueManager.h"
#include "ShareManager.h"
#include "StringTokenizer.h"
#include "SimpleXML.h"
#include "FilteredFile.h"
#include "BZUtils.h"
#include "ResourceManager.h"
#include "SimpleXMLReader.h"
#include "User.h"
#include "ADLSearch.h"
#include "DirectoryListingManager.h"
#include "ScopedFunctor.h"
namespace dcpp {
using boost::range::for_each;
using boost::range::find_if;
DirectoryListing::DirectoryListing(const HintedUser& aUser, bool aPartial, const string& aFileName, bool aIsClientView, bool aIsOwnList) :
hintedUser(aUser), abort(false), root(new Directory(nullptr, Util::emptyString, Directory::TYPE_INCOMPLETE_NOCHILD)), partialList(aPartial), isOwnList(aIsOwnList), fileName(aFileName),
isClientView(aIsClientView), curSearch(nullptr), lastResult(0), matchADL(SETTING(USE_ADLS) && !aPartial), typingFilter(false), waiting(false), maxResultCount(0), curResultCount(0)
{
running.clear();
ClientManager::getInstance()->addListener(this);
}
DirectoryListing::~DirectoryListing() {
ClientManager::getInstance()->removeListener(this);
delete root;
}
void DirectoryListing::sortDirs() {
root->sortDirs();
}
void DirectoryListing::Directory::sortDirs(bool recursive /*true*/) {
if (recursive) {
for(auto d: directories)
d->sortDirs();
}
sort(directories.begin(), directories.end(), Directory::DefaultSort());
}
void DirectoryListing::Directory::sortFiles() {
sort(files.begin(), files.end(), File::DefaultSort());
}
bool DirectoryListing::Directory::Sort::operator()(const Ptr& a, const Ptr& b) const {
return compare(a->getName(), b->getName()) < 0;
}
bool DirectoryListing::Directory::DefaultSort::operator()(const Ptr& a, const Ptr& b) const {
if (a->getAdls() && !b->getAdls())
return true;
if (!a->getAdls() && b->getAdls())
return false;
return Util::DefaultSort(Text::toT(a->getName()).c_str(), Text::toT(b->getName()).c_str()) < 0;
}
bool DirectoryListing::File::DefaultSort::operator()(const Ptr& a, const Ptr& b) const {
return Util::DefaultSort(Text::toT(a->getName()).c_str(), Text::toT(b->getName()).c_str()) < 0;
}
bool DirectoryListing::File::Sort::operator()(const Ptr& a, const Ptr& b) const {
return compare(a->getName(), b->getName()) < 0;
}
string DirectoryListing::getNick(bool firstOnly) const {
string ret;
if (!hintedUser.user->isOnline()) {
if (isOwnList) {
ret = SETTING(NICK);
} else if (!partialList) {
ret = DirectoryListing::getNickFromFilename(fileName);
}
}
if (ret.empty()) {
if (firstOnly) {
ret = ClientManager::getInstance()->getNick(hintedUser.user, hintedUser.hint, true);
} else {
ret = ClientManager::getInstance()->getFormatedNicks(hintedUser);
}
}
return ret;
}
void stripExtensions(string& name) {
if(stricmp(name.c_str() + name.length() - 4, ".bz2") == 0) {
name.erase(name.length() - 4);
}
if(stricmp(name.c_str() + name.length() - 4, ".xml") == 0) {
name.erase(name.length() - 4);
}
}
string DirectoryListing::getNickFromFilename(const string& fileName) {
// General file list name format: [username].[CID].[xml|xml.bz2]
string name = Util::getFileName(fileName);
// Strip off any extensions
stripExtensions(name);
// Find CID
string::size_type i = name.rfind('.');
if(i == string::npos) {
return STRING(UNKNOWN);
}
return name.substr(0, i);
}
UserPtr DirectoryListing::getUserFromFilename(const string& fileName) {
// General file list name format: [username].[CID].[xml|xml.bz2]
string name = Util::getFileName(fileName);
// Strip off any extensions
stripExtensions(name);
// Find CID
string::size_type i = name.rfind('.');
if(i == string::npos) {
return UserPtr();
}
size_t n = name.length() - (i + 1);
// CID's always 39 chars long...
if(n != 39)
return UserPtr();
CID cid(name.substr(i + 1));
if(cid.isZero())
return UserPtr();
return ClientManager::getInstance()->getUser(cid);
}
bool DirectoryListing::supportsASCH() const {
return !partialList || isOwnList || hintedUser.user->isSet(User::ASCH);
}
void DirectoryListing::loadFile() {
if (isOwnList) {
auto mis = ShareManager::getInstance()->generatePartialList("/", true, Util::toInt(fileName));
if (mis) {
loadXML(*mis, true);
} else {
throw Exception(CSTRING(FILE_NOT_AVAILABLE));
}
} else {
// For now, we detect type by ending...
string ext = Util::getFileExt(fileName);
dcpp::File ff(fileName, dcpp::File::READ, dcpp::File::OPEN);
if(stricmp(ext, ".bz2") == 0) {
FilteredInputStream<UnBZFilter, false> f(&ff);
loadXML(f, false);
} else if(stricmp(ext, ".xml") == 0) {
loadXML(ff, false);
}
}
}
class ListLoader : public SimpleXMLReader::CallBack {
public:
ListLoader(DirectoryListing* aList, DirectoryListing::Directory* root, const string& aBase, bool aUpdating, const UserPtr& aUser, bool aCheckDupe, bool aPartialList) :
list(aList), cur(root), base(aBase), inListing(false), updating(aUpdating), user(aUser), checkDupe(aCheckDupe), partialList(aPartialList), dirsLoaded(0) {
}
virtual ~ListLoader() { }
void startTag(const string& name, StringPairList& attribs, bool simple);
void endTag(const string& name);
//const string& getBase() const { return base; }
int getLoadedDirs() { return dirsLoaded; }
private:
DirectoryListing* list;
DirectoryListing::Directory* cur;
UserPtr user;
string baseLower;
string base;
bool inListing;
bool updating;
bool checkDupe;
bool partialList;
int dirsLoaded;
};
int DirectoryListing::updateXML(const string& xml, const string& aBase) {
MemoryInputStream mis(xml);
return loadXML(mis, true, aBase);
}
int DirectoryListing::loadXML(InputStream& is, bool updating, const string& aBase) {
ListLoader ll(this, root, aBase, updating, getUser(), !isOwnList && isClientView && SETTING(DUPES_IN_FILELIST), partialList);
try {
dcpp::SimpleXMLReader(&ll).parse(is);
} catch(SimpleXMLException& e) {
//Better to abort and show the error, than just leave it hanging.
LogManager::getInstance()->message("Error in Filelist loading: " + e.getError() + ". User: [ " +
getNick(false) + " ]", LogManager::LOG_ERROR);
//dcdebug("DirectoryListing loadxml error: %s", e.getError());
}
return ll.getLoadedDirs();
}
static const string sFileListing = "FileListing";
static const string sBase = "Base";
static const string sBaseDate = "BaseDate";
static const string sGenerator = "Generator";
static const string sDirectory = "Directory";
static const string sIncomplete = "Incomplete";
static const string sChildren = "Children";
static const string sFile = "File";
static const string sName = "Name";
static const string sSize = "Size";
static const string sTTH = "TTH";
static const string sDate = "Date";
void ListLoader::startTag(const string& name, StringPairList& attribs, bool simple) {
if(list->getAbort()) {
throw AbortException();
}
if(inListing) {
if(name == sFile) {
const string& n = getAttrib(attribs, sName, 0);
if(n.empty())
return;
const string& s = getAttrib(attribs, sSize, 1);
if(s.empty())
return;
auto size = Util::toInt64(s);
const string& h = getAttrib(attribs, sTTH, 2);
if(h.empty() && !SettingsManager::lanMode)
return;
TTHValue tth(h); /// @todo verify validity?
DirectoryListing::File* f = new DirectoryListing::File(cur, n, size, tth, checkDupe, Util::toUInt32(getAttrib(attribs, sDate, 3)));
cur->files.push_back(f);
} else if(name == sDirectory) {
const string& n = getAttrib(attribs, sName, 0);
if(n.empty()) {
throw SimpleXMLException("Directory missing name attribute");
}
bool incomp = getAttrib(attribs, sIncomplete, 1) == "1";
bool children = getAttrib(attribs, sChildren, 2) == "1";
const string& size = getAttrib(attribs, sSize, 2);
const string& date = getAttrib(attribs, sDate, 3);
DirectoryListing::Directory* d = nullptr;
if(updating) {
dirsLoaded++;
auto s = list->baseDirs.find(baseLower + Text::toLower(n) + '/');
if (s != list->baseDirs.end()) {
d = s->second.first;
}
}
if(!d) {
d = new DirectoryListing::Directory(cur, n, incomp ? (children ? DirectoryListing::Directory::TYPE_INCOMPLETE_CHILD : DirectoryListing::Directory::TYPE_INCOMPLETE_NOCHILD) :
DirectoryListing::Directory::TYPE_NORMAL, (partialList && checkDupe), size, Util::toUInt32(date));
cur->directories.push_back(d);
if (updating && !incomp)
list->baseDirs[baseLower + Text::toLower(n) + '/'] = make_pair(d, true); //recursive partial lists
} else {
if(!incomp) {
d->setComplete();
}
d->setDate(Util::toUInt32(date));
}
cur = d;
if (updating && cur->isComplete())
baseLower += Text::toLower(n) + '/';
if(simple) {
// To handle <Directory Name="..." />
endTag(name);
}
}
} else if(name == sFileListing) {
if (updating) {
const string& b = getAttrib(attribs, sBase, 2);
if(b.size() >= 1 && b[0] == '/' && b[b.size()-1] == '/') {
base = b;
if (b != base)
throw AbortException("The base directory specified in the file list (" + b + ") doesn't match with the excepted base (" + base + ")");
}
const string& date = getAttrib(attribs, sBaseDate, 3);
StringList sl = StringTokenizer<string>(base.substr(1), '/').getTokens();
for(auto& name: sl) {
auto s = find_if(cur->directories, [&name](DirectoryListing::Directory* dir) { return dir->getName() == name; });
if (s == cur->directories.end()) {
auto d = new DirectoryListing::Directory(cur, name, DirectoryListing::Directory::TYPE_INCOMPLETE_CHILD, true);
cur->directories.push_back(d);
list->baseDirs[Text::toLower(Util::toAdcFile(d->getPath()))] = make_pair(d, false);
cur = d;
} else {
cur = *s;
}
}
baseLower = Text::toLower(base);
auto& p = list->baseDirs[baseLower];
//set the dir as visited
p.second = true;
cur->setDate(Util::toUInt32(date));
}
//set the root complete only after we have finished loading (will prevent possible problems like the GUI counting the size for this folder)
inListing = true;
if(simple) {
// To handle <Directory Name="..." />
endTag(name);
}
}
}
void ListLoader::endTag(const string& name) {
if(inListing) {
if(name == sDirectory) {
if (updating && cur->isComplete())
baseLower = baseLower.substr(0, baseLower.length()-cur->getName().length()-1);
cur = cur->getParent();
} else if(name == sFileListing) {
// cur should be root now, set it complete
cur->setComplete();
inListing = false;
}
}
}
DirectoryListing::File::File(Directory* aDir, const string& aName, int64_t aSize, const TTHValue& aTTH, bool checkDupe, time_t aDate) noexcept :
name(aName), size(aSize), parent(aDir), tthRoot(aTTH), adls(false), dupe(DUPE_NONE), date(aDate) {
if (checkDupe && size > 0) {
dupe = SettingsManager::lanMode ? AirUtil::checkFileDupe(name, size) : AirUtil::checkFileDupe(tthRoot, name);
}
}
DirectoryListing::Directory::Directory(Directory* aParent, const string& aName, Directory::DirType aType, bool checkDupe, const string& aSize, time_t aDate /*0*/)
: name(aName), parent(aParent), type(aType), dupe(DUPE_NONE), partialSize(0), date(aDate), loading(false) {
if (!aSize.empty()) {
partialSize = Util::toInt64(aSize);
}
if (checkDupe) {
dupe = AirUtil::checkDirDupe(getPath(), partialSize);
}
}
void DirectoryListing::Directory::search(OrderedStringSet& aResults, AdcSearch& aStrings, StringList::size_type maxResults) {
if (getAdls())
return;
if (aStrings.hasRoot) {
auto pos = find_if(files, [aStrings](File* aFile) { return aFile->getTTH() == aStrings.root; });
if (pos != files.end()) {
aResults.insert(getPath());
}
} else {
if(aStrings.matchesDirectory(name)) {
auto path = parent ? parent->getPath() : Util::emptyString;
auto res = find(aResults, path);
if (res == aResults.end() && aStrings.matchesSize(getTotalSize(false))) {
aResults.insert(path);
}
}
if(aStrings.itemType != AdcSearch::TYPE_DIRECTORY) {
for(auto& f: files) {
if(aStrings.matchesFileLower(Text::toLower(f->getName()), f->getSize(), f->getDate())) {
aResults.insert(getPath());
break;
}
}
}
}
for(auto l = directories.begin(); (l != directories.end()) && (aResults.size() < maxResults); ++l) {
(*l)->search(aResults, aStrings, maxResults);
}
}
string DirectoryListing::getPath(const Directory* d) const {
if(d == root)
return Util::emptyString;
string dir;
dir.reserve(128);
dir.append(d->getName());
dir.append(1, '\\');
Directory* cur = d->getParent();
while(cur!=root) {
dir.insert(0, cur->getName() + '\\');
cur = cur->getParent();
}
return dir;
}
bool DirectoryListing::Directory::findIncomplete() {
/* Recursive check for incomplete dirs */
if(!isComplete()) {
return true;
}
return find_if(directories, [](Directory* dir) { return dir->findIncomplete(); }) != directories.end();
}
void DirectoryListing::Directory::download(const string& aTarget, BundleFileList& aFiles) {
// First, recurse over the directories
sort(directories.begin(), directories.end(), Directory::Sort());
for(auto d: directories) {
d->download(aTarget + d->getName() + PATH_SEPARATOR, aFiles);
}
// Then add the files
sort(files.begin(), files.end(), File::Sort());
for(auto& f: files) {
aFiles.emplace_back(aTarget + f->getName(), f->getTTH(), f->getSize());
}
}
bool DirectoryListing::createBundle(Directory* aDir, const string& aTarget, QueueItemBase::Priority prio, ProfileToken aAutoSearch) {
string target = aTarget;
if (aDir != root)
target += aDir->getName() + PATH_SEPARATOR;
BundleFileList aFiles;
aDir->download(Util::emptyString, aFiles);
if (aFiles.empty() || (SETTING(SKIP_ZERO_BYTE) && none_of(aFiles.begin(), aFiles.end(), [](const BundleFileInfo& aFile) { return aFile.size > 0; }))) {
fire(DirectoryListingListener::UpdateStatusMessage(), STRING(DIR_EMPTY) + " " + aDir->getName());
return false;
}
string errorMsg;
BundlePtr b = QueueManager::getInstance()->createDirectoryBundle(target, hintedUser, aFiles, prio, aDir->getDate(), errorMsg);
if (!errorMsg.empty()) {
if (aAutoSearch == 0) {
LogManager::getInstance()->message(STRING_F(ADD_BUNDLE_ERRORS_OCC, target % getNick(false) % errorMsg), LogManager::LOG_WARNING);
} else {
AutoSearchManager::getInstance()->onBundleError(aAutoSearch, errorMsg, target, hintedUser);
}
}
if (b) {
if (aAutoSearch > 0) {
AutoSearchManager::getInstance()->onBundleCreated(b, aAutoSearch);
}
return true;
}
return false;
}
bool DirectoryListing::downloadDir(Directory* aDir, const string& aTarget, TargetUtil::TargetType aTargetType, bool isSizeUnknown, QueueItemBase::Priority prio, ProfileToken aAutoSearch) {
//check if there are incomplete dirs in a partial list
if (partialList && aDir->findIncomplete()) {
if (isClientView) {
DirectoryListingManager::getInstance()->addDirectoryDownload(aDir->getPath(), hintedUser, aTarget, aTargetType, isSizeUnknown ? ASK_USER : NO_CHECK, prio);
} else {
//there shoudn't be incomplete dirs in recursive partial lists, most likely the other client doesn't support the RE flag
DirectoryListingManager::getInstance()->addDirectoryDownload(aDir->getPath(), hintedUser, aTarget, aTargetType, isSizeUnknown ? ASK_USER : NO_CHECK, prio, true);
}
return false;
}
/* Check if this is a root dir containing release dirs */
boost::regex reg;
reg.assign(AirUtil::getReleaseRegBasic());
if (!boost::regex_match(aDir->getName(), reg) && aDir->files.empty() && !aDir->directories.empty() &&
all_of(aDir->directories.begin(), aDir->directories.end(), [®](Directory* d) { return boost::regex_match(d->getName(), reg); })) {
/* Create bundles from each subfolder */
bool queued = false;
for(auto d: aDir->directories) {
if (createBundle(d, aTarget + aDir->getName() + PATH_SEPARATOR, prio, aAutoSearch))
queued = true;
}
return queued;
}
return createBundle(aDir, aTarget, prio, aAutoSearch);
}
bool DirectoryListing::downloadDir(const string& aDir, const string& aTarget, TargetUtil::TargetType aTargetType, bool highPrio, QueueItemBase::Priority prio, ProfileToken aAutoSearch) {
dcassert(aDir.size() > 2);
dcassert(aDir[aDir.size() - 1] == '\\'); // This should not be PATH_SEPARATOR
Directory* d = findDirectory(aDir, root);
if(d)
return downloadDir(d, aTarget, aTargetType, highPrio, prio, aAutoSearch);
return false;
}
int64_t DirectoryListing::getDirSize(const string& aDir) {
dcassert(aDir.size() > 2);
dcassert(aDir[aDir.size() - 1] == '\\'); // This should not be PATH_SEPARATOR
Directory* d = findDirectory(aDir, root);
if(d)
return d->getTotalSize(false);
return 0;
}
void DirectoryListing::openFile(File* aFile, bool isClientView) {
QueueManager::getInstance()->addOpenedItem(aFile->getName(), aFile->getSize(), aFile->getTTH(), hintedUser, isClientView);
}
DirectoryListing::Directory* DirectoryListing::findDirectory(const string& aName, const Directory* current) const {
if (aName.empty())
return root;
string::size_type end = aName.find('\\');
dcassert(end != string::npos);
string name = aName.substr(0, end);
auto i = find(current->directories.begin(), current->directories.end(), name);
if(i != current->directories.end()) {
if(end == (aName.size() - 1))
return *i;
else
return findDirectory(aName.substr(end + 1), *i);
}
return nullptr;
}
void DirectoryListing::Directory::findFiles(const boost::regex& aReg, File::List& aResults) const {
copy_if(files.begin(), files.end(), back_inserter(aResults), [&aReg](File* df) { return boost::regex_match(df->getName(), aReg); });
for(auto d: directories)
d->findFiles(aReg, aResults);
}
bool DirectoryListing::findNfo(const string& aPath) {
auto dir = findDirectory(aPath, root);
if (dir) {
boost::regex reg;
reg.assign("(.+\\.nfo)", boost::regex_constants::icase);
File::List results;
dir->findFiles(reg, results);
if (!results.empty()) {
try {
openFile(results.front(), true);
} catch(const Exception&) { }
return true;
}
}
if (isClientView)
fire(DirectoryListingListener::UpdateStatusMessage(), CSTRING(NO_NFO_FOUND));
else
LogManager::getInstance()->message(getNick(false) + ": " + STRING(NO_NFO_FOUND), LogManager::LOG_INFO);
return false;
}
struct HashContained {
HashContained(const DirectoryListing::Directory::TTHSet& l) : tl(l) { }
const DirectoryListing::Directory::TTHSet& tl;
bool operator()(const DirectoryListing::File::Ptr i) const {
return tl.count((i->getTTH())) && (DeleteFunction()(i), true);
}
private:
HashContained& operator=(HashContained&);
};
struct DirectoryEmpty {
bool operator()(const DirectoryListing::Directory::Ptr i) const {
bool r = i->getFileCount() + i->directories.size() == 0;
if (r) DeleteFunction()(i);
return r;
}
};
struct SizeLess {
bool operator()(const DirectoryListing::File::Ptr f) const {
return f->getSize() < (SETTING(SKIP_SUBTRACT) *1024);
}
};
DirectoryListing::Directory::~Directory() {
for_each(directories, DeleteFunction());
for_each(files, DeleteFunction());
}
void DirectoryListing::Directory::clearAll() {
for_each(directories, DeleteFunction());
for_each(files, DeleteFunction());
directories.clear();
files.clear();
}
void DirectoryListing::Directory::filterList(DirectoryListing& dirList) {
DirectoryListing::Directory* d = dirList.getRoot();
TTHSet l;
d->getHashList(l);
filterList(l);
}
void DirectoryListing::Directory::filterList(DirectoryListing::Directory::TTHSet& l) {
for(auto d: directories)
d->filterList(l);
directories.erase(remove_if(directories.begin(), directories.end(), DirectoryEmpty()), directories.end());
files.erase(remove_if(files.begin(), files.end(), HashContained(l)), files.end());
if((SETTING(SKIP_SUBTRACT) > 0) && (files.size() < 2)) { //setting for only skip if folder filecount under x ?
files.erase(remove_if(files.begin(), files.end(), SizeLess()), files.end());
}
}
void DirectoryListing::Directory::getHashList(DirectoryListing::Directory::TTHSet& l) {
for(auto d: directories)
d->getHashList(l);
for(auto d: files)
l.insert(d->getTTH());
}
void DirectoryListing::getLocalPaths(const File* f, StringList& ret) {
if(f->getParent()->getAdls() && (f->getParent()->getParent() == root || !isOwnList))
return;
string path;
if (f->getParent()->getAdls())
path = ((AdlDirectory*)f->getParent())->getFullPath();
else
path = getPath(f->getParent());
ShareManager::getInstance()->getRealPaths(Util::toAdcFile(path + f->getName()), ret, Util::toInt(fileName));
}
void DirectoryListing::getLocalPaths(const Directory* d, StringList& ret) {
if(d->getAdls() && (d->getParent() == root || !isOwnList))
return;
string path;
if (d->getAdls())
path = ((AdlDirectory*)d)->getFullPath();
else
path = getPath(d);
ShareManager::getInstance()->getRealPaths(Util::toAdcFile(path), ret, Util::toInt(fileName));
}
int64_t DirectoryListing::Directory::getTotalSize(bool countAdls) {
if(!isComplete())
return partialSize;
if(!countAdls && getAdls())
return 0;
int64_t x = getFilesSize();
for(auto d: directories) {
if(!countAdls && d->getAdls())
continue;
x += d->getTotalSize(getAdls());
}
return x;
}
size_t DirectoryListing::Directory::getTotalFileCount(bool countAdls) {
if(!countAdls && getAdls())
return 0;
size_t x = getFileCount();
for(auto d: directories) {
if(!countAdls && d->getAdls())
continue;
x += d->getTotalFileCount(getAdls());
}
return x;
}
void DirectoryListing::Directory::clearAdls() {
for(auto i = directories.begin(); i != directories.end();) {
if((*i)->getAdls()) {
delete *i;
i = directories.erase(i);
} else {
++i;
}
}
}
string DirectoryListing::Directory::getPath() const {
string tmp;
//make sure to not try and get the name of the root dir
if(getParent() && getParent()->getParent()){
return getParent()->getPath() + getName() + '\\';
}
return getName() + '\\';
}
int64_t DirectoryListing::Directory::getFilesSize() const {
int64_t x = 0;
for(auto f: files) {
x += f->getSize();
}
return x;
}
uint8_t DirectoryListing::Directory::checkShareDupes() {
uint8_t result = DUPE_NONE;
bool first = true;
for(auto d: directories) {
result = d->checkShareDupes();
if(dupe == DUPE_NONE && first)
setDupe((DupeType)result);
//full dupe with same type for non-dupe dir, change to partial (or pass partial dupes to upper level folder)
else if((result == SHARE_DUPE || result == PARTIAL_SHARE_DUPE) && (dupe == DUPE_NONE || dupe == SHARE_DUPE) && !first)
setDupe(PARTIAL_SHARE_DUPE);
else if((result == QUEUE_DUPE || result == PARTIAL_QUEUE_DUPE) && (dupe == DUPE_NONE || dupe == QUEUE_DUPE) && !first)
setDupe(PARTIAL_QUEUE_DUPE);
//change to mixed dupe type
else if((getDupe() == SHARE_DUPE || dupe == PARTIAL_SHARE_DUPE) && (result == QUEUE_DUPE || result == PARTIAL_QUEUE_DUPE))
setDupe(SHARE_QUEUE_DUPE);
else if((getDupe() == QUEUE_DUPE || dupe == PARTIAL_QUEUE_DUPE) && (result == SHARE_DUPE || result == PARTIAL_SHARE_DUPE))
setDupe(SHARE_QUEUE_DUPE);
else if (result == SHARE_QUEUE_DUPE)
setDupe(SHARE_QUEUE_DUPE);
first = false;
}
first = true;
for(auto f: files) {
//don't count 0 byte files since it'll give lots of partial dupes
//of no interest
if(f->getSize() > 0) {
//if it's the first file in the dir and no sub-folders exist mark it as a dupe.
if(getDupe() == DUPE_NONE && f->getDupe() == SHARE_DUPE && directories.empty() && first)
setDupe(SHARE_DUPE);
else if(getDupe() == DUPE_NONE && f->isQueued() && directories.empty() && first)
setDupe(QUEUE_DUPE);
//if it's the first file in the dir and we do have sub-folders but no dupes, mark as partial.
else if(getDupe() == DUPE_NONE && f->getDupe() == SHARE_DUPE && !directories.empty() && first)
setDupe(PARTIAL_SHARE_DUPE);
else if(getDupe() == DUPE_NONE && f->isQueued() && !directories.empty() && first)
setDupe(PARTIAL_QUEUE_DUPE);
//if it's not the first file in the dir and we still don't have a dupe, mark it as partial.
else if(getDupe() == DUPE_NONE && f->getDupe() == SHARE_DUPE && !first)
setDupe(PARTIAL_SHARE_DUPE);
else if(getDupe() == DUPE_NONE && f->isQueued() && !first)
setDupe(PARTIAL_QUEUE_DUPE);
//if it's a dupe and we find a non-dupe, mark as partial.
else if(getDupe() == SHARE_DUPE && f->getDupe() != SHARE_DUPE)
setDupe(PARTIAL_SHARE_DUPE);
else if(getDupe() == QUEUE_DUPE && !f->isQueued())
setDupe(PARTIAL_QUEUE_DUPE);
//if we find different type of dupe, change to mixed
else if((getDupe() == SHARE_DUPE || getDupe() == PARTIAL_SHARE_DUPE) && f->isQueued())
setDupe(SHARE_QUEUE_DUPE);
else if((getDupe() == QUEUE_DUPE || getDupe() == PARTIAL_QUEUE_DUPE) && f->getDupe() == SHARE_DUPE)
setDupe(SHARE_QUEUE_DUPE);
first = false;
}
}
return getDupe();
}
void DirectoryListing::checkShareDupes() {
root->checkShareDupes();
root->setDupe(DUPE_NONE); //never show the root as a dupe or partial dupe.
}
void DirectoryListing::addMatchADLTask() {
tasks.addUnique(MATCH_ADL, nullptr);
runTasks();
}
struct ListDiffTask : public Task {
ListDiffTask(const string& aName, bool aOwnList) : name(aName),
ownList(aOwnList) { }
string name;
bool ownList;
};
void DirectoryListing::addListDiffTask(const string& aFile, bool aOwnList) {
tasks.add(LISTDIFF, unique_ptr<Task>(new ListDiffTask(aFile, aOwnList)));
runTasks();
}
struct PartialLoadingTask : public Task {
PartialLoadingTask(const string& aXml, const string& aBaseDir, std::function<void ()> aF) : f(aF), xml(aXml), baseDir(aBaseDir) { }
string xml;
string baseDir;
std::function<void ()> f;
};
void DirectoryListing::addPartialListTask(const string& aXml, const string& aBase, std::function<void ()> f) {
tasks.add(REFRESH_DIR, unique_ptr<Task>(new PartialLoadingTask(aXml, Util::toAdcFile(aBase), f)));
runTasks();
}
void DirectoryListing::addFullListTask(const string& aDir) {
tasks.addUnique(LOAD_FILE, unique_ptr<Task>(new StringTask(aDir)));
runTasks();
}
void DirectoryListing::addQueueMatchTask() {
tasks.addUnique(MATCH_QUEUE, nullptr);
runTasks();
}
void DirectoryListing::close() {
tasks.add(CLOSE, nullptr);
runTasks();
}
struct SearchTask : public Task {
SearchTask(const string& aSearchString, int64_t aSize, int aTypeMode, int aSizeMode, const StringList& aExtList, const string& aDir) : searchString(aSearchString),
size(aSize), typeMode(aTypeMode), sizeMode(aSizeMode), extList(aExtList), directory(aDir) { }
string searchString;
int64_t size;
int typeMode;
int sizeMode;
StringList extList;
string directory;
};
void DirectoryListing::addSearchTask(const string& aSearchString, int64_t aSize, int aTypeMode, int aSizeMode, const StringList& aExtList, const string& aDir) {
tasks.add(SEARCH, unique_ptr<Task>(new SearchTask(aSearchString, aSize, aTypeMode, aSizeMode, aExtList, aDir)));
runTasks();
}
struct DirDownloadTask : public Task {
DirDownloadTask(DirectoryListing::Directory* aDir, const string& aTarget, TargetUtil::TargetType aTargetType, bool aIsSizeUnknown, QueueItemBase::Priority aPrio) : dir(aDir),
target(aTarget), targetType(aTargetType), isSizeUnknown(aIsSizeUnknown), prio(aPrio) { }
DirectoryListing::Directory* dir;
QueueItemBase::Priority prio;
bool isSizeUnknown;
TargetUtil::TargetType targetType;
string target;
};
void DirectoryListing::addDirDownloadTask(Directory* aDir, const string& aTarget, TargetUtil::TargetType aTargetType, bool isSizeUnknown, QueueItemBase::Priority prio) {
tasks.add(DIR_DOWNLOAD, unique_ptr<Task>(new DirDownloadTask(aDir, aTarget, aTargetType, isSizeUnknown, prio)));
runTasks();
}
void DirectoryListing::addFilterTask() {
if (tasks.addUnique(FILTER, nullptr))
runTasks();
else
typingFilter = true;
}
void DirectoryListing::runTasks() {
if (!running.test_and_set()) {
join();
try {
start();
} catch(const ThreadException& /*e*/) {
LogManager::getInstance()->message("DirListThread error", LogManager::LOG_WARNING);
running.clear();
}
}
}
int DirectoryListing::run() {
for (;;) {
TaskQueue::TaskPair t;
if (!tasks.getFront(t))
break;
ScopedFunctor([this] { tasks.pop_front(); });
auto waitFinished = [this] {
while (waiting)
sleep(50);
};
try {
int64_t start = GET_TICK();
if (t.first == LISTDIFF) {
if (isOwnList && partialList) {
auto mis = ShareManager::getInstance()->generatePartialList("/", true, Util::toInt(fileName));
if (mis) {
loadXML(*mis, true);
partialList = false;
} else {
throw CSTRING(FILE_NOT_AVAILABLE);
}
}
auto ldt = static_cast<ListDiffTask*>(t.second);
DirectoryListing dirList(hintedUser, false, ldt->name, false, ldt->ownList);
dirList.loadFile();
root->filterList(dirList);
fire(DirectoryListingListener::LoadingFinished(), start, Util::emptyString, false, true, false);
} else if(t.first == MATCH_ADL) {
root->clearAdls(); //not much to check even if its the first time loaded without adls...
ADLSearchManager::getInstance()->matchListing(*this);
fire(DirectoryListingListener::LoadingFinished(), start, Util::emptyString, false, true, false);
} else if(t.first == FILTER) {
for(;;) {
typingFilter = false;
sleep(500);
if (!typingFilter)
break;
}
fire(DirectoryListingListener::Filter());
}else if(t.first == LOAD_FILE) {
partialList = false;
waiting = true;
fire(DirectoryListingListener::LoadingStarted(), false);
bool reloading = !root->directories.empty();
if (reloading) {
//wait for the gui to disable the window
waitFinished();
root->clearAll();
baseDirs.clear();
}
loadFile();
if(matchADL) {
fire(DirectoryListingListener::UpdateStatusMessage(), CSTRING(MATCHING_ADL));
ADLSearchManager::getInstance()->matchListing(*this);
}
fire(DirectoryListingListener::LoadingFinished(), start, static_cast<StringTask*>(t.second)->str, reloading, true, false);
reloading = false;
} else if (t.first == REFRESH_DIR) {
if (!partialList)
continue;
auto lt = static_cast<PartialLoadingTask*>(t.second);
bool reloading = false;
auto bd = baseDirs.find(Text::toLower(lt->baseDir));
if (bd != baseDirs.end()) {
reloading = bd->second.second;
if (reloading) {
waiting = true;
fire(DirectoryListingListener::LoadingStarted(), false);
//wait for the gui to disable the window
waitFinished();