File indexing completed on 2025-01-19 03:55:37

0001 #include <QJsonArray>
0002 #include <QJsonDocument>
0003 #include <QJsonObject>
0004 
0005 #include "o1requestor.h"
0006 
0007 #include "twitterapi.h"
0008 
0009 TwitterApi::TwitterApi(QObject *parent): QObject(parent), authenticator_(0) {
0010     manager_ = new QNetworkAccessManager(this);
0011     tweetModel_ = new TweetModel(this);
0012 }
0013 
0014 TwitterApi::~TwitterApi() {
0015 }
0016 
0017 TweetModel *TwitterApi::tweetModel() {
0018     return tweetModel_;
0019 }
0020 
0021 O1Twitter *TwitterApi::authenticator() const {
0022     return authenticator_;
0023 }
0024 void TwitterApi::setAuthenticator(O1Twitter *v) {
0025     authenticator_ = v;
0026 }
0027 
0028 void TwitterApi::requestTweets() {
0029     if (!authenticator_ || !authenticator_->linked()) {
0030         tweetModel_->clearTweets();
0031         emit tweetModelChanged();
0032         return;
0033     }
0034     O1Requestor *requestor = new O1Requestor(manager_, authenticator_, this);
0035     QUrl url = QUrl("https://api.twitter.com/1.1/statuses/home_timeline.json");
0036     QNetworkRequest request(url);
0037     QNetworkReply *reply = requestor->get(request, QList<O0RequestParameter>());
0038     connect(reply, SIGNAL(finished()), this, SLOT(tweetsReceived()));
0039     connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(requestFailed(QNetworkReply::NetworkError)));
0040 }
0041 
0042 void TwitterApi::tweetsReceived() {
0043     QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
0044     QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll());
0045     tweetModel_->clearTweets();
0046     QJsonArray jsonArray = jsonResponse.array();
0047     foreach (const QJsonValue &v, jsonArray) {
0048         QVariantMap item = v.toObject().toVariantMap();
0049         tweetModel_->addTweet(item);
0050     }
0051     emit tweetModelChanged();
0052 }
0053 
0054 void TwitterApi::requestFailed(QNetworkReply::NetworkError error) {
0055     QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
0056     qWarning() << "TwitterApi::requestFailed:" << (int)error << reply->errorString() << reply->readAll();
0057 }
0058 
0059 #include "moc_twitterapi.cpp"