Skip to content

Commit

Permalink
following list example
Browse files Browse the repository at this point in the history
  • Loading branch information
cyle committed Nov 27, 2023
1 parent d1bedce commit 72ef705
Show file tree
Hide file tree
Showing 5 changed files with 273 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Expand Up @@ -3,3 +3,5 @@
/phpunit.xml
/build/
/.*.cache
/.idea/

4 changes: 4 additions & 0 deletions README.md
Expand Up @@ -70,6 +70,10 @@ $client->reblogPost($blogName, $id, $reblogKey, $options = null);
$client->getTaggedPosts($tag, $options = null);
```

## Examples

Examples and "Getting Started" guide are available in [the `examples` folder](examples).

## Dependencies

tumblr.php is available [on Packagist](https://packagist.org/packages/tumblr/tumblr)
Expand Down
29 changes: 29 additions & 0 deletions examples/README.md
@@ -0,0 +1,29 @@
# Getting Started with the Tumblr API

This is a quick-start guide to making something with Tumblr's public API. It assumes very little prior knowledge of programming, but to get the most out of Tumblr's API, you'll need to learn some concepts and do some setup. From here, you can dive into some of the examples in this folder for more!

## What is the Tumblr API?

The Tumblr API is a publicly-accessible interface for getting information out of or into Tumblr, such as a blog's posts, your own likes, or search results for a certain tag. The Tumblr API is what powers Tumblr itself, including our website and our mobile apps. The API is what provides the details about what you're seeing on Tumblr. The website and our mobile apps are just our officially-supported ways of accessing Tumblr, but you can build your own!

## How to set up your first Tumblr API application

To get started, [check out our public documentation about using the API](https://github.com/tumblr/docs/blob/master/api.md). This will be your primary resource for figuring out what you want to do, how to do it, and what different Tumblr-specific things mean.

Next, go to [the developer applications page](https://www.tumblr.com/oauth/apps), and click "Register application" to set up your first API application. Fill in the required information, but note for the purposes of this guide, what you put inside "Default callback URL" and "OAuth2 redirect URLs" doesn't actually matter, so put whatever you want.

Once you've created your first application, it should appear under "[Applications](https://www.tumblr.com/oauth/apps)", and you'll be able to get your "OAuth Consumer Key" and "Secret Key". They'll look like long sequences of numbers and letters. As the name implies, please keep that secret key a secret! Don't give it to other people. These two things are what identify your application to us at Tumblr.

## Getting your own Tumblr API OAuth credentials

Now that you have your OAuth consumer key and secret, you can get some credentials to try to get information from the Tumblr API using your actual account. You can also start playing with the Tumblr API Console. To get these credentials, go to [the API console](https://api.tumblr.com/console) and enter your new consumer key and secret, and then click "Authenticate". You'll be redirected to a page that authorizes your application to use your account, and when you accept that and land on the API console, you'll be given a demo of using one of our Tumblr API libraries, along with a "Token" and "Token Secret".

Those two long jumbles of numbers and letters, the "Token" and "Token secret", represent your account, so keep them secret, just like you should keep the OAuth Consumer Secret Key a secret! With all four of these pieces of information, you can hit the Tumblr API and get all kinds of info, and even make posts, see who you're following, do searches, etc.

## Installing PHP, Composer, and Tumblr.php

We'll use [PHP](https://www.php.net/) as our programming language for examples in this folder. If you're on a Mac, the easiest way to install PHP is to open up the Terminal app, [install Homebrew](https://brew.sh/), and then run "brew install php" in Terminal after Homebrew is installed. (We'll be spending a lot of time in the Terminal app.) After PHP installs, you should be able to run `php --version` in Terminal to see what version of PHP you have. If you're using Windows, you'll likely use [PowerShell](https://docs.microsoft.com/en-us/powershell/) instead of Terminal, and you'll have to [install the PHP binaries manually](https://windows.php.net/download).

Next, we need to install [Composer](https://getcomposer.org/), which is a PHP tool that will help you install the Tumblr PHP API client library. Luckily, if you installed Homebrew, you'll be able to just run `brew install composer` to get it. Otherwise, [download Composer to install it](https://getcomposer.org/download/) (if you're on Windows, you should follow those instructions).

From here, check out [the Following List example](following-list) to write a script that gets who you're following and shows more information than what we do in the actual Following screen on Tumblr itself.
60 changes: 60 additions & 0 deletions examples/following-list/README.md
@@ -0,0 +1,60 @@
# A simple demo script: Information about who you're following

The end result of this tutorial is a script that'll list out who you're following, showing who you're mutuals with and when they last posted.

## Install dependencies

If you followed along from the example folder README, you're halfway there.

Once Composer is installed, we'll want to create a folder for our project. Make a folder anywhere, such as in your local Documents folder, and then go there in Terminal (or PowerShell on Windows). If you used your Documents folder and made a new folder there, then the command to go there will be `cd ~/Documents/your-folder-name-here`

When you're inside that new project folder, run `composer require tumblr/tumblr` in Terminal (or PowerShell) to install [the official PHP Tumblr API client](https://github.com/tumblr/tumblr.php). Then, create a new file for our demonstration script, named `following.php`, and open that in a text editor of some kind. At Tumblr, we like [PHPStorm](https://www.jetbrains.com/phpstorm/) (paid) and [Visual Studio Code](https://code.visualstudio.com/) (free) a lot, but any "plain text" editor will do. (Note that text editors like Microsoft Word or Google Docs are not "plain text", so they won't necessarily work.)

## Creating our script

The first thing to do in your new `following.php` file is to just "echo" something to make sure PHP is working. So just put in:

```php
<?php

echo 'hello!';
```

... and save the file, and in Terminal (or PowerShell), type in `php following.php` and press Enter/Return, and you should see "hello!" – congratulations, you just wrote a PHP script!

From here, we need to import our Composer packages, of which Tumblr's API client is included, so replace everything in the "following.php" file with:

```php
<?php

// this loads our tumblr.php library automagically
require __DIR__ . '/vendor/autoload.php';
```

... and now let's set up the Tumblr API client itself, so we can start asking Tumblr for information. After the above four lines, add these:

```php
$consumer_key = ''; // put your consumer key between the ‘'
$consumer_secret = ''; // put your consumer secret between the ‘'
$token_key = ''; // put your token between the ‘'
$token_secret = ''; // put your token secret between the ‘'

$tumblr = new \Tumblr\API\Client($consumer_key, $consumer_secret, $token_key, $token_secret);
```

... and fill all of that information out as described. There's an example of the kinds of data this expects in [the User Info console page](https://api.tumblr.com/console/calls/user/info).

And now let's add to the end of the file our first actual call to the Tumblr API:

```php
$blogs_response = $tumblr->getFollowedBlogs();
foreach ($blogs_response->blogs as $blog) {
echo "{$blog->url}\n";
}
```

... and if you run `php following.php` now, you'll likely get a list of blog URLs you're following, which is actually the first "page" of who you're following on Tumblr. Congratulations, you've just used the Tumblr API!

From here, you'll have to [learn PHP](https://www.php.net/manual/en/getting-started.php), [our PHP client library](https://github.com/tumblr/tumblr.php), and [the Tumblr API endpoints and fields](https://github.com/tumblr/docs/blob/master/api.md) to do more.

As a bigger, more complete example, in this folder is a more complete `following.php` script you can run, as promised at the start of this guide. Copy that script somewhere, run the composer install as described at the top of the file, and run `php following.php help` for more information on what it can do!
178 changes: 178 additions & 0 deletions examples/following-list/following.php
@@ -0,0 +1,178 @@
<?php
/**
* A tool for grabbing a list of the blogs you're following on Tumblr,
* and output a table of information about them, like when they last posted, and whether
* you're mutuals or not. With a couple of command options for fun!
*
* This expects PHP 7.4+ as a runtime, with tumblr.php installed via composer.
* See: Composer https://getcomposer.org/
* See: Tumblr.php API client https://github.com/Tumblr/tumblr.php
* See: Tumblr's API docs https://github.com/tumblr/docs/blob/master/api.md
*
* If you're on a Mac, I suggest using Homebrew to install php
* See: https://brew.sh/
* Then try:
* $ brew install php@7.4
* Then install Composer from the link above
* Then try:
* $ composer require tumblr/tumblr
*
* Then you have to fill in your API consumer and token details below.
*
* For help on how to use this, run:
* $ php following.php help
*/

// loads our tumblr.php library automagically
require __DIR__ . '/vendor/autoload.php';

// fill in this info about your API consumer info + user token info!
// set up your own at https://www.tumblr.com/oauth/apps
$consumer_key = '';
$consumer_secret = '';
$token_key = '';
$token_secret = '';
date_default_timezone_set('US/Eastern'); // also, update this to your timezone!

echo 'Following info script! Hello!' . "\n";

// show help info if we're asked
if (($argv[1] ?? null) === 'help') {
echo 'Run with no arguments for the default, which is to list all followed blogs by last updated time:' ."\n";
echo '$ php following.php' . "\n";
echo 'Or pass along some arguments. The first one is the sort order, the second is mutuals only or not:' . "\n";
echo '$ php following.php last_updated 1' . "\n";
echo 'Sort order can be "last_updated" or "alphabetical", mutuals only can be 1 (yes) or 0 (no).' . "\n";
exit(0);
}

if ($consumer_key === '' || $consumer_secret === '' || $token_key === '' || $token_secret === '') {
echo 'You need to fill out your consumer key, consumer secret, token key, and token secret in this script for it to work.' . "\n";
exit(1);
}

$tumblr = new \Tumblr\API\Client($consumer_key, $consumer_secret, $token_key, $token_secret);

// figure out our configurable options
$sort_by = $argv[1] ?? 'last_updated';
$mutuals_only = boolval($argv[2] ?? false) ?? false;

echo 'Sorting by: ' . $sort_by . "\n";
echo 'Mutuals only? ' . ($mutuals_only ? 'yeah' : 'nope') . "\n";

$blogs = []; // we'll keep the blog objects here for display later
$next_offset = 0; // keep track of the next offset to ask for

echo "Fetching the blogs you're following, this may take awhile depending on how many you follow.\n";

// while we have an offset, keep asking Tumblr for the blogs we're following
while ($next_offset !== null) {
$blogs_response = $tumblr->getFollowedBlogs([
// some special fields that we can use to learn more
'fields' => [
'blogs' => 'name,updated,url,?duration_blog_following_you,?duration_following_blog',
],
'offset' => $next_offset,
]);

// if we have a next offset to use, capture it for the next loop
$next_offset = $blogs_response->_links->next->query_params->offset ?? null;

foreach ($blogs_response->blogs as $blog_object) {
$blogs[] = $blog_object; // for sorting after we fetch all of them
}

// be nice to the API and sleep for a second between each request,
// or else it may rate limit us
if ($next_offset !== null) {
sleep(1);
}

echo '.'; // love logging dots as progress
}

echo ' done!' . "\n";

// our default sorting option, latest-first
function sort_blogs_last_updated_first($blog1, $blog2) {
return $blog2->updated <=> $blog1->updated;
}

// another sorting option, basic alphabetical
function sort_blogs_alphabetically($blog1, $blog2) {
return $blog1->name <=> $blog2->name;
}

switch ($sort_by) {
case 'last_updated':
usort($blogs, 'sort_blogs_last_updated_first');
break;
case 'alphabetical':
usort($blogs, 'sort_blogs_alphabetically');
break;
default:
// lol, always have a fallback
echo 'Actually I have no idea how to sort the list, you gave me an invalid option...' . "\n";
}

// let's keep track of some stuff to show at the end
$mutual_counter = 0;
$following_count = 0;
$now = time();
$oldest_mutual_name = null;
$oldest_mutual_duration = null;

// manually doing some spacing here as an uncomplicated hack
echo "blog name last updated time mutual status \n";
$max_name_length = 32; // we'll use this to determine the padding after each blog name

// let's go through each blog and write out some data
foreach ($blogs as $blog) {
$mutuals = $blog->duration_blog_following_you > -1 && $blog->duration_following_blog > -1;
if ($mutuals_only && !$mutuals) {
continue; // skip if we're only showing mutuals
}

echo $blog->name; // we also have $blog->url

// figure out how much padding is needed to make the output look nice
$padding = $max_name_length - strlen($blog->name) + 2;
for ($i = 0; $i < $padding; $i++) {
echo ' ';
}

echo date('Y-m-d h:i A', $blog->updated);
echo " ";

if ($mutuals) {
echo 'Mutuals!';
$mutual_counter++;
if ($oldest_mutual_duration === null || $oldest_mutual_duration < $blog->duration_blog_following_you) {
$oldest_mutual_duration = $blog->duration_blog_following_you;
$oldest_mutual_name = $blog->name;
}
} else {
echo 'Not mutuals.';
}

echo "\n";
$following_count++;
}

// output some interesting info at the end as well
if ($mutuals_only) {
echo sprintf('You have %d mutuals!', $mutual_counter) . "\n";
} else {
echo sprintf('Following %d blogs, %d of which are mutuals', $following_count, $mutual_counter) . "\n";
}

// if we have an "oldest" mutual, give us some info about them as well
if ($oldest_mutual_name !== null) {
echo sprintf(
'Your oldest mutual is %s who has been following you since %s!',
$oldest_mutual_name,
date('F d, Y', $now - $oldest_mutual_duration)
) . "\n";
}

echo "Thanks for calling! Have a nice day! \n";

0 comments on commit 72ef705

Please sign in to comment.