Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

spouts: Port Twitter spouts to Guzzle #1102

Merged
merged 1 commit into from
Oct 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
### Other changes
- Removed broken instapaper scraping from Reddit spout ([#1033](https://github.com/SSilence/selfoss/pull/1033))
- RSS feed will be fetched more reliably ([#1052](https://github.com/SSilence/selfoss/pull/1052))
- Guzzle is now used for Twitter as well, allowing users to [install certificates](https://github.com/SSilence/selfoss/issues/1099#issuecomment-477112598) on outdated hosts easily. ([#1102](https://github.com/SSilence/selfoss/pull/1102))
- More of user interface is now translatable ([#1054](https://github.com/SSilence/selfoss/pull/1054))
- Open Sans font is no longer bundled, resulting in smaller installations. Additionally, `use_system_font` option was removed. The typeface is still set as the default font family, so if you want to use it, install it to your devices. If you want to use a different typeface, add `body { font-family: 'Foo Face'; }` to your `user.css`. ([#1072](https://github.com/SSilence/selfoss/pull/1072))
- The file name of exported sources now includes a timestamp ([#1078](https://github.com/SSilence/selfoss/pull/1078))
Expand Down
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,10 @@ Special thanks to the great programmers of this libraries which will be used in
* [WideImage](http://wideimage.sourceforge.net/)
* [htmLawed](http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/)
* [PHP Universal Feed Generator](https://github.com/ajaxray/FeedWriter)
* [twitteroauth](https://github.com/abraham/twitteroauth)
* [Elphin IcoFileLoader](https://github.com/lordelph/icofileloader)
* [jQuery hotkeys](https://github.com/tzuryby/jquery.hotkeys)
* [Spectrum Colorpicker](https://github.com/bgrins/spectrum)
* [jQuery custom content scroller](http://manos.malihu.gr/jquery-custom-content-scroller/)
* [twitter oauth library](https://github.com/abraham/twitteroauth)
* [FullTextRSS](http://help.fivefilters.org/customer/portal/articles/223153-site-patterns)
* [Graby](https://github.com/j0k3r/graby)

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
"type": "project",
"require": {
"php": ">= 5.6",
"abraham/twitteroauth": "^1.0",
"bcosca/fatfree-core": "dev-selfoss#cc3aa6af9a038dd9d0e136f42d9d18a02e077f39",
"danielstjules/stringy": "^3.1",
"fossar/tcpdf-parser": "^6.2",
"fossar/guzzle-transcoder": "^0.1.0",
"guzzlehttp/guzzle": "^6.3",
"guzzlehttp/oauth-subscriber": "^0.3.0",
"guzzlehttp/psr7": "^1.5",
"fossar/htmlawed": "^1.2.4.1",
"j0k3r/graby": "2.0.0-alpha.0",
Expand Down
107 changes: 52 additions & 55 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 2 additions & 22 deletions src/spouts/twitter/hometimeline.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

namespace spouts\twitter;

use Abraham\TwitterOAuth\TwitterOAuth;

/**
* Spout for fetching the twitter timeline of your twitter account
*
Expand Down Expand Up @@ -58,27 +56,9 @@ class hometimeline extends \spouts\twitter\usertimeline {
* @return void
*/
public function load(array $params) {
$twitter = new TwitterOAuth($params['consumer_key'], $params['consumer_secret'], $params['access_key'], $params['access_secret']);
$timeline = $twitter->get('statuses/home_timeline', [
'include_rts' => 1,
'count' => 50,
'tweet_mode' => 'extended',
]);

if (isset($timeline->errors)) {
$errors = '';

foreach ($timeline->errors as $error) {
$errors .= $error->message . "\n";
}

throw new \Exception($errors);
}
$this->client = self::getHttpClient($params['consumer_key'], $params['consumer_secret'], $params['access_key'], $params['access_secret']);

if (!is_array($timeline)) {
throw new \Exception('invalid twitter response');
}
$this->items = $timeline;
$this->items = $this->fetchTwitterTimeline('statuses/home_timeline');

$this->htmlUrl = 'https://twitter.com/';

Expand Down
31 changes: 5 additions & 26 deletions src/spouts/twitter/listtimeline.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

namespace spouts\twitter;

use Abraham\TwitterOAuth\TwitterOAuth;

/**
* Spout for fetching a twitter list
*
Expand Down Expand Up @@ -69,31 +67,12 @@ public function __construct() {
* @return void
*/
public function load(array $params) {
$access_token_used = !empty($params['access_token']) && !empty($params['access_token_secret']);
$twitter = new TwitterOAuth($params['consumer_key'], $params['consumer_secret'], $access_token_used ? $params['access_token'] : null, $access_token_used ? $params['access_token_secret'] : null);
$timeline = $twitter->get('lists/statuses',
[
'slug' => $params['slug'],
'owner_screen_name' => $params['owner_screen_name'],
'include_rts' => 1,
'count' => 50,
'tweet_mode' => 'extended',
]);

if (isset($timeline->errors)) {
$errors = '';

foreach ($timeline->errors as $error) {
$errors .= $error->message . "\n";
}

throw new \Exception($errors);
}
$this->client = self::getHttpClient($params['consumer_key'], $params['consumer_secret'], $params['access_token'], $params['access_token_secret']);

if (!is_array($timeline)) {
throw new \Exception('invalid twitter response');
}
$this->items = $timeline;
$this->items = $this->fetchTwitterTimeline('lists/statuses', [
'slug' => $params['slug'],
'owner_screen_name' => $params['owner_screen_name'],
]);

$this->htmlUrl = 'https://twitter.com/' . urlencode($params['owner_screen_name']);

Expand Down
113 changes: 91 additions & 22 deletions src/spouts/twitter/usertimeline.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

namespace spouts\twitter;

use Abraham\TwitterOAuth\TwitterOAuth;
use GuzzleHttp;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
use helpers\WebClient;
use stdClass;

/**
Expand Down Expand Up @@ -64,6 +67,90 @@ class usertimeline extends \spouts\spout {
/** @var string URL of the source */
protected $htmlUrl = '';

/** @var ?GuzzleHttp\Client HTTP client configured with Twitter OAuth support */
protected $client = null;

/**
* Provide a HTTP client for use by spouts
*
* @param string $consumerKey
* @param string $consumerSecret
* @param string $accessToken
* @param string $accessTokenSecret
*
* @return GuzzleHttp\Client
*/
public static function getHttpClient($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret) {
$access_token_used = !empty($accessToken) && !empty($accessTokenSecret);

$oldClient = WebClient::getHttpClient();
$config = $oldClient->getConfig();

$config['base_uri'] = 'https://api.twitter.com/1.1/';
$config['auth'] = 'oauth';
$middleware = new Oauth1([
'consumer_key' => $consumerKey,
'consumer_secret' => $consumerSecret,
'token' => $access_token_used ? $accessToken : '',
'token_secret' => $access_token_used ? $accessTokenSecret : '',
]);
$config['handler'] = clone $config['handler']; // we do not want to contaminate other spouts
$config['handler']->push($middleware);

return new GuzzleHttp\Client($config);
}

/**
* Fetch timeline from Twitter API.
*
* Assumes client property is initialized to Guzzle client configured to access Twitter.
*
* @param string $endpoint API endpoint to use
* @param array $params extra query arguments to pass to the API call
*
* @throws Exception when API request fails
* @throws GuzzleHttp\Exception\RequestException when HTTP request fails for API-unrelated reasons
*
* @return stdClass[]
*/
protected function fetchTwitterTimeline($endpoint, array $params = []) {
if (!isset($this->client)) {
throw new \Exception('Twitter client was not initialized.');
}

try {
$response = $this->client->get("$endpoint.json", [
'query' => array_merge([
'include_rts' => 1,
'count' => 50,
'tweet_mode' => 'extended',
], $params),
]);

$timeline = json_decode((string) $response->getBody());

if (!is_array($timeline)) {
throw new \Exception('Invalid twitter response');
}

return $timeline;
} catch (BadResponseException $e) {
if ($e->hasResponse()) {
$body = json_decode((string) $e->getResponse()->getBody());

if (isset($body->errors)) {
$errors = implode("\n", array_map(function($error) {
return $error->message;
}, $body->errors));

throw new \Exception($errors, $e->getCode(), $e);
}
}

throw $e;
}
}

//
// Iterator Interface
//
Expand Down Expand Up @@ -145,30 +232,12 @@ public function valid() {
* @return void
*/
public function load(array $params) {
$access_token_used = !empty($params['access_token']) && !empty($params['access_token_secret']);
$twitter = new TwitterOAuth($params['consumer_key'], $params['consumer_secret'], $access_token_used ? $params['access_token'] : null, $access_token_used ? $params['access_token_secret'] : null);
$timeline = $twitter->get('statuses/user_timeline', [
$this->client = self::getHttpClient($params['consumer_key'], $params['consumer_secret'], $params['access_token'], $params['access_token_secret']);

$this->items = $this->fetchTwitterTimeline('statuses/user_timeline', [
'screen_name' => $params['username'],
'include_rts' => 1,
'count' => 50,
'tweet_mode' => 'extended',
]);

if (isset($timeline->errors)) {
$errors = '';

foreach ($timeline->errors as $error) {
$errors .= $error->message . "\n";
}

throw new \Exception($errors);
}

if (!is_array($timeline)) {
throw new \Exception('invalid twitter response');
}
$this->items = $timeline;

$this->htmlUrl = 'https://twitter.com/' . urlencode($params['username']);

$this->spoutTitle = "@{$params['username']}";
Expand Down