RequestGroup.cc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "RequestGroup.h"
  36. #include "DownloadEngine.h"
  37. #include "DefaultSegmentManFactory.h"
  38. #include "NullProgressInfoFile.h"
  39. #include "SegmentManFactory.h"
  40. #include "Dependency.h"
  41. #include "prefs.h"
  42. #include "InitiateConnectionCommandFactory.h"
  43. #include "CUIDCounter.h"
  44. #include "File.h"
  45. #include "message.h"
  46. #include "Util.h"
  47. #include "BtRegistry.h"
  48. #include "LogFactory.h"
  49. #include "DiskAdaptor.h"
  50. #include "DiskWriterFactory.h"
  51. #include "RecoverableException.h"
  52. #include "StreamCheckIntegrityEntry.h"
  53. #include "CheckIntegrityCommand.h"
  54. #include "UnknownLengthPieceStorage.h"
  55. #include "SingleFileDownloadContext.h"
  56. #include "DlAbortEx.h"
  57. #include "DownloadFailureException.h"
  58. #include "RequestGroupMan.h"
  59. #include "DefaultBtProgressInfoFile.h"
  60. #include "DefaultPieceStorage.h"
  61. #include "DownloadResult.h"
  62. #include "DownloadHandlerFactory.h"
  63. #include "MemoryBufferPreDownloadHandler.h"
  64. #include "DownloadHandlerConstants.h"
  65. #ifdef ENABLE_MESSAGE_DIGEST
  66. # include "CheckIntegrityCommand.h"
  67. #endif // ENABLE_MESSAGE_DIGEST
  68. #ifdef ENABLE_BITTORRENT
  69. # include "BtCheckIntegrityEntry.h"
  70. # include "DefaultPeerStorage.h"
  71. # include "DefaultBtAnnounce.h"
  72. # include "BtSetup.h"
  73. # include "BtFileAllocationEntry.h"
  74. # include "BtPostDownloadHandler.h"
  75. #endif // ENABLE_BITTORRENT
  76. #ifdef ENABLE_METALINK
  77. # include "MetalinkPostDownloadHandler.h"
  78. #endif // ENABLE_METALINK
  79. int32_t RequestGroup::_gidCounter = 0;
  80. RequestGroup::RequestGroup(const Option* option,
  81. const Strings& uris):
  82. _gid(++_gidCounter),
  83. _uris(uris),
  84. _numConcurrentCommand(0),
  85. _numStreamConnection(0),
  86. _numCommand(0),
  87. _segmentMan(0),
  88. _segmentManFactory(new DefaultSegmentManFactory(option)),
  89. _downloadContext(0),
  90. _pieceStorage(0),
  91. _progressInfoFile(new NullProgressInfoFile()),
  92. _diskWriterFactory(0),
  93. _dependency(0),
  94. _preLocalFileCheckEnabled(true),
  95. _haltRequested(false),
  96. _forceHaltRequested(false),
  97. _option(option),
  98. _logger(LogFactory::getInstance())
  99. {
  100. if(_option->get(PREF_FILE_ALLOCATION) == V_PREALLOC) {
  101. _fileAllocationEnabled = true;
  102. } else {
  103. _fileAllocationEnabled = false;
  104. }
  105. initializePreDownloadHandler();
  106. initializePostDownloadHandler();
  107. }
  108. RequestGroup::~RequestGroup() {}
  109. SegmentManHandle RequestGroup::initSegmentMan()
  110. {
  111. _segmentMan = _segmentManFactory->createNewInstance(_downloadContext,
  112. _pieceStorage);
  113. return _segmentMan;
  114. }
  115. bool RequestGroup::downloadFinished() const
  116. {
  117. if(_pieceStorage.isNull()) {
  118. return false;
  119. } else {
  120. return _pieceStorage->downloadFinished();
  121. }
  122. }
  123. bool RequestGroup::allDownloadFinished() const
  124. {
  125. if(_pieceStorage.isNull()) {
  126. return false;
  127. } else {
  128. return _pieceStorage->allDownloadFinished();
  129. }
  130. }
  131. void RequestGroup::closeFile()
  132. {
  133. if(!_pieceStorage.isNull()) {
  134. _pieceStorage->getDiskAdaptor()->closeFile();
  135. }
  136. }
  137. Commands RequestGroup::createInitialCommand(DownloadEngine* e)
  138. {
  139. #ifdef ENABLE_BITTORRENT
  140. {
  141. BtContextHandle btContext = _downloadContext;
  142. if(!btContext.isNull()) {
  143. if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
  144. throw new DownloadFailureException(EX_DUPLICATE_FILE_DOWNLOAD,
  145. getFilePath().c_str());
  146. }
  147. initPieceStorage();
  148. if(btContext->getFileEntries().size() > 1) {
  149. // this is really multi file torrent.
  150. // clear http/ftp uris because the current implementation does not
  151. // allow integrating multi-file torrent and http/ftp.
  152. _logger->debug("Clearing http/ftp URIs because the current implementation does not allow integrating multi-file torrent and http/ftp.");
  153. _uris.clear();
  154. _pieceStorage->setFileFilter(Util::parseIntRange(_option->get(PREF_SELECT_FILE)));
  155. }
  156. BtProgressInfoFileHandle progressInfoFile =
  157. new DefaultBtProgressInfoFile(_downloadContext,
  158. _pieceStorage,
  159. _option);
  160. BtRegistry::registerBtContext(btContext->getInfoHashAsString(), btContext);
  161. BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(),
  162. _pieceStorage);
  163. BtRegistry::registerBtProgressInfoFile(btContext->getInfoHashAsString(),
  164. progressInfoFile);
  165. BtRuntimeHandle btRuntime = new BtRuntime();
  166. btRuntime->setListenPort(_option->getAsInt(PREF_LISTEN_PORT));
  167. BtRegistry::registerBtRuntime(btContext->getInfoHashAsString(), btRuntime);
  168. PeerStorageHandle peerStorage = new DefaultPeerStorage(btContext, _option);
  169. BtRegistry::registerPeerStorage(btContext->getInfoHashAsString(), peerStorage);
  170. BtAnnounceHandle btAnnounce = new DefaultBtAnnounce(btContext, _option);
  171. BtRegistry::registerBtAnnounce(btContext->getInfoHashAsString(), btAnnounce);
  172. btAnnounce->shuffleAnnounce();
  173. BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
  174. new PeerObjectCluster());
  175. // Call Load, Save and file allocation command here
  176. if(progressInfoFile->exists()) {
  177. // load .aria2 file if it exists.
  178. progressInfoFile->load();
  179. _pieceStorage->getDiskAdaptor()->openFile();
  180. } else {
  181. if(_pieceStorage->getDiskAdaptor()->fileExists()) {
  182. if(_option->get(PREF_CHECK_INTEGRITY) != V_TRUE &&
  183. _option->get(PREF_ALLOW_OVERWRITE) != V_TRUE) {
  184. // TODO we need this->haltRequested = true?
  185. throw new DownloadFailureException(MSG_FILE_ALREADY_EXISTS,
  186. _pieceStorage->getDiskAdaptor()->getFilePath().c_str());
  187. } else {
  188. _pieceStorage->getDiskAdaptor()->openFile();
  189. }
  190. } else {
  191. _pieceStorage->getDiskAdaptor()->openFile();
  192. }
  193. }
  194. _progressInfoFile = progressInfoFile;
  195. CheckIntegrityEntryHandle entry = new BtCheckIntegrityEntry(this);
  196. return processCheckIntegrityEntry(entry, e);
  197. }
  198. }
  199. #endif // ENABLE_BITTORRENT
  200. // TODO I assume here when totallength is set to DownloadContext and it is
  201. // not 0, then filepath is also set DownloadContext correctly....
  202. if(_downloadContext->getTotalLength() == 0) {
  203. return createNextCommand(e, 1);
  204. }else {
  205. if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
  206. throw new DownloadFailureException(EX_DUPLICATE_FILE_DOWNLOAD,
  207. getFilePath().c_str());
  208. }
  209. initPieceStorage();
  210. BtProgressInfoFileHandle infoFile =
  211. new DefaultBtProgressInfoFile(_downloadContext, _pieceStorage, _option);
  212. if(!infoFile->exists() && downloadFinishedByFileLength()) {
  213. return Commands();
  214. }
  215. loadAndOpenFile(infoFile);
  216. return processCheckIntegrityEntry(new StreamCheckIntegrityEntry(0, this), e);
  217. }
  218. }
  219. Commands RequestGroup::processCheckIntegrityEntry(const CheckIntegrityEntryHandle& entry, DownloadEngine* e)
  220. {
  221. #ifdef ENABLE_MESSAGE_DIGEST
  222. if(e->option->get(PREF_CHECK_INTEGRITY) == V_TRUE &&
  223. entry->isValidationReady()) {
  224. entry->initValidator();
  225. CheckIntegrityCommand* command =
  226. new CheckIntegrityCommand(CUIDCounterSingletonHolder::instance()->newID(), this, e, entry);
  227. Commands commands;
  228. commands.push_back(command);
  229. return commands;
  230. } else
  231. #endif // ENABLE_MESSAGE_DIGEST
  232. {
  233. return entry->onDownloadIncomplete(e);
  234. }
  235. }
  236. void RequestGroup::initPieceStorage()
  237. {
  238. if(_downloadContext->getTotalLength() == 0) {
  239. UnknownLengthPieceStorageHandle ps = new UnknownLengthPieceStorage(_downloadContext, _option);
  240. if(!_diskWriterFactory.isNull()) {
  241. ps->setDiskWriterFactory(_diskWriterFactory);
  242. }
  243. _pieceStorage = ps;
  244. } else {
  245. DefaultPieceStorageHandle ps = new DefaultPieceStorage(_downloadContext, _option);
  246. if(!_diskWriterFactory.isNull()) {
  247. ps->setDiskWriterFactory(_diskWriterFactory);
  248. }
  249. _pieceStorage = ps;
  250. }
  251. _pieceStorage->initStorage();
  252. initSegmentMan();
  253. }
  254. bool RequestGroup::downloadFinishedByFileLength()
  255. {
  256. // assuming that a control file doesn't exist.
  257. if(!isPreLocalFileCheckEnabled() ||
  258. _option->get(PREF_ALLOW_OVERWRITE) == V_TRUE ||
  259. _option->get(PREF_CHECK_INTEGRITY) == V_TRUE &&
  260. !_downloadContext->getPieceHashes().empty()) {
  261. return false;
  262. }
  263. // TODO consider the case when the getFilePath() returns dir path.
  264. File outfile(getFilePath());
  265. if(outfile.exists() && getTotalLength() == outfile.size()) {
  266. _pieceStorage->markAllPiecesDone();
  267. _logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, _gid, getFilePath().c_str());
  268. return true;
  269. } else {
  270. return false;
  271. }
  272. }
  273. void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoFile)
  274. {
  275. try {
  276. if(!isPreLocalFileCheckEnabled()) {
  277. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  278. return;
  279. }
  280. if(progressInfoFile->exists()) {
  281. progressInfoFile->load();
  282. _pieceStorage->getDiskAdaptor()->openExistingFile();
  283. } else {
  284. File outfile(getFilePath());
  285. if(outfile.exists() && _option->get(PREF_CONTINUE) == V_TRUE) {
  286. if(getTotalLength() < outfile.size()) {
  287. throw new DlAbortEx(EX_FILE_LENGTH_MISMATCH_BETWEEN_LOCAL_AND_REMOTE,
  288. getFilePath().c_str(),
  289. Util::llitos(outfile.size()).c_str(),
  290. Util::llitos(getTotalLength()).c_str());
  291. }
  292. _pieceStorage->getDiskAdaptor()->openExistingFile();
  293. _pieceStorage->markPiecesDone(outfile.size());
  294. } else {
  295. #ifdef ENABLE_MESSAGE_DIGEST
  296. if(outfile.exists() && _option->get(PREF_CHECK_INTEGRITY) == V_TRUE) {
  297. _pieceStorage->getDiskAdaptor()->openExistingFile();
  298. } else {
  299. shouldCancelDownloadForSafety();
  300. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  301. }
  302. #else // ENABLE_MESSAGE_DIGEST
  303. shouldCancelDownloadForSafety();
  304. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  305. #endif // ENABLE_MESSAGE_DIGEST
  306. }
  307. }
  308. setProgressInfoFile(progressInfoFile);
  309. } catch(RecoverableException* e) {
  310. throw new DownloadFailureException(e, EX_DOWNLOAD_ABORTED);
  311. }
  312. }
  313. // assuming that a control file does not exist
  314. void RequestGroup::shouldCancelDownloadForSafety()
  315. {
  316. if(_option->get(PREF_ALLOW_OVERWRITE) == V_TRUE) {
  317. return;
  318. }
  319. File outfile(getFilePath());
  320. if(outfile.exists()) {
  321. if(_option->get(PREF_AUTO_FILE_RENAMING) == V_TRUE) {
  322. if(tryAutoFileRenaming()) {
  323. _logger->notice(MSG_FILE_RENAMED, getFilePath().c_str());
  324. } else {
  325. throw new DownloadFailureException("File renaming failed: %s",
  326. getFilePath().c_str());
  327. }
  328. } else {
  329. throw new DownloadFailureException(MSG_FILE_ALREADY_EXISTS,
  330. getFilePath().c_str());
  331. }
  332. }
  333. }
  334. bool RequestGroup::tryAutoFileRenaming()
  335. {
  336. string filepath = getFilePath();
  337. if(filepath.empty()) {
  338. return false;
  339. }
  340. for(int32_t i = 1; i < 10000; ++i) {
  341. File newfile(filepath+"."+Util::itos(i));
  342. if(!newfile.exists()) {
  343. SingleFileDownloadContextHandle(_downloadContext)->setUFilename(newfile.getBasename());
  344. return true;
  345. }
  346. }
  347. return false;
  348. }
  349. Commands RequestGroup::createNextCommandWithAdj(DownloadEngine* e, int32_t numAdj)
  350. {
  351. int32_t numCommand = _numConcurrentCommand == 0 ? _uris.size() : _numConcurrentCommand+numAdj;
  352. return createNextCommand(e, numCommand, "GET");
  353. }
  354. Commands RequestGroup::createNextCommand(DownloadEngine* e, int32_t numCommand, const string& method)
  355. {
  356. Commands commands;
  357. for(;!_uris.empty() && numCommand--; _uris.pop_front()) {
  358. string uri = _uris.front();
  359. _spentUris.push_back(uri);
  360. RequestHandle req = new Request();
  361. req->setReferer(_option->get(PREF_REFERER));
  362. req->setMethod(method);
  363. if(req->setUrl(uri)) {
  364. commands.push_back(InitiateConnectionCommandFactory::createInitiateConnectionCommand(CUIDCounterSingletonHolder::instance()->newID(), req, this, e));
  365. } else {
  366. _logger->error(MSG_UNRECOGNIZED_URI, req->getUrl().c_str());
  367. }
  368. }
  369. return commands;
  370. }
  371. string RequestGroup::getFilePath() const
  372. {
  373. assert(!_downloadContext.isNull());
  374. if(_downloadContext.isNull()) {
  375. return "";
  376. } else {
  377. return _downloadContext->getActualBasePath();
  378. }
  379. }
  380. int64_t RequestGroup::getTotalLength() const
  381. {
  382. if(_pieceStorage.isNull()) {
  383. return 0;
  384. } else {
  385. if(_pieceStorage->isSelectiveDownloadingMode()) {
  386. return _pieceStorage->getFilteredTotalLength();
  387. } else {
  388. return _pieceStorage->getTotalLength();
  389. }
  390. }
  391. }
  392. int64_t RequestGroup::getCompletedLength() const
  393. {
  394. if(_pieceStorage.isNull()) {
  395. return 0;
  396. } else {
  397. if(_pieceStorage->isSelectiveDownloadingMode()) {
  398. return _pieceStorage->getFilteredCompletedLength();
  399. } else {
  400. return _pieceStorage->getCompletedLength();
  401. }
  402. }
  403. }
  404. void RequestGroup::validateFilename(const string& expectedFilename,
  405. const string& actualFilename) const
  406. {
  407. if(expectedFilename.empty()) {
  408. return;
  409. }
  410. if(expectedFilename != actualFilename) {
  411. throw new DlAbortEx(EX_FILENAME_MISMATCH,
  412. expectedFilename.c_str(),
  413. actualFilename.c_str());
  414. }
  415. }
  416. void RequestGroup::validateTotalLength(int64_t expectedTotalLength,
  417. int64_t actualTotalLength) const
  418. {
  419. if(expectedTotalLength <= 0) {
  420. return;
  421. }
  422. if(expectedTotalLength != actualTotalLength) {
  423. throw new DlAbortEx(EX_SIZE_MISMATCH,
  424. Util::llitos(expectedTotalLength, true).c_str(),
  425. Util::llitos(actualTotalLength, true).c_str());
  426. }
  427. }
  428. void RequestGroup::validateFilename(const string& actualFilename) const
  429. {
  430. validateFilename(_downloadContext->getFileEntries().front()->getBasename(), actualFilename);
  431. }
  432. void RequestGroup::validateTotalLength(int64_t actualTotalLength) const
  433. {
  434. validateTotalLength(getTotalLength(), actualTotalLength);
  435. }
  436. void RequestGroup::increaseStreamConnection()
  437. {
  438. ++_numStreamConnection;
  439. }
  440. void RequestGroup::decreaseStreamConnection()
  441. {
  442. --_numStreamConnection;
  443. }
  444. int32_t RequestGroup::getNumConnection() const
  445. {
  446. int32_t numConnection = _numStreamConnection;
  447. #ifdef ENABLE_BITTORRENT
  448. {
  449. BtContextHandle btContext = _downloadContext;
  450. if(!btContext.isNull()) {
  451. BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
  452. if(!btRuntime.isNull()) {
  453. numConnection += btRuntime->getConnections();
  454. }
  455. }
  456. }
  457. #endif // ENABLE_BITTORRENT
  458. return numConnection;
  459. }
  460. void RequestGroup::increaseNumCommand()
  461. {
  462. ++_numCommand;
  463. }
  464. void RequestGroup::decreaseNumCommand()
  465. {
  466. --_numCommand;
  467. }
  468. TransferStat RequestGroup::calculateStat()
  469. {
  470. TransferStat stat;
  471. #ifdef ENABLE_BITTORRENT
  472. {
  473. BtContextHandle btContext = _downloadContext;
  474. if(!btContext.isNull()) {
  475. PeerStorageHandle peerStorage = PEER_STORAGE(btContext);
  476. if(!peerStorage.isNull()) {
  477. stat = peerStorage->calculateStat();
  478. }
  479. }
  480. }
  481. #endif // ENABLE_BITTORRENT
  482. if(!_segmentMan.isNull()) {
  483. stat.setDownloadSpeed(stat.getDownloadSpeed()+_segmentMan->calculateDownloadSpeed());
  484. }
  485. return stat;
  486. }
  487. void RequestGroup::setHaltRequested(bool f)
  488. {
  489. _haltRequested = f;
  490. #ifdef ENABLE_BITTORRENT
  491. {
  492. BtContextHandle btContext = _downloadContext;
  493. if(!btContext.isNull()) {
  494. BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
  495. if(!btRuntime.isNull()) {
  496. btRuntime->setHalt(f);
  497. }
  498. }
  499. }
  500. #endif // ENABLE_BITTORRENT
  501. }
  502. void RequestGroup::setForceHaltRequested(bool f)
  503. {
  504. setHaltRequested(f);
  505. _forceHaltRequested = f;
  506. }
  507. void RequestGroup::releaseRuntimeResource()
  508. {
  509. #ifdef ENABLE_BITTORRENT
  510. BtContextHandle btContext = _downloadContext;
  511. if(!btContext.isNull()) {
  512. BtContextHandle btContextInReg = BtRegistry::getBtContext(btContext->getInfoHashAsString());
  513. if(!btContextInReg.isNull() &&
  514. btContextInReg->getOwnerRequestGroup()->getGID() ==
  515. btContext->getOwnerRequestGroup()->getGID()) {
  516. BtRegistry::unregister(btContext->getInfoHashAsString());
  517. }
  518. }
  519. #endif // ENABLE_BITTORRENT
  520. if(!_pieceStorage.isNull()) {
  521. _pieceStorage->removeAdvertisedPiece(0);
  522. }
  523. }
  524. void RequestGroup::preDownloadProcessing()
  525. {
  526. _logger->debug("Finding PreDownloadHandler for path %s.", getFilePath().c_str());
  527. try {
  528. for(PreDownloadHandlers::const_iterator itr = _preDownloadHandlers.begin();
  529. itr != _preDownloadHandlers.end(); ++itr) {
  530. if((*itr)->canHandle(this)) {
  531. (*itr)->execute(this);
  532. return;
  533. }
  534. }
  535. } catch(RecoverableException* ex) {
  536. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  537. delete ex;
  538. return;
  539. }
  540. _logger->debug("No PreDownloadHandler found.");
  541. return;
  542. }
  543. RequestGroups RequestGroup::postDownloadProcessing()
  544. {
  545. _logger->debug("Finding PostDownloadHandler for path %s.", getFilePath().c_str());
  546. try {
  547. for(PostDownloadHandlers::const_iterator itr = _postDownloadHandlers.begin();
  548. itr != _postDownloadHandlers.end(); ++itr) {
  549. if((*itr)->canHandle(this)) {
  550. return (*itr)->getNextRequestGroups(this);
  551. }
  552. }
  553. } catch(RecoverableException* ex) {
  554. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  555. delete ex;
  556. return RequestGroups();
  557. }
  558. _logger->debug("No PostDownloadHandler found.");
  559. return RequestGroups();
  560. }
  561. void RequestGroup::initializePreDownloadHandler()
  562. {
  563. #ifdef ENABLE_BITTORRENT
  564. if(_option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  565. _preDownloadHandlers.push_back(DownloadHandlerFactory::getBtPreDownloadHandler());
  566. }
  567. #endif // ENABLE_BITTORRENT
  568. #ifdef ENABLE_METALINK
  569. if(_option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  570. _preDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPreDownloadHandler());
  571. }
  572. #endif // ENABLE_METALINK
  573. }
  574. void RequestGroup::initializePostDownloadHandler()
  575. {
  576. #ifdef ENABLE_BITTORRENT
  577. if(_option->get(PREF_FOLLOW_TORRENT) == V_TRUE ||
  578. _option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  579. _postDownloadHandlers.push_back(DownloadHandlerFactory::getBtPostDownloadHandler());
  580. }
  581. #endif // ENABLE_BITTORRENT
  582. #ifdef ENABLE_METALINK
  583. if(_option->get(PREF_FOLLOW_METALINK) == V_TRUE ||
  584. _option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  585. _postDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPostDownloadHandler());
  586. }
  587. #endif // ENABLE_METALINK
  588. }
  589. Strings RequestGroup::getUris() const
  590. {
  591. Strings temp(_spentUris.begin(), _spentUris.end());
  592. temp.insert(temp.end(), _uris.begin(), _uris.end());
  593. return temp;
  594. }
  595. bool RequestGroup::isDependencyResolved()
  596. {
  597. if(_dependency.isNull()) {
  598. return true;
  599. }
  600. return _dependency->resolve();
  601. }
  602. void RequestGroup::setSegmentManFactory(const SegmentManFactoryHandle& segmentManFactory)
  603. {
  604. _segmentManFactory = segmentManFactory;
  605. }
  606. void RequestGroup::dependsOn(const DependencyHandle& dep)
  607. {
  608. _dependency = dep;
  609. }
  610. void RequestGroup::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  611. {
  612. _diskWriterFactory = diskWriterFactory;
  613. }
  614. DiskWriterFactoryHandle RequestGroup::getDiskWriterFactory() const
  615. {
  616. return _diskWriterFactory;
  617. }
  618. void RequestGroup::addPostDownloadHandler(const PostDownloadHandlerHandle& handler)
  619. {
  620. _postDownloadHandlers.push_back(handler);
  621. }
  622. void RequestGroup::addPreDownloadHandler(const PreDownloadHandlerHandle& handler)
  623. {
  624. _preDownloadHandlers.push_back(handler);
  625. }
  626. void RequestGroup::clearPostDowloadHandler()
  627. {
  628. _postDownloadHandlers.clear();
  629. }
  630. void RequestGroup::clearPreDowloadHandler()
  631. {
  632. _preDownloadHandlers.clear();
  633. }
  634. SegmentManHandle RequestGroup::getSegmentMan() const
  635. {
  636. return _segmentMan;
  637. }
  638. DownloadContextHandle RequestGroup::getDownloadContext() const
  639. {
  640. return _downloadContext;
  641. }
  642. void RequestGroup::setDownloadContext(const DownloadContextHandle& downloadContext)
  643. {
  644. _downloadContext = downloadContext;
  645. }
  646. PieceStorageHandle RequestGroup::getPieceStorage() const
  647. {
  648. return _pieceStorage;
  649. }
  650. void RequestGroup::setPieceStorage(const PieceStorageHandle& pieceStorage)
  651. {
  652. _pieceStorage = pieceStorage;
  653. }
  654. BtProgressInfoFileHandle RequestGroup::getProgressInfoFile() const
  655. {
  656. return _progressInfoFile;
  657. }
  658. void RequestGroup::setProgressInfoFile(const BtProgressInfoFileHandle& progressInfoFile)
  659. {
  660. _progressInfoFile = progressInfoFile;
  661. }
  662. bool RequestGroup::needsFileAllocation() const
  663. {
  664. return isFileAllocationEnabled() &&
  665. _option->getAsLLInt(PREF_NO_FILE_ALLOCATION_LIMIT) <= getTotalLength() &&
  666. !_pieceStorage->getDiskAdaptor()->fileAllocationIterator()->finished();
  667. }
  668. DownloadResultHandle RequestGroup::createDownloadResult() const
  669. {
  670. Strings uris = getUris();
  671. return new DownloadResult(_gid,
  672. getFilePath(),
  673. getTotalLength(),
  674. uris.empty() ? "":uris.front(),
  675. uris.size(),
  676. downloadFinished()?
  677. DownloadResult::FINISHED :
  678. DownloadResult::NOT_YET);
  679. }