UBFileSystemUtils.cpp 25.9 KB
Newer Older
Claudio Valerio's avatar
Claudio Valerio committed
1
/*
2
 * Copyright (C) 2015-2018 Département de l'Instruction Publique (DIP-SEM)
Craig Watson's avatar
Craig Watson committed
3
 *
Claudio Valerio's avatar
Claudio Valerio committed
4
 * Copyright (C) 2013 Open Education Foundation
Claudio Valerio's avatar
Claudio Valerio committed
5
 *
Claudio Valerio's avatar
Claudio Valerio committed
6 7
 * Copyright (C) 2010-2013 Groupement d'Intérêt Public pour
 * l'Education Numérique en Afrique (GIP ENA)
8
 *
Claudio Valerio's avatar
Claudio Valerio committed
9 10 11
 * This file is part of OpenBoard.
 *
 * OpenBoard is free software: you can redistribute it and/or modify
Claudio Valerio's avatar
Claudio Valerio committed
12 13
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License,
14 15 16 17
 * with a specific linking exception for the OpenSSL project's
 * "OpenSSL" library (or with modified versions of it that use the
 * same license as the "OpenSSL" library).
 *
Claudio Valerio's avatar
Claudio Valerio committed
18
 * OpenBoard is distributed in the hope that it will be useful,
Claudio Valerio's avatar
Claudio Valerio committed
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Claudio Valerio's avatar
Claudio Valerio committed
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Claudio Valerio's avatar
Claudio Valerio committed
21
 * GNU General Public License for more details.
Claudio Valerio's avatar
Claudio Valerio committed
22
 *
Claudio Valerio's avatar
Claudio Valerio committed
23
 * You should have received a copy of the GNU General Public License
Claudio Valerio's avatar
Claudio Valerio committed
24
 * along with OpenBoard. If not, see <http://www.gnu.org/licenses/>.
Claudio Valerio's avatar
Claudio Valerio committed
25 26
 */

27

Claudio Valerio's avatar
Claudio Valerio committed
28

Claudio Valerio's avatar
Claudio Valerio committed
29

Claudio Valerio's avatar
Claudio Valerio committed
30 31 32
#include "UBFileSystemUtils.h"

#include <QtGui>
33 34 35

#include "core/UBApplication.h"

36
#include "globals/UBGlobals.h"
Claudio Valerio's avatar
Claudio Valerio committed
37

38
THIRD_PARTY_WARNINGS_DISABLE
39
#include "quazipfile.h"
Claudio Valerio's avatar
Claudio Valerio committed
40
#include <openssl/md5.h>
41
THIRD_PARTY_WARNINGS_ENABLE
Claudio Valerio's avatar
Claudio Valerio committed
42

43 44
#include "core/memcheck.h"

Claudio Valerio's avatar
Claudio Valerio committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58
QStringList UBFileSystemUtils::sTempDirToCleanUp;


UBFileSystemUtils::UBFileSystemUtils()
{
    // NOOP
}


UBFileSystemUtils::~UBFileSystemUtils()
{
    // NOOP
}

59 60 61

QString UBFileSystemUtils::removeLocalFilePrefix(QString input)
{
62
#ifdef Q_OS_WIN
63 64 65 66 67 68 69 70 71 72 73 74
    if(input.startsWith("file:///"))
        return input.mid(8);
    else
        return input;
#else
    if(input.startsWith("file://"))
        return input.mid(7);
    else
        return input;
#endif
}

Claudio Valerio's avatar
Claudio Valerio committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
bool UBFileSystemUtils::isAZipFile(QString &filePath)
{
   if(QFileInfo(filePath).isDir()) return false;
   QFile file(filePath);
   if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
       return false;

   bool result = false;
   QByteArray responseArray = file.readLine(10);
   QString responseString(responseArray);

   result = responseString.startsWith("pk", Qt::CaseInsensitive);

   file.close();
   return result;
}

92
bool UBFileSystemUtils::copyFile(const QString &source, const QString &destination, bool overwrite)
93 94 95 96 97
{
    if (!QFile::exists(source)) {
        qDebug() << "file" << source << "does not present in fs";
        return false;
    }
98

99
    QString normalizedDestination = destination;
100 101 102
    if (QFile::exists(normalizedDestination)) {
        if  (QFileInfo(normalizedDestination).isFile() && overwrite) {
            QFile::remove(normalizedDestination);
103 104
        }
    } else {
105 106
        normalizedDestination = normalizedDestination.replace(QString("\\"), QString("/"));
        int pos = normalizedDestination.lastIndexOf("/");
107
        if (pos != -1) {
108
            QString newpath = normalizedDestination.left(pos);
109 110 111 112 113
            if (!QDir().mkpath(newpath)) {
                qDebug() << "can't create a new path at " << newpath;
            }
        }
    }
114
    return QFile::copy(source, normalizedDestination);
115 116
}

117 118 119 120 121 122 123 124 125
bool UBFileSystemUtils::copy(const QString &source, const QString &destination, bool overwrite)
{
    if (QFileInfo(source).isDir()) {
        return copyDir(source, destination);
    } else {
        return copyFile(source, destination, overwrite);
    }
}

126 127 128 129 130 131 132
bool UBFileSystemUtils::deleteFile(const QString &path)
{
    QFile f(path);
    f.setPermissions(path, QFile::ReadOwner | QFile::WriteOwner);
    return f.remove();
}

Claudio Valerio's avatar
Claudio Valerio committed
133 134
QString UBFileSystemUtils::defaultTempDirPath()
{
135
    return QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/" + defaultTempDirName();
Claudio Valerio's avatar
Claudio Valerio committed
136 137 138 139
}

QString UBFileSystemUtils::createTempDir(const QString& templateString, bool autoDeleteOnExit)
{
140
    QString appTempDir =  QStandardPaths::writableLocation(QStandardPaths::TempLocation)
Claudio Valerio's avatar
Claudio Valerio committed
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
                                  + "/" + templateString;

    int index = 0;
    QDir dir;

    do
    {
        index++;
        QString dirName = appTempDir + QString("%1").arg(index);
        dir = QDir(dirName);
    }
    while(dir.exists() && index < 10000);

    dir.mkpath(dir.path());

    if (autoDeleteOnExit)
        UBFileSystemUtils::sTempDirToCleanUp << dir.path();

    return dir.path();
}


QString UBFileSystemUtils::nextAvailableFileName(const QString& filename, const QString& inter)
{
    QFile f(filename);

    if (!f.exists())
        return filename;

    int index = 0;

    QString uniqueFilename;
    QFileInfo fi(filename);

    QString base = fi.dir().path() + "/" + fi.baseName();
    QString suffix = fi.suffix();

    do
    {
        index++;
        uniqueFilename = base + QString("%1%2").arg(inter).arg(index) + "." + suffix;
        f.setFileName(uniqueFilename);
    }
    while(f.exists() && index < 10000);

    return uniqueFilename;

}


void UBFileSystemUtils::deleteAllTempDirCreatedDuringSession()
{
    foreach (QString dirPath, sTempDirToCleanUp)
    {
        qWarning() << "will delete" << dirPath;

        deleteDir(dirPath);
    }
}



void UBFileSystemUtils::cleanupGhostTempFolders(const QString& templateString)
{
205
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
Claudio Valerio's avatar
Claudio Valerio committed
206 207 208 209 210 211 212 213 214 215 216
    foreach (QFileInfo dirContent, dir.entryInfoList(QDir::Dirs
          | QDir::NoDotAndDotDot | QDir::Hidden , QDir::Name))
    {
        if (dirContent.fileName().startsWith(templateString))
        {
            deleteDir(dirContent.absoluteFilePath());
        }
    }
}


217
QStringList UBFileSystemUtils::allFiles(const QString& pDirPath, bool isRecursive)
Claudio Valerio's avatar
Claudio Valerio committed
218 219 220 221 222 223 224 225 226
{
    QStringList result;
    if (pDirPath == "" || pDirPath == "." || pDirPath == "..")
        return result;

    QDir dir(pDirPath);

    foreach(QFileInfo dirContent, dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot , QDir::Name))
    {
227
        if (isRecursive && dirContent.isDir())
Claudio Valerio's avatar
Claudio Valerio committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241
        {
            result << allFiles(dirContent.absoluteFilePath());
        }
        else
        {
            result << dirContent.absoluteFilePath();
        }
    }
    return result;
}

QFileInfoList UBFileSystemUtils::allElementsInDirectory(const QString& pDirPath)
{
    QDir dir = QDir(pDirPath);
Claudio Valerio's avatar
Claudio Valerio committed
242
    dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
Claudio Valerio's avatar
Claudio Valerio committed
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
    dir.setSorting(QDir::DirsFirst);

    return QFileInfoList(dir.entryInfoList());
}


bool UBFileSystemUtils::deleteDir(const QString& pDirPath)
{
    if (pDirPath == "" || pDirPath == "." || pDirPath == "..")
        return false;

    QDir dir(pDirPath);

    if (dir.exists())
    {
        foreach(QFileInfo dirContent, dir.entryInfoList(QDir::Files | QDir::Dirs
                | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System , QDir::Name))
        {
            if (dirContent.isDir())
            {
                deleteDir(dirContent.absoluteFilePath());
            }
            else
            {
                if (!dirContent.dir().remove(dirContent.fileName()))
                {
                    return false;
                }
            }
        }
    }

    return dir.rmdir(pDirPath);
}


bool UBFileSystemUtils::copyDir(const QString& pSourceDirPath, const QString& pTargetDirPath)
{
    if (pSourceDirPath == "" || pSourceDirPath == "." || pSourceDirPath == "..")
        return false;

    QDir dirSource(pSourceDirPath);
    QDir dirTarget(pTargetDirPath);

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
287 288
    if (!dirTarget.mkpath(pTargetDirPath))
        return false;
Claudio Valerio's avatar
Claudio Valerio committed
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

    bool successSoFar = true;

    foreach(QFileInfo dirContent, dirSource.entryInfoList(QDir::Files | QDir::Dirs
            | QDir::NoDotAndDotDot | QDir::Hidden , QDir::Name))
    {
        if (successSoFar)
        {
            if (dirContent.isDir())
            {
                successSoFar = copyDir(pSourceDirPath + "/" + dirContent.fileName(), pTargetDirPath + "/" + dirContent.fileName());
            }
            else
            {
                QFile f(pSourceDirPath + "/" + dirContent.fileName());
                successSoFar = f.copy(pTargetDirPath + "/" + dirContent.fileName());
            }
        }
        else
        {
            break;
        }
    }

    return successSoFar;
}


bool UBFileSystemUtils::moveDir(const QString& pSourceDirPath, const QString& pTargetDirPath)
{
    bool copySuccess = copyDir(pSourceDirPath, pTargetDirPath);

    if (copySuccess)
    {
        return deleteDir(pSourceDirPath);
    }
    else
    {
        return false;
    }
}



QString UBFileSystemUtils::cleanName(const QString& name)
{
    QString result = name;
    result = result.remove("/");
    result = result.remove(":");
    result = result.remove("?");
    result = result.remove("*");
    result = result.remove("\\");

    //http://support.microsoft.com/kb/177506

    result = result.remove("<");
    result = result.remove(">");
    result = result.remove("|");

    return result;
}

QString UBFileSystemUtils::normalizeFilePath(const QString& pFilePath)
{
    QString result = pFilePath;
    return result.replace("\\", "/");
}

QString UBFileSystemUtils::digitFileFormat(const QString& s, int digit)
{
359
    return s.arg(digit, 3, 10, QLatin1Char('0'));
Claudio Valerio's avatar
Claudio Valerio committed
360 361 362 363 364 365 366
}


QString UBFileSystemUtils::thumbnailPath(const QString& path)
{
    QFileInfo pathInfo(path);

367
    return pathInfo.dir().absolutePath() + "/" + pathInfo.completeBaseName() + ".thumbnail.png";
Claudio Valerio's avatar
Claudio Valerio committed
368 369 370 371
}

QString UBFileSystemUtils::extension(const QString& fileName)
{
Claudio Valerio's avatar
Claudio Valerio committed
372
    QString extension("");
Claudio Valerio's avatar
Claudio Valerio committed
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

    int lastDotIndex = fileName.lastIndexOf(".");

    if (lastDotIndex > 0)
    {
        extension = fileName.right(fileName.length() - lastDotIndex - 1).toLower();

        if (extension.endsWith("/") || extension.endsWith("\\"))
            extension = extension.left(extension.length() - 1);
    }

    return extension;
}

QString UBFileSystemUtils::lastPathComponent(const QString& path)
{
    QString lastPathComponent = normalizeFilePath(path);

    int lastSeparatorIndex = lastPathComponent.lastIndexOf("/");

    if (lastSeparatorIndex + 1 == path.length()) {
        lastPathComponent = lastPathComponent.left(lastPathComponent.length() - 1);
        lastSeparatorIndex = lastPathComponent.lastIndexOf("/");
    }

    if (lastSeparatorIndex > 0){
        lastPathComponent = lastPathComponent.right(lastPathComponent.length() - lastSeparatorIndex - 1);
    }
    else {
        return 0;
    }

    return lastPathComponent;
}

QString UBFileSystemUtils::mimeTypeFromFileName(const QString& fileName)
{
    QString ext = extension(fileName);

412
    if (ext == "xls" || ext == "xlsx") return "application/msexcel";
Claudio Valerio's avatar
Claudio Valerio committed
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
    if (ext == "ppt" || ext == "pptx") return "application/mspowerpoint";
    if (ext == "ief") return "image/ief";
    if (ext == "m3u") return "audio/x-mpegurl";
    if (ext == "key") return "application/x-iwork-keynote-sffkeynote";
    if (ext == "odf") return "application/vnd.oasis.opendocument.formula";
    if (ext == "aif" || ext == "aiff" || ext == "aifc") return "audio/x-aiff";
    if (ext == "odp") return "application/vnd.oasis.opendocument.presentation";
    if (ext == "xml") return "application/xml";
    if (ext == "rgb") return "image/x-rgb";
    if (ext == "ods") return "application/vnd.oasis.opendocument.spreadsheet";
    if (ext == "rtf") return "text/rtf";
    if (ext == "odt") return "application/vnd.oasis.opendocument.text";
    if (ext == "xbm") return "image/x-xbitmap";
    if (ext == "lsx" || ext == "lsf") return "video/x-la-asf";
    if (ext == "jfif") return "image/pipeg";
    if (ext == "ppm") return "image/x-portable-pixmap";
    if (ext == "csv") return "text/csv";
    if (ext == "pgm") return "image/x-portable-graymap";
    if (ext == "odc") return "application/vnd.oasis.opendocument.chart";
    if (ext == "odb") return "application/vnd.oasis.opendocument.database";
    if (ext == "cmx") return "image/x-cmx";
    if (ext == "ico") return "image/x-icon";
    if (ext == "mp3") return "audio/mpeg";
    if (ext == "wav") return "audio/x-wav";
    if (ext == "pbm") return "image/x-portable-bitmap";
    if (ext == "ras") return "image/x-cmu-raster";
    if (ext == "txt") return "text/plain";
    if (ext == "xpm") return "image/x-xpixmap";
    if (ext == "ra" || ext == "ram") return "audio/x-pn-realaudio";
    if (ext == "numbers") return "application/x-iwork-numbers-sffnumbers";
    if (ext == "snd" || ext == "au") return "audio/basic";
    if (ext == "zip") return "application/zip";
    if (ext == "pages") return "application/x-iwork-pages-sffpages";
    if (ext == "movie") return "video/x-sgi-movie";
    if (ext == "xwd") return "image/x-xwindowdump";
    if (ext == "pnm") return "image/x-portable-anymap";
    if (ext == "cod") return "image/cis-cod";
    if (ext == "doc" || ext == "docx") return "application/msword";
    if (ext == "html") return "text/html";
    if (ext == "mid" || ext == "rmi") return "audio/mid";
    if (ext == "jpeg" || ext == "jpg" || ext == "jpe") return "image/jpeg";
    if (ext == "png") return "image/png";
    if (ext == "bmp") return "image/bmp";
    if (ext == "tiff" || ext == "tif") return "image/tiff";
    if (ext == "gif") return "image/gif";
    if (ext == "svg" || ext == "svgz") return "image/svg+xml";
    if (ext == "pdf") return "application/pdf";
    if (ext == "mov" || ext == "qt") return "video/quicktime";
    if (ext == "mpg" || ext == "mpeg" || ext == "mp2" || ext == "mpe" || ext == "mpa" || ext == "mpv2") return "video/mpeg";
    if (ext == "mp4") return "video/mp4";
    if (ext == "asf" || ext == "asx" || ext == "asr") return "video/x-ms-asf";
    if (ext == "wmv") return "video/x-ms-wmv";
    if (ext == "wvx") return "video/x-ms-wvx";
    if (ext == "wm") return "video/x-ms-wm";
    if (ext == "wmx") return "video/x-ms-wmx";
    if (ext == "avi") return "video/x-msvideo";
    if (ext == "ogv") return "video/ogg";
    if (ext == "flv") return "video/x-flv"; // TODO UB 4.x  ... we need to be smarter ... flash may need an external plugin :-(
    if (ext == "m4v") return "video/x-m4v";
    // W3C widget
    if (ext == "wgt") return "application/widget";
474
    if (ext == "wgs") return "application/search";
Claudio Valerio's avatar
Claudio Valerio committed
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
    // Apple widget
    if (ext == "wdgt") return "application/vnd.apple-widget"; //mime type invented by us :-(
    if (ext == "swf") return "application/x-shockwave-flash";

    return "";

}


QString UBFileSystemUtils::fileExtensionFromMimeType(const QString& pMimeType)
{
    // TODO  UB 4.x map from config file, based on a "good" source

    if (pMimeType == "application/msexcel") return "xls";
    if (pMimeType == "application/mspowerpoint") return "ppt";
    if (pMimeType == "image/ief") return "ief";
    if (pMimeType == "audio/x-mpegurl") return "m3u";
    if (pMimeType == "application/x-iwork-keynote-sffkeynote") return "key";
    if (pMimeType == "application/vnd.oasis.opendocument.formula") return "odf";
    if (pMimeType == "audio/x-aiff") return "aif";
    if (pMimeType == "application/vnd.oasis.opendocument.presentation") return "odp";
    if (pMimeType == "application/xml") return "xml";
    if (pMimeType == "image/x-rgb") return "rgb";
    if (pMimeType == "application/vnd.oasis.opendocument.spreadsheet") return "ods";
    if (pMimeType == "text/rtf") return "rtf";
    if (pMimeType == "application/vnd.oasis.opendocument.text") return "odt";
    if (pMimeType == "image/x-xbitmap") return "xbm";
    if (pMimeType == "video/x-la-asf") return "lsx";
    if (pMimeType == "image/pipeg") return "jfif";
    if (pMimeType == "image/x-portable-pixmap") return "ppm";
    if (pMimeType == "text/csv") return "csv";
    if (pMimeType == "image/x-portable-graymap") return "pgm";
    if (pMimeType == "application/vnd.oasis.opendocument.chart") return "odc";
    if (pMimeType == "application/vnd.oasis.opendocument.database") return "odb";
    if (pMimeType == "image/x-cmx") return "cmx";
    if (pMimeType == "image/x-icon") return "ico";
    if (pMimeType == "audio/mpeg") return "mp3";
    if (pMimeType == "audio/x-wav") return "wav";
    if (pMimeType == "image/x-portable-bitmap") return "pbm";
    if (pMimeType == "image/x-cmu-raster") return "ras";
    if (pMimeType == "text/plain") return "txt";
    if (pMimeType == "image/x-xpixmap") return "xpm";
    if (pMimeType == "audio/x-pn-realaudio") return "ram";
    if (pMimeType == "application/x-iwork-numbers-sffnumbers") return "numbers";
    if (pMimeType == "audio/basic") return "snd";
    if (pMimeType == "application/zip") return "zip";
    if (pMimeType == "application/x-iwork-pages-sffpages") return "pages";
    if (pMimeType == "video/x-sgi-movie") return "movie";
    if (pMimeType == "image/x-xwindowdump") return "xwd";
    if (pMimeType == "image/x-portable-anymap") return "pnm";
    if (pMimeType == "image/cis-cod") return "cod";
    if (pMimeType == "application/msword") return "doc";
    if (pMimeType == "text/html") return "html";
    if (pMimeType == "audio/mid") return "mid";
    if (pMimeType == "image/jpeg") return "jpeg";
    if (pMimeType == "image/png") return "png";
    if (pMimeType == "image/bmp") return "bmp";
    if (pMimeType == "image/tiff") return "tiff";
    if (pMimeType == "image/gif") return "gif";
    if (pMimeType == "image/svg+xml") return "svg";
    if (pMimeType == "application/pdf") return "pdf";
    if (pMimeType == "video/quicktime") return "mov";
    if (pMimeType == "video/mpeg") return "mpg";
    if (pMimeType == "video/mp4") return "mp4";
    if (pMimeType == "video/x-ms-asf") return "asf";
    if (pMimeType == "video/x-ms-wmv") return "wmv";
    if (pMimeType == "video/x-ms-wvx") return "wvx";
    if (pMimeType == "video/x-ms-wm") return "wm";
    if (pMimeType == "video/x-ms-wmx") return "wmx";
    if (pMimeType == "video/x-msvideo") return "avi";
    if (pMimeType == "video/ogg") return "ogv";
    if (pMimeType == "video/x-flv") return "flv";
    if (pMimeType == "video/x-m4v") return "m4v";
    if (pMimeType == "application/widget") return "wgt";
    if (pMimeType == "application/vnd.apple-widget") return "wdgt"; //mime type invented by us :-(
    if (pMimeType == "application/x-shockwave-flash") return "swf";

    return "";

}


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
UBMimeType::Enum UBFileSystemUtils::mimeTypeFromString(const QString& typeString)
{
    UBMimeType::Enum type = UBMimeType::UNKNOWN;

    if (typeString == "image/jpeg"
        || typeString == "image/png"
        || typeString == "image/gif"
        || typeString == "image/tiff"
        || typeString == "image/bmp")
    {
        type = UBMimeType::RasterImage;
    }
    else if (typeString == "image/svg+xml")
    {
        type = UBMimeType::VectorImage;
    }
    else if (typeString == "application/vnd.apple-widget")
    {
        type = UBMimeType::AppleWidget;
    }
    else if (typeString == "application/widget")
    {
        type = UBMimeType::W3CWidget;
    }
    else if (typeString.startsWith("video/"))
    {
        type = UBMimeType::Video;
    }
    else if (typeString.startsWith("audio/"))
    {
        type = UBMimeType::Audio;
    }
    else if (typeString.startsWith("application/x-shockwave-flash"))
    {
        type = UBMimeType::Flash;
    }
    else if (typeString.startsWith("application/pdf"))
    {
        type = UBMimeType::PDF;
    }
597
   /* else if (typeString.startsWith("application/vnd.mnemis-uniboard-tool"))
598 599
    {
        type = UBMimeType::UniboardTool;
600
    } */
601

602 603 604 605
    else if (typeString.startsWith("application/openboard-tool"))
    {
        type = UBMimeType::OpenboardTool;
    }
606
    return type;
607

608 609 610 611 612 613 614
}

UBMimeType::Enum UBFileSystemUtils::mimeTypeFromUrl(const QUrl& url)
{
    return mimeTypeFromString(mimeTypeFromFileName(url.toString()));
}

Claudio Valerio's avatar
Claudio Valerio committed
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
QString UBFileSystemUtils::getFirstExistingFileFromList(const QString& path, const QStringList& files)
{

    QString fullpath = path;

    if (!path.endsWith("/"))
    {
        fullpath += "/";
    }

    foreach(QString filename, files)
    {
        QFile file;

        file.setFileName(fullpath + filename);

        if (file.exists())
        {
            return fullpath + filename;
        }
    }

    return "";

}


642
bool UBFileSystemUtils::compressDirInZip(const QDir& pDir, const QString& pDestPath, QuaZipFile *pOutZipFile, bool pRootDocumentFolder, UBProcessingProgressListener* progressListener)
Claudio Valerio's avatar
Claudio Valerio committed
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
{
    QFileInfoList files = pDir.entryInfoList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);

    QStringList filters;
    filters << "*.svg";
    QFileInfoList pageFiles = pDir.entryInfoList(filters);

    foreach (QFileInfo file, files)
    {
        if (file.isDir())
        {
            QDir dir(file.absoluteFilePath());
            if (!compressDirInZip(dir, pDestPath + dir.dirName() + "/" , pOutZipFile, false))
            {
                return false;
            }
        }

        if (file.isFile())
        {
            QString objectType;
            if (pRootDocumentFolder)
            {
                objectType = "Page";
            }
            else
            {
                objectType = pDir.dirName();
            }

            if (!pRootDocumentFolder)
            {
                if (progressListener)
                    progressListener->processing(objectType, files.indexOf(file), files.size());
            }
            // we ignore thumbnails message because it is very fast.
            else if (progressListener && file.suffix() == "svg")
            {
                progressListener->processing(objectType, pageFiles.indexOf(file), pageFiles.size());
            }

            QFile inFile(file.absoluteFilePath());
            if(!inFile.open(QIODevice::ReadOnly))
            {
                qWarning() << "Compression of file" << inFile.fileName() << " failed. Cause: inFile.open(): " << inFile.errorString();
                return false;
            }

            qDebug() << "will open" << pDestPath << file.fileName() << inFile.fileName();

            if(!pOutZipFile->open(QIODevice::WriteOnly, QuaZipNewInfo(pDestPath + file.fileName(), inFile.fileName())))
            {
                qWarning() << "Compression of file" << inFile.fileName() << " failed. Cause: outFile.open(): " << pOutZipFile->getZipError();
                inFile.close();
                return false;
            }

            pOutZipFile->write(inFile.readAll());
            if(pOutZipFile->getZipError() != UNZ_OK)
            {
                qWarning() << "Compression of file" << inFile.fileName() << " failed. Cause: outFile.write(): " << pOutZipFile->getZipError();

                inFile.close();
                pOutZipFile->close();
                return false;
            }

            pOutZipFile->close();
            if(pOutZipFile->getZipError() != UNZ_OK)
            {
                qWarning() << "Compression of file" << inFile.fileName() << " failed. Cause: outFile.close(): " << pOutZipFile->getZipError();

                inFile.close();
                return false;
            }

            inFile.close();
        }
    }

    return true;
}



bool UBFileSystemUtils::expandZipToDir(const QFile& pZipFile, const QDir& pTargetDir)
{
    QuaZip zip(pZipFile.fileName());

    if(!zip.open(QuaZip::mdUnzip))
    {
        qWarning() << "ZIP expand failed. Cause zip.open(): " << zip.getZipError();
        return false;
    }

    zip.setFileNameCodec("UTF-8");
    QuaZipFileInfo info;
    QuaZipFile file(&zip);

    QString documentRootFolder = pTargetDir.absolutePath();

    if(!pTargetDir.exists())
        pTargetDir.mkpath(documentRootFolder);

    QFile out;
    char c;
    for(bool more = zip.goToFirstFile(); more; more = zip.goToNextFile())
    {
        if(!zip.getCurrentFileInfo(&info))
        {
            //TOD UB 4.3 O display error to user or use crash reporter
            qWarning() << "ZIP expand failed. Cause: getCurrentFileInfo(): " << zip.getZipError();
            return false;
        }

        if(!file.open(QIODevice::ReadOnly))
        {
            qWarning() << "ZIP expand failed. Cause: file.open(): " << zip.getZipError();
            return false;
        }

        if(file.getZipError()!= UNZ_OK)
        {
            qWarning() << "ZIP expand failed. Cause: file.getFileName(): " << zip.getZipError();
            return false;
        }

        QString newFileName = documentRootFolder + "/" + file.getActualFileName();
        QFileInfo newFileInfo(newFileName);
        QDir root(documentRootFolder);
        root.mkpath(newFileInfo.absolutePath());

        out.setFileName(newFileName);
        out.open(QIODevice::WriteOnly);

        // Slow like hell (on GNU/Linux at least), but it is not my fault.
        // Not ZIP/UNZIP package's fault either.
        // The slowest thing here is out.putChar(c).
        QByteArray outFileContent = file.readAll();
        if (out.write(outFileContent) == -1)
        {
            // qWarning() << "ZIP expand failed. Cause: Unable to write file";
            // this may happen if we are decompressing a directory
        }

        while(file.getChar(&c))
            out.putChar(c);

        out.close();

        if(file.getZipError()!= UNZ_OK)
        {
            qWarning() << "ZIP expand failed. Cause: " << zip.getZipError();
            return false;
        }

        if(!file.atEnd())
        {
            qWarning() << "ZIP expand failed. Cause: read all but not EOF";
            return false;
        }

        file.close();

        if(file.getZipError()!= UNZ_OK)
        {
            qWarning() << "ZIP expand failed. Cause: file.close(): " <<  file.getZipError();
            return false;
        }

    }

    zip.close();

    if(zip.getZipError()!= UNZ_OK)
    {
      qWarning() << "ZIP expand failed. Cause: zip.close(): " << zip.getZipError();
      return false;
    }

    return true;
}


QString UBFileSystemUtils::md5InHex(const QByteArray &pByteArray)
{
    MD5_CTX ctx;
    MD5_Init(&ctx);
    MD5_Update(&ctx, pByteArray.data(), pByteArray.size());

    unsigned char result[16];
    MD5_Final(result, &ctx);

    return QString(QByteArray((char *)result, 16).toHex());
}

QString UBFileSystemUtils::md5(const QByteArray &pByteArray)
{
    MD5_CTX ctx;
    MD5_Init(&ctx);
    MD5_Update(&ctx, pByteArray.data(), pByteArray.size());

    unsigned char result[16];
    MD5_Final(result, &ctx);
    QString s;

    for(int i = 0; i < 16; i++)
    {
        s += QChar(result[i]);
    }

    return s;
}

QString UBFileSystemUtils::readTextFile(QString path)
{
    QFile file(path);

    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream in(&file);
        return in.readAll();
    }

    return "";
Claudio Valerio's avatar
Claudio Valerio committed
868
}