I have only just started writing this article, and I already know it will be a long one. So long that it will be split into two parts, to give you (and me) a breather while still letting me cover every aspect in more detail. It will also be a fairly technical article, aimed mainly at web developers, though not only at them. It serves as a "proof of concept": a demonstration of how to approach a comment system on a blog or any other website in a way that saves you some work, delivers an interesting idea, and ties the news more closely to the social world. Editors and portal owners may like that, especially when they count the cost of software development.

Of course, someone might say that an external comment system is nothing new in the blogging world. Disqus exists, and some sites embed injected Facebook comments. Still, not everyone likes paying, or putting up with the limits of the free versions (ads in particular), or being tied to a "big player". On top of that, it still means putting accounts and messages on some company's external server. We are used to that, but we do not always have to like it. So what if we used the existing mechanisms of smaller, open social networks and simply displayed already public posts as comments? These messages could be added both from the blog and from the social media service itself, yet treated as one shared thread. And all of that for free, on servers usually owned by the community, by the people who make it up? That is exactly the idea of using Mastodon.

As I mentioned, the article is split into two parts. In the first one (the one you are reading now) we will explain or recap:

  • what our goal actually is,
  • what Mastodon actually is and why it is a good candidate for a comment system,
  • how to fetch comments and display them as a thread,
  • where to find a working example.

In the second part we will look at replying to posts directly from the blog, which is a more complex topic. We will not stop at a dry description of how it works. We will also point out places where optimization can happen, and I mean not only execution time but also data transfer. We will also cover a few general mechanisms used especially when working with an API, and slip in a few remarks about coding standards.

On the one hand the article is technical. On the other hand it shows the general possibilities of this ecosystem, which may appeal to social media specialists, for example. Developers and people who look after their own blog and are not afraid to open the code now and then will certainly benefit. But we have to be aware that this is not a description of a ready-made library to drop in, nor the one right solution. It is rather a look at how the mechanism works, with sample code that achieves the intended goal. The demonstration is in PHP, but that of course does not mean this is the only technology in which such a comment system can be built. What I describe fits other languages and frameworks too. Although, admittedly, most blogs do run on Personal Home Page.

A ready-made example

In the text I will also cover the "theoretical" basics, explaining some fundamental concepts and showing their pros and cons. I realize, however, that not everyone is interested in that. Some people want an immediate answer to the question "how do I implement a comment system". For that reason we prepared an example, which will also be the basis for the discussion later in the text. Here it is:

https://github.com/WildaSoftware/MastodonCommentSystem

It is a Laravel application modeled on this blog, with one sample article and the source of its comments. If you prefer to learn by analyzing code yourself and trying solutions in practice, feel free to clone the repository. Setup instructions are in the README.md file. Good luck! Still, I hope that out of curiosity you will come back to this text afterwards, or work through both at the same time :)

One note: I know perfectly well that the code is not an ideal example of a web application written in Laravel. It is only an example that shows how certain issues can be handled in practice, something to glance at while implementing a comment system of your own. That does not mean we do not build applications in this framework. We have experience with it too, even though our main technology is Yii 2.0. Just in case, you know how to contact us.

What do we want to achieve?

First we need to define what we actually want to do. Our goal is for a thread of comments to appear under blog articles. Technically, these will be posts on a social network (here: any Mastodon instance, which we will get to in a moment) that are replies to a certain source post. We will make use of the fact that we usually announce a new article with a social media post that people can reply to. And that is exactly what we will display here, in a slightly more more suitable form.

As an example, take our article about the role of chess in a programmer's development. Scroll to the bottom of the page and you reach the comments section, where a thread appears whose source is, among others, my toot inviting people to read the text ("toot" is a post on Mastodon). All the replies (sometimes replies to other replies) are displayed in the thread, and they are real toots written by other Fediverse users (we will get to that too) or by me. When you click the date or the username of a given participant, you go to the specific message or profile on the social network itself. At the same time, we take only public posts into account. If a user writes a non-public or even a direct toot, that message will not appear in the thread on the blog, for privacy reasons.

It would also be good to be able not only to read and display toots as comments, but also to reply to them. Since the blog is an external site, this is not trivial. The user has to use their Mastodon account, but we would like them to feel that they are writing a comment from the page itself. So after clicking the reply icon, the user is redirected to Mastodon to confirm who they are (very much like logging in with a Google or Facebook account), and then sent back to the blog to write the message, which still passes through Mastodon.

All of this gives us a comment system that shows the discussion under an article, yet does not use up the blog's resources and, what is more, does not require storing account data in our database, which spares us many authentication and authorization mechanisms.

What are internal and external comment systems?

In many cases, comments under articles are handled entirely within the site itself. In the old days this was very "carefree": adding a post often required neither logging in nor any confirmation of identity. That was convenient, but it resulted in spam, posts not fit for quoting, and a general junk heap that had to be cleaned up or switched off. For this reason CAPTCHA became more common, or account registration was required, in various forms. If a site cares about heavy traffic (news sites, for example), the authentication process is very simple. In other cases it resembles a normal registration, with account activation and so on. More and more often, sites rely mainly on accounts from large services (so-called SSO, Single Sign-On), such as Google, Facebook or Apple, which are convenient for users on the one hand and take some duties off the site owners on the other.

The mechanism described above we call "internal", because everything is handled on the site's side. Both the mechanics of displaying and replying to comments and the handling of accounts (even when SSO is used) must be implemented by the site's creators. On the one hand this is tempting, because we have complete control over everything, including aesthetics, and such a comment system is easier to integrate visually with the site. On the other hand, it is laborious, perhaps even more than everyone assumes. It requires implementing every element and taking care of the authentication process (which gets easier when the system requires logging in for other features anyway). In addition, there are two issues to consider. One is the moderation of content added by users, which can be difficult for large sites but also necessary because of spam and inappropriate content that malicious users can post. The other problem is that internet users increasingly shy away from creating masses of accounts on various sites, because they later forget the passwords, or forget they have the account at all. SSO solves this problem to some extent.

At the opposite pole we have external comment systems such as Disqus, OpenWeb and many others. They work on a similar principle to the Feedybacky plugin: the system lives on an external server and is injected into a blog or portal with an iframe tag or an appropriate JavaScript script. This requires creating an account with the external provider, configuring parameters (for example the maximum comment length), and then using the right data on the right page. In such a setup the developer does not have to implement the mechanism, let alone worry about handling accounts. It is all on the provider's side. This looks like a very convenient solution, and it really is, and it is also standardized. A user browsing blogs who comes across Disqus, for example, recognizes it, knows what to expect, and may even have a single account that they use to comment on all their favorite blogs.

Of course, this approach has a few drawbacks. First, these solutions are often paid or limited in some way, which is understandable: the external provider has to protect its resources from people "testing" the comment system beyond its capacity. It also has to earn money somehow and pay its developers and servers, which requires a subscription or ads. Second, in exchange for not having to implement anything yourself, site owners have fewer options for fitting the comment system to their own layout. There are ways around this, or providers allow custom settings (through CSS files or simply by "clicking through" the options), but it is certainly not as "customizable" as a native system. Third, we depend on an outside company. If it changes the terms of service, the price, the limits or the way comments work, or simply shuts the service down, we have to accept it and/or switch providers.

Where does the comment system we are going to implement fit in? In between. You could call it a hybrid solution. The external part is that the source of comments is an external service, which moreover is not a single portal (more on that in a moment), and that helps in coping with losing access to the service. User accounts are also on Mastodon's side, and we are not interested in passwords or other sensitive data of individual profiles. The "internal" part shows in the need to prepare a mechanism for displaying and entering comments, which is a drawback on the one hand and an advantage on the other, since we can adapt a lot to our needs. This is the approach we will discuss today and in the next part. What is more, the solution presented here could also be packaged as a library, creating in effect an external comment system that is easier for others to "implement". That would be a "task for the willing".

What are Mastodon and the Fediverse?

It is worth recalling and going over once more what Mastodon actually is, together with the related Fediverse. Once more, because we already did this some time ago. Back then we focused on its social side, whereas here we will look at the subject from a more technical angle, and also at the philosophy behind it. If you are curious, read the next paragraphs. If you want to get to the "meat", feel free to skip this section, though I recommend at least looking at the end of this chapter.

Imagine any social service that lets people create content. Giants such as Facebook, Twitter, Instagram or YouTube probably came to mind. These are so-called centralized systems. When we register an account on Twitter, for example, we land in the same database as millions of other users and have easy access to every public message. What matters most is that access to the whole service is under one specific address, which points to one server (or rather a server farm, but let's not be picky). This is convenient, but it also has various drawbacks and sometimes moral doubts. Such a social network is run by a specific company, because it is no longer a simple site for enthusiasts of some topic. It is a global behemoth whose development and maintenance require enormous spending, which in turn makes companies want to earn a lot. It would be half bad if this happened in a way that raised no ethical doubts, but here the data of free (and not only free) accounts is often used to personalize ads better, and ads are the main source of income for these services. Ads may not bother you (and personalization may even help in some cases), but sometimes they do, completing the picture of the service as a de facto "billboard" system in which everyone promotes themselves and lives beyond their means (which is how Instagram or LinkedIn are often seen). In addition, the service has terms of use and rules of conduct, which is good. But given such a huge base of creators and content, the owners cannot moderate posts by hand. Bots do it, and they sometimes make mistakes and block users who did nothing wrong. Dealing with such situations means stress, writing to technical support, and losing trust in the portal, and sometimes moving to so-called owned media. It is also worth mentioning that a centralized system is more prone to outages. Of course, with several hundred (or even more) servers running a portal, problems with a single machine are not a big deal, but if some change shows up on many machines, the whole system can stop working, and we have seen examples of that in the past.

Many people did not like these conditions. Some disliked the technical problems, some the ease of getting blocked, and others the privacy and more ideological issues. After the initial enthusiasm for the giants, part of the internet community wanted to create its own open solution. That is how Mastodon came about, for example (we will return to other applications in a moment, because it is not the only one): a microblogging platform without ads that resembles Twitter, although it is not Twitter and there are some functional differences. Those are not interesting in the context of this article, though. Now imagine we can set up such a Mastodon ourselves, on our own server, without asking the author. We can even accept users on that server, though of course probably relatively few, since we do not have the resources of large companies. This is a bit like the era of internet forums and smaller communities centered on a specific topic. Coming back to owning a server, note that we are not alone. Our neighbor can also configure their machine with Mastodon. So can other people. Each of them becomes the administrator of their instance and can accept a certain number of users or keep the server just for themselves. And now comes the climax: these instances can communicate with each other. They are on different servers and have separate databases, but a user on instance A can follow a user on instance B and reply to them. This is not a set of forums that are not connected to each other. Here we are talking about a "federation of servers" and about creating one big system made of autonomous units run by local (or less local) communities. It resembles the world and the communication between citizens of different countries, who make up one global village. Of course, as in diplomacy, it can happen that two instances do not "talk" to each other, but these are marginal cases.

The matter of instances and the communication between them will be extremely important in the second part of our adventure, that is, when commenting on an article from the blog. Incidentally, federation is a wonderful example of one kind of distributed systems.

All right, so what is the Fediverse? We have answered that indirectly above: it is the ability of instances to group into federations and create the impression of one big system, but there is one more aspect. Let's go back to Twitter for a moment. With an account there, we see posts from other users of that site, we can reply to them, add them to favorites and so on. But from the same account we cannot follow someone on Instagram or Facebook. We also cannot comment on a friend's video on YouTube using LinkedIn. To do that, we have to have a profile on each of these sites and use them separately. In the federated world, by contrast, Mastodon is not the only possible application. In fact, it is not even the only microblogging platform, since there are Pleroma, Soapbox, Misskey and the promising Calckey (which is known to be changing its name, though the new name is not known at the time of writing). Other "central" platforms have their counterparts too. Instagram fans will feel at home in Pixelfed, YouTube viewers will be interested in PeerTube, and Reddit or Wykop users will welcome Lemmy or the Polish /kbin. Even book lovers have an alternative to Goodreads in BookWyrm. Why am I writing about all this? Because all of these sites use one base system (without going into detail, they implement its interface) called ActivityPub. As a result, with an account on Mastodon (or rather on one Mastodon instance) we can comment on a friend's photo on Pixelfed (and again, rather on one Pixelfed instance), and a moment later be followed by a user from a Soapbox instance who mentions a colleague from a Calckey instance. Of course, there are exceptions and some specific features available only in particular applications, but all the sites can be connected to each other. And there are thousands of them.

Another interesting metaphor was proposed by Tomasz Dunia on his blog, who compares the Fediverse to a whole Universe in which there are galaxies (Mastodon, Pixelfed, Friendica and so on) made up of planets (specific instances). ActivityPub, in turn, is the currents we travel along in our vehicle parked on a specific planet (our account on one of the instances), from one planet to another or even between galaxies. Of course, nothing prevents you from having many accounts on different sites, and it is even common. Still, you can successfully use a single profile.

That is what the idea looks like, and it is available for free (it relies on donations from the community and possibly extra services), which fits perfectly as a base for a comment system. Whether centralized social systems are a real danger is a matter of debate and depends on your point of view and often on your life philosophy, including your attitude to corporations. Everything has advantages and disadvantages, the Fediverse included, so it is worth knowing this concept to broaden your horizons. It is also worth mentioning that large companies have taken an interest in federations too and have provided (or are providing) integration with them. I have in mind WordPress, Tumblr and Flipboard, for example. This is not the only attempt to "cut loose" from so-called "big tech". Alternative solutions have appeared on the horizon in the form of Nostr and Bluesky, a creation of Twitter's former founder Jack Dorsey. We should also remember a protocol for direct communication, namely Matrix.

The comment system described in this article relies entirely on Mastodon, because we use not so much the Fediverse as the API of the application itself. That differs from site to site, but if Calckey, for example, had an API compatible with Mastodon's (and there is some chance of that), the solution presented here would work with it too. But why can't the blog simply implement ActivityPub? It could, but we deliberately did not go that way, to avoid handling user accounts. If you are interested in that topic, though, WordPress is going down that road.

Displaying the comment thread

Time for specifics, where the ready-made example mentioned earlier will come in handy, and we will refer to it often. As I wrote, in this part we will focus on reading comments only. This requires the following steps:

  1. Marking certain toots (posts) as "source" toots.
  2. Fetching from the API the content of both the source toots and the replies to them.
  3. Formatting the content so that it can be displayed safely on the blog.
  4. Displaying the comments as a thread.

The approach to reading is not very original, since I based it on implementations proposed by Carl Schwan, Daniel Pecos Martinez and Patrick Curry, adapting them to PHP and improving them in a few places, such as indentation and the handling of exceptional cases.

Marking certain toots (posts) as "source" toots

Let's go back to the article about chess mentioned earlier. When we scroll to the comment system, we see two toots in yellow that are clearly highlighted. These are the so-called source toots. They are the base for the replies, which our system in turn treats as comments. So they are a kind of "anchor point". A note here: we could skip displaying them and focus on the replies alone, but it is worth considering that source toots also have some text, and that is what commenting users usually respond to. There can also be many of them, which means we have to be ready for more than one thread of replies. That does not get in our way at all and even gives more flexibility, if someone else tooted about our article and we wanted to include the replies under their post too (of course, it is worth asking for permission first).

In the database that holds the articles themselves (in the post and post_translation tables, since we care about multilingual support), there is a post_comment_source table that contains information about the source toots:

CREATE TABLE post_comment_source (
	id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
	post_id BIGINT UNSIGNED NOT NULL,
	language_id BIGINT UNSIGNED NOT NULL,
	mastodon_instance VARCHAR(128) NOT NULL,
	mastodon_user VARCHAR(128) NOT NULL,
	mastodon_toot_id VARCHAR(128) NOT NULL,
	data_received MEDIUMTEXT NULL COLLATE,
	date_data_received TIMESTAMP NULL DEFAULT NULL,
	PRIMARY KEY (id),
	CONSTRAINT post_comment_source_language_id_foreign FOREIGN KEY (language_id) REFERENCES language (id),
	CONSTRAINT post_comment_source_post_id_foreign FOREIGN KEY (post_id) REFERENCES post (id)
);

Przykład danych:

{
	id: 1,
	post_id: 1,
	language_id: 1,
	mastodon_instance: "social.wildasoftware.pl",
	mastodon_user: "wilda",
	mastodon_toot_id: "110435606334801439"
}

As you can see, not only can we attach many source toots to each article (here there is just one), we can also distinguish them by language. In our example, the "one" in language stands for English. The toot data leads to this post, where you can see in the link that all the information matches. We will discuss the data_received and date_data_received fields later. They are related to caching values.

It is worth mentioning that one drawback of this solution is the need to add the links to toots by hand, which happens after those posts are published. So for a few minutes the page will not show any comments. This is not a big problem, but avoiding it may take more work and preparing infrastructure to publish the toot and add it to the database at the same time, which we will not cover here.

Fetching from the API the content of both the source toots and the replies to them

If you run the sample project or look closely at the comments on our blog, you will notice that they are not loaded right away. They appear only a moment after you scroll the page to the section with the posts. We say that they are loaded on demand, or that this is lazy loading: the data is loaded only when it is actually needed. In this case it has a big advantage. We do not burden either our blog or the instance with the source toots when the user is not interested in comments, that is, does not want to display them at all. Ensuring this is not that hard. Let's look at the files in the example. When we open, say, the first article through the URL /post/1, we go through BlogController, where we fetch information about the article itself and about the source toots, passing the data to the blog-post.blade.php view (as you can see, we use the Blade template engine), in which we call the post.js script:

// blog-post.blade.php
...
<div>
	...
	@if (count($commentSourceIds) > 0)
		<div class="row pb-3">
			<div id="comment-container" class="col-12">
				<h2 class="comments-header pb-3">{{ __('comments') }}</h2>
				<div id="comment-container-internal">{{ __('loadingComments') }} </div>
			</div>
		</div>
	@endif
	...
</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>

// post.js
class PostScript {

    constructor(baseUrl, postId, commentSourceIds, translations, mastodonCode) {
        ...
        this.isCommentContainerLoaded = false;
    }

    init() {
		...
		if(this.commentSourceIds.length > 0 && !this.mastodonCode) {
			const observer = new IntersectionObserver((entries, observer) => {
				entries.forEach(entry => {
					if(entry.intersectionRatio > 0) {
						this.loadComments();
					}
				});
			}, { root: null });

			observer.observe(document.getElementById('comment-container'));
		}		
		...
	}
		
	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) {
				// later in the second part: initializing the answer form
			}
		});
	}
}

We create a container into which we will load the comments. Note that if no source toots are given for an article, there will be no comments, so this div is not needed, hence the conditional statement. One general remark: we will not discuss styling in detail here (Bootstrap helps with it), nor internationalization (the translations of individual texts are in this file). We will not touch on Laravel itself or MVC either, but I hope the examples can show the right direction.

In the init function we see the fragment responsible for the reaction when the user scrolls the page to the place with the comments and some source toots exist. Technically it relies on the IntersectionObserver class, which reacts when the user displays the part of the page containing a given HTML element, that is, our container. Then the fetching of comments from our controller starts, based on the IDs of the records with source toots in the database. For now, let's not worry about the variables mastodonCode and withFormInitiating. They will be used only for the commenting itself.

What remains is the most important part: using the Mastodon API to fetch the toot content. That happens in the BlogController controller, which has a comments method that the routing points to.

We will go through the controller method's code in parts.

public function comments(Request $request) {
	$sourceIds = $request->get('sourceIds', []);
	if(empty($sourceIds)) {
		return response('Missing comment source IDs', 400);
	}

	$commentSources = $this->postCommentSourceRepository->getByIds($sourceIds);
	$mastodonToots = [];

	$now = new \DateTime();

	foreach($commentSources as $source) {
		//...
	}

	return view('inc/blog-post-comments', $this->presenter->formatComments(['mastodonToots' => $mastodonToots]));
}

First of all, when this method is called, it is worth checking that nobody has done so "maliciously" by sending an empty list of source toots. In that case there is no point in performing further operations, so we return HTTP status 400 (Bad Request). We also make sure that in normal operation this situation never occurs anywhere in the application. If we trace the code above and this code from the start, we will see that comments is called only when some source toots exist. These safeguards were introduced in case of attack attempts and are a kind of standard, also tied to optimizing code execution.

Next we fetch the rest of the information about the source toots, namely the Mastodon instance mentioned earlier, the user's login and the toot ID. Someone may say that we did this suboptimally: we could have fetched this information the first time, when displaying the post, saving one database query (you can follow this by reading the whole BlogController class). But then we would have to pass all this information from the controller to the view, from the view to the JavaScript script, and later from the script to the method in the controller, artificially lengthening the HTTP request. So this optimization is aesthetic rather than a matter of time (although with too many source records and too long pieces of information, the server might at some point refuse to accept a URL that is too long, with all those parameters in it). It is also worth noting the mastodonToots variable, which will hold the fetched toots. Why do we write the "mastodon" prefix everywhere (including in the database)? It lengthens the names of fields and variables, and it "limits us" if we ever wanted to change the source of comments. Yes, that is true, but note that the code is also prepared for the situation in which we fetch comments from other applications, each of which will require a slightly different approach. If we look at the post_comment_source table described earlier, we will see that we could just as well add further fields there for Facebook or Pixelfed, for example, and still not have to rename the table. In the same way, the comments method can contain further parts of the function that collect posts from other sites and build a larger conglomerate than just mastodonToots. Hence this small nuance in variable naming, which was applied deliberately.

We also see that we get the current time (useful in a moment for caching), and that at the end we return an HTML view with the processed comments. We will get to that shortly. Let's now go inside the foreach loop.

foreach($commentSources as $source) {
	if(!empty($source->data_received)) {
		$cacheDate = new \DateTime($source->date_data_received);
		$diff = $now->getTimestamp() - $cacheDate->getTimestamp();

		if($diff <= 600) {
			$mastodonToots[] = json_decode($source->data_received, true);
			continue;
		}
	}

	try {
		$url = 'http://'.$source->mastodon_instance.'/api/v1/statuses/'.$source->mastodon_toot_id;
		$response = Http::get($url);
		if($response->successful()) {
			$toot = json_decode($response->body(), true);

			$url .= '/context';
			$commentsResponse = Http::get($url);
			if($commentsResponse->successful()) {
				$comments = json_decode($commentsResponse->body(), true)['descendants'];
				$toot['comments'] = $comments;

				$mastodonToots[] = $toot;
			}
			else {
				Log::error('Error during calling '.$url);
				Log::error($commentsResponse->status().': '.print_r($commentsResponse->body(), true));
			}

			PostCommentSource::where('id', $source->id)->update([
				'data_received' => json_encode($toot),
				'date_data_received' => $now->format('Y-m-d H:i:s'),
			]);
		}
		else {
			Log::error('Error during calling '.$url);
			Log::error($response->status().': '.print_r($response->body(), true));
		}
	}
	catch(\Exception $e) {
		Log::error($e->getMessage());
		Log::error($e->getTraceAsString());
	}
}

Let's skip the first "if" statement for now and focus on the contents of the try block. For each source toot we have to make two requests:

It is worth mentioning that the term "toot" associated with Mastodon is used mostly among ordinary users. Technically these are statuses. That is why this word appears in the API calls (made in our code with the Guzzle library) to a specific instance. Without going into detail, we first fetch the toot itself, convert the JSON into a PHP array, and then fetch all the comments, appending them to the original toot. Then we add the entry to the array and move on to the next source. If some operation fails, we record that in the logs and, importantly, we check the next sources or correctly return the result, even if it is empty. There must be no situation in which the user waits forever for comments to load, unaware that, say, one instance is not responding and is blocking the whole operation.

Let's now go back to the places where the data_received and date_data_received fields are used. Why do we need them at all? Consider a situation in which we publish an article on the site, post a toot, and within a minute 100 people visit it, reading at a fairly even pace and reaching the comments section. That means that for each of them we have to make 2 requests to the Mastodon API for each source toot. What is more, in such a short time these requests return the same two results, because no new posts have had time to appear in the meantime. So we can see there is room for optimization and for caching the results, which we can achieve by saving the fetched data together with a timestamp. That is exactly what these fields are for. Then, on other requests (say a second person "arrived" at the comments section), we check whether the saved data is "recent enough" (in our case the cutoff is 600 seconds, that is 10 minutes; incidentally, this value should be a parameter and as easy to change as possible). And indeed, if we open an article with comments for the first time, triggering the fetching of comments, and then refresh the page, the posts will probably load much faster, because they come from the local database and not from another server (the Mastodon instance). That holds for the next 10 minutes.

This is an optimization of more than just time, and it is a good moment to return to the federated nature of Mastodon. Remember that our code queries the API of a real instance, which is run by a person with whatever server they can afford. Some services limit the number of bytes transferred, and the servers themselves have restrictions on the number of requests they process. That means our very popular article with many comments can temporarily load the instance's server, and ordinary users will suffer, as will the administrator if they pay for transfer in the cloud, for example. That is why Mastodon itself has default settings that block too frequent requests from one source. But to avoid straining the instance and exposing the administrator and our blog to losses, it is worth using caching.

These are not big numbers. A single fetch of the comments for the chess article is about 14 KB of transfer and 350 ms of waiting for a response. With 50 such double requests that is 700 KB, which is still little. But with larger numbers, or popularity that lasts a long time, and out of plain decency, it is worth keeping part of the data on your side.

Formatting the content so that it can be displayed safely on the blog

All right, we have the data. Now we can display it. But before we do that, we still have to process it.

public function comments(Request $request) {
	...
	return view('inc/blog-post-comments', $this->presenter->formatComments(['mastodonToots' => $mastodonToots]));
}

We can see that before sending the data to the view, we transform it in a so-called presenter, that is, a class that "cleans" the data before the HTML processing. According to the MVC approach and good practice, the view should take care only of displaying data, not of formatting it further. At the same time, neither the controller nor the model should do it. That is why presenters are sometimes placed between these two layers to do the "dirty work". In Angular applications so-called pipes are often used for this.

And we are talking here not only about a possible change of structure but also about removing certain information for security. Note that Mastodon users have quite a lot of freedom in filling in information about themselves and can, for example, add various emoji to their nicknames. In addition, in the toots themselves we should check whether malicious JS scripts have been placed there that would expose us to a so-called XSS (Cross-Site Scripting) attack.

There are also purely aesthetic operations, such as formatting the post date properly. There is no point in discussing the whole code, so below is the content of the BlogPresenter class. It is worth noting, though, the calculation of the depth of a post, because we will need it in a moment for displaying.

class BlogPresenter {

    public function formatComments(array $input): array {
        $output = $input;

        $replyCount = [];

        foreach($output['mastodonToots'] as &$toot) {
            $toot = $this->presentComment($toot);
            if(!empty($toot['in_reply_to_id'])) {
                if(!array_key_exists($toot['in_reply_to_id'], $replyCount)) {
                    $replyCount[$toot['in_reply_to_id']] = 0;
                }
                $replyCount[$toot['in_reply_to_id']]++;
            }

            foreach($toot['comments'] as &$reply) {
                $reply = $this->presentComment($reply);
                if(!empty($reply['in_reply_to_id'])) {
                    if(!array_key_exists($reply['in_reply_to_id'], $replyCount)) {
                        $replyCount[$reply['in_reply_to_id']] = 0;
                    }
                    $replyCount[$reply['in_reply_to_id']]++;
                }
            }
        }

        $depths = [];
        $isIncreasingChildrenDepth = [];
        
        // setting an appropriate toot's depth in terms of responded post
        foreach($output['mastodonToots'] as &$toot) {
            $isIncreasingChildrenDepth[$toot['id']] = false;
            
            $depth = 0;
            $toot['depth'] = $depth;
            $depths[$toot['id']] = $depth;

            foreach($toot['comments'] as &$reply) {
                $isIncreasingChildrenDepth[$reply['id']] = false;

                $depth = ($depths[$reply['in_reply_to_id']] ?: 1)
                    + (!empty($isIncreasingChildrenDepth[$reply['in_reply_to_id']]) ? 1 : 0);
                $reply['depth'] = $depth;
                $depths[$reply['id']] = $depth;

                if($replyCount[$reply['in_reply_to_id']] > 1) {
                    $isIncreasingChildrenDepth[$reply['id']] = true;
                }
            }
        }

        return $output;
    }

    private function presentComment(array $comment) {
        $output = $comment;
        $output['account']['display_name'] = htmlspecialchars($output['account']['display_name']);
        $output['account']['avatar_static'] = htmlspecialchars($output['account']['avatar_static']);

        foreach($output['account']['emojis'] as $emoji) {
            $code = ':'.$emoji['shortcode'];
            $staticUrl = htmlspecialchars($emoji['static_url']);
            $output['account']['display_name'] = str_replace($code, '<img src="'.$staticUrl.'" alt="Emoji '.$code.'" height="20" width="20" />', $comment['account']['display_name']);
        }

        if(!strpos($output['account']['acct'], '@')) {
            $parsedUrl = parse_url($output['account']['url']);
            if(!empty($parsedUrl)) {
                $output['account']['acct'] .= '@'.$parsedUrl['host'];
            }
        }

        $output['created_at'] = (new DateTime($output['created_at']))->format('d.m.Y H:i:s');

        return $output;
    }
}

Displaying the comments as a thread

In this last stage, two challenges await us. The first is displaying the comment box itself. The second is calculating the right indentation. We will stay on the latter for a moment.

When we open the comments of the chess article, we see that some comments are indented, starting of course with replies directly to the source toot. But when someone replies to a reply, in theory extra spacing should be added too, and yet that does not always happen. The situation changes when two independent threads of replies to one toot appear, because then extra margin is necessary, or at least useful. Well, this is not an easy problem.

That is why in the presenter shown above, at the end of the formatComments method, the depth is calculated with the following algorithm, which we will first present in strictly technical terms.

  1. We prepare a replyCount array containing the number of replies to a given toot.
  2. We prepare an isIncreasingChildrenDepth array (iicd for short) and a depths array for each toot.
  3. For a source toot the depth is 0 and iicd is false.
  4. For each comment the depth is the depth of the toot it replies to, or 1.
  5. If the toot being replied to has true set in iicd, the comment's depth is increased by 1.
  6. If the number of replies to the toot being replied to is greater than 1, the iicd value for that toot changes to true.

I admit that following this requires working through an example on paper. So let's put this description into more human terms.

  1. Source toots always have a depth of 0.
  2. If a toot replies directly to a source toot, it always has a depth of 1.
  3. If toot X is a reply to toot Y, which has no more than one reply, the depth of toot X equals the depth of toot Y (they follow each other directly).
  4. If toot X is a reply to toot Y, which has more than 1 reply, the depth of toot X equals the depth of toot Y plus 1.

This depth is added to each toot in the presenter and then passed to the view like this:

// blog-post-comments.blade.php

@if (count($mastodonToots) > 0)
    @foreach($mastodonToots as $toot)
        @include('inc/blog-post-comment-box', ['comment' => $toot, 'isReply' => false])

        @foreach($toot['comments'] as $reply)
            @include('inc/blog-post-comment-box', ['comment' => $reply, 'isReply' => true])
        @endforeach
    @endforeach
@else
    {{ __('noComments') }}
@endif

// blog-post-comment-box.php

<div class="col-12 comment {{ $isReply ? 'reply' : '' }}" style="
        margin-left: calc(var(--comment-base-indent) * {{ $comment['depth'] }});
        max-width: calc(100% - (var(--comment-base-indent) * {{ $comment['depth'] }}))
    ">
    <div class="comment-author row">
        <div class="comment-author-avatar col-3 col-md-2 col-lg-1">
            <img src="{{ $comment['account']['avatar_static'] }}" alt="">
        </div>
        <div class="comment-author-details col-9 col-md-7 col-lg-8">
            <div class="row">
                <a class="comment-author-details-name col-12" href="{{ $comment['account']['url'] }}" target="_blank" rel="nofollow">{!! $comment['account']['display_name'] !!}</a>
                <div class="comment-author-details-user col-12">{{ $comment['account']['acct'] }}</div>
            </div>
        </div>
        <div class="comment-date col-12 col-md-3 text-right">
            <a href="{{ $comment['url'] }}" target="_blank" rel="nofollow">{{ $comment['created_at'] }}</a>
        </div>
    </div>
    <div class="comment-content row">
        <div class="col-12">
            {!! $comment['content'] !!}
        </div>
    </div>
    <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>

As I wrote, we will not dig into styling (the relevant directives are in the SCSS file), but the spacing deserves attention. There is a base margin of 1.5rem, but it is only a CSS variable, from which we work out the actual offset of the box. That is the result of multiplying the base margin by the depth calculated for the comment. Importantly, the work does not end there. If we stop at moving the box over, it keeps the same width, and in very complex threads the right edges would run off the screen. So we also have to calculate the max-width style in an analogous way, which gives the correct width of the comment.

The other pieces of HTML are standard, and you can see them at work on our blog or in the sample project.

Summary

This part explained the foundations on which we build our comment system and the mechanics of displaying existing comments. We are pausing here, and we invite you to ask questions and to read the second part of the article, which explains how to reply to toots directly from the blog. That will let us get to know the Mastodon API better, along with the OAuth authorization process and the SSO mechanism.

If you think this mechanism can be improved, or you have found any inaccuracies in it, do not hesitate to write. The more opinions from different people and the more discussion, the more knowledge and insight developers and other people interested in the topic can take away.

Best regards, and thank you. Jakub Rojek.