Qt/QML App for Friendiqa
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.

xhr.cpp 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // This file is part of Friendiqa
  2. // https://github.com/lubuwest/Friendiqa
  3. // Copyright (C) 2017 Marco R. <thomasschmidt45@gmx.net>
  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. // In addition, as a special exception, the copyright holders give
  11. // permission to link the code of portions of this program with the
  12. // OpenSSL library under certain conditions as described in each
  13. // individual source file, and distribute linked combinations including
  14. // the two.
  15. //
  16. // You must obey the GNU General Public License in all respects for all
  17. // of the code used other than OpenSSL. If you modify file(s) with this
  18. // exception, you may extend this exception to your version of the
  19. // file(s), but you are not obligated to do so. If you do not wish to do
  20. // so, delete this exception statement from your version. If you delete
  21. // this exception statement from all source files in the program, then
  22. // also delete it here.
  23. //
  24. // This program is distributed in the hope that it will be useful,
  25. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. // GNU General Public License for more details.
  28. //
  29. // You should have received a copy of the GNU General Public License
  30. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  31. #include "xhr.h"
  32. #include <QHttpPart>
  33. #include <QTextCodec>
  34. #include <QUrlQuery>
  35. #include <QList>
  36. #include <QDataStream>
  37. #include <QJsonDocument>
  38. #include <QJsonObject>
  39. #include "uploadableimage.h"
  40. XHR *XHR::instance()
  41. {
  42. static XHR xhr;
  43. return &xhr;
  44. }
  45. XHR::XHR(QObject *parent) : QObject(parent)
  46. {
  47. request.setSslConfiguration(QSslConfiguration::defaultConfiguration());
  48. }
  49. void XHR::setUrl(QString url)
  50. {
  51. if (url!=m_url) {
  52. m_url = url;
  53. emit urlChanged();
  54. }
  55. }
  56. void XHR::setApi(QString api)
  57. {
  58. if (api!=m_api) {
  59. m_api = api;
  60. emit apiChanged();
  61. }
  62. }
  63. void XHR::setLogin(QString login)
  64. {
  65. if (login!=m_login) {
  66. m_login = login;
  67. emit loginChanged();
  68. }
  69. }
  70. void XHR::setFilename(QString filename)
  71. {
  72. if (filename!=m_filename) {
  73. m_filename = filename;
  74. emit filenameChanged();
  75. }
  76. }
  77. void XHR::setContactlist(QList<QString> contactlist)
  78. {
  79. if (contactlist!=m_contactlist) {
  80. m_contactlist = contactlist;
  81. emit contactlistChanged();
  82. }
  83. }
  84. void XHR::setFilelist(QList<QString> filelist)
  85. {
  86. if (filelist!=m_filelist) {
  87. m_filelist = filelist;
  88. emit filelistChanged();
  89. }
  90. }
  91. void XHR::setImagedir(QString imagedir)
  92. {
  93. if (imagedir!=m_imagedir) {
  94. m_imagedir = imagedir;
  95. emit imagedirChanged();
  96. }
  97. }
  98. void XHR::setDownloadtype(QString downloadtype)
  99. {
  100. if (downloadtype!=m_downloadtype) {
  101. m_downloadtype = downloadtype;
  102. emit downloadtypeChanged();
  103. }
  104. }
  105. QString XHR::url() const
  106. {
  107. return m_url;
  108. }
  109. QString XHR::api() const
  110. {
  111. return m_api;
  112. }
  113. QString XHR::login() const
  114. {
  115. return m_login;
  116. }
  117. QString XHR::filename() const
  118. {
  119. return m_filename;
  120. }
  121. QList<QString> XHR::contactlist() const
  122. {
  123. return m_contactlist;
  124. }
  125. QList<QString> XHR::filelist() const
  126. {
  127. return m_filelist;
  128. }
  129. QString XHR::imagedir() const
  130. {
  131. return m_imagedir;
  132. }
  133. QString XHR::downloadtype() const
  134. {
  135. return m_downloadtype;
  136. }
  137. QString XHR::networktype() const
  138. {
  139. return nc.bearerTypeFamily() + nc.bearerTypeName();
  140. }
  141. void XHR::setParam(QString name, QString value)
  142. {
  143. params.insert(name, value);
  144. }
  145. void XHR::setImageFileParam(QString name, QString url)
  146. {
  147. files.insert(name, url);
  148. }
  149. void XHR::clearParams()
  150. {
  151. files.clear();
  152. params.clear();
  153. }
  154. void XHR::download()
  155. {
  156. QUrl requrl(m_url);
  157. if(m_downloadtype=="picturelist"){
  158. QByteArray loginData = m_login.toLocal8Bit().toBase64();
  159. QString headerData = "Basic " + loginData;
  160. request.setRawHeader("Authorization", headerData.toLocal8Bit());
  161. }
  162. request.setUrl(requrl);
  163. //qDebug() << requrl;
  164. reply = manager.get(request);
  165. reply->ignoreSslErrors();
  166. connect(reply, &QNetworkReply::readyRead,this, &XHR::onReadyRead);
  167. //connect(reply,SIGNAL(downloadProgress(qint64,qint64)), this,SLOT(updateDownloadProgress(qint64,qint64)));
  168. connect(reply, &QNetworkReply::finished,this, &XHR::onRequestFinished);
  169. connect(reply, &QNetworkReply::sslErrors, this, &XHR::onSSLError);
  170. connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onReplyError(QNetworkReply::NetworkError)));
  171. }
  172. void XHR::get()
  173. {
  174. QUrlQuery query;
  175. QHashIterator<QString, QString> i(params);
  176. while(i.hasNext()) {
  177. i.next();
  178. query.addQueryItem(i.key(), i.value());
  179. }
  180. QUrl requrl(m_url+m_api);
  181. //qDebug() << requrl;
  182. requrl.setQuery(query);
  183. QByteArray loginData = m_login.toLocal8Bit().toBase64();
  184. QString headerData = "Basic " + loginData;
  185. request.setRawHeader("Authorization", headerData.toLocal8Bit());
  186. request.setUrl(requrl);
  187. reply = manager.get(request);
  188. connect(reply, &QNetworkReply::finished, this, &XHR::onReplySuccess);
  189. connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onReplyError(QNetworkReply::NetworkError)));
  190. connect(reply, &QNetworkReply::readyRead, this, &XHR::onReadyRead);
  191. connect(reply, &QNetworkReply::sslErrors, this, &XHR::onSSLError);
  192. }
  193. void XHR::getlist()
  194. {
  195. if(dlindex < m_filelist.size()) {
  196. QString cleanfilename;
  197. if (m_downloadtype=="contactlist"){cleanfilename = m_contactlist.at(dlindex)+"-"+ m_filelist.at(dlindex).section('/',-1).section('?',0,0);
  198. XHR::setFilename(imagedir()+"contacts/"+cleanfilename);
  199. XHR::setUrl(m_filelist.at(dlindex));}
  200. else {
  201. XHR::setUrl(m_filelist.at(dlindex));}
  202. XHR::download();
  203. } else {dlindex=0;}
  204. }
  205. void XHR::post()
  206. {
  207. //qDebug() << "start post to " << m_url;
  208. QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
  209. QHashIterator<QString, QString> iparams(params);
  210. while(iparams.hasNext()) {
  211. iparams.next();
  212. //qDebug() << "\t add param " << iparams.key() << " : " << iparams.value();
  213. QHttpPart textPart;
  214. textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"" + iparams.key() + "\""));
  215. textPart.setBody(iparams.value().toUtf8());
  216. multiPart->append(textPart);
  217. }
  218. UploadableImage uimg;
  219. QHashIterator<QString, QString> ifiles(files);
  220. while(ifiles.hasNext()) {
  221. ifiles.next();
  222. uimg.setSource(ifiles.value());
  223. //qDebug() << "\t image: " << uimg.mimetype() << ", " << ifiles.key();
  224. QHttpPart imagePart;
  225. imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(uimg.mimetype()));
  226. imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"" + ifiles.key() + "\"; filename=\""+uimg.filename()+"\""));
  227. imagePart.setBody(uimg.bytes());
  228. multiPart->append(imagePart);
  229. }
  230. QByteArray loginData = m_login.toLocal8Bit().toBase64();
  231. QString headerData = "Basic " + loginData;
  232. request.setRawHeader(QByteArray("Authorization"), headerData.toLocal8Bit());
  233. request.setUrl(m_url+m_api);
  234. reply = manager.post(request, multiPart);
  235. qDebug() << "\t request sent";
  236. connect(reply, &QNetworkReply::finished, this, &XHR::onReplySuccess);
  237. connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onReplyError(QNetworkReply::NetworkError)));
  238. connect(reply, &QNetworkReply::readyRead, this, &XHR::onReadyRead);
  239. connect(reply, &QNetworkReply::sslErrors, this, &XHR::onSSLError);
  240. qDebug() << "\t reply signals connected";
  241. }
  242. void XHR::onReplyError(QNetworkReply::NetworkError code)
  243. {
  244. qDebug() << code;
  245. emit this->error( bufferToString(), m_url,m_api, (int) code);
  246. buffer.clear();
  247. reply->deleteLater();
  248. }
  249. void XHR::onReplySuccess()
  250. {
  251. qDebug() << "!";
  252. emit this->success(buffer, m_api);
  253. buffer.clear();
  254. // reply->deleteLater();
  255. }
  256. void XHR::onRequestFinished()
  257. {
  258. // Save the file here
  259. if (buffer.isNull()){qDebug() << "File empty"<<m_url; buffer.clear(); emit this->error(m_downloadtype,m_url,m_api,1);}
  260. else if (m_downloadtype=="picturelist") {
  261. QJsonDocument jsonResponse = QJsonDocument::fromJson(buffer);
  262. QJsonObject jsonObject = jsonResponse.object();
  263. int arraystart=buffer.indexOf('{"data":"')+8;
  264. int arraylength=buffer.indexOf('"',9)-arraystart;
  265. QByteArray b64=buffer.mid(arraystart,arraylength);
  266. QString helpfilename=jsonObject["filename"].toString();
  267. QString helpfile=helpfilename.left(helpfilename.lastIndexOf("."));
  268. QString filesuffix="";
  269. if (jsonObject["type"].toString()=="image/jpeg"){filesuffix=".jpg";}
  270. else if (jsonObject["type"].toString()=="image/png"){filesuffix=".png";}
  271. else {filesuffix="";}
  272. if (helpfilename==""){// check if file has any filename
  273. helpfile=jsonObject["id"].toString();
  274. setFilename(imagedir()+"albums/"+jsonObject["album"].toString()+"/"+jsonObject["id"].toString()+filesuffix);
  275. }
  276. else{setFilename(imagedir()+"albums/"+jsonObject["album"].toString()+"/"+helpfile+filesuffix);}
  277. //qDebug()<<"Filename "<<m_filename;
  278. QFile file(m_filename);
  279. file.open(QIODevice::WriteOnly);
  280. file.write(QByteArray::fromBase64(b64));
  281. buffer.clear();
  282. b64.clear();
  283. file.close();
  284. jsonObject["data"]="";
  285. jsonObject["filename"]=helpfile+filesuffix;
  286. emit this->downloadedjson(m_downloadtype,m_url,m_filename,dlindex,jsonObject);
  287. if(downloadtype()=="picturelist"){dlindex=dlindex+1;XHR::getlist();}
  288. }
  289. else {
  290. QFile file(m_filename);
  291. file.open(QIODevice::WriteOnly);
  292. file.write(buffer);
  293. buffer.clear();
  294. file.close();
  295. emit this->downloaded(m_downloadtype,m_url,m_filename,dlindex);
  296. if(downloadtype()=="contactlist"){dlindex=dlindex+1;XHR::getlist();}
  297. //reply->deleteLater();
  298. }
  299. }
  300. void XHR::onReadyRead()
  301. {
  302. qDebug() << ".";
  303. buffer += reply->readAll();
  304. }
  305. //void XHR::updateDownloadProgress(qint64 bytesRead, qint64 totalBytes)
  306. //{
  307. // qDebug() << "Bytes: " << bytesRead<<" / "<<totalBytes;
  308. //}
  309. void XHR::onSSLError(const QList<QSslError> &errors)
  310. {
  311. qDebug() << "XHR::onSSLError :" ;
  312. QListIterator<QSslError> ierrs(errors);
  313. while(ierrs.hasNext()) {
  314. qDebug() << "\t" << ierrs.next().errorString();
  315. }
  316. }
  317. QString XHR::bufferToString()
  318. {
  319. return QTextCodec::codecForName("utf-8")->toUnicode(buffer);
  320. }