Desktop Qt based XMPP messenger https://macaw.me
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

515 lines
21 KiB

11 months ago
11 months ago
11 months ago
  1. /*
  2. * Squawk messenger.
  3. * Copyright (C) 2019 Yury Gubich <blue@macaw.me>
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "networkaccess.h"
  19. Core::NetworkAccess::NetworkAccess(QObject* parent):
  20. QObject(parent),
  21. running(false),
  22. manager(0),
  23. files("files"),
  24. downloads(),
  25. uploads()
  26. {
  27. }
  28. Core::NetworkAccess::~NetworkAccess()
  29. {
  30. stop();
  31. }
  32. void Core::NetworkAccess::fileLocalPathRequest(const QString& messageId, const QString& url)
  33. {
  34. std::map<QString, Transfer*>::iterator itr = downloads.find(url);
  35. if (itr != downloads.end()) {
  36. Transfer* dwn = itr->second;
  37. std::set<QString>::const_iterator mItr = dwn->messages.find(messageId);
  38. if (mItr == dwn->messages.end()) {
  39. dwn->messages.insert(messageId);
  40. }
  41. emit downloadFileProgress(messageId, dwn->progress);
  42. } else {
  43. try {
  44. QString path = files.getRecord(url);
  45. QFileInfo info(path);
  46. if (info.exists() && info.isFile()) {
  47. emit fileLocalPathResponse(messageId, path);
  48. } else {
  49. files.removeRecord(url);
  50. emit fileLocalPathResponse(messageId, "");
  51. }
  52. } catch (const Archive::NotFound& e) {
  53. emit fileLocalPathResponse(messageId, "");
  54. } catch (const Archive::Unknown& e) {
  55. qDebug() << "Error requesting file path:" << e.what();
  56. emit fileLocalPathResponse(messageId, "");
  57. }
  58. }
  59. }
  60. void Core::NetworkAccess::downladFileRequest(const QString& messageId, const QString& url)
  61. {
  62. std::map<QString, Transfer*>::iterator itr = downloads.find(url);
  63. if (itr != downloads.end()) {
  64. Transfer* dwn = itr->second;
  65. std::set<QString>::const_iterator mItr = dwn->messages.find(messageId);
  66. if (mItr == dwn->messages.end()) {
  67. dwn->messages.insert(messageId);
  68. }
  69. emit downloadFileProgress(messageId, dwn->progress);
  70. } else {
  71. try {
  72. QString path = files.getRecord(url);
  73. QFileInfo info(path);
  74. if (info.exists() && info.isFile()) {
  75. emit fileLocalPathResponse(messageId, path);
  76. } else {
  77. files.removeRecord(url);
  78. startDownload(messageId, url);
  79. }
  80. } catch (const Archive::NotFound& e) {
  81. startDownload(messageId, url);
  82. } catch (const Archive::Unknown& e) {
  83. qDebug() << "Error requesting file path:" << e.what();
  84. emit downloadFileError(messageId, QString("Database error: ") + e.what());
  85. }
  86. }
  87. }
  88. void Core::NetworkAccess::start()
  89. {
  90. if (!running) {
  91. manager = new QNetworkAccessManager();
  92. files.open();
  93. running = true;
  94. }
  95. }
  96. void Core::NetworkAccess::stop()
  97. {
  98. if (running) {
  99. files.close();
  100. manager->deleteLater();
  101. manager = 0;
  102. running = false;
  103. for (std::map<QString, Transfer*>::const_iterator itr = downloads.begin(), end = downloads.end(); itr != end; ++itr) {
  104. itr->second->success = false;
  105. itr->second->reply->abort(); //assuming it's gonna call onRequestFinished slot
  106. }
  107. }
  108. }
  109. void Core::NetworkAccess::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
  110. {
  111. QNetworkReply* rpl = static_cast<QNetworkReply*>(sender());
  112. QString url = rpl->url().toString();
  113. std::map<QString, Transfer*>::const_iterator itr = downloads.find(url);
  114. if (itr == downloads.end()) {
  115. qDebug() << "an error downloading" << url << ": the request had some progress but seems like no one is waiting for it, skipping";
  116. } else {
  117. Transfer* dwn = itr->second;
  118. qreal received = bytesReceived;
  119. qreal total = bytesTotal;
  120. qreal progress = received/total;
  121. dwn->progress = progress;
  122. for (std::set<QString>::const_iterator mItr = dwn->messages.begin(), end = dwn->messages.end(); mItr != end; ++mItr) {
  123. emit downloadFileProgress(*mItr, progress);
  124. }
  125. }
  126. }
  127. void Core::NetworkAccess::onDownloadError(QNetworkReply::NetworkError code)
  128. {
  129. QNetworkReply* rpl = static_cast<QNetworkReply*>(sender());
  130. QString url = rpl->url().toString();
  131. std::map<QString, Transfer*>::const_iterator itr = downloads.find(url);
  132. if (itr == downloads.end()) {
  133. qDebug() << "an error downloading" << url << ": the request is reporting an error but seems like no one is waiting for it, skipping";
  134. } else {
  135. QString errorText = getErrorText(code);
  136. if (errorText.size() > 0) {
  137. itr->second->success = false;
  138. Transfer* dwn = itr->second;
  139. for (std::set<QString>::const_iterator mItr = dwn->messages.begin(), end = dwn->messages.end(); mItr != end; ++mItr) {
  140. emit downloadFileError(*mItr, errorText);
  141. }
  142. }
  143. }
  144. }
  145. QString Core::NetworkAccess::getErrorText(QNetworkReply::NetworkError code)
  146. {
  147. QString errorText("");
  148. switch (code) {
  149. case QNetworkReply::NoError:
  150. //this never is supposed to happen
  151. break;
  152. // network layer errors [relating to the destination server] (1-99):
  153. case QNetworkReply::ConnectionRefusedError:
  154. errorText = "Connection refused";
  155. break;
  156. case QNetworkReply::RemoteHostClosedError:
  157. errorText = "Remote server closed the connection";
  158. break;
  159. case QNetworkReply::HostNotFoundError:
  160. errorText = "Remote host is not found";
  161. break;
  162. case QNetworkReply::TimeoutError:
  163. errorText = "Connection was closed because it timed out";
  164. break;
  165. case QNetworkReply::OperationCanceledError:
  166. //this means I closed it myself by abort() or close(), don't think I need to notify here
  167. break;
  168. case QNetworkReply::SslHandshakeFailedError:
  169. errorText = "Security error"; //TODO need to handle sslErrors signal to get a better description here
  170. break;
  171. case QNetworkReply::TemporaryNetworkFailureError:
  172. //this means the connection is lost by opened route, but it's going to be resumed, not sure I need to notify
  173. break;
  174. case QNetworkReply::NetworkSessionFailedError:
  175. errorText = "Outgoing connection problem";
  176. break;
  177. case QNetworkReply::BackgroundRequestNotAllowedError:
  178. errorText = "Background request is not allowed";
  179. break;
  180. case QNetworkReply::TooManyRedirectsError:
  181. errorText = "The request was redirected too many times";
  182. break;
  183. case QNetworkReply::InsecureRedirectError:
  184. errorText = "The request was redirected to insecure connection";
  185. break;
  186. case QNetworkReply::UnknownNetworkError:
  187. errorText = "Unknown network error";
  188. break;
  189. // proxy errors (101-199):
  190. case QNetworkReply::ProxyConnectionRefusedError:
  191. errorText = "The connection to the proxy server was refused";
  192. break;
  193. case QNetworkReply::ProxyConnectionClosedError:
  194. errorText = "Proxy server closed the connection";
  195. break;
  196. case QNetworkReply::ProxyNotFoundError:
  197. errorText = "Proxy host was not found";
  198. break;
  199. case QNetworkReply::ProxyTimeoutError:
  200. errorText = "Connection to the proxy server was closed because it timed out";
  201. break;
  202. case QNetworkReply::ProxyAuthenticationRequiredError:
  203. errorText = "Couldn't connect to proxy server, authentication is required";
  204. break;
  205. case QNetworkReply::UnknownProxyError:
  206. errorText = "Unknown proxy error";
  207. break;
  208. // content errors (201-299):
  209. case QNetworkReply::ContentAccessDenied:
  210. errorText = "The access to file is denied";
  211. break;
  212. case QNetworkReply::ContentOperationNotPermittedError:
  213. errorText = "The operation over requesting file is not permitted";
  214. break;
  215. case QNetworkReply::ContentNotFoundError:
  216. errorText = "The file was not found";
  217. break;
  218. case QNetworkReply::AuthenticationRequiredError:
  219. errorText = "Couldn't access the file, authentication is required";
  220. break;
  221. case QNetworkReply::ContentReSendError:
  222. errorText = "Sending error, one more attempt will probably solve this problem";
  223. break;
  224. case QNetworkReply::ContentConflictError:
  225. errorText = "The request could not be completed due to a conflict with the current state of the resource";
  226. break;
  227. case QNetworkReply::ContentGoneError:
  228. errorText = "The requested resource is no longer available at the server";
  229. break;
  230. case QNetworkReply::UnknownContentError:
  231. errorText = "Unknown content error";
  232. break;
  233. // protocol errors
  234. case QNetworkReply::ProtocolUnknownError:
  235. errorText = "Unknown protocol error";
  236. break;
  237. case QNetworkReply::ProtocolInvalidOperationError:
  238. errorText = "Requested operation is not permitted in this protocol";
  239. break;
  240. case QNetworkReply::ProtocolFailure:
  241. errorText = "Low level protocol error";
  242. break;
  243. // Server side errors (401-499)
  244. case QNetworkReply::InternalServerError:
  245. errorText = "Internal server error";
  246. break;
  247. case QNetworkReply::OperationNotImplementedError:
  248. errorText = "Server doesn't support requested operation";
  249. break;
  250. case QNetworkReply::ServiceUnavailableError:
  251. errorText = "The server is not available for this operation right now";
  252. break;
  253. case QNetworkReply::UnknownServerError:
  254. errorText = "Unknown server error";
  255. break;
  256. }
  257. return errorText;
  258. }
  259. void Core::NetworkAccess::onDownloadFinished()
  260. {
  261. QString path("");
  262. QNetworkReply* rpl = static_cast<QNetworkReply*>(sender());
  263. QString url = rpl->url().toString();
  264. std::map<QString, Transfer*>::const_iterator itr = downloads.find(url);
  265. if (itr == downloads.end()) {
  266. qDebug() << "an error downloading" << url << ": the request is done but seems like noone is waiting for it, skipping";
  267. } else {
  268. Transfer* dwn = itr->second;
  269. if (dwn->success) {
  270. qDebug() << "download success for" << url;
  271. QStringList hops = url.split("/");
  272. QString fileName = hops.back();
  273. QStringList parts = fileName.split(".");
  274. path = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + "/";
  275. QString suffix("");
  276. QStringList::const_iterator sItr = parts.begin();
  277. QString realName = *sItr;
  278. ++sItr;
  279. for (QStringList::const_iterator sEnd = parts.end(); sItr != sEnd; ++sItr) {
  280. suffix += "." + (*sItr);
  281. }
  282. QString postfix("");
  283. QFileInfo proposedName(path + realName + postfix + suffix);
  284. int counter = 0;
  285. while (proposedName.exists()) {
  286. postfix = QString("(") + std::to_string(++counter).c_str() + ")";
  287. proposedName = QFileInfo(path + realName + postfix + suffix);
  288. }
  289. path = proposedName.absoluteFilePath();
  290. QFile file(path);
  291. if (file.open(QIODevice::WriteOnly)) {
  292. file.write(dwn->reply->readAll());
  293. file.close();
  294. files.addRecord(url, path);
  295. qDebug() << "file" << path << "was successfully downloaded";
  296. } else {
  297. qDebug() << "couldn't save file" << path;
  298. path = "";
  299. }
  300. }
  301. for (std::set<QString>::const_iterator mItr = dwn->messages.begin(), end = dwn->messages.end(); mItr != end; ++mItr) {
  302. emit fileLocalPathResponse(*mItr, path);
  303. }
  304. dwn->reply->deleteLater();
  305. delete dwn;
  306. downloads.erase(itr);
  307. }
  308. }
  309. void Core::NetworkAccess::startDownload(const QString& messageId, const QString& url)
  310. {
  311. Transfer* dwn = new Transfer({{messageId}, 0, 0, true, "", url, 0});
  312. QNetworkRequest req(url);
  313. dwn->reply = manager->get(req);
  314. connect(dwn->reply, &QNetworkReply::downloadProgress, this, &NetworkAccess::onDownloadProgress);
  315. #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
  316. connect(dwn->reply, qOverload<QNetworkReply::NetworkError>(&QNetworkReply::errorOccurred), this, &NetworkAccess::onDownloadError);
  317. #else
  318. connect(dwn->reply, qOverload<QNetworkReply::NetworkError>(&QNetworkReply::error), this, &NetworkAccess::onDownloadError);
  319. #endif
  320. connect(dwn->reply, &QNetworkReply::finished, this, &NetworkAccess::onDownloadFinished);
  321. downloads.insert(std::make_pair(url, dwn));
  322. emit downloadFileProgress(messageId, 0);
  323. }
  324. void Core::NetworkAccess::onUploadError(QNetworkReply::NetworkError code)
  325. {
  326. QNetworkReply* rpl = static_cast<QNetworkReply*>(sender());
  327. QString url = rpl->url().toString();
  328. std::map<QString, Transfer*>::const_iterator itr = uploads.find(url);
  329. if (itr == uploads.end()) {
  330. qDebug() << "an error uploading" << url << ": the request is reporting an error but seems like noone is waiting for it, skipping";
  331. } else {
  332. QString errorText = getErrorText(code);
  333. if (errorText.size() > 0) {
  334. itr->second->success = false;
  335. Transfer* upl = itr->second;
  336. for (std::set<QString>::const_iterator mItr = upl->messages.begin(), end = upl->messages.end(); mItr != end; ++mItr) {
  337. emit uploadFileError(*mItr, errorText);
  338. }
  339. }
  340. }
  341. }
  342. void Core::NetworkAccess::onUploadFinished()
  343. {
  344. QNetworkReply* rpl = static_cast<QNetworkReply*>(sender());
  345. QString url = rpl->url().toString();
  346. std::map<QString, Transfer*>::const_iterator itr = uploads.find(url);
  347. if (itr == downloads.end()) {
  348. qDebug() << "an error uploading" << url << ": the request is done but seems like no one is waiting for it, skipping";
  349. } else {
  350. Transfer* upl = itr->second;
  351. if (upl->success) {
  352. qDebug() << "upload success for" << url;
  353. files.addRecord(upl->url, upl->path);
  354. for (std::set<QString>::const_iterator mItr = upl->messages.begin(), end = upl->messages.end(); mItr != end; ++mItr) {
  355. emit fileLocalPathResponse(*mItr, upl->path);
  356. emit uploadFileComplete(*mItr, upl->url);
  357. }
  358. }
  359. upl->reply->deleteLater();
  360. upl->file->close();
  361. upl->file->deleteLater();
  362. delete upl;
  363. uploads.erase(itr);
  364. }
  365. }
  366. void Core::NetworkAccess::onUploadProgress(qint64 bytesReceived, qint64 bytesTotal)
  367. {
  368. QNetworkReply* rpl = static_cast<QNetworkReply*>(sender());
  369. QString url = rpl->url().toString();
  370. std::map<QString, Transfer*>::const_iterator itr = uploads.find(url);
  371. if (itr == uploads.end()) {
  372. qDebug() << "an error downloading" << url << ": the request had some progress but seems like no one is waiting for it, skipping";
  373. } else {
  374. Transfer* upl = itr->second;
  375. qreal received = bytesReceived;
  376. qreal total = bytesTotal;
  377. qreal progress = received/total;
  378. upl->progress = progress;
  379. for (std::set<QString>::const_iterator mItr = upl->messages.begin(), end = upl->messages.end(); mItr != end; ++mItr) {
  380. emit uploadFileProgress(*mItr, progress);
  381. }
  382. }
  383. }
  384. void Core::NetworkAccess::startUpload(const QString& messageId, const QString& url, const QString& path)
  385. {
  386. Transfer* upl = new Transfer({{messageId}, 0, 0, true, path, url, 0});
  387. QNetworkRequest req(url);
  388. QFile* file = new QFile(path);
  389. if (file->open(QIODevice::ReadOnly)) {
  390. upl->reply = manager->put(req, file);
  391. connect(upl->reply, &QNetworkReply::uploadProgress, this, &NetworkAccess::onUploadProgress);
  392. #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
  393. connect(upl->reply, qOverload<QNetworkReply::NetworkError>(&QNetworkReply::errorOccurred), this, &NetworkAccess::onUploadError);
  394. #else
  395. connect(upl->reply, qOverload<QNetworkReply::NetworkError>(&QNetworkReply::error), this, &NetworkAccess::onUploadError);
  396. #endif
  397. connect(upl->reply, &QNetworkReply::finished, this, &NetworkAccess::onUploadFinished);
  398. uploads.insert(std::make_pair(url, upl));
  399. emit downloadFileProgress(messageId, 0);
  400. } else {
  401. qDebug() << "couldn't upload file" << path;
  402. emit uploadFileError(messageId, "Error opening file");
  403. delete file;
  404. }
  405. }
  406. void Core::NetworkAccess::uploadFileRequest(const QString& messageId, const QString& url, const QString& path)
  407. {
  408. std::map<QString, Transfer*>::iterator itr = uploads.find(url);
  409. if (itr != uploads.end()) {
  410. Transfer* upl = itr->second;
  411. std::set<QString>::const_iterator mItr = upl->messages.find(messageId);
  412. if (mItr == upl->messages.end()) {
  413. upl->messages.insert(messageId);
  414. }
  415. emit uploadFileProgress(messageId, upl->progress);
  416. } else {
  417. try {
  418. QString ePath = files.getRecord(url);
  419. if (ePath == path) {
  420. QFileInfo info(path);
  421. if (info.exists() && info.isFile()) {
  422. emit fileLocalPathResponse(messageId, path);
  423. } else {
  424. files.removeRecord(url);
  425. startUpload(messageId, url, path);
  426. }
  427. } else {
  428. QFileInfo info(path);
  429. if (info.exists() && info.isFile()) {
  430. files.changeRecord(url, path);
  431. emit fileLocalPathResponse(messageId, path);
  432. } else {
  433. files.removeRecord(url);
  434. startUpload(messageId, url, path);
  435. }
  436. }
  437. } catch (const Archive::NotFound& e) {
  438. startUpload(messageId, url, path);
  439. } catch (const Archive::Unknown& e) {
  440. qDebug() << "Error requesting file path on upload:" << e.what();
  441. emit uploadFileError(messageId, QString("Database error: ") + e.what());
  442. }
  443. }
  444. }
  445. QString Core::NetworkAccess::getFileRemoteUrl(const QString& path)
  446. {
  447. return ""; //TODO this is a way not to upload some file more then 1 time, here I'm supposed to return that file GET url
  448. }
  449. bool Core::NetworkAccess::isUploading(const QString& path, const QString& messageId)
  450. {
  451. return false; //TODO this is a way to avoid parallel uploading of the same files by different chats
  452. // message is is supposed to be added to the uploading messageids list
  453. // the result should be true if there was an uploading file with this path
  454. // message id can be empty, then it's just to check and not to add
  455. }
  456. void Core::NetworkAccess::uploadFile(const QString& messageId, const QString& path, const QUrl& put, const QUrl& get, const QMap<QString, QString> headers)
  457. {
  458. QFile* file = new QFile(path);
  459. Transfer* upl = new Transfer({{messageId}, 0, 0, true, path, get.toString(), file});
  460. QNetworkRequest req(put);
  461. for (QMap<QString, QString>::const_iterator itr = headers.begin(), end = headers.end(); itr != end; itr++) {
  462. req.setRawHeader(itr.key().toUtf8(), itr.value().toUtf8());
  463. }
  464. if (file->open(QIODevice::ReadOnly)) {
  465. upl->reply = manager->put(req, file);
  466. connect(upl->reply, &QNetworkReply::uploadProgress, this, &NetworkAccess::onUploadProgress);
  467. #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
  468. connect(upl->reply, qOverload<QNetworkReply::NetworkError>(&QNetworkReply::errorOccurred), this, &NetworkAccess::onUploadError);
  469. #else
  470. connect(upl->reply, qOverload<QNetworkReply::NetworkError>(&QNetworkReply::error), this, &NetworkAccess::onUploadError);
  471. #endif
  472. connect(upl->reply, &QNetworkReply::finished, this, &NetworkAccess::onUploadFinished);
  473. uploads.insert(std::make_pair(put.toString(), upl));
  474. emit downloadFileProgress(messageId, 0);
  475. } else {
  476. qDebug() << "couldn't upload file" << path;
  477. emit uploadFileError(messageId, "Error opening file");
  478. delete file;
  479. }
  480. }