One of the things I wanted to automate was that when Syncthing pulled new Markdown files from my Mac to my server, it would trigger Hugo to rebuild the site. Someone on Mastodon recommended that I look into the Syncthing API, mainly the “FolderSummary” event. After many hours of toying with this in Python, I finally got things to work, with a small limitation.
TL;DR
I wrote a Python script that will check the Syncthing API every minute, specifically looking for that “FolderSummary” event type. If it finds the event, it will run “hugo” in the proper directory so that the site is rebuilt.
If you are interested in the script, check it out below. Just don’t make fun of my code, ok?
import json, requests, time, os
headers = {"X-API-Key": "API_KEY_HERE"}
firstRun = True
def GetEventID():
re = requests.get("http://localhost:8384/rest/events?limit=1", headers=headers)
data = re.json()
return str(data[0]['id'])
def GetLatestEvents(jsonID):
url = "http://localhost:8384/rest/events?since="+jsonID
re = requests.get(url, headers=headers)
events = re.json()
print(len(events))
if events:
for event in events:
if 'FolderSummary' in event['type']:
print(event)
print("Telling Hugo to BUILD!")
os.system('cd /hugo/site && hugo')
print("Sleeping for 5 minutes after building")
time.sleep(360)
# Main Loop
while True:
# Check for first run
if firstRun == True:
print("Start of loop")
# Grab the latest event ID
latestEventId = GetEventID()
# Wait 30 seconds before trying again
print("First run complete with ID: "+latestEventId)
firstRun = False
time.sleep(15)
else:
# Grab latest event ID
newestEventId = GetEventID()
# Compare Event IDs for Updates
if newestEventId != latestEventId:
print("Found new ID "+newestEventId)
GetLatestEvents(latestEventId)
latestEventId = newestEventId
else:
print("No new events")
print("First ID: "+latestEventId)
print("Last ID: "+newestEventId)
# Sleep for 1 minute
time.sleep(60)
Complaining Goes Here
I had a hard time remembering some basic Python things like the fact that Syncthing/Requests will give you the JSON in a List, NOT a Dictionary. Once I found this out, I was able to access things properly and manipulate them. Second, I tripped myself up and wasn’t putting the right event ID in the URL. ARGH! The joys of programming and scripting, right?
Next Steps
How will I run this? Would it be better to run on startup or as a Linux service? The Windows SysAdmin in me thinks it would be more manageable as a service, but maybe that running the script under cron might be as easy? I think I’ve stared at this long enough today so I’m going to walk away and decide on this tomorrow.
This is day 5 of #100DaysToOffload.