File indexing completed on 2024-04-28 15:40:17
0001 // SPDX-FileCopyrightText: 2014-2022 The KPhotoAlbum Development Team 0002 // 0003 // SPDX-License-Identifier: GPL-2.0-or-later 0004 0005 #include "Server.h" 0006 0007 #include "RemoteCommand.h" 0008 0009 #include <KLocalizedString> 0010 #include <QMessageBox> 0011 #include <QTcpSocket> 0012 #include <QUdpSocket> 0013 0014 using namespace RemoteControl; 0015 0016 Server::Server(QObject *parent) 0017 : RemoteConnection(parent) 0018 { 0019 } 0020 0021 bool Server::isConnected() const 0022 { 0023 return m_isConnected; 0024 } 0025 0026 void Server::listen(QHostAddress address) 0027 { 0028 if (!m_socket) { 0029 m_socket = new QUdpSocket(this); 0030 bool ok = m_socket->bind(address, UDPPORT); 0031 if (!ok) { 0032 QMessageBox::critical(0, i18n("Unable to bind to socket"), 0033 i18n("Unable to listen for remote Android connections. " 0034 "This is likely because you have another KPhotoAlbum application running.")); 0035 } 0036 connect(m_socket, &QUdpSocket::readyRead, this, &Server::readIncommingUDP); 0037 } 0038 } 0039 0040 void Server::stopListening() 0041 { 0042 delete m_socket; 0043 m_socket = nullptr; 0044 delete m_tcpSocket; 0045 m_tcpSocket = nullptr; 0046 Q_EMIT stoppedListening(); 0047 } 0048 0049 QTcpSocket *Server::socket() 0050 { 0051 return m_tcpSocket; 0052 } 0053 0054 void Server::readIncommingUDP() 0055 { 0056 Q_ASSERT(m_socket->hasPendingDatagrams()); 0057 char data[1000]; 0058 0059 QHostAddress address; 0060 qint64 len = m_socket->readDatagram(data, 1000, &address); 0061 QString string = QString::fromUtf8(data).left(len); 0062 QStringList list = string.split(QChar::fromLatin1(' ')); 0063 if (list[0] != QString::fromUtf8("KPhotoAlbum")) { 0064 return; 0065 } 0066 if (list[1] != QString::number(RemoteControl::VERSION)) { 0067 QMessageBox::critical(0, i18n("Invalid Version"), 0068 i18n("Version mismatch between Remote Client and KPhotoAlbum on the desktop.\n" 0069 "Desktop protocol version: %1\n" 0070 "Remote Control protocol version: %2", 0071 RemoteControl::VERSION, 0072 list[1])); 0073 stopListening(); 0074 return; 0075 } 0076 0077 connectToTcpServer(address); 0078 } 0079 0080 void Server::connectToTcpServer(const QHostAddress &address) 0081 { 0082 m_tcpSocket = new QTcpSocket; 0083 connect(m_tcpSocket, &QTcpSocket::connected, this, &Server::gotConnected); 0084 connect(m_tcpSocket, &QTcpSocket::readyRead, this, &Server::dataReceived); 0085 m_tcpSocket->connectToHost(address, TCPPORT); 0086 connect(m_tcpSocket, &QTcpSocket::disconnected, this, &Server::lostConnection); 0087 } 0088 0089 void Server::gotConnected() 0090 { 0091 m_isConnected = true; 0092 Q_EMIT connected(); 0093 } 0094 0095 void Server::lostConnection() 0096 { 0097 m_isConnected = false; 0098 Q_EMIT disConnected(); 0099 } 0100 0101 #include "moc_Server.cpp"