samyyc.dev
LOC::Macau, China

..UTC+8

samyyc.dev

-- BPM

Wed May 24 2023

Adding Random Images to the Halo Photos Plugin

#81

/

samyyc

/

419 words

/

Updated 1290 days ago

/

[中文]

Adding Random Images to the Halo Photos Plugin

The theme I'm using has a random cover image feature. You can set an API, and every time the page loads it calls that API to get an image for the cover. Halo also has a Photos plugin, so I figured I'd see if I could wire the two together.

Prerequisites

First install the Photos plugin GitHub - halo-sigs/plugin-photos.

After installing it, upload some images to the attachment library for later use, then create a new group on the Photos page in the admin panel and add the images to it.

Once that was set up, I ran into an awkward problem: the API endpoint the theme expects needs to 302-redirect straight to the image URL, but the Photos plugin only supports rendering Thymeleaf pages.

Modifying the Photos Plugin

So I had to modify the Photos plugin myself and expose an API endpoint that returns a random image.

First, clone the repo:

git clone https://github.com/halo-sigs/plugin-photos

Following Halo's development guide, I wrote a RandomPhotoController class myself. Here's my code:

package run.halo.photos;
    public Mono<String> redirect(@PathVariable(value="groupId") String groupId) {

Note that after making the changes, you need to build and update the plugin. If the version number of the Photos plugin you already have installed matches the one you modified, clicking Update won't do anything.

So we need to bump the version in gradle.properties, or just delete the original Photos plugin first and then install the modified one.

After making the changes, build it:

gradlew build

The output is in the build/libs folder. Just upload it through the server admin panel.

Using the API

This code exposes an API endpoint. Visiting it redirects straight to an image. The URL is:

https://www.XXXXX.net/apis/api.plugin.halo.run/v1alpha1/plugins/PluginPhotos/randomPhoto/{photoGroupID}

Note that photoGroupID here is the ID of the group in your Photos library. After you open the Photos page in the admin panel, the URL will look roughly like this:

https://www.XXXXX.net/console/#/photos?group=photo-group-XXXXX
Here, photo-group-XXXXX is your photo group ID.

Configuring the Theme

Configuring the theme is simple. Just go to the setting for the API endpoint. For theme-butterfly, the setting is under Theme -> Butterfly -> Loading -> Random Image Link.

Enter the API endpoint from above.

Update, March 14, 2024:

  1. Because of a Spring framework update, you now need to fill in the @PathVariable parameter.
  2. Changed the way the version number is updated.