1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the examples of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** You may use this file under the terms of the BSD license as follows:
11 ** "Redistribution and use in source and binary forms, with or without
12 ** modification, are permitted provided that the following conditions are
14 ** * Redistributions of source code must retain the above copyright
15 ** notice, this list of conditions and the following disclaimer.
16 ** * Redistributions in binary form must reproduce the above copyright
17 ** notice, this list of conditions and the following disclaimer in
18 ** the documentation and/or other materials provided with the
20 ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
21 ** of its contributors may be used to endorse or promote products derived
22 ** from this software without specific prior written permission.
25 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
39 ****************************************************************************/
41 #include "filemanager.h"
48 #include <QTimerEvent>
49 #include <QCryptographicHash>
51 FileManager::FileManager(QObject *parent)
57 startVerification = false;
61 verifiedPieces.fill(false);
64 FileManager::~FileManager()
70 foreach (QFile *file, files) {
76 int FileManager::read(int pieceIndex, int offset, int length)
79 request.pieceIndex = pieceIndex;
80 request.offset = offset;
81 request.length = length;
83 QMutexLocker locker(&mutex);
84 request.id = readId++;
85 readRequests << request;
89 QMetaObject::invokeMethod(this, "wakeUp", Qt::QueuedConnection);
95 void FileManager::write(int pieceIndex, int offset, const QByteArray &data)
98 request.pieceIndex = pieceIndex;
99 request.offset = offset;
102 QMutexLocker locker(&mutex);
103 writeRequests << request;
107 QMetaObject::invokeMethod(this, "wakeUp", Qt::QueuedConnection);
111 void FileManager::verifyPiece(int pieceIndex)
113 QMutexLocker locker(&mutex);
114 pendingVerificationRequests << pieceIndex;
115 startVerification = true;
119 QMetaObject::invokeMethod(this, "wakeUp", Qt::QueuedConnection);
123 int FileManager::pieceLengthAt(int pieceIndex) const
125 QMutexLocker locker(&mutex);
126 return (sha1s.size() == pieceIndex + 1)
127 ? (totalLength % pieceLength) : pieceLength;
130 QBitArray FileManager::completedPieces() const
132 QMutexLocker locker(&mutex);
133 return verifiedPieces;
136 void FileManager::setCompletedPieces(const QBitArray &pieces)
138 QMutexLocker locker(&mutex);
139 verifiedPieces = pieces;
142 QString FileManager::errorString() const
147 void FileManager::run()
149 if (!generateFiles())
154 // Go to sleep if there's nothing to do.
155 QMutexLocker locker(&mutex);
156 if (!quit && readRequests.isEmpty() && writeRequests.isEmpty() && !startVerification)
160 // Read pending read requests
162 QList<ReadRequest> newReadRequests = readRequests;
163 readRequests.clear();
165 while (!newReadRequests.isEmpty()) {
166 ReadRequest request = newReadRequests.takeFirst();
167 QByteArray block = readBlock(request.pieceIndex, request.offset, request.length);
168 emit dataRead(request.id, request.pieceIndex, request.offset, block);
171 // Write pending write requests
173 QList<WriteRequest> newWriteRequests = writeRequests;
174 writeRequests.clear();
175 while (!quit && !newWriteRequests.isEmpty()) {
176 WriteRequest request = newWriteRequests.takeFirst();
177 writeBlock(request.pieceIndex, request.offset, request.data);
180 // Process pending verification requests
181 if (startVerification) {
182 newPendingVerificationRequests = pendingVerificationRequests;
183 pendingVerificationRequests.clear();
184 verifyFileContents();
185 startVerification = false;
188 newPendingVerificationRequests.clear();
192 // Write pending write requests
194 QList<WriteRequest> newWriteRequests = writeRequests;
195 writeRequests.clear();
197 while (!newWriteRequests.isEmpty()) {
198 WriteRequest request = newWriteRequests.takeFirst();
199 writeBlock(request.pieceIndex, request.offset, request.data);
203 void FileManager::startDataVerification()
205 QMutexLocker locker(&mutex);
206 startVerification = true;
210 bool FileManager::generateFiles()
214 // Set up the thread local data
215 if (metaInfo.fileForm() == MetaInfo::SingleFileForm) {
216 QMutexLocker locker(&mutex);
217 MetaInfoSingleFile singleFile = metaInfo.singleFile();
220 if (!destinationPath.isEmpty()) {
221 prefix = destinationPath;
222 if (!prefix.endsWith("/"))
225 if (!dir.mkpath(prefix)) {
226 errString = tr("Failed to create directory %1").arg(prefix);
231 QFile *file = new QFile(prefix + singleFile.name);
232 if (!file->open(QFile::ReadWrite)) {
233 errString = tr("Failed to open/create file %1: %2")
234 .arg(file->fileName()).arg(file->errorString());
239 if (file->size() != singleFile.length) {
241 if (!file->resize(singleFile.length)) {
242 errString = tr("Failed to resize file %1: %2")
243 .arg(file->fileName()).arg(file->errorString());
248 fileSizes << file->size();
252 pieceLength = singleFile.pieceLength;
253 totalLength = singleFile.length;
254 sha1s = singleFile.sha1Sums;
256 QMutexLocker locker(&mutex);
260 if (!destinationPath.isEmpty()) {
261 prefix = destinationPath;
262 if (!prefix.endsWith("/"))
265 if (!metaInfo.name().isEmpty()) {
266 prefix += metaInfo.name();
267 if (!prefix.endsWith("/"))
270 if (!dir.mkpath(prefix)) {
271 errString = tr("Failed to create directory %1").arg(prefix);
276 foreach (const MetaInfoMultiFile &entry, metaInfo.multiFiles()) {
277 QString filePath = QFileInfo(prefix + entry.path).path();
278 if (!QFile::exists(filePath)) {
279 if (!dir.mkpath(filePath)) {
280 errString = tr("Failed to create directory %1").arg(filePath);
286 QFile *file = new QFile(prefix + entry.path);
287 if (!file->open(QFile::ReadWrite)) {
288 errString = tr("Failed to open/create file %1: %2")
289 .arg(file->fileName()).arg(file->errorString());
294 if (file->size() != entry.length) {
296 if (!file->resize(entry.length)) {
297 errString = tr("Failed to resize file %1: %2")
298 .arg(file->fileName()).arg(file->errorString());
303 fileSizes << file->size();
307 totalLength += entry.length;
310 sha1s = metaInfo.sha1Sums();
311 pieceLength = metaInfo.pieceLength();
313 numPieces = sha1s.size();
317 QByteArray FileManager::readBlock(int pieceIndex, int offset, int length)
320 qint64 startReadIndex = (quint64(pieceIndex) * pieceLength) + offset;
321 qint64 currentIndex = 0;
323 for (int i = 0; !quit && i < files.size() && length > 0; ++i) {
324 QFile *file = files[i];
325 qint64 currentFileSize = fileSizes.at(i);
326 if ((currentIndex + currentFileSize) > startReadIndex) {
327 if (!file->isOpen()) {
328 if (!file->open(QFile::ReadWrite)) {
329 errString = tr("Failed to read from file %1: %2")
330 .arg(file->fileName()).arg(file->errorString());
336 file->seek(startReadIndex - currentIndex);
337 QByteArray chunk = file->read(qMin<qint64>(length, currentFileSize - file->pos()));
341 length -= chunk.size();
342 startReadIndex += chunk.size();
344 errString = tr("Failed to read from file %1 (read %3 bytes): %2")
345 .arg(file->fileName()).arg(file->errorString()).arg(length);
350 currentIndex += currentFileSize;
355 bool FileManager::writeBlock(int pieceIndex, int offset, const QByteArray &data)
357 qint64 startWriteIndex = (qint64(pieceIndex) * pieceLength) + offset;
358 qint64 currentIndex = 0;
359 int bytesToWrite = data.size();
362 for (int i = 0; !quit && i < files.size(); ++i) {
363 QFile *file = files[i];
364 qint64 currentFileSize = fileSizes.at(i);
366 if ((currentIndex + currentFileSize) > startWriteIndex) {
367 if (!file->isOpen()) {
368 if (!file->open(QFile::ReadWrite)) {
369 errString = tr("Failed to write to file %1: %2")
370 .arg(file->fileName()).arg(file->errorString());
376 file->seek(startWriteIndex - currentIndex);
377 qint64 bytesWritten = file->write(data.constData() + written,
378 qMin<qint64>(bytesToWrite, currentFileSize - file->pos()));
381 if (bytesWritten <= 0) {
382 errString = tr("Failed to write to file %1: %2")
383 .arg(file->fileName()).arg(file->errorString());
388 written += bytesWritten;
389 startWriteIndex += bytesWritten;
390 bytesToWrite -= bytesWritten;
391 if (bytesToWrite == 0)
394 currentIndex += currentFileSize;
399 void FileManager::verifyFileContents()
401 // Verify all pieces the first time
402 if (newPendingVerificationRequests.isEmpty()) {
403 if (verifiedPieces.count(true) == 0) {
404 verifiedPieces.resize(sha1s.size());
408 int numPieces = sha1s.size();
410 for (int index = 0; index < numPieces; ++index) {
411 verifySinglePiece(index);
413 int percent = ((index + 1) * 100) / numPieces;
414 if (oldPercent != percent) {
415 emit verificationProgress(percent);
416 oldPercent = percent;
421 emit verificationDone();
425 // Verify all pending pieces
426 foreach (int index, newPendingVerificationRequests)
427 emit pieceVerified(index, verifySinglePiece(index));
430 bool FileManager::verifySinglePiece(int pieceIndex)
432 QByteArray block = readBlock(pieceIndex, 0, pieceLength);
433 QByteArray sha1Sum = QCryptographicHash::hash(block, QCryptographicHash::Sha1);
435 if (sha1Sum != sha1s.at(pieceIndex))
437 verifiedPieces.setBit(pieceIndex);
441 void FileManager::wakeUp()
443 QMutexLocker locker(&mutex);