1/*
2 This file is part of the KDE libraries
3 SPDX-FileCopyrightText: 2020 Ahmad Samir <a.samirh78@gmail.com>
4
5 SPDX-License-Identifier: LGPL-2.0-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
6*/
7
8#include "namefinderjob.h"
9
10#include "../utils_p.h"
11#include "kiocoredebug.h"
12#include <KFileUtils>
13#include <KIO/StatJob>
14
15#include <QUrl>
16
17class KIO::NameFinderJobPrivate
18{
19public:
20 explicit NameFinderJobPrivate(const QUrl &baseUrl, const QString &name, NameFinderJob *qq)
21 : m_baseUrl(baseUrl)
22 , m_name(name)
23 , m_statJob(nullptr)
24 , q(qq)
25 {
26 }
27
28 QUrl m_baseUrl;
29 QString m_name;
30 QUrl m_finalUrl;
31 KIO::StatJob *m_statJob;
32 bool m_firstStat = true;
33
34 KIO::NameFinderJob *const q;
35
36 void statUrl();
37 void slotStatResult();
38};
39
40KIO::NameFinderJob::NameFinderJob(const QUrl &baseUrl, const QString &name, QObject *parent)
41 : KCompositeJob(parent)
42 , d(new NameFinderJobPrivate(baseUrl, name, this))
43{
44}
45
46KIO::NameFinderJob::~NameFinderJob()
47{
48}
49
50void KIO::NameFinderJob::start()
51{
52 if (!d->m_baseUrl.isValid() || d->m_baseUrl.scheme().isEmpty()) {
53 qCDebug(KIO_CORE) << "Malformed URL" << d->m_baseUrl;
54 setError(KIO::ERR_MALFORMED_URL);
55 emitResult();
56 return;
57 }
58
59 d->statUrl();
60}
61
62void KIO::NameFinderJobPrivate::statUrl()
63{
64 m_finalUrl = m_baseUrl;
65 m_finalUrl.setPath(path: Utils::concatPaths(path1: m_baseUrl.path(), path2: m_name));
66
67 m_statJob = KIO::stat(url: m_finalUrl,
68 side: KIO::StatJob::DestinationSide,
69 details: KIO::StatNoDetails, // Just checking if it exists
70 flags: KIO::HideProgressInfo);
71
72 QObject::connect(sender: m_statJob, signal: &KJob::result, context: q, slot: [this]() {
73 slotStatResult();
74 });
75}
76
77void KIO::NameFinderJobPrivate::slotStatResult()
78{
79 // m_statJob will resolve the url to the most local one in the first run
80 if (m_firstStat) {
81 m_finalUrl = m_statJob->mostLocalUrl();
82 m_firstStat = false;
83 }
84
85 // StripTrailingSlash so that fileName() doesn't return an empty string
86 m_finalUrl = m_finalUrl.adjusted(options: QUrl::StripTrailingSlash);
87 m_baseUrl = m_finalUrl.adjusted(options: QUrl::RemoveFilename);
88 m_name = m_finalUrl.fileName();
89
90 if (m_statJob->error()) { // Doesn't exist, we're done
91 q->emitResult();
92 } else { // Exists, create a new name, then stat again
93 m_name = KFileUtils::makeSuggestedName(oldName: m_name);
94 statUrl();
95 }
96}
97
98QUrl KIO::NameFinderJob::finalUrl() const
99{
100 return d->m_finalUrl;
101}
102
103QUrl KIO::NameFinderJob::baseUrl() const
104{
105 return d->m_baseUrl;
106}
107
108QString KIO::NameFinderJob::finalName() const
109{
110 return d->m_name;
111}
112
113#include "moc_namefinderjob.cpp"
114

source code of kio/src/core/namefinderjob.cpp