File indexing completed on 2024-12-22 04:40:14
0001 /* 0002 SPDX-FileCopyrightText: 2007-2009 Sergio Pistone <sergio_pistone@yahoo.com.ar> 0003 SPDX-FileCopyrightText: 2010-2022 Mladen Milinkovic <max@smoothware.net> 0004 0005 SPDX-License-Identifier: GPL-2.0-or-later 0006 */ 0007 0008 #include "filesavehelper.h" 0009 0010 #include <QDebug> 0011 #include <QSaveFile> 0012 #include <QTemporaryFile> 0013 #include <QFileDevice> 0014 0015 #include <kio_version.h> 0016 #include <kio/filecopyjob.h> 0017 #include <kio/statjob.h> 0018 0019 FileSaveHelper::FileSaveHelper(const QUrl &url, bool overwrite) : 0020 m_url(url), 0021 m_overwrite(overwrite), 0022 m_file(0) 0023 {} 0024 0025 FileSaveHelper::~FileSaveHelper() 0026 { 0027 if(m_file) 0028 close(); 0029 } 0030 0031 const QUrl & 0032 FileSaveHelper::url() 0033 { 0034 return m_url; 0035 } 0036 0037 bool 0038 FileSaveHelper::overwrite() 0039 { 0040 return m_overwrite; 0041 } 0042 0043 QFileDevice * 0044 FileSaveHelper::file() 0045 { 0046 return m_file; 0047 } 0048 0049 bool 0050 FileSaveHelper::open() 0051 { 0052 if(m_file) 0053 return false; 0054 0055 if(!m_overwrite && exists(m_url)) 0056 return false; 0057 0058 if(m_url.isLocalFile()) { 0059 m_file = new QSaveFile(m_url.toLocalFile()); 0060 if(!m_file->open(QIODevice::WriteOnly | QIODevice::Truncate)) { 0061 qDebug() << "Couldn't open output file" << m_file->fileName(); 0062 delete m_file; 0063 m_file = nullptr; 0064 return false; 0065 } 0066 } else { 0067 m_file = new QTemporaryFile(); 0068 if(!static_cast<QTemporaryFile *>(m_file)->open()) { 0069 qDebug() << "Couldn't open output file" << m_file->fileName(); 0070 delete m_file; 0071 m_file = nullptr; 0072 return false; 0073 } 0074 } 0075 return true; 0076 } 0077 0078 bool 0079 FileSaveHelper::close() 0080 { 0081 if(!m_file) 0082 return false; 0083 0084 if(m_url.isLocalFile()) { 0085 static_cast<QSaveFile*>(m_file)->commit(); 0086 delete m_file; 0087 m_file = nullptr; 0088 return true; 0089 } else { 0090 m_file->close(); 0091 KIO::Job *job = KIO::file_copy(QUrl::fromLocalFile(m_file->fileName()), m_url, -1, m_overwrite ? KIO::Overwrite : KIO::DefaultFlags); 0092 bool success = job->exec(); 0093 delete m_file; 0094 m_file = nullptr; 0095 0096 return success; 0097 } 0098 } 0099 0100 bool 0101 FileSaveHelper::exists(const QUrl &url) 0102 { 0103 #if KIO_VERSION < QT_VERSION_CHECK(5, 69, 0) 0104 KIO::Job *job = KIO::stat(url, KIO::StatJob::DestinationSide, 2); 0105 #else 0106 KIO::Job *job = KIO::statDetails(url, KIO::StatJob::DestinationSide, KIO::StatDefaultDetails, KIO::HideProgressInfo); 0107 #endif 0108 return job->exec(); 0109 }