d07ea3801edcc614d4dd142bbcae33e3631c9788
[emufront] / src / utils / fileutil.cpp
1 /*
2 ** EmuFront
3 ** Copyright 2010 Mikko Keinänen
4 **
5 ** This file is part of EmuFront.
6 **
7 **
8 ** EmuFront is free software: you can redistribute it and/or modify
9 ** it under the terms of the GNU General Public License version 2 as published by
10 ** the Free Software Foundation and appearing in the file gpl.txt included in the
11 ** packaging of this file.
12 **
13 ** EmuFront is distributed in the hope that it will be useful,
14 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ** GNU General Public License for more details.
17 **
18 ** You should have received a copy of the GNU General Public License
19 ** along with EmuFront.  If not, see <http://www.gnu.org/licenses/>.
20 */
21 #include <QDir>
22 #include <QDebug>
23 #include <QProcess>
24 #include <QProgressDialog>
25 #include "fileutil.h"
26 #include "zlib.h" /* crc32 */
27 #include "emufrontexception.h"
28 #include "setup.h"
29 #include "mediaimage.h"
30 #include "mediaimagecontainer.h"
31 #include "mediatype.h"
32 #include "platform.h"
33 #include "dbmediaimagecontainer.h"
34 #include "unziphelper.h"
35
36 FileUtil::FileUtil(QObject *parent) : QObject(parent)
37 {
38     buf = new char[READ_BUFFER];
39     unzipHelper = new UnzipHelper(this);
40 }
41
42 FileUtil::~FileUtil()
43 {
44     delete[] buf;
45 }
46
47 /* Throws EmuFrontException */
48 int FileUtil::scanFilePath(FilePathObject *fp,
49     QStringList filters, DbMediaImageContainer *dbMic,
50     QProgressDialog *progressDialog)
51 {
52     if (!fp->getSetup()){
53         throw EmuFrontException(tr("Setup not available with %1.").arg(fp->getName()));
54     }
55     else if(!fp->getSetup()->getPlatform()){
56         throw EmuFrontException(tr("No platform object available with %1.")
57             .arg(fp->getSetup()->getName()));
58     }
59     else if (!fp->getSetup()->getMediaType()){
60         throw EmuFrontException(tr("No media type available with %1.")
61             .arg(fp->getSetup()->getName()));
62     }
63
64     int count = 0;
65     /*qDebug() << QString("We have a platform %1, media type %2")
66         .arg(fp->getSetup()->getPlatform()->getName())
67         .arg(fp->getSetup()->getMediaType()->getName());*/
68     QDir dir(fp->getName());
69     if (!dir.exists() || !dir.isReadable())
70         throw EmuFrontException(tr("Directory %1 doesn't exists or isn't readable!").arg(fp->getName()));
71
72     //qDebug() << QString("Scanning directory %1.").arg(fp->getName());
73     dir.setFilter(QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot | QDir::Readable);
74
75     if (filters.count() > 0) dir.setNameFilters(filters);
76
77     // we'll go through the filtered archive files...
78     QFileInfoList list = dir.entryInfoList();
79     //qDebug() << "We have " << list.count() << " files to go through.";
80     QList<MediaImageContainer*> containers;
81     try {
82         progressDialog->setMinimum(0);
83         progressDialog->setMaximum(list.size());
84         for (int i = 0; i < list.size(); ++i)
85         {
86             progressDialog->setValue(i);
87             if (progressDialog->wasCanceled())
88                 break;
89             QFileInfo fileInfo = list.at(i);
90             //qDebug() << QString("%1 %2").arg(fileInfo.size(), 10).arg(fileInfo.absoluteFilePath());
91
92             //... and collect the contents of each archive
93             QMap<QString, EmuFrontObject*> files = unzipHelper->listContents(fileInfo.absoluteFilePath(), fp);
94
95             if (files.count() > 0)
96             {
97                 // read crc32 checksum for media image container
98                 quint32 crc = readCrc32(fileInfo.absoluteFilePath());
99                 FilePathObject *fpo = new FilePathObject(*fp);
100                 MediaImageContainer *con = new MediaImageContainer (
101                         fileInfo.fileName(),
102                         QString("%1").arg(crc, 0, 16),
103                         fileInfo.size(),
104                         files,
105                         fpo // we need a copy since MediaImageContainers are deleted and the original filepath object would get deleted also.
106                         );
107                 containers.append(con);
108                 ++count;
109                 //qDebug() << "We have " << containers.count() << " containers.";
110
111                 if (containers.count() >= MIC_BUFFER_SIZE)  {
112                     //qDebug() << "We have " << containers.count() << " containers .. storing to db.";
113                     showDbUpdating(progressDialog);
114                     dbMic->storeContainers(containers, fp);
115                     hideDbUpdating(progressDialog);
116                     qDeleteAll(containers);
117                     containers.clear();
118                     //qDebug() << "containers now: " << containers.count();
119                 }
120                 //qDebug() << "We have " << containers.size() << " containers.";
121             } // files.count() > 0
122             else {
123                 qDebug() << "No files from container " << fileInfo.absoluteFilePath();
124             }
125         }
126         progressDialog->setValue(list.size());
127         if (containers.count() > 0) {
128             //qDebug() << "Storing the rest " << containers.count() << " containers.";
129             //emit dbUpdateInProgress();
130             showDbUpdating(progressDialog);
131             dbMic->storeContainers(containers, fp);
132             hideDbUpdating(progressDialog);
133             //emit dbUpdateFinished();
134             qDeleteAll(containers);
135             containers.clear();
136  } } catch (EmuFrontException &e) { qDebug() << "Got exception " << e.what() << ", aborting & deleting created data objects.";
137         qDeleteAll(containers);
138         throw e;
139     }
140     //qDebug() << "Done scanning files!";
141     return count;
142 }
143
144 /* Uses crc32 from zlib.h to count crc32 checksum value */
145 /* Throws EmuFrontException */
146 quint32 FileUtil::readCrc32(QString filePath)
147 {
148     // todo ... use some crc32 tool for this ... or maybe use md5 or something like that!!!
149     QFile file(filePath);
150     //qDebug() << "readCrc32: " << filePath;
151     if (!file.open(QIODevice::ReadOnly)) {
152         throw EmuFrontException(QString(tr("Failed opening file %1 for reading the checksum!")).arg(filePath));
153     }
154     quint32 crc = crc32(0L, Z_NULL, 0);
155     int read = 0;
156     while((read = file.read(buf, READ_BUFFER))) {
157         crc = crc32(crc, (const Bytef*) buf, read);
158     }
159     file.close();
160     if (crc <= 0)
161         throw EmuFrontException(QString(tr("Failed reading crc checksum for file %1!")).arg(filePath));
162     //qDebug() << QString("readCrc32, crc: %1").arg(crc, 0, 16);
163     return crc;
164 }
165
166 bool FileUtil::isSupportedFile(const QString filename, const QStringList supportedFileExtensions)
167 {
168     QString ext = filename.section('.', -1);
169     return supportedFileExtensions.contains(ext, Qt::CaseInsensitive);
170 }
171
172 void FileUtil::showDbUpdating(QProgressDialog *progressDialog)
173 {
174     qDebug() << "DB updating";
175     // TODO: the following is not currently working
176     progressDialog->setWindowTitle(tr("Updating DB... please wait!"));
177     progressDialog->setEnabled(false);
178 }
179
180 void FileUtil::hideDbUpdating(QProgressDialog *progressDialog)
181 {
182     qDebug() << "DB update finished";
183     // TODO: the following is not currently working
184     progressDialog->setEnabled(true);
185     progressDialog->setWindowTitle(tr("Scanning files"));
186 }
187