downloadmanager.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /**
  2. * Copyright (c) 2011 Nokia Corporation.
  3. */
  4. #include "downloadmanager.h"
  5. #include <QFile>
  6. #include <QFileInfo>
  7. #include <QList>
  8. #include <QtCore/QUrl>
  9. #include <QtCore/QDebug>
  10. #include <QtGui/QApplication>
  11. #include <QtNetwork/QNetworkRequest>
  12. #include <QtNetwork/QNetworkReply>
  13. #include <QtNetwork/QNetworkConfiguration>
  14. #include <QtNetwork/QNetworkConfigurationManager>
  15. #include <QStringList>
  16. #include "product.h"
  17. /*!
  18. \class DownloadManager
  19. \brief Manages the downloads of purchased products.
  20. */
  21. /*!
  22. Constructor.
  23. */
  24. DownloadManager::DownloadManager(QObject *parent)
  25. : QObject(parent),
  26. m_manager(0),
  27. m_session(0),
  28. m_scriptEngine(0)
  29. {
  30. m_manager = new QNetworkAccessManager(this);
  31. QNetworkConfigurationManager cfgManager;
  32. QNetworkConfiguration cfg = cfgManager.defaultConfiguration();
  33. m_session = new QNetworkSession(cfg, this);
  34. m_session->open();
  35. m_session->waitForOpened(10000);
  36. connect(m_manager, SIGNAL(finished(QNetworkReply*)),
  37. SLOT(downloadFinished(QNetworkReply*)));
  38. m_scriptEngine = new QScriptEngine(this);
  39. }
  40. /*!
  41. Destructor.
  42. */
  43. DownloadManager::~DownloadManager()
  44. {
  45. cancel(); // Aborts and deletes all requests
  46. m_session->close();
  47. }
  48. /*!
  49. Requests product IDs from \a url.
  50. */
  51. void DownloadManager::requestProductsIds(const QUrl &url)
  52. {
  53. QNetworkRequest request(url);
  54. Request *req = new Request();
  55. req->type = Request::EProductIds;
  56. req->netRequest = m_manager->get(request);
  57. m_currentDownloads.append(req);
  58. }
  59. /*!
  60. Starts downloading a .sis file. The correct file is identified with
  61. \a productId and the purchase is validated with \a purchaseTicket.
  62. */
  63. void DownloadManager::downloadSis(QString productId,
  64. QString purchaseTicket,
  65. const QUrl &url)
  66. {
  67. QNetworkRequest request(url);
  68. Request* req = new Request();
  69. req->type = Request::EDownloadSis;
  70. req->id = productId;
  71. QString bodyString;
  72. bodyString.append("{");
  73. bodyString.append("\"purchaseTicket\":");
  74. bodyString.append("\""+purchaseTicket+"\"");
  75. bodyString.append("}");
  76. request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
  77. request.setHeader(QNetworkRequest::ContentLengthHeader,
  78. QString::number(bodyString.length()));
  79. request.setRawHeader("User-Agent","QuickHit");
  80. QByteArray bodyBytes = bodyString.toAscii();
  81. req->netRequest = m_manager->post(request,bodyBytes);
  82. QObject::connect(req->netRequest, SIGNAL(downloadProgress(qint64,qint64)),
  83. this, SLOT(onDownloadProgress(qint64,qint64)));
  84. m_currentDownloads.append(req);
  85. }
  86. /*!
  87. Returns a request from the list of downloads by \a reply or NULL if not
  88. found.
  89. */
  90. Request *DownloadManager::findRequestForReply(QNetworkReply *reply)
  91. {
  92. for (int i = 0; i < m_currentDownloads.count(); i++) {
  93. if (m_currentDownloads[i]->netRequest == reply) {
  94. return m_currentDownloads[i];
  95. }
  96. }
  97. return 0;
  98. }
  99. /*!
  100. Removes \a request from the list of downloads if found. Note that the
  101. removed instance is not destroyed.
  102. */
  103. void DownloadManager::removeRequest(Request *request)
  104. {
  105. if (request) {
  106. for (int i = 0; i < m_currentDownloads.count(); i++) {
  107. if (m_currentDownloads[i]->netRequest == request->netRequest) {
  108. m_currentDownloads.removeAt(i);
  109. break;
  110. }
  111. }
  112. }
  113. }
  114. /*!
  115. Handles a finished download.
  116. */
  117. void DownloadManager::downloadFinished(QNetworkReply *reply)
  118. {
  119. Request *request = findRequestForReply(reply);
  120. if (request) {
  121. if (reply->error() != QNetworkReply::NoError) {
  122. // ERROR
  123. emit downloadCompleted(request->type, request->id, "", reply->error());
  124. }
  125. else {
  126. // NO ERRORS
  127. switch (request->type) {
  128. case Request::EDownloadSis :
  129. {
  130. QUrl url = reply->url();
  131. QString filename = saveFileName(url);
  132. if (saveToDisk(filename, reply)) {
  133. emit(downloadCompleted(request->type, request->id, filename, 0));
  134. }
  135. else {
  136. // Failed to save the file to disk!
  137. emit(downloadCompleted(request->type, request->id, filename, -1));
  138. }
  139. break;
  140. }
  141. case Request::EProductIds :
  142. {
  143. processJsonReply(request,reply);
  144. break;
  145. }
  146. };
  147. }
  148. }
  149. removeRequest(request);
  150. reply->deleteLater();
  151. delete request;
  152. }
  153. /*!
  154. Symbian SIS downloading progress
  155. */
  156. void DownloadManager::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
  157. {
  158. QNetworkReply* nr = (QNetworkReply*)sender();
  159. if (nr) {
  160. Request* request = findRequestForReply(nr);
  161. if (request) {
  162. // Emit progress
  163. emit downloadProgress(request->id, bytesReceived, bytesTotal);
  164. }
  165. }
  166. }
  167. /*!
  168. Cancels and deletes all requests.
  169. */
  170. void DownloadManager::cancel()
  171. {
  172. Request *request(0);
  173. while (m_currentDownloads.count()) {
  174. request = m_currentDownloads[0];
  175. if (request && request->netRequest) {
  176. request->netRequest->abort();
  177. request->netRequest->deleteLater();
  178. }
  179. m_currentDownloads.removeAt(0);
  180. delete request;
  181. }
  182. }
  183. /*!
  184. Resolves and returns the file name (including the path), based on \a url, for
  185. the file to save.
  186. */
  187. QString DownloadManager::saveFileName(const QUrl &url)
  188. {
  189. QString path = url.path();
  190. QString basename = QFileInfo(path).fileName();
  191. // Verify the file name.
  192. if (basename.isEmpty()) {
  193. basename = "level.sis";
  194. }
  195. if (!basename.contains(".sis", Qt::CaseInsensitive)) {
  196. basename.append(".sis");
  197. }
  198. basename = QString("c:/Data/") + basename;
  199. if (QFile::exists(basename)) {
  200. // File already exists, remove.
  201. QFile::remove(basename);
  202. }
  203. return basename;
  204. }
  205. /*!
  206. Saves \a data to a file with \a filename. Returns true if successful, false
  207. otherwise.
  208. */
  209. bool DownloadManager::saveToDisk(const QString &filename, QIODevice *data)
  210. {
  211. QFile file(filename);
  212. if (!file.open(QIODevice::WriteOnly)) {
  213. return false;
  214. }
  215. file.write(data->readAll());
  216. file.close();
  217. return true;
  218. }
  219. /*!
  220. Parses and processes the JSON reply, in \a reply, received from the server.
  221. */
  222. void DownloadManager::processJsonReply(Request *request, QNetworkReply *reply)
  223. {
  224. switch (request->type) {
  225. case Request::EProductIds: {
  226. QByteArray bytes = reply->readAll();
  227. QString data(bytes);
  228. // JSON parsing
  229. QScriptValue sc =
  230. m_scriptEngine->evaluate("JSON.parse").call(QScriptValue(),
  231. QScriptValueList() << data);
  232. QList<QObject*> productList;
  233. if (sc.property("products").isArray()) {
  234. QStringList items;
  235. qScriptValueToSequence(sc.property("products"), items);
  236. QScriptValueIterator it(sc.property("products"));
  237. while (it.hasNext()) {
  238. it.next();
  239. if (it.value().property("id").isNull()) {
  240. break;
  241. }
  242. // Single product data exists
  243. Product *product = new Product();
  244. if (it.value().property("id").isString()) {
  245. QString id = it.value().property("id").toString();
  246. product->setId(id);
  247. if (it.value().property("image").isString()) {
  248. QString image = it.value().property("image").toString();
  249. product->setThumbnail(image);
  250. productList.append(product);
  251. }
  252. else {
  253. product->setThumbnail("");
  254. productList.append(product);
  255. }
  256. }
  257. else {
  258. delete product;
  259. }
  260. } // while ()
  261. }
  262. else {
  263. emit downloadCompleted(request->type, request->id, "", -1);
  264. }
  265. // Send result if products exist
  266. if (productList.length() > 0) {
  267. emit productIdsCompleted(productList);
  268. }
  269. break;
  270. } // case Request::EProductIds
  271. }; // switch (request->type)
  272. }