-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplausible-stats
executable file
·220 lines (180 loc) · 7.82 KB
/
plausible-stats
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#!/usr/bin/env python3
"""
Load site data from Plausible Analytics API and print to stdout.
Input is a TSV file containing the name of the site and its Plausible domain
"""
import argparse
import datetime
import json
import os
import sys
from calendar import month
from collections import OrderedDict
import csv
from typing import List
import requests
try:
PLAUSIBLE_KEY = os.environ['PLAUSIBLE_KEY']
except KeyError:
print("Please set PLAUSIBLE_KEY environment variable")
sys.exit(1)
FIELDS = ["visitors", "visits", "pageviews", "views_per_visit", "bounce_rate", "visit_duration"]
START = '2023-06-01'
def geo(args, sites: OrderedDict):
"""Load geo data"""
session = requests.session()
session.headers = {'Authorization': "Bearer " + PLAUSIBLE_KEY}
data = OrderedDict()
for short_name, domain in sites.items():
name = f"{short_name} Geo"
# parse the month of the given start date:
start = datetime.datetime.strptime(args.start, "%Y-%m-01")
# get a list of months from start to the current date:
months = [start + datetime.timedelta(days=31 * i) for i in range(0, (datetime.date.today().year - start.year) * 12 + datetime.date.today().month - start.month + 1)]
# get the data for each month:
data[name] = OrderedDict()
first_of_months = [m.strftime("%Y-%m-01") for m in months]
country_data = OrderedDict()
# in order the get all available countries we need to collect all the
for i, fom in enumerate(first_of_months):
r = session.get('https://plausible.io/api/v1/stats/breakdown', params=dict(
site_id=domain,
period='month',
property='visit:country',
date=fom
))
results = r.json()['results']
for result in results:
country_code = result['country']
visitors = result['visitors']
if country_code not in country_data:
country_data[country_code] = {fom: visitors}
else:
country_data[country_code][fom] = visitors
# reformat the results:
data[name] = [["country"] + [m.strftime("%Y-%m") for m in months]]
for country_code, visitors in country_data.items():
data[name].append([country_code] + [visitors.get(fom, 0) for fom in first_of_months])
json.dump(data, fp=sys.stdout, indent=2)
def visits(args, sites: OrderedDict):
"""Load all site data"""
session = requests.session()
session.headers = {'Authorization': "Bearer " + PLAUSIBLE_KEY}
data = OrderedDict()
for name, domain in sites.items():
r = session.get('https://plausible.io/api/v1/stats/timeseries', params=dict(
site_id=domain,
period='custom',
metrics=','.join(FIELDS),
date=args.start + "," + datetime.date.today().isoformat()
))
data[name] = [["date"] + FIELDS]
data[name].extend([[i["date"]] + [i[field] for field in FIELDS] for i in r.json()['results']])
json.dump(data, fp=sys.stdout, indent=2)
def totals(args, sites: OrderedDict):
"""Load all site data"""
session = requests.session()
session.headers = {
'Authorization': "Bearer " + PLAUSIBLE_KEY,
'Content-Type': 'application/json'
}
# Parse the start date and convert to first of that year
start = datetime.datetime.strptime(args.start, "%Y-%m-%d").date()
start_date = start.replace(month=1, day=1)
end_date = start.replace(month=12, day=31)
data = OrderedDict()
metrics = ["visitors", "pageviews"]
filters = ["contains", "event:page", args.page] if args.page else []
date_ranges = [(year, [start_date.replace(year=year).strftime('%Y-%m-%d'),
end_date.replace(year=year).strftime('%Y-%m-%d')])
for year in range(start.year, datetime.date.today().year + 1)]
if args.months:
date_ranges = [(d, [d.strftime('%Y-%m-%d'),
last_day_of_month(d).strftime('%Y-%m-%d')])
for d in get_monthly_dates(start_date)]
for period, ranges in date_ranges:
for name, domain in sites.items():
payload = dict(
site_id=domain,
# period='custom',
filters=[filters],
metrics=metrics,
date_range=ranges,
include=dict(imports=True)
)
# print(json.dumps(payload), file=sys.stderr)
r = session.post('https://plausible.io/api/v2/query', json=payload)
# print(r.status_code, file=sys.stderr)
if name not in data:
data[name] = []
apidata = r.json()
if 'error' in apidata:
print("Error from Plausible API: " + apidata['error'], file=sys.stderr)
sys.exit(2)
results = r.json()['results'][0]['metrics'][0:len(metrics)]
data[name].append([period] + results)
if args.format == "csv":
import csv
writer = csv.writer(sys.stdout)
writer.writerow(['site', 'month' if args.months else 'year'] + metrics)
for site, metrics in data.items():
for row in metrics:
writer.writerow([site] + row)
else:
json.dump(data, fp=sys.stdout, indent=2)
def last_day_of_month(first_day):
"""
Get the last day of the month given the first day using only standard library.
"""
# Calculate the year and month of the next month
year = first_day.year + (first_day.month // 12)
month = (first_day.month % 12) + 1
# First day of next month
next_month = datetime.date(year, month, 1)
# Subtract one day to get the last day of the original month
last_day = next_month - datetime.timedelta(days=1)
return last_day
def get_monthly_dates(start_date):
"""
Generate a list of dates, one per month,
from the start date until today.
"""
# Get today's date
today = datetime.date.today().replace(day=1)
# Initialize result list and current date
dates = []
current = start_date.replace(day=1)
# Generate dates until we reach or exceed today
while current <= today:
dates.append(current)
# Move to the first day of the next month
year = current.year + (current.month // 12)
month = (current.month % 12) + 1
current = datetime.date(year, month, 1) # Always use day 1
return dates
if __name__ == "__main__":
# Parse arguments
parser = argparse.ArgumentParser(description='Load site data from Plausible Analytics API and print to stdout.')
parser.add_argument('-g', '--geo', action='store_true', help="Extract geospatial data for months to date")
parser.add_argument('-p', '--page', nargs='*', help="Count unique visitors for one or more matching "
"page prefixes, e.g. /units/de-002302")
parser.add_argument('-s', '--start', default=START, help="Start date for data as YYYY-MM-DD")
parser.add_argument('-t', '--totals', action='store_true', help="Extract totals data for years to date")
parser.add_argument('-S', '--site', nargs='*', help='A specific site to query')
parser.add_argument('-f', '--format', default="json", help="Output format: either json or csv")
parser.add_argument('-m', '--months', action="store_true", help="Output date in month (not year) ranges")
args = parser.parse_args()
# Load SITES from TSV file passed via stdin
sites = OrderedDict()
if args.site:
for i, site in enumerate(args.site):
sites["Site {}".format(i + 1)] = site
else:
for row in csv.reader(sys.stdin, delimiter="\t"):
sites[row[0]] = row[1]
if args.geo:
geo(args, sites)
elif args.totals:
totals(args, sites)
else:
visits(args, sites)