example/LastFmAuthApp/src/requestSP.cpp
changeset 26 83d6a149c755
equal deleted inserted replaced
25:a180113055cb 26:83d6a149c755
       
     1 /**
       
     2 * Copyright (c) 2010 Sasken Communication Technologies Ltd.
       
     3 * All rights reserved.
       
     4 * This component and the accompanying materials are made available
       
     5 * under the terms of the "{License}"
       
     6 * which accompanies  this distribution, and is available
       
     7 * at the URL "{LicenseUrl}".
       
     8 *
       
     9 * Initial Contributors:
       
    10 * Narasimhulu Kavadapu, Sasken Communication Technologies Ltd - Initial contribution
       
    11 *
       
    12 * Contributors:
       
    13 * Siddhartha Chandra, Sasken Communication Technologies Ltd
       
    14 * Description:
       
    15 * class to handle calls to rest Server API's
       
    16 */
       
    17 
       
    18 #define EMULATORTESTING 1
       
    19 
       
    20 #include "requestSP.h"
       
    21 #include "sessionSP.h"
       
    22 #include "xmlParser.h"
       
    23 #include "errorCodes.h"
       
    24 
       
    25 #include <QNetworkRequest>
       
    26 #include <QXmlSimpleReader>
       
    27 #include <QXmlInputSource>
       
    28 #include <QCryptographicHash>
       
    29 #include <QtAlgorithms>
       
    30 #include <QDebug>
       
    31 #include <qnetworkproxy.h>
       
    32 #include "keys.h"
       
    33 ///////////////////////////////////////////////////////////////////////////////////////////////////
       
    34 // global
       
    35 
       
    36 static const QString kAPIVersion = "1.0";
       
    37 static const QString kAPIFormat = "XML";
       
    38 static const QString kStringBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
       
    39 
       
    40 
       
    41 ///////////////////////////////////////////////////////////////////////////////////////////////////
       
    42 
       
    43 static bool caseInsensitiveLessThan(const QString &s1, const QString &s2)
       
    44 {
       
    45     return s1.toLower() < s2.toLower();
       
    46 }
       
    47 
       
    48 ///////////////////////////////////////////////////////////////////////////////////////////////////
       
    49 // Static class functions
       
    50 
       
    51 FBRequest* FBRequest::request()
       
    52 {
       
    53     return FBRequest::requestWithSession(FBSession::session());
       
    54 }
       
    55 
       
    56 FBRequest* FBRequest::requestWithSession (FBSession* aSession)
       
    57 {
       
    58     FBRequest* request = new FBRequest(aSession);
       
    59     return request;
       
    60 }
       
    61 
       
    62 ///////////////////////////////////////////////////////////////////////////////////////////////////
       
    63 // instance public functions
       
    64 FBRequest::FBRequest(FBSession* aSession) : iSession ( aSession ), iNetworkAccessManager ( this )
       
    65 {}
       
    66 
       
    67 const QDateTime& FBRequest::timeStamp() const
       
    68 {
       
    69     return iTimestamp;
       
    70 }
       
    71 
       
    72 void FBRequest::connect()
       
    73 {
       
    74 	qDebug()<<"Inside FBRequest::connect";
       
    75     QString url ;
       
    76     url = generateGetURL();
       
    77     qDebug() << "Complete URL  : " << url;
       
    78     QNetworkRequest request;
       
    79     request.setUrl(QUrl(url));
       
    80     if (iMethod.length())
       
    81     {
       
    82         pbar = new progressbar;
       
    83         pbar->show();
       
    84 		#ifdef __WINSCW__
       
    85 			proxysettings();
       
    86 		#endif
       
    87         QNetworkReply* reply = iNetworkAccessManager.get(request);
       
    88         QObject::connect(reply, SIGNAL(finished()),  this, SLOT(networkReplyFinished()));
       
    89         QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
       
    90                          this, SLOT(networkReplyError(QNetworkReply::NetworkError)));
       
    91     }
       
    92 }
       
    93 void FBRequest::proxysettings()
       
    94 {
       
    95 #ifdef EMULATORTESTING
       
    96 	qDebug()<<"proxysettings";
       
    97 	
       
    98 	// Reading the keys, CSM Stubbed - START
       
    99 	QFile file("c://data//DoNotShare.txt");
       
   100 	if (!file.open(QIODevice::ReadOnly))
       
   101 		{
       
   102 		qDebug()<<"File to read the windows username and password could not be opened, returning!!!";
       
   103 		return;
       
   104 		}
       
   105 	
       
   106 	QByteArray arr = file.readAll();
       
   107 	QList<QByteArray> list = arr.split(' ');
       
   108 	file.close();
       
   109 	
       
   110 	QString username(list[0]);
       
   111 	QString password(list[1]);
       
   112 	
       
   113     QString httpProxy = "10.1.0.214";//ipwproxy.sasken.com
       
   114     QString httpPort = "3128";
       
   115 
       
   116     QString httpUser =username;/* This could be taken thru an QDialog implmentation to remove the Hard coding */
       
   117     QString httpPass =password;/* This could be taken thru an QDialog implmentation to remove the Hard coding */
       
   118 
       
   119     /*==Classes used from Network Module==*/
       
   120     QNetworkProxy proxy;
       
   121 
       
   122     proxy.setType(QNetworkProxy::HttpProxy);
       
   123     proxy.setHostName(httpProxy);
       
   124     proxy.setPort(httpPort.toInt());
       
   125     proxy.setUser(httpUser);
       
   126     proxy.setPassword(httpPass);
       
   127 
       
   128     QNetworkProxy::setApplicationProxy(proxy);
       
   129 #endif
       
   130 }
       
   131 ///////////////////////////////////////////////////////////////////////////////////////////////////
       
   132 // instance private functions
       
   133 QString FBRequest::md5(const QString& aData)
       
   134 {
       
   135     QByteArray byteArray;
       
   136     byteArray.insert(0, aData.toUtf8());
       
   137 
       
   138     QByteArray md5Hash = QCryptographicHash::hash(byteArray,QCryptographicHash::Md5 ).toHex();
       
   139     QString returnString ( md5Hash );
       
   140 
       
   141     return returnString;
       
   142 }
       
   143 
       
   144 bool FBRequest::isSpecialMethod() const {
       
   145     return ( iMethod.compare("facebook.auth.getSession", Qt::CaseInsensitive) == 0
       
   146              ||   iMethod.compare("facebook.auth.createToken", Qt::CaseInsensitive) == 0 );
       
   147 }
       
   148 
       
   149 QString FBRequest::urlForMethod (const QString& aMethod) const {
       
   150 
       
   151 	Q_UNUSED(aMethod)
       
   152 	return iSession->apiURL();
       
   153 }
       
   154 
       
   155 QString FBRequest::generateGetURL() const
       
   156 {
       
   157     const QUrl url(iUrl);
       
   158     const QString queryPrefix = url.hasQuery() ? "&" : "?";
       
   159 
       
   160     QStringList pairs;
       
   161     DictionaryIterator i(iParams);
       
   162 
       
   163     while (i.hasNext()) {
       
   164         i.next();
       
   165         pairs << i.key().toUtf8() + "=" + i.value().toUtf8();
       
   166     }
       
   167 
       
   168     return iUrl + queryPrefix + pairs.join("&");
       
   169 }
       
   170 
       
   171 QString FBRequest::generateCallId() const {
       
   172     QDateTime dateTime = QDateTime::currentDateTime();
       
   173     uint secs = dateTime.toTime_t();
       
   174     QString result = QString::number(secs, 10);
       
   175     return result;
       
   176 }
       
   177 
       
   178 QString FBRequest::generateSig(Dictionary Params)
       
   179 {
       
   180     QString joined;
       
   181     QStringList keys = Params.keys();
       
   182 
       
   183     qSort(keys.begin(), keys.end(), caseInsensitiveLessThan);
       
   184 
       
   185     QListIterator<QString> i(keys);
       
   186     
       
   187     joined.append(iSession->apiSecret().toUtf8());
       
   188     
       
   189     while (i.hasNext())
       
   190     {
       
   191         const QString key = i.next();
       
   192         joined.append(key.toUtf8());
       
   193         //joined.append("=");
       
   194         joined.append(Params.value(key).toUtf8());
       
   195     }
       
   196 
       
   197     return md5(joined);
       
   198 }
       
   199 
       
   200 void FBRequest::generatePostBody( QByteArray& body )
       
   201 {
       
   202     QString endLine = "\r\n--" + kStringBoundary + "\r\n";
       
   203     body.append( "--" + kStringBoundary.toUtf8() + "\r\n" ) ;
       
   204 
       
   205 
       
   206     DictionaryIterator i (iParams);
       
   207 
       
   208     while (i.hasNext())
       
   209     {
       
   210         i.next();
       
   211 
       
   212         body.append("Content-Disposition: form-data; name=\"" + i.key().toUtf8() + "\"\r\n\r\n" );
       
   213         body.append(i.value().toUtf8());
       
   214         body.append(endLine.toUtf8());
       
   215     }
       
   216 
       
   217 
       
   218     if (iDataParam.size())
       
   219     {
       
   220         if (iDataParamPicture)
       
   221         {
       
   222             body.append("Content-Disposition: form-data; filename=\"photo\"\r\n" );
       
   223             body.append("Content-Type: image/png\r\n\r\n" );
       
   224         }
       
   225         else
       
   226         {
       
   227             body.append("Content-Disposition: form-data; filename=\"data\"\r\n");
       
   228             body.append("Content-Type: content/unknown\r\n\r\n");
       
   229         }
       
   230 
       
   231         body.append(iDataParam);
       
   232         body.append(endLine.toUtf8());
       
   233 
       
   234     }
       
   235 }
       
   236 
       
   237 void FBRequest::handleResponseData( const QByteArray& aResponseData )
       
   238 {
       
   239 	qDebug()<<"Inside FBRequest::handleResponseData";
       
   240     FBError error;
       
   241     QVariant result =  parseXMLResponse( aResponseData, error);
       
   242     
       
   243     qDebug() << "parsed result : " << result;
       
   244     
       
   245     if (error.code() != 0)
       
   246     {
       
   247         emit requestFailedWithFlickrError(error);
       
   248     }
       
   249     else
       
   250     {
       
   251 		emit requestDidLoad(result);
       
   252     }
       
   253     delete pbar;
       
   254 }
       
   255 
       
   256 void FBRequest::post( const QString& aUrl, const Dictionary& aParams)
       
   257 {
       
   258     iUrl = aUrl;
       
   259     iParams = aParams;
       
   260 
       
   261     iSession->send(this);
       
   262 }
       
   263 
       
   264 void FBRequest::cancel()
       
   265 {
       
   266 
       
   267 }
       
   268 
       
   269 
       
   270 void FBRequest::call (const QString& aMethod, const Dictionary& aParams)
       
   271 {
       
   272 	qDebug()<<"Inside FBRequest::call";
       
   273     QByteArray dataParams;
       
   274     callWithDataParams(aMethod, aParams, dataParams, false);
       
   275 
       
   276 }
       
   277 void FBRequest::callforToken ()
       
   278 {
       
   279 	
       
   280 	iUrl = iSession->apiURL();
       
   281 	iMethod = "auth.getSession";
       
   282 
       
   283 	Dictionary params;
       
   284 	params["method"] = iMethod;
       
   285 	params["api_key"] = iSession->apiKey();
       
   286 	params["token"] = iSession->apiToken();
       
   287 	QString qstr = "api_key" + iSession->apiKey() + "methodauth.getSessiontoken" + iSession->apiToken() + iSession->apiSecret();
       
   288 	qDebug()<<"Api Key"<<iSession->apiKey(); 
       
   289 	qDebug()<<"Api Token"<<iSession->apiToken(); 
       
   290 	qDebug()<<"Api Secret"<<iSession->apiSecret(); 
       
   291 	qDebug()<<"qstr - sig"<<qstr<<"\n";
       
   292 	params["api_sig"] = md5(qstr);
       
   293 	
       
   294 	iParams = params;
       
   295 	
       
   296 	iSession->send(this);
       
   297 }
       
   298 
       
   299 void FBRequest::callWithDataParams (const QString& aMethod, const Dictionary& aParams, const QByteArray& aDataParam, bool aDataParamPicture)
       
   300 {
       
   301 	qDebug()<<"Inside FBRequest::callWithDataParams";
       
   302     iUrl = urlForMethod(aMethod);
       
   303     iMethod = aMethod;
       
   304     iParams = aParams;
       
   305     iDataParam = aDataParam;
       
   306     iDataParamPicture = aDataParamPicture;
       
   307 
       
   308     
       
   309     iParams["method"] = iMethod;
       
   310     iParams["api_key"] = iSession->apiKey();
       
   311     
       
   312     // XXX: workaround what seems to be a Qt bug with the extras-devel libraries.
       
   313     QString signature = generateSig(iParams);
       
   314     iParams["api_sig"] = signature;
       
   315     // XXX: end workaround.
       
   316     
       
   317     iSession->send(this);
       
   318 }
       
   319 
       
   320 
       
   321 QVariant FBRequest::parseXMLResponse ( const QByteArray& aResponseData, FBError& aError)
       
   322 {
       
   323 	qDebug()<<"Inside FBRequest::parseXMLResponse";
       
   324     QXmlInputSource input;
       
   325     input.setData(aResponseData);
       
   326 
       
   327     FBXMLHandler handler;
       
   328     QXmlSimpleReader parser;
       
   329     parser.setContentHandler(&handler);
       
   330     bool result = parser.parse(&input);
       
   331 
       
   332     QVariant rootObject = handler.rootObject();
       
   333     
       
   334 
       
   335     if (handler.parseError() || !result)
       
   336     {
       
   337         aError.setCode( FBRESPONSE_PARSE_ERROR );
       
   338         aError.setDescription("parser was unable to parse the xml response from facebook server.");
       
   339 
       
   340         return QVariant();
       
   341     }
       
   342     else if (handler.rootName().compare("error_response")==0)
       
   343     {
       
   344         QVariantHash errorDict =  rootObject.toHash();
       
   345 
       
   346         bool result;
       
   347         int errorCode = errorDict.value("error_code").toInt(&result);
       
   348 
       
   349         aError.setCode( errorCode );
       
   350         aError.setDescription( errorDict.value("error_msg").toString() );
       
   351 
       
   352         return rootObject;
       
   353     }
       
   354     else
       
   355     {
       
   356         return rootObject;
       
   357     }
       
   358 
       
   359 }
       
   360 
       
   361 ///////////////////////////////////////////////////////////////////////////////////////////////////
       
   362 // instance provate slots
       
   363 void FBRequest::networkReplyError ( QNetworkReply::NetworkError aCode )
       
   364 {
       
   365     emit requestFailedWithNetworkError(aCode );
       
   366 }
       
   367 
       
   368 void FBRequest::networkReplyFinished ()
       
   369 {
       
   370 	qDebug()<<"Inside FBRequest::networkReplyFinished";
       
   371     QNetworkReply* reply = static_cast<QNetworkReply*> ( sender() );
       
   372     QByteArray responseData = reply->readAll();
       
   373 
       
   374     qDebug() << "Response Data(QByteArray) : " << responseData;
       
   375     QString str(responseData);
       
   376     qDebug() << "Response Data(QString) : " << str;
       
   377     handleResponseData ( responseData );
       
   378 
       
   379 }