1//
2// Twitter.cpp
3//
4// A C++ implementation of a Twitter client based on the POCO Net library.
5//
6// Copyright (c) 2009-2013, Applied Informatics Software Engineering GmbH.
7// and Contributors.
8//
9// SPDX-License-Identifier: BSL-1.0
10//
11
12
13#include "Twitter.h"
14#include "Poco/Net/HTTPSClientSession.h"
15#include "Poco/Net/HTTPRequest.h"
16#include "Poco/Net/HTTPResponse.h"
17#include "Poco/Net/OAuth10Credentials.h"
18#include "Poco/Util/JSONConfiguration.h"
19#include "Poco/URI.h"
20#include "Poco/Format.h"
21#include "Poco/StreamCopier.h"
22
23
24const std::string Twitter::TWITTER_URI("https://api.twitter.com/1.1/statuses/");
25
26
27Twitter::Twitter():
28 _uri(TWITTER_URI)
29{
30}
31
32
33Twitter::Twitter(const std::string& twitterURI):
34 _uri(twitterURI)
35{
36}
37
38
39Twitter::~Twitter()
40{
41}
42
43
44void Twitter::login(const std::string& consumerKey, const std::string& consumerSecret, const std::string& token, const std::string& tokenSecret)
45{
46 _consumerKey = consumerKey;
47 _consumerSecret = consumerSecret;
48 _token = token;
49 _tokenSecret = tokenSecret;
50}
51
52
53Poco::Int64 Twitter::update(const std::string& status)
54{
55 Poco::Net::HTMLForm form;
56 form.set("status", status);
57 Poco::AutoPtr<Poco::Util::AbstractConfiguration> pResult = invoke(Poco::Net::HTTPRequest::HTTP_POST, "update", form);
58 return pResult->getInt64("id", 0);
59}
60
61
62Poco::AutoPtr<Poco::Util::AbstractConfiguration> Twitter::invoke(const std::string& httpMethod, const std::string& twitterMethod, Poco::Net::HTMLForm& form)
63{
64 // Create the request URI.
65 // We use the JSON version of the Twitter API.
66 Poco::URI uri(_uri + twitterMethod + ".json");
67
68 Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort());
69 Poco::Net::HTTPRequest req(httpMethod, uri.getPath(), Poco::Net::HTTPMessage::HTTP_1_1);
70
71 // Sign request
72 Poco::Net::OAuth10Credentials creds(_consumerKey, _consumerSecret, _token, _tokenSecret);
73 creds.authenticate(req, uri, form);
74
75 // Send the request.
76 form.prepareSubmit(req);
77 std::ostream& ostr = session.sendRequest(req);
78 form.write(ostr);
79
80 // Receive the response.
81 Poco::Net::HTTPResponse res;
82 std::istream& rs = session.receiveResponse(res);
83
84 Poco::AutoPtr<Poco::Util::JSONConfiguration> pResult = new Poco::Util::JSONConfiguration(rs);
85
86 // If everything went fine, return the JSON document.
87 // Otherwise throw an exception.
88 if (res.getStatus() == Poco::Net::HTTPResponse::HTTP_OK)
89 {
90 return pResult;
91 }
92 else
93 {
94 throw Poco::ApplicationException("Twitter Error", pResult->getString("errors[0].message", ""));
95 }
96}
97