File: FileSource.cpp

package info (click to toggle)
sonic-visualiser 5.2.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 24,744 kB
  • sloc: cpp: 158,888; ansic: 11,920; sh: 1,785; makefile: 517; xml: 64; perl: 31
file content (978 lines) | stat: -rw-r--r-- 26,251 bytes parent folder | download | duplicates (2)
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
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */

/*
    Sonic Visualiser
    An audio file viewer and annotation editor.
    Centre for Digital Music, Queen Mary, University of London.
    This file copyright 2007 QMUL.
    
    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.  See the file
    COPYING included with this distribution for more information.
*/

#include "FileSource.h"

#include "base/TempDirectory.h"
#include "base/Exceptions.h"
#include "base/ProgressReporter.h"
#include "system/System.h"

#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QFileInfo>
#include <QDir>
#include <QCoreApplication>
#include <QThreadStorage>
#include <QRegularExpression>

#include <iostream>
#include <cstdlib>

//#define DEBUG_FILE_SOURCE 1

namespace sv {

int
FileSource::m_count = 0;

QMutex
FileSource::m_fileCreationMutex;

FileSource::RemoteRefCountMap
FileSource::m_refCountMap;

FileSource::RemoteLocalMap
FileSource::m_remoteLocalMap;

QMutex
FileSource::m_mapMutex;

#ifdef DEBUG_FILE_SOURCE
static int extantCount = 0;
static int threadCount = 0;
static std::map<QString, int> urlExtantCountMap;
static QMutex countMutex;
static void incCount(QString url) {
    QMutexLocker locker(&countMutex);
    ++extantCount;
    if (urlExtantCountMap.find(url) == urlExtantCountMap.end()) {
        urlExtantCountMap[url] = 1;
    } else {
        ++urlExtantCountMap[url];
    }
    SVCERR << "FileSource: Now " << urlExtantCountMap[url] << " for this url, " << extantCount << " total" << endl;
}
static void decCount(QString url) {
    QMutexLocker locker(&countMutex);
    --extantCount;
    --urlExtantCountMap[url];
    SVCERR << "FileSource: Now " << urlExtantCountMap[url] << " for this url, " << extantCount << " total" << endl;
}
void
FileSource::debugReport()
{
    QMutexLocker locker(&countMutex);
    SVCERR << "\nFileSource::debugReport: Have " << extantCount << " FileSource object(s) extant across " << threadCount << " thread(s)" << endl;
    SVCERR << "URLs by extant count:" << endl;
    SVCERR << "Count | URL" << endl;
    for (std::map<QString, int>::const_iterator i = urlExtantCountMap.begin();
         i != urlExtantCountMap.end(); ++i) {
        SVCERR << i->second << " | " << i->first << endl;
    }
    SVCERR << "FileSource::debugReport done\n" << endl;
}
#else
void FileSource::debugReport() { }
#endif

static QThreadStorage<QNetworkAccessManager *> nms;

FileSource::FileSource(QString fileOrUrl, ProgressReporter *reporter,
                       QString preferredContentType) :
    m_rawFileOrUrl(fileOrUrl),
    m_url(fileOrUrl, QUrl::StrictMode),
    m_localFile(nullptr),
    m_reply(nullptr),
    m_preferredContentType(preferredContentType),
    m_ok(false),
    m_cancelled(false),
    m_lastStatus(0),
    m_resource(fileOrUrl.startsWith(':')),
    m_remote(isRemote(fileOrUrl)),
    m_done(false),
    m_leaveLocalFile(false),
    m_reporter(reporter),
    m_refCounted(false)
{
    if (m_resource) { // qrc file
        m_url = QUrl("qrc" + fileOrUrl);
    }

    if (m_url.toString() == "") {
        m_url = QUrl(fileOrUrl, QUrl::TolerantMode);
    }
 
#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::FileSource(" << fileOrUrl << "): url <" << m_url.toString() << ">" << endl;
    incCount(m_url.toString());
#endif

    if (!canHandleScheme(m_url)) {
        SVCERR << "FileSource::FileSource: ERROR: Unsupported scheme in URL \"" << m_url.toString() << "\"" << endl;
        m_errorString = tr("Unsupported scheme in URL");
        return;
    }

    init();

    if (!isRemote() &&
        !isAvailable()) {
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::FileSource: Failed to open local file with URL \"" << m_url.toString() << "\"; trying again assuming filename was encoded" << endl;
#endif
        m_url = QUrl::fromEncoded(fileOrUrl.toLatin1());
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::FileSource: URL is now \"" << m_url.toString() << "\"" << endl;
#endif
        init();
    }

    if (isRemote() &&
        (fileOrUrl.contains('%') ||
         fileOrUrl.contains("--"))) { // for IDNA

        waitForStatus();

        if (!isAvailable()) {

            // The URL was created on the assumption that the string
            // was human-readable.  Let's try again, this time
            // assuming it was already encoded.
            SVCERR << "FileSource::FileSource: Failed to retrieve URL \""
                      << fileOrUrl 
                      << "\" as human-readable URL; "
                      << "trying again treating it as encoded URL"
                      << endl;

            // even though our cache file doesn't exist (because the
            // resource was 404), we still need to ensure we're no
            // longer associating a filename with this url in the
            // refcount map -- or createCacheFile will think we've
            // already done all the work and no request will be sent
            deleteCacheFile();

            m_url = QUrl::fromEncoded(fileOrUrl.toLatin1());

            m_ok = false;
            m_done = false;
            m_lastStatus = 0;
            init();
        }
    }

    if (!isRemote()) {
        emit statusAvailable();
        emit ready();
    }

#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::FileSource(string) exiting" << endl;
#endif
}

FileSource::FileSource(QUrl url, ProgressReporter *reporter) :
    m_url(url),
    m_localFile(nullptr),
    m_reply(nullptr),
    m_ok(false),
    m_cancelled(false),
    m_lastStatus(0),
    m_resource(false),
    m_remote(isRemote(url.toString())),
    m_done(false),
    m_leaveLocalFile(false),
    m_reporter(reporter),
    m_refCounted(false)
{
#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::FileSource(" << url.toString() << ") [as url]" << endl;
    incCount(m_url.toString());
#endif

    if (!canHandleScheme(m_url)) {
        SVCERR << "FileSource::FileSource: ERROR: Unsupported scheme in URL \"" << m_url.toString() << "\"" << endl;
        m_errorString = tr("Unsupported scheme in URL");
        return;
    }

    init();

#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::FileSource(url) exiting" << endl;
#endif
}

FileSource::FileSource(const FileSource &rf) :
    QObject(),
    m_url(rf.m_url),
    m_localFile(nullptr),
    m_reply(nullptr),
    m_ok(rf.m_ok),
    m_cancelled(rf.m_cancelled),
    m_lastStatus(rf.m_lastStatus),
    m_resource(rf.m_resource),
    m_remote(rf.m_remote),
    m_done(false),
    m_leaveLocalFile(false),
    m_reporter(rf.m_reporter),
    m_refCounted(false)
{
#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::FileSource(" << m_url.toString() << ") [copy ctor]" << endl;
    incCount(m_url.toString());
#endif

    if (!canHandleScheme(m_url)) {
        SVCERR << "FileSource::FileSource: ERROR: Unsupported scheme in URL \"" << m_url.toString() << "\"" << endl;
        m_errorString = tr("Unsupported scheme in URL");
        return;
    }

    if (!isRemote()) {
        m_localFilename = rf.m_localFilename;
    } else {
        QMutexLocker locker(&m_mapMutex);
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::FileSource(copy ctor): ref count is "
                  << m_refCountMap[m_url] << endl;
#endif
        if (m_refCountMap[m_url] > 0) {
            m_refCountMap[m_url]++;
#ifdef DEBUG_FILE_SOURCE
            SVCERR << "raised it to " << m_refCountMap[m_url] << endl;
#endif
            m_localFilename = m_remoteLocalMap[m_url];
            m_refCounted = true;
        } else {
            m_ok = false;
            m_lastStatus = 404;
        }
    }

    m_done = true;

#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::FileSource(" << m_url.toString() << ") [copy ctor]: note: local filename is \"" << m_localFilename << "\"" << endl;
#endif

#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::FileSource(copy ctor) exiting" << endl;
#endif
}

FileSource::~FileSource()
{
#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource(" << m_url.toString() << ")::~FileSource" << endl;
    decCount(m_url.toString());
#endif

    cleanup();

    if (isRemote() && !m_leaveLocalFile) deleteCacheFile();
}

void
FileSource::init()
{
    if (isResource()) {
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::init: Is a resource" << endl;
#endif
        QString resourceFile = m_url.toString();
        resourceFile.replace(QRegularExpression("^qrc:"), ":");
        
        if (!QFileInfo(resourceFile).exists()) {
#ifdef DEBUG_FILE_SOURCE
            SVCERR << "FileSource::init: Resource file of this name does not exist, switching to non-resource URL" << endl;
#endif
            m_url = resourceFile;
            m_resource = false;
        }
    }

    if (!isRemote() && !isResource()) {
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::init: Not a remote URL" << endl;
#endif
        bool literal = false;
        m_localFilename = m_url.toLocalFile();

        if (m_localFilename == "") {
            // QUrl may have mishandled the scheme (e.g. in a DOS path)
            m_localFilename = m_rawFileOrUrl;
#ifdef DEBUG_FILE_SOURCE
            SVCERR << "FileSource::init: Trying literal local filename \""
                      << m_localFilename << "\"" << endl;
#endif
            literal = true;
        }
        m_localFilename = QFileInfo(m_localFilename).absoluteFilePath();

#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::init: URL translates to absolute filename \""
                  << m_localFilename << "\" (with literal=" << literal << ")"
                  << endl;
#endif
        m_ok = true;
        m_lastStatus = 200;

        if (!QFileInfo(m_localFilename).exists()) {
            if (literal) {
                m_lastStatus = 404;
            } else {
#ifdef DEBUG_FILE_SOURCE
                SVCERR << "FileSource::init: Local file of this name does not exist, trying URL as a literal filename" << endl;
#endif
                // Again, QUrl may have been mistreating us --
                // e.g. dropping a part that looks like query data
                m_localFilename = m_rawFileOrUrl;
                literal = true;
                if (!QFileInfo(m_localFilename).exists()) {
                    m_lastStatus = 404;
                }
            }
        }

        m_done = true;
        return;
    }

    if (createCacheFile()) {
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::init: Already have this one" << endl;
#endif
        m_ok = true;
        if (!QFileInfo(m_localFilename).exists()) {
            m_lastStatus = 404;
        } else {
            m_lastStatus = 200;
        }
        m_done = true;
        return;
    }

    if (m_localFilename == "") return;

    m_localFile = new QFile(m_localFilename);
    m_localFile->open(QFile::WriteOnly);

    if (isResource()) {

        // Absent resource file case was dealt with at the top -- this
        // is the successful case

        QString resourceFileName = m_url.toString();
        resourceFileName.replace(QRegularExpression("^qrc:"), ":");
        QFile resourceFile(resourceFileName);
        resourceFile.open(QFile::ReadOnly);
        QByteArray ba(resourceFile.readAll());
        
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "Copying " << ba.size() << " bytes from resource file to cache file" << endl;
#endif

        qint64 written = m_localFile->write(ba);
        m_localFile->close();
        delete m_localFile;
        m_localFile = nullptr;

        if (written != ba.size()) {
#ifdef DEBUG_FILE_SOURCE
            SVCERR << "Copy failed (wrote " << written << " bytes)" << endl;
#endif
            m_ok = false;
            return;
        } else {
            m_ok = true;
            m_lastStatus = 200;
            m_done = true;
        }

    } else {

        QString scheme = m_url.scheme().toLower();

#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::init: Don't have local copy of \""
                  << m_url.toString() << "\", retrieving" << endl;
#endif

        if (scheme == "http" || scheme == "https" || scheme == "ftp") {
            initRemote();
#ifdef DEBUG_FILE_SOURCE
            SVCERR << "FileSource: initRemote returned" << endl;
#endif
        } else {
            m_remote = false;
            m_ok = false;
        }
    }

    if (m_ok) {
        
        QMutexLocker locker(&m_mapMutex);

        if (m_refCountMap[m_url] > 0) {
            // someone else has been doing the same thing at the same time,
            // but has got there first
            cleanup();
            m_refCountMap[m_url]++;
#ifdef DEBUG_FILE_SOURCE
            SVCERR << "FileSource::init: Another FileSource has got there first, abandoning our download and using theirs" << endl;
#endif
            m_localFilename = m_remoteLocalMap[m_url];
            m_refCounted = true;
            m_ok = true;
            if (!QFileInfo(m_localFilename).exists()) {
                m_lastStatus = 404;
            }
            m_done = true;
            return;
        }

        m_remoteLocalMap[m_url] = m_localFilename;
        m_refCountMap[m_url]++;
        m_refCounted = true;

        if (m_reporter && !m_done) {
            m_reporter->setMessage
                (tr("Downloading %1...").arg(m_url.toString()));
            connect(m_reporter, SIGNAL(cancelled()), this, SLOT(cancelled()));
            connect(this, SIGNAL(progress(int)),
                    m_reporter, SLOT(setProgress(int)));
        }
    }
}

void
FileSource::initRemote()
{
    m_ok = true;

    QNetworkRequest req;
    req.setUrl(m_url);
    
    if (m_preferredContentType != "") {
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource: indicating preferred content type of \""
                  << m_preferredContentType << "\"" << endl;
#endif
        req.setRawHeader
            ("Accept",
             QString("%1, */*").arg(m_preferredContentType).toLatin1());
    }

    { // check we have a QNetworkAccessManager
        QMutexLocker locker(&m_mapMutex);
        if (!nms.hasLocalData()) {
#ifdef DEBUG_FILE_SOURCE
            ++threadCount;
#endif
            nms.setLocalData(new QNetworkAccessManager());
        }
    }

    m_reply = nms.localData()->get(req);

    connect(m_reply, SIGNAL(readyRead()),
            this, SLOT(readyRead()));
    connect(m_reply, SIGNAL(errorOccurred(QNetworkReply::NetworkError)),
            this, SLOT(replyFailed(QNetworkReply::NetworkError)));
    connect(m_reply, SIGNAL(finished()),
            this, SLOT(replyFinished()));
    connect(m_reply, SIGNAL(metaDataChanged()),
            this, SLOT(metaDataChanged()));
    connect(m_reply, SIGNAL(downloadProgress(qint64, qint64)),
            this, SLOT(downloadProgress(qint64, qint64)));
}

void
FileSource::cleanup()
{
    if (m_done) {
        delete m_localFile; // does not actually delete the file
        m_localFile = nullptr;
    }
    m_done = true;
    if (m_reply) {
        QNetworkReply *r = m_reply;
        disconnect(r, nullptr, this, nullptr);
        m_reply = nullptr;
        // Can only call abort() when there are no errors.
        if (r->error() == QNetworkReply::NoError) {
            r->abort();
        }
        r->deleteLater();
    }
    if (m_localFile) {
        delete m_localFile; // does not actually delete the file
        m_localFile = nullptr;
    }
}

bool
FileSource::isRemote(QString fileOrUrl)
{
    // Note that a "scheme" with length 1 is probably a DOS drive letter
    QString scheme = QUrl(fileOrUrl).scheme().toLower();
    if (scheme == "" || scheme == "file" || scheme.length() == 1) return false;
    return true;
}

bool
FileSource::canHandleScheme(QUrl url)
{
    // Note that a "scheme" with length 1 is probably a DOS drive letter
    QString scheme = url.scheme().toLower();
    return (scheme == "http" || scheme == "https" ||
            scheme == "ftp" || scheme == "file" || scheme == "qrc" ||
            scheme == "" || scheme.length() == 1);
}

bool
FileSource::isAvailable()
{
    waitForStatus();
    bool available = true;
    if (!m_ok) {
        available = false;
    } else {
        // http 2xx status codes mean success
        available = (m_lastStatus / 100 == 2);
    }
#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::isAvailable: " << (available ? "yes" : "no") << endl;
#endif
    return available;
}

void
FileSource::waitForStatus()
{
    while (m_ok && (!m_done && m_lastStatus == 0)) {
//        SVCERR << "waitForStatus: processing (last status " << m_lastStatus << ")" << endl;
        QCoreApplication::processEvents();
    }
}

void
FileSource::waitForData()
{
    while (m_ok && !m_done) {
//        SVCERR << "FileSource::waitForData: calling QApplication::processEvents" << endl;
        QCoreApplication::processEvents();
        usleep(10000);
    }
}

void
FileSource::setLeaveLocalFile(bool leave)
{
    m_leaveLocalFile = leave;
}

bool
FileSource::isOK() const
{
    return m_ok;
}

bool
FileSource::isDone() const
{
    return m_done;
}

bool
FileSource::wasCancelled() const
{
    return m_cancelled;
}

bool
FileSource::isResource() const
{
    return m_resource;
}

bool
FileSource::isRemote() const
{
    return m_remote;
}

QString
FileSource::getLocation() const
{
    return m_url.toString();
}

QString
FileSource::getLocalFilename() const
{
    return m_localFilename;
}

QString
FileSource::getBasename() const
{
    return QFileInfo(m_localFilename).fileName();
}

QString
FileSource::getContentType() const
{
    return m_contentType;
}

QString
FileSource::getExtension() const
{
    if (m_localFilename != "") {
        return QFileInfo(m_localFilename).suffix().toLower();
    } else {
        return QFileInfo(m_url.toLocalFile()).suffix().toLower();
    }
}

QString
FileSource::getErrorString() const
{
    return m_errorString;
}

void
FileSource::readyRead()
{
    m_localFile->write(m_reply->readAll());
}

void
FileSource::metaDataChanged()
{
#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::metaDataChanged" << endl;
#endif

    if (!m_reply) {
        SVCERR << "WARNING: FileSource::metaDataChanged() called without a reply object being known to us" << endl;
        return;
    }

    // Handle http transfer status codes.

    int status =
        m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    // If this is a redirection (3xx) code, do the redirect
    if (status / 100 == 3) {
        QString location = m_reply->header
            (QNetworkRequest::LocationHeader).toString();
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::metaDataChanged: redirect to \""
                  << location << "\" received" << endl;
#endif
        if (location != "") {
            QUrl newUrl(location);
            if (newUrl != m_url) {
                cleanup();
                deleteCacheFile();
#ifdef DEBUG_FILE_SOURCE
                decCount(m_url.toString());
                incCount(newUrl.toString());
#endif
                m_url = newUrl;
                m_localFile = nullptr;
                m_lastStatus = 0;
                m_done = false;
                m_refCounted = false;
                init();
                return;
            }
        }
    }

    m_lastStatus = status;

    // 400 and up are failures, get the error string
    if (m_lastStatus / 100 >= 4) {
        m_errorString = QString("%1 %2")
            .arg(status)
            .arg(m_reply->attribute
                 (QNetworkRequest::HttpReasonPhraseAttribute).toString());
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::metaDataChanged: "
                  << m_errorString << endl;
#endif
    } else {
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::metaDataChanged: "
                  << m_lastStatus << endl;
#endif
        m_contentType =
            m_reply->header(QNetworkRequest::ContentTypeHeader).toString();
    }
    emit statusAvailable();
}

void
FileSource::downloadProgress(qint64 done, qint64 total)
{
    int percent = int((double(done) / double(total)) * 100.0 - 0.1);
    emit progress(percent);
}

void
FileSource::cancelled()
{
    m_done = true;
    cleanup();

    m_ok = false;
    m_cancelled = true;
    m_errorString = tr("Download cancelled");
}

void
FileSource::replyFinished()
{
    emit progress(100);

#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::replyFinished()" << endl;
#endif

    if (m_done) return;

    QString scheme = m_url.scheme().toLower();
    // For ftp transfers, replyFinished() will be called on success.
    // metaDataChanged() is never called for ftp transfers.
    if (scheme == "ftp") {
        m_lastStatus = 200;  // http ok
    }

    bool error = (m_lastStatus / 100 >= 4);

    cleanup();

    if (!error) {
        QFileInfo fi(m_localFilename);
        if (!fi.exists()) {
            m_errorString = tr("Failed to create local file %1").arg(m_localFilename);
            error = true;
        } else if (fi.size() == 0) {
            m_errorString = tr("File contains no data!");
            error = true;
        }
    }

    if (error) {
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::done: error is " << error << ", deleting cache file" << endl;
#endif
        deleteCacheFile();
    }

    m_ok = !error;
    if (m_localFile) m_localFile->flush();
    m_done = true;
    emit ready();
}

void
FileSource::replyFailed(QNetworkReply::NetworkError)
{
    emit progress(100);
    if (!m_reply) {
        SVCERR << "WARNING: FileSource::replyFailed() called without a reply object being known to us" << endl;
    } else {
        m_errorString = m_reply->errorString();
    }
    m_ok = false;
    m_done = true;
    cleanup();
    emit ready();
}

void
FileSource::deleteCacheFile()
{
#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::deleteCacheFile(\"" << m_localFilename << "\")" << endl;
#endif

    cleanup();

    if (m_localFilename == "") {
        return;
    }

    if (!isRemote()) {
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "not a cache file" << endl;
#endif
        return;
    }

    if (m_refCounted) {

        QMutexLocker locker(&m_mapMutex);
        m_refCounted = false;

        if (m_refCountMap[m_url] > 0) {
            m_refCountMap[m_url]--;
#ifdef DEBUG_FILE_SOURCE
            SVCERR << "reduced ref count to " << m_refCountMap[m_url] << endl;
#endif
            if (m_refCountMap[m_url] > 0) {
                m_done = true;
                return;
            }
        }
    }

    m_fileCreationMutex.lock();

    if (!QFile(m_localFilename).remove()) {
#ifdef DEBUG_FILE_SOURCE
        SVCERR
#else
        SVDEBUG
#endif
            << "FileSource::deleteCacheFile: ERROR: Failed to delete file \"" << m_localFilename << "\"" << endl;
    } else {
#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::deleteCacheFile: Deleted cache file \"" << m_localFilename << "\"" << endl;
#endif
        m_localFilename = "";
    }

    m_fileCreationMutex.unlock();

    m_done = true;
}

bool
FileSource::createCacheFile()
{
    {
        QMutexLocker locker(&m_mapMutex);

#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::createCacheFile: refcount is " << m_refCountMap[m_url] << endl;
#endif

        if (m_refCountMap[m_url] > 0) {
            m_refCountMap[m_url]++;
            m_localFilename = m_remoteLocalMap[m_url];
#ifdef DEBUG_FILE_SOURCE
            SVCERR << "raised it to " << m_refCountMap[m_url] << endl;
#endif
            m_refCounted = true;
            return true;
        }
    }

    QDir dir;
    try {
        dir.setPath(TempDirectory::getInstance()->
                    getSubDirectoryPath("download"));
    } catch (const DirectoryCreationFailed &f) {
#ifdef DEBUG_FILE_SOURCE
        SVCERR 
#else
        SVDEBUG
#endif
            << "FileSource::createCacheFile: ERROR: Failed to create temporary directory: " << f.what() << endl;
        return false;
    }

    QString filepart = m_url.path().section('/', -1, -1,
                                            QString::SectionSkipEmpty);

    QString extension = "";
    if (filepart.contains('.')) extension = filepart.section('.', -1);

    QString base = filepart;
    if (extension != "") {
        base = base.left(base.length() - extension.length() - 1);
    }
    if (base == "") base = "remote";

    QString filename;

    if (extension == "") {
        filename = base;
    } else {
        filename = QString("%1.%2").arg(base).arg(extension);
    }

    QString filepath(dir.filePath(filename));

#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::createCacheFile: URL is \"" << m_url.toString() << "\", dir is \"" << dir.path() << "\", base \"" << base << "\", extension \"" << extension << "\", filebase \"" << filename << "\", filename \"" << filepath << "\"" << endl;
#endif

    QMutexLocker fcLocker(&m_fileCreationMutex);

    ++m_count;

    if (QFileInfo(filepath).exists() ||
        !QFile(filepath).open(QFile::WriteOnly)) {

#ifdef DEBUG_FILE_SOURCE
        SVCERR << "FileSource::createCacheFile: Failed to create local file \""
                  << filepath << "\" for URL \""
                  << m_url.toString() << "\" (or file already exists): appending suffix instead" << endl;
#endif

        if (extension == "") {
            filename = QString("%1_%2").arg(base).arg(m_count);
        } else {
            filename = QString("%1_%2.%3").arg(base).arg(m_count).arg(extension);
        }
        filepath = dir.filePath(filename);

        if (QFileInfo(filepath).exists() ||
            !QFile(filepath).open(QFile::WriteOnly)) {

#ifdef DEBUG_FILE_SOURCE
            SVCERR
#else
            SVDEBUG
#endif
                << "FileSource::createCacheFile: ERROR: Failed to create local file \""
                      << filepath << "\" for URL \""
                      << m_url.toString() << "\" (or file already exists)" << endl;

            return false;
        }
    }

#ifdef DEBUG_FILE_SOURCE
    SVCERR << "FileSource::createCacheFile: url "
              << m_url.toString() << " -> local filename "
              << filepath << endl;
#endif
    
    m_localFilename = filepath;

    return false;
}

} // end namespace sv