Last time we covered the idea of building a comment system for a blog or website on top of Mastodon. Specifically, we introduced the topic and looked at displaying such posts, along with an explanation of why the concept can be tempting. If you missed that article or want to refresh your memory, you can find it here. Without further ado, welcome to part two, where we deal with adding comments from the blog itself, still through Mastodon, of course. Along the way we will also talk a bit more about the federated nature of this social network.
We start with a few theoretical points. If you are already comfortable with the Fediverse or OAuth 2.0, feel free to skip those sections and go straight to the example implementation.
Why is adding comments not easy?
In most features of most applications, displaying data is easier than entering it. Showing information on the screen usually requires only a GET request and some structuring and styling of the results. Adding or updating data, on the other hand, calls for form handling, validation, error messages and, finally, saving the values in a specific format. Now imagine that we have to do that last part through an external API.
That is exactly the situation with Mastodon, though it is no exception: any system in its place would feel the same. The next thing we have to deal with is authorizing the user who wants to post. In large systems that allow SSO (Single Sign-On, we will come back to it shortly), there is no way to simply send a password in an API request. For one, it would raise security concerns (even though HTTPS is our friend here). For another, users should not have to type their password for an external service into, say, our website and worry about it. That is why we need to learn how to use OAuth 2.0.
First, though, we have to face one more issue that relates directly to Mastodon, or rather the whole Fediverse: the federated, distributed design of the whole system. With Twitter, for example, integrating would be relatively simple. There is one server (yes, it is really a server farm, but that does not matter from our point of view), and anyone who wants to use their account on the bird app has a single entry point to go to (twitter.com). With Mastodon it is not that obvious: every user who visits our blog and wants to comment on an article may have an account on a different instance. Fortunately, all instances have the same API, but we have to be aware that an authorization token obtained for one server will not work on another. We will deal with that problem today as well.
The federated nature also raises another problem: how posts are distributed between instances. We need to stop here for a moment.
How is a post distributed on Mastodon?
In a centralized system everything is fairly simple. A user logs in to the service, fills in the post, clicks "send", and the post goes to the server. Every user who sees it gets exactly the same package of data that was originally published, under the same identifier as every other recipient. That makes it easy to send someone a link to a message, because there is only one such link. And how does it work in a federated system? Things get a bit more complicated, and it matters for us.
The idea of federation is that individual instances are independent entities, but they let users communicate with each other as if it were a single organism. So if a user on instance A writes a post, it can be seen not only by users of instance A, but also by those users of instance B who follow that user (in simplified terms). The usual rule of social networks applies: if we follow someone, or someone we follow boosts a toot, or we open the conversation directly, we can see posts from another instance. There may be a noticeable delay at times, but in the end it works. The catch is that technically, these posts are not the same as the originals.
Imagine that we are on instance A and browsing a post from our home server, or simply looking at our timeline. We may do this many times a day, and most of the time we see not only posts published on instance A, but also ones that reached us from instances B, C, D and so on. In the most basic approach, our copy of Mastodon would have to check other instances every time to find out which posts to fetch. Without any experiments we can say that this makes no sense: in a system that serves thousands of users (the largest instances have several hundred thousand), fetching external data for every person in every situation is a sure path to performance problems (and could even prevent normal operation, and not only on "our" machine). For this reason, toots and profile information from other instances are copied onto every instance where they were displayed. Of course, it does not work perfectly, but this kind of caching is a much better solution than going back to the source every time. Along with the copy, links to the original are stored, so that at certain moments the data is updated, for example when the original post has been edited.
The most important lesson from this, and one we will need later, is that a toot can have completely different identifiers on the original instance and on others. Take the introductory Wilda Software post on our instance as an example. The original link to it looks like this:
https://social.wildasoftware.pl/@wilda/110010384660147893
But when someone from, say, the instance 101010.pl views this post, they see a different address:
https://101010.pl/@wilda@social.wildasoftware.pl/110010384696884554
It is easy to tell that this toot does not come from the current server: the domain is appended to the username, and the identifier at the end is different as well. That is not strange, because different instances have separate databases and therefore a different numbering sequence. If a post got ID = 10 on instance A, we cannot expect that after it is fetched to instance B, C or D it will have the same ID there, or that it will be next in line. On every server the number will be different, but the content stays the same.
And when are our posts copied to instance A in the first place? In simplified terms, when they are replies to a toot from instance A (even to a copy of that toot), when someone on instance A follows us, or when the post is a private message. It does not always happen immediately. When mastodon.social (the largest Mastodon instance, run by its creator himself) had serious performance problems some time ago, posts from there showed up on other instances with a long delay. Copying is not an idea specific to Mastodon, either. It comes from ActivityPub, the interface that ties together all Fediverse applications, such as Pixelfed, /kbin or Friendica.
As you can see, federation is not a simple concept and it will make our task a bit harder, but it definitely works and allows horizontal scaling of the whole system, improving its availability and performance (performance problems mostly affect very large instances, that is, points that try to centralize everything). Now it is time for the second "trouble": using the API on behalf of a given user, which means getting to know how a certain protocol works.
OAuth 2.0
Just in case, let me point out right away that OAuth 2.0 has nothing to do with federation. It is a standard protocol for user authorization that is used in the APIs of many different IT systems. Not all of them: there are other approaches, including simpler ones based on JWT (JSON Web Token), which is also widely used and has its own pros and cons, just like the hero of this section. OAuth 2.0 is usually used when you want to achieve so-called single sign-on, SSO for short (Single Sign-On), that is, logging in to many services with one account. Some readers may now have a light bulb go on: many websites offer authentication with a Google, Facebook or Apple account. Yes, that is OAuth 2.0 as well, and although integrating with such systems will always differ (because the implementation of the protocol itself differs), the general principle is similar.
Formally, this protocol can be treated as a mechanism for authorizing the delegation of access to a user's resources. Put simply, this is how we can give an external site (for example, a blog) the ability to save data on Mastodon through our account. The uses are much broader, of course, but in our case it will mainly be about posting toots and reading search results and profile data.
How does the whole process go?
- On the blog, the user chooses to perform an action using their account in an external service (Mastodon). Most often this is logging in, but in our case it will be replying to a comment.
- The site redirects the user to the external provider (a specific Mastodon instance) with a request for authorization of specific types of operations (the so-called scope). If the person is not logged in, they have to enter their credentials (usually an email address and a password).
- The external provider displays the types of operations the blog needs for its purposes (for example, the ability to post). The user confirms.
- The external provider generates a code and returns with it to the blog, to a previously specified address (sent along with the authorization request).
- Using the code (token), the blog can perform further operations on behalf of the user's account.
As I said, this is a general procedure and it may change depending on the needs and the external service. It looks a little different for Google and for Mastodon. Still, the principle is similar and leads to confirming that the user agrees to the use of their account within a given blog or website for specific purposes. In our case, it confirms that a post made from our blog will appear in the Fediverse under their account. It is also worth noting that in most cases, authorization for a given set of operations is remembered for some time, so there is no need to confirm it every time, for example when we log in with a Google account. If we do it regularly, it usually happens automatically.
If you want to learn this protocol in more detail, or focus on HTTP requests and security, or find out why it should not be used for plain authentication, we recommend this article from Sekurak.
Example implementation
Armed with knowledge of how posts "travel" on Mastodon and how to authorize operations there, we can move on to the example implementation. As before, we will use the example we prepared earlier in PHP, Laravel and Bootstrap, available here:
https://github.com/WildaSoftware/MastodonCommentSystem
Let me stress once more that this is an example implementation. It is not a library ready to be dropped into your project, nor an ideal to aim for. There is plenty of room for your own ideas, fixes and, above all, adapting it to the system in which the comment system is to be embedded. We would be glad to see how you implemented your own Mastodon-based comments on your blogs or websites. It is always a chance to exchange experience.
Adding a comment takes a few more steps than displaying them. That is why we will not start with an outline of the whole process, but go through it stage by stage until we reach the goal.
Starting the procedure and choosing an instance
First, we have to remember that, unlike with Twitter, for example, an integration with Mastodon has no clearly assigned server. Users may come to us from mastodon.social, pol.social, 101010.pl, wspanialy.eu or a completely different instance. This matters because it determines the server where a person's account lives, and therefore where the API call goes. So at the start the user has to choose an instance. We do this by opening a modal window in response to a click on the reply button.
// fragment pliku blog-post-comment-box.blade.php
<div class="col-12 comment" ...>
...
<div class="comment-reply-to row">
<div class="col-12 text-right">
<i class="comment-reply-link fa-solid fa-reply fa-lg" data-src="{{ $comment['url'] }}" title="{{ __('replyToThisCommentWithMastodon') }}"></i>
</div>
</div>
</div>
// fragment pliku blog-post.blade.php
<body>
...
<div class="modal fade" id="mastodon-reply-modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ __('enterMastodonDomain') }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="{{ __('closeModal') }}">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>{!! __('provideMastodonInstanceToReply') !!}</p>
<input type="hidden" id="mastodon-src-reply"/>
<input type="text" class="form-control" id="mastodon-domain-reply" placeholder="{{ __('provideMastodonInstanceShort') }}">
</div>
<div class="modal-footer">
<button type="button" id="mastodon-reply-modal-confirm" class="btn btn-primary">{{ __('confirmModal') }}</button>
<button type="button" id="mastodon-reply-modal-cancel" class="btn btn-secondary" data-dismiss="modal">{{ __('cancelModal') }}</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="mastodon-reply-modal-failure" tabindex="-1" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ __('mastodonFailure') }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="{{ __('closeModal') }}">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>{{ __('noMastodonConnectionDescription') }}</p>
</div>
<div class="modal-footer">
<button type="button" id="mastodon-reply-modal-ok" class="btn btn-primary">{{ __('ok') }}</button>
</div>
</div>
</div>
</div>
...
<script src="<?= URL::to('/') ?>/js/post.js"></script>
<script>
(new PostScript(
"<?= URL::to('/') ?>",
<?= $post->id ?>,
<?= json_encode($commentSourceIds) ?>,
<?= json_encode([
'enterMastodonDomain' => __('enterMastodonDomain'),
]) ?>,
<?= !empty($mastodonCode) ? '"'.$mastodonCode.'"' : '' ?>
)).init();
</script>
</body>
// fragment pliku post.js
class PostScript {
constructor(baseUrl, postId, commentSourceIds, translations, mastodonCode) {
this.baseUrl = baseUrl + '/';
this.postId = postId;
this.commentSourceIds = commentSourceIds;
this.translations = translations;
this.mastodonCode = mastodonCode;
this.isCommentContainerLoaded = false;
}
init() {
$('#comment-container').on('click', '.comment-reply-link', (event) => {
const savedDomain = localStorage.getItem('lastMastodonDomain');
if(savedDomain) {
$('#mastodon-domain-reply').val(savedDomain);
}
const src = $(event.target).data('src');
$('#mastodon-src-reply').val(src);
$('#mastodon-domain-reply').removeClass('error');
$('#mastodon-reply-modal').modal('show');
});
$('#mastodon-reply-modal-confirm').on('click', (event) => {
$('#mastodon-domain-reply').removeClass('error');
const domain = $('#mastodon-domain-reply').val();
const src = $('#mastodon-src-reply').val();
if(domain && src) {
$('#mastodon-reply-modal').modal('hide');
localStorage.setItem('lastMastodonDomain', domain);
localStorage.setItem('lastMastodonSrc', src);
$.ajax({
...
},
error: (err) => {
$('#mastodon-reply-modal-failure').modal('show');
}
});
}
else {
$('#mastodon-domain-reply').addClass('error');
}
});
$('#mastodon-reply-modal-ok').click((event) => {
$('#mastodon-reply-modal-failure').modal('hide');
});
}
...
}
These are only the fragments of the files that interest us at the moment. The first thing we see is that under every comment there is an icon where the whole operation starts. It has the HTML class comment-reply-link and, in response to a click, shows the modal window.
I want to point out right away that this can be solved differently: instead of a modal window you can choose a dropdown list, a plain text field or yet another implementation. It makes no difference. We did it this way, but any other method that leads to the right instance is just as good. The right one, because we have to be prepared for the user entering a nonexistent address or one that is not a Mastodon server. That is why our logic is so complicated and there are as many as two modal windows, one for entering the instance and the other for reporting an error at the connection stage (which we will get to in the next step). Additionally, if this is not the user's first contact with the comment system on our blog, the value entered earlier is recalled from local storage, that is, the browser's local data store. In response to the button, we check whether an instance was given previously and, if so, restore it. Then, once the user confirms the domain, we check for possible errors (mainly an empty string) and, if everything is fine, we save the updated value and move on to the integration with Mastodon.
Getting an application
Here we need to cover three things. First, from now on we will make heavy use of the Mastodon API, which is described here, and specifically connecting to a Fediverse account, described here. Second, all requests are triggered from JavaScript, but they go through the PHP controller MastodonController, which will stay with us until the end. This is because along the way we will use a few optimization tricks that require our database, and Laravel lets us talk to it. In theory, however, nothing stops us from calling these requests directly from JS.
Third, to use the Mastodon API we need a so-called application. This term covers a set of credentials (so-called secrets) that we use to make further requests. For a single instance, these credentials can also be created manually, in your Mastodon account panel. In our situation, however, we do not know which instance we will be talking to, and above all we will not have an account on each of them. Fortunately, such an application can be created "remotely", through the API.
// fragment pliku post.js
$('#mastodon-reply-modal-confirm').on('click', (event) => {
$('#mastodon-domain-reply').removeClass('error');
const domain = $('#mastodon-domain-reply').val();
const src = $('#mastodon-src-reply').val();
if(domain && src) {
$('#mastodon-reply-modal').modal('hide');
localStorage.setItem('lastMastodonDomain', domain);
localStorage.setItem('lastMastodonSrc', src);
$.ajax({
type: 'GET',
url: this.baseUrl + 'mastodon/app/' + domain,
data: { redirectUri: window.location.href },
cache: true,
success: (res) => {
const json = JSON.parse(res);
const authorizeUrl = 'https://' + domain + '/oauth/authorize?'
+ 'client_id=' + json.clientId
+ '&scope=' + json.scope
+ '&redirect_uri=' + json.redirectUri
+ '&response_type=code';
window.location.href = authorizeUrl;
},
error: (err) => {
$('#mastodon-reply-modal-failure').modal('show');
}
});
}
else {
$('#mastodon-domain-reply').addClass('error');
}
});
// fragment pliku web.php z routingiem
Route::get('/mastodon/app/{instance}', [MastodonController::class, 'getAppCredentials']);
Route::get('/mastodon/token/{instance}/{code}', [MastodonController::class, 'getToken']);
Route::get('/mastodon/post/{instance}', [MastodonController::class, 'getPostInfoOnInstance']);
Route::post('/mastodon/toot/{instance}', [MastodonController::class, 'sendToot']);
// fragment pliku MastodonController.php
class MastodonController extends Controller {
private $presenter;
private $mastodonInstanceCredentialsRepository;
private $postCommentSourceRepository;
public function __construct() {
parent::__construct();
$this->presenter = new MastodonPresenter();
$this->mastodonInstanceCredentialsRepository = new MastodonInstanceCredentialsRepository();
$this->postCommentSourceRepository = new PostCommentSourceRepository();
}
public function getAppCredentials(Request $request, $instance) {
$redirectUri = $request->get('redirectUri', env('MASTODON_APP_REDIRECT_URI'));
if(App::environment('local')) {
$redirectUri = env('MASTODON_APP_REDIRECT_URI');
}
$credentials = $this->mastodonInstanceCredentialsRepository->getByInstance($instance);
if(empty($credentials)) {
$url = 'https://'.$instance.'/api/v1/apps';
$body = [
'client_name' => env('MASTODON_APP_NAME'),
'redirect_uris' => $redirectUri,
'scopes' => str_replace('+', ' ', env('MASTODON_APP_SCOPES')),
'website' => URL::to('/'),
];
$response = Http::asForm()->post($url, $body);
if($response->successful()) {
$rawOutput = $response->body();
$output = json_decode($response->body(), true);
$now = (new DateTime())->format('Y-m-d H:i:s');
$credentials = new MastodonInstanceCredentials();
$credentials->instance = $instance;
$credentials->client_id = $output['client_id'];
$credentials->client_secret = $output['client_secret'];
$credentials->vapid_key = $output['vapid_key'];
$credentials->response = $rawOutput;
$credentials->save();
}
else {
$message = 'Error during calling '.$url.' with body '.print_r($body, true);
Log::error($message);
Log::error($response->status().': '.print_r($response->body(), true));
return response(json_encode(['message' => $message], 500));
}
}
$response = [
'clientId' => $credentials->client_id,
'redirectUri' => $redirectUri,
'scope' => env('MASTODON_APP_SCOPES'),
];
return response(json_encode($response), 200);
}
...
}
// fragment pliku .env
MASTODON_APP_NAME=MastodonCommentSystem_test
MASTODON_APP_REDIRECT_URI=urn:ietf:wg:oauth:2.0:oob
MASTODON_APP_SCOPES="write:statuses+read:search+read:accounts"
That is quite a lot of code, so at the start it is worth explaining how it goes from a bird's-eye view. The first thing is the continuation of the instance selection, which triggers the internal service GET /mastodon/app/{instance}. How do we know where it is in the code? That is the job of the web.php file, Laravel's place for "translating" URLs into specific controllers and their methods. Here we see that a call such as GET /mastodon/app/mastodon.social will match the address to the first entry and forward it to MastodonController->getAppCredentials('mastodon.social').
In the controller method itself, we first have to get the redirect address (redirectUri), which was also sent in the background. It is nothing other than the address of our article, to which Mastodon will have to send the user back once authorization is granted. And a warning here: when testing on a local machine (localhost), we cannot pass the return address directly. In that case we use a special string hidden behind the environment variable MASTODON_APP_REDIRECT_URI, namely urn:ietf:wg:oauth:2.0:oob.
At this point we could directly send the appropriate request to the Mastodon instance chosen by the user, but let us pause for a moment. Creating an application on a given server needs to happen only once in a while, and we can store the secrets obtained that way. Of course, we could generate them every time, but just as in the previous part, we should feel some solidarity with the instance administrators, who run them with their own money or with donations from their users. Remember that every request to create an application is not just an HTTP request, but also a new record in the instance's database. If many users from a given server start writing comments on our site, in the long run this can mean unnecessary load on that particular server. So, just as with reading comments, we will cache this data here too.
We will use the table mastodon_instance_credentials:
CREATE TABLE mastodon_instance_credentials ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, instance VARCHAR(512) NOT NULL, client_id VARCHAR(1024) NULL DEFAULT NULL, client_secret VARCHAR(1024) NULL DEFAULT NULL, vapid_key VARCHAR(1024) NULL DEFAULT NULL, response TEXT NULL, created_at TIMESTAMP NULL DEFAULT NULL, updated_at TIMESTAMP NULL DEFAULT NULL, PRIMARY KEY (id), UNIQUE INDEX mastodon_instance_credentials_instance_unique (instance) );
As the code shows, we query it (using a repository class, that is, MastodonInstanceCredentialsRepository.php) to check whether we have the right data for a given instance. This means CLIENT_ID, CLIENT_SECRET and VAPID_KEY. If we do, we use it and simply return it for further processing. If not, we actually send a request to the specific instance, using our data (including the scope, more on that in a moment) and save the result in the database for later use. This way we create the application on a given instance only once in a while, which saves not only transfer between servers, but also time.
Note: we cannot store this data indefinitely, because it is valid only for a certain period. That is why it is recommended to clear the contents of the mastodon_instance_credentials table from time to time, for example with cron jobs. We leave this as an exercise for the reader.
In the code you can see several uses of the environment variable MASTODON_APP_SCOPES. These are the permissions required for communication with the OAuth 2.0 protocol. We surely remember being asked by an app store, when installing an application on a mobile device, whether we allow access to, say, our contact list. It is something similar here: every application, and every later authorization request to the Mastodon API, applies to a specific range of operations. In this case they are:
- write:statuses: we want to post toots through the user's account.
- read:search: we want to search for toots or accounts on a given instance.
- read:accounts: we want to read the profile data stored on a given instance.
Three important notes before we move on. First, you may rightly point out that in the previous part, reading the content of toots and comments was public, and that is true: not all API services are available only after authorization by the user. Here, however, we do need such confirmation, hence all the OAuth 2.0 actions and the introduction to the topic. Second, if we want to find out which permissions (making up the scope) we will need, we should look at the documentation of the specific Mastodon API services, which has the relevant information. Third, if during development it turns out that we have to widen the range of granted permissions, then unfortunately all applications created so far have to be created anew and the tokens generated so far have to be reset.
Finally, we can see that in return we get the required CLIENT_ID, as well as the scope and the redirect address. We will need this data on the Mastodon side.
Redirecting to Mastodon and getting the code
You surely noticed this fragment in post.js:
$.ajax({
type: 'GET',
url: this.baseUrl + 'mastodon/app/' + domain,
data: { redirectUri: window.location.href },
cache: true,
success: (res) => {
const json = JSON.parse(res);
const authorizeUrl = 'https://' + domain + '/oauth/authorize?'
+ 'client_id=' + json.clientId
+ '&scope=' + json.scope
+ '&redirect_uri=' + json.redirectUri
+ '&response_type=code';
window.location.href = authorizeUrl;
},
error: (err) => {
$('#mastodon-reply-modal-failure').modal('show');
}
});
With the right data in hand, we have to redirect the user to the external provider (in this case Mastodon, or rather a specific Mastodon instance) and ask the user to grant authorization and, as a result, a code (hence the parameter response_type=code). This is the moment when the commenter briefly leaves our blog and sees a view similar to this:
On this screen the user is asked to confirm the operation. Once they agree, Mastodon automatically redirects the user back to our blog, but this time it adds the code to the GET parameters of the URL.
Using the code for further operations
Now a lot is going to happen. First, we can see that if we passed the address https://naszblog/artykul, the new URL will look roughly like this:
https://naszblog.pl/artykul?code=dlugiKod
We will use this to:
- load the comments right away (without waiting for any user action),
- fetch an additional authentication token (confirming that we identify ourselves as the given user),
- fetch the data of the toot and of our account,
- prepare a form for entering a comment,
- display the form and take the user to it.
As you can see, that is quite a lot of work. First, note that in BlogController and in the view we made a small change that additionally reads our code, if it was passed.
// fragment BlogController.php
public function post(Request $request, $id, $lang = null) {
$post = $this->postRepository->getById($id, App::currentLocale());
if(!empty($post)) {
$commentSourceIds = $this->postCommentSourceRepository->getIdsByPostId($post->id, App::currentLocale());
// code after Mastodon authorization
$mastodonCode = $request->input('code');
return view('blog-post', [
'post' => $post, 'commentSourceIds' => $commentSourceIds, 'mastodonCode' => $mastodonCode,
]);
}
else {
abort(404);
}
}
...
// fragment blog-post.blade.php
<script>
(new PostScript(
"<?= URL::to('/') ?>",
<?= $post->id ?>,
<?= json_encode($commentSourceIds) ?>,
<?= json_encode([
'enterMastodonDomain' => __('enterMastodonDomain'),
]) ?>,
<?= !empty($mastodonCode) ? '"'.$mastodonCode.'"' : '' ?>
)).init();
</script>
Much more happens in post.js, though. Now we can see what the variable withFormInitiating is for, which we skipped last time when discussing reading comments.
init() {
...
if(this.mastodonCode) {
if(this.commentSourceIds.length > 0) {
this.loadComments(true);
}
}
...
}
...
loadComments(withFormInitiating = false) {
if(this.isCommentContainerLoaded) {
return;
}
$.get(this.baseUrl + 'post/comment', { sourceIds: this.commentSourceIds }, (page) => {
$('#comment-container-internal').html(page);
this.isCommentContainerLoaded = true;
if(withFormInitiating) {
const instance = localStorage.getItem('lastMastodonDomain');
const postSrc = localStorage.getItem('lastMastodonSrc');
let accessToken = localStorage.getItem('mastodonAccessToken');
let accessTokenCreatedBy = localStorage.getItem('mastodonCreatedBy');
const accessTokenLifespan = 4 * 3600 * 1000;
if(!accessToken || !accessTokenCreatedBy || instance != localStorage.getItem('mastodonAccessTokenInstance')
|| (Date.now - accessTokenLifespan > accessTokenCreatedBy)
) {
$.ajax({
type: 'GET',
url: this.baseUrl + 'mastodon/token/' + instance + '/' + this.mastodonCode,
data: { redirectUri: window.location.href },
cache: false,
success: (res) => {
const json = JSON.parse(res);
accessToken = json.accessToken;
accessTokenCreatedBy = json.createdBy;
localStorage.setItem('mastodonAccessToken', accessToken);
localStorage.setItem('mastodonCreatedBy', Date.now());
localStorage.setItem('mastodonAccessTokenInstance', instance);
this.prepareCommentBox(instance, postSrc, accessToken);
},
error: (err) => {
$('#mastodon-reply-modal-failure').modal('show');
}
});
}
else {
this.prepareCommentBox(instance, postSrc, accessToken);
}
}
});
}
If the code is available, we do not wait and load the comments right away in the same way as before, but with the flag withFormInitiating we signal that after the posts are loaded we have to take the instance data (saved in local storage) and use it to get an authentication token. Before that happens, however, we check whether we already have such a token. It may well happen that a given user replies to many comments on our blog within a short time, so there is no need to authenticate them again and again. It can be done, for example, once every 4 hours (which is stored in the constant accessTokenLifespan). If we do not have a token or it is older than the set time, we have to go to the Mastodon API again for the required information. Let us return to MastodonController:
public function getToken(Request $request, $instance, $code) {
$redirectUri = $request->get('redirectUri', env('MASTODON_APP_REDIRECT_URI'));
if(App::environment('local')) {
$redirectUri = env('MASTODON_APP_REDIRECT_URI');
}
$credentials = $this->mastodonInstanceCredentialsRepository->getByInstance($instance);
$accessToken = null;
$createdAt = null;
if(!empty($credentials)) {
$url = 'https://'.$instance.'/oauth/token';
$body = [
'client_id' => $credentials->client_id,
'client_secret' => $credentials->client_secret,
'redirect_uri' => $redirectUri,
'grant_type' => 'authorization_code',
'code' => $code,
'scope' => str_replace('+', ' ', env('MASTODON_APP_SCOPES')),
];
$response = Http::asForm()->post($url, $body);
if($response->successful()) {
$body = json_decode($response->body(), true);
$accessToken = $body['access_token'];
$createdAt = $body['created_at'];
}
else {
$message = 'Error during calling '.$url.' with body '.print_r($body, true);
Log::error($message);
Log::error($response->status().': '.print_r($response->body(), true));
return response(json_encode(['message' => $message], 500));
}
}
else {
$message = 'mastodon/getToken fail - there is no instance like '.$instance;
Log::error($message);
return response(json_encode(['message' => $message], 500));
}
$response = [
'accessToken' => $accessToken,
'createdAt' => $createdAt,
];
return response(json_encode($response), 200);
}
The code seems very "long" because at this stage we have to check every possibility of an unauthorized request for such a token and prevent further errors. What interests us most is getting the application data for the relevant instance again and calling POST /oauth/token. Interestingly, we can see an inconsistency on the part of the Mastodon authors here, because this time the scope is given in a different form: with spaces instead of plus signs.
The result of this request is several pieces of information, of which the most important for us are the access token (accessToken) and the creation date (createdAt). We return this data and save it in local storage in JS. Then we use it to start generating the field where the user will be able to type a comment.
prepareCommentBox(instance, postSrc, accessToken) {
$.ajax({
type: 'GET',
url: this.baseUrl + 'mastodon/post/' + instance,
data: { postUrl: postSrc, accessToken},
cache: false,
success: (resPost) => {
const postJson = JSON.parse(resPost);
$.get(this.baseUrl + 'post/comment/form', postJson, (form) => {
$('#comment-form').remove();
const commentBox = $('.comment-reply-link[data-src="' + postSrc + '"]').closest('.comment');
commentBox.after(form);
document.querySelector('#comment-form').scrollIntoView({
behavior: 'smooth'
});
});
},
error: (errPost) => {
$('#mastodon-reply-modal-failure').modal('show');
}
});
}
Here we also have to make not one but two requests to Mastodon. It would be good to show the user their avatar and nickname, so that they feel they are using their own account. More important, though, is fetching the identifier of the toot being replied to. But "wait a moment", attentive readers will say, pointing to the variable postSrc, which should have held this identifier since the user clicked the reply icon next to the toot. Isn't that the value we need? Well, no, and this is where the knowledge about federation we gained earlier comes in.
The variable postSrc is indeed the number of the post, but within the original instance of that toot. This is easy to understand with an example: imagine that our source toot is a post from the instance social.wildasoftware.pl, and one user replied to it from the instance wspanialy.eu. On our blog we display both posts, but the identifier of the first one comes from the social.wildasoftware.pl database and that of the second from wspanialy.eu. Our new user, however, wants to reply to this post from the instance pol.social and has already authorized access from their account. To be able to send a toot that replies to the chosen toot, we need to know the identifier of that toot on the new user's instance, that is, pol.social. So, in this particular case, the post the person is replying to has to be copied to the instance pol.social.
So with mastodon/post, and thus the MastodonController controller, we will fetch both the profile information and search for the toot in order to get the right identifier from it. Searching for the post automatically fetches its copy to the instance pol.social, if it was not there yet.
public function getPostInfoOnInstance(Request $request, $instance) {
$postUrl = $request->input('postUrl');
$accessToken = $request->input('accessToken');
$output = [
'postId' => null,
'instance' => $instance,
'acct' => null,
'avatarStatic' => null,
'displayName' => null,
'emojis' => null,
'accountUrl' => null,
];
$url = 'https://'.$instance.'/api/v2/search';
$params = [
'q' => $postUrl,
'type' => 'statuses',
'resolve' => true,
'limit' => 1,
];
$response = Http::withHeaders([
'Authorization' => 'Bearer '.$accessToken,
])->get($url, $params);
if($response->successful()) {
$body = json_decode($response->body(), true);
if(!empty($body['statuses'])) {
$output['postId'] = $body['statuses'][0]['id'];
}
else {
$message = 'mastodon/getPostIdOnInstance fail - there is no post '.$url.' on instance '.$instance;
Log::error($message);
return response(json_encode(['message' => $message], 500));
}
}
else {
$message = 'Error during calling '.$url.' with body '.print_r($params, true);
Log::error($message);
Log::error($response->status().': '.print_r($response->body(), true));
return response(json_encode(['message' => $message], 500));
}
//--
$urlAccount = 'https://'.$instance.'/api/v1/accounts/verify_credentials';
$responseAccount = Http::withHeaders([
'Authorization' => 'Bearer '.$accessToken,
])->get($urlAccount);
if($responseAccount->successful()) {
$body = json_decode($responseAccount->body(), true);
$output['acct'] = $body['acct'];
$output['displayName'] = $body['display_name'];
$output['avatarStatic'] = $body['avatar_static'];
$output['emojis'] = $body['emojis'];
$output['accountUrl'] = $body['url'];
}
else {
$message = 'Error during calling '.$url;
Log::error($message);
Log::error($responseAccount->status().': '.print_r($responseAccount->body(), true));
return response(json_encode(['message' => $message], 500));
}
return response(json_encode($this->presenter->formatGetPostInfoOnInstance($output)), 200);
}
Two things are worth noting. First, because these two requests are independent of each other, they can be sent in parallel rather than synchronously, as we did. The Guzzle library makes this possible, but we leave it as a task for willing readers. Second, after fetching the user's data we have to reformat it, similarly to what we did when displaying the comments themselves. Here, too, we do it with a presenter class, but you will allow me to skip the detailed description. For the details, I refer you to the code and the previous part of our article.
Finally, we have to display the place for entering the comment text. Armed with the user's profile information, we go to the BlogController controller and the relevant view to fetch the appropriate block via AJAX, display it and scroll the page to that spot. I will skip the description here, because the form itself uses the code discussed in the previous article and is simply boring. It is worth browsing the sources on GitHub. The end result is this view:
Sending the toot, refreshing the comments
When the user types the content of their comment and presses "Send", we of course have to send that content to the previously chosen Mastodon instance through the API. We start with post.js:
$('#comment-container').on('click', '.comment-form-send-button', (event) => {
const answer = $(event.target).closest('.answer');
const answeredTootId = answer.find('.comment-form-postid').val();
const message = answer.find('.comment-form-message').val();
const instance = localStorage.getItem('lastMastodonDomain');
const accessToken = localStorage.getItem('mastodonAccessToken');
if(message) {
$.ajax({
type: 'POST',
url: this.baseUrl + 'mastodon/toot/' + instance,
data: { message: message, answeredTootId: answeredTootId, accessToken: accessToken, postId: this.postId },
cache: false,
success: (res) => {
answer.remove();
this.isCommentContainerLoaded = false;
this.loadComments();
},
error: (err) => {
$('#mastodon-reply-modal-failure').modal('show');
}
});
}
});
As you can see, the form also kept the identifier of the toot we are replying to (on the instance chosen by the user), and we take the server data and the token from local storage. Then we call our method in MastodonController:
// fragment MastodonController.php
public function sendToot(Request $request, $instance) {
$message = $request->post('message');
$answeredTootId = $request->post('answeredTootId');
$accessToken = $request->post('accessToken');
$postId = $request->post('postId');
$url = 'https://'.$instance.'/api/v1/statuses';
$params = [
'status' => $message,
'in_reply_to_id' => $answeredTootId,
];
$response = Http::withHeaders([
'Authorization' => 'Bearer '.$accessToken,
])->post($url, $params);
if($response->successful()) {
$this->postCommentSourceRepository->resetCache($postId);
}
else {
$message = 'Error during calling '.$url.' with body '.print_r($params, true);
Log::error($message);
Log::error($response->status().': '.print_r($response->body(), true));
return response(json_encode(['message' => $message], 500));
}
return response('', 200);
}
// fragment PostCommentSourceRepository.php
public function resetCache(int $postId) {
PostCommentSource::where('post_id', $postId)->update(['data_received' => null]);
}
What is interesting here is resetting the cache in post_comment_source. Why do we do it? We remember from the previous part that comments, once fetched, are stored on our side for some time in order to optimize transfer and time. After adding a comment, however, we want to show the updated list and not use the cache. The simplest way is to delete the previously saved data for the given post. A small inefficiency crept in here: we do not know which source toot we replied under (after all, we could have been commenting on another user's post rather than the original), so we have to delete the cache for all source toots of the given article. It is not a big problem, though.
After a comment is successfully added on Mastodon, we can update our thread of posts. Hence the repeated call of loadComments() in the JS code shown earlier.
Room for improvement
While reading you surely noticed places where the whole mechanism could be improved. I mentioned some of them at individual points, and others will have occurred to each of you. What certainly stands out is the need for even better error handling, for example when, after authenticating, the user takes too long to write and send the comment. But you can also think about developing the system itself, for example by displaying boosts or likes, or by allowing a user to follow another user from the blog itself. This is entirely possible through the API and would tie the blog even more strongly to the world of social networks. Whether that is a good thing is up to you to judge.
Summary
Phew, we made it to the end. Thank you to everyone who read both parts of the article, and I hope the trip was not boring. I realize that not everyone is interested in the code itself. So I hope many of you enjoyed the introduction and the explanation of how individual protocols work and how specific operations are handled. Above all, I will be satisfied if, thanks to this two-part text, someone actually implements a Mastodon-based comment system on their blog or website. That will be a sign to me that the effort paid off.
Best regards, and thank you. Jakub Rojek.


