File indexing completed on 2024-05-12 04:58:51

0001 /*
0002  * SPDX-FileCopyrightText: 2016 Saikrishna Arcot <saiarcot895@gmail.com>
0003  * SPDX-FileCopyrightText: 2018 Matthijs TIjink <matthijstijink@gmail.com>
0004  *
0005  * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0006  */
0007 
0008 #include "bluetoothuploadjob.h"
0009 #include "connectionmultiplexer.h"
0010 #include "multiplexchannel.h"
0011 
0012 #include "core_debug.h"
0013 #include <QBluetoothSocket>
0014 #include <QCoreApplication>
0015 
0016 BluetoothUploadJob::BluetoothUploadJob(const QSharedPointer<QIODevice> &data, ConnectionMultiplexer *connection, QObject *parent)
0017     : QObject(parent)
0018     , mData(data)
0019     , mTransferUuid(connection->newChannel())
0020 {
0021     mSocket = QSharedPointer<MultiplexChannel>{connection->getChannel(mTransferUuid).release()};
0022 }
0023 
0024 QVariantMap BluetoothUploadJob::transferInfo() const
0025 {
0026     QVariantMap ret;
0027     ret[QStringLiteral("uuid")] = mTransferUuid.toString().mid(1, 36);
0028     return ret;
0029 }
0030 
0031 void BluetoothUploadJob::start()
0032 {
0033     if (!mData->open(QIODevice::ReadOnly)) {
0034         qCWarning(KDECONNECT_CORE) << "error when opening the input to upload";
0035         return; // TODO: Handle error, clean up...
0036     }
0037     connect(mSocket.data(), &MultiplexChannel::bytesWritten, this, &BluetoothUploadJob::writeSome);
0038     connect(mSocket.data(), &MultiplexChannel::aboutToClose, this, &BluetoothUploadJob::closeConnection);
0039     writeSome();
0040 }
0041 
0042 void BluetoothUploadJob::writeSome()
0043 {
0044     bool errorOccurred = false;
0045     while (mSocket->bytesToWrite() == 0 && mData->bytesAvailable() && mSocket->isWritable()) {
0046         qint64 bytes = qMin<qint64>(mData->bytesAvailable(), 4096);
0047         int bytesWritten = mSocket->write(mData->read(bytes));
0048 
0049         if (bytesWritten < 0) {
0050             qCWarning(KDECONNECT_CORE) << "error when writing data to bluetooth upload" << bytes << mData->bytesAvailable();
0051             errorOccurred = true;
0052             break;
0053         }
0054     }
0055 
0056     if (mData->atEnd() || errorOccurred) {
0057         mData->close();
0058         mSocket->close();
0059     }
0060 }
0061 
0062 void BluetoothUploadJob::closeConnection()
0063 {
0064     mData->close();
0065     deleteLater();
0066 }
0067 
0068 #include "moc_bluetoothuploadjob.cpp"