import sqlite3 import sys import os from datetime import datetime # see https://github.com/arp242/goatcounter/blob/master/db/query/hit_list.List-stats.sql # date format: "2022-11-01 23:00:00" q = """ select path, title, hour, sum(total) as total from hit_counts where hit_counts.site = 1 and hour >= "2022-11-01" and hour < "2022-12-01" and path like '/post/%' group by path order by total desc limit 5 """ dbpath = "/var/www/goatcounter/db/goatcounter.sqlite3" if len(sys.argv) > 1: dbpath = sys.argv[1] if not os.path.exists(dbpath): exit("DB file " + dbpath + " does not exist, quitting!") connection = sqlite3.connect(dbpath) cursor = connection.cursor() cursor.execute(q) rows = cursor.fetchall() total = sum(map(lambda r: int(r[3]), rows)) title = lambda r: r[1].split('|')[0].strip() url = lambda r: r[0] date = lambda r: datetime.strptime(r[2], "%Y-%m-%d %H:%M:%S").strftime("%d %b %Y") rank = lambda r: str(round((int(r[3]) / total) * 100)) + "%" print('[') print(',\n'.join(map(lambda r: "{ \"url\": \"" + url(r) + "\", \"title\": \"" + title(r) + "\", \"rank\": \"" + rank(r) + "\" }", rows))) print(']')