@daemonitor/plugins 1.1.31 → 1.1.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugins/index.js
CHANGED
|
@@ -11,6 +11,7 @@ import { createSnmpPlugin } from "./monitoring/SnmpPlugin.js";
|
|
|
11
11
|
import { createThreeCXPlugin } from "./monitoring/ThreeCXPlugin.js";
|
|
12
12
|
import { createTplinkPlugin } from "./monitoring/TplinkPlugin.js";
|
|
13
13
|
import { createPatroniPlugin } from "./monitoring/PatroniPlugin.js";
|
|
14
|
+
import { createAdsensePlugin } from "./monitoring/AdsensePlugin.js";
|
|
14
15
|
// In future, implement other plugin factory functions using the same pattern
|
|
15
16
|
// import { createOSPlugin } from "./monitoring/OSPlugin.js"
|
|
16
17
|
// import { createMongoDBPlugin } from "./monitoring/MongoDBPlugin.js"
|
|
@@ -33,6 +34,7 @@ export default {
|
|
|
33
34
|
ThreeCX: createThreeCXPlugin,
|
|
34
35
|
Tplink: createTplinkPlugin,
|
|
35
36
|
Patroni: createPatroniPlugin,
|
|
37
|
+
Adsense: createAdsensePlugin,
|
|
36
38
|
// CloudflarePlugin: createCloudflarePlugin,
|
|
37
39
|
// EwelinkPlugin: createEwelinkPlugin,
|
|
38
40
|
// MongoDBPlugin: createMongoDBPlugin,
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { createMonitoringPlugin } from "../../lib/MonitoringPlugin.js";
|
|
2
|
+
// Google AdSense earnings monitor.
|
|
3
|
+
//
|
|
4
|
+
// AdSense has no service-account access, so this runs on a user refresh token
|
|
5
|
+
// (scope adsense.readonly) minted once by hand. Each poll trades it for a
|
|
6
|
+
// one-hour access token and pulls ONE report: earnings and page views per day,
|
|
7
|
+
// from whichever is earlier of the 1st of the month or 29 days ago, through
|
|
8
|
+
// today. Every figure on the tile (today, yesterday, 7 days, month to date, RPM,
|
|
9
|
+
// the daily sparkline) is summed locally from those rows, so the numbers cannot
|
|
10
|
+
// disagree with each other the way separate report calls can mid-update.
|
|
11
|
+
//
|
|
12
|
+
// Dates are the ACCOUNT's time zone, not this host's: "today" for an account in
|
|
13
|
+
// New York is still yesterday on a UTC box for a few hours every night.
|
|
14
|
+
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
15
|
+
const API = "https://adsense.googleapis.com/v2";
|
|
16
|
+
/** YYYY-MM-DD shifted by whole days. */
|
|
17
|
+
export function shiftDate(date, days) {
|
|
18
|
+
const t = new Date(`${date}T00:00:00Z`);
|
|
19
|
+
t.setUTCDate(t.getUTCDate() + days);
|
|
20
|
+
return t.toISOString().slice(0, 10);
|
|
21
|
+
}
|
|
22
|
+
/** Today's date as the account sees it. */
|
|
23
|
+
export function todayIn(timeZone, now = new Date()) {
|
|
24
|
+
// en-CA formats as YYYY-MM-DD.
|
|
25
|
+
return new Intl.DateTimeFormat("en-CA", { timeZone: timeZone || "UTC" }).format(now);
|
|
26
|
+
}
|
|
27
|
+
/** Earlier of the 1st of this month and 29 days back, so one report covers both windows. */
|
|
28
|
+
export function reportStart(today) {
|
|
29
|
+
const monthStart = `${today.slice(0, 7)}-01`;
|
|
30
|
+
const back = shiftDate(today, -29);
|
|
31
|
+
return back < monthStart ? back : monthStart;
|
|
32
|
+
}
|
|
33
|
+
export function reportUrl(account, start, end) {
|
|
34
|
+
const q = new URLSearchParams({ dateRange: "CUSTOM", reportingTimeZone: "ACCOUNT_TIME_ZONE", dimensions: "DATE" });
|
|
35
|
+
for (const [k, v] of [["startDate", start], ["endDate", end]]) {
|
|
36
|
+
const [y, m, d] = v.split("-").map(Number);
|
|
37
|
+
q.set(`${k}.year`, String(y));
|
|
38
|
+
q.set(`${k}.month`, String(m));
|
|
39
|
+
q.set(`${k}.day`, String(d));
|
|
40
|
+
}
|
|
41
|
+
q.append("metrics", "ESTIMATED_EARNINGS");
|
|
42
|
+
q.append("metrics", "PAGE_VIEWS");
|
|
43
|
+
return `${API}/${account}/reports:generate?${q}`;
|
|
44
|
+
}
|
|
45
|
+
/** reports:generate response -> per-day rows. Columns are found by header name, not position. */
|
|
46
|
+
export function parseReport(report) {
|
|
47
|
+
const headers = Array.isArray(report?.headers) ? report.headers : [];
|
|
48
|
+
const col = (name) => headers.findIndex((h) => h?.name === name);
|
|
49
|
+
const [iDate, iEarn, iViews] = [col("DATE"), col("ESTIMATED_EARNINGS"), col("PAGE_VIEWS")];
|
|
50
|
+
if (iDate < 0 || iEarn < 0)
|
|
51
|
+
throw new Error("unexpected report shape (no DATE/ESTIMATED_EARNINGS column)");
|
|
52
|
+
// A day with no traffic has no row at all, so an empty report is valid.
|
|
53
|
+
const rows = Array.isArray(report?.rows) ? report.rows : [];
|
|
54
|
+
return {
|
|
55
|
+
currency: headers[iEarn]?.currencyCode || "USD",
|
|
56
|
+
days: rows.map((r) => ({
|
|
57
|
+
date: String(r?.cells?.[iDate]?.value || ""),
|
|
58
|
+
earnings: Number(r?.cells?.[iEarn]?.value) || 0,
|
|
59
|
+
pageViews: iViews < 0 ? 0 : Number(r?.cells?.[iViews]?.value) || 0,
|
|
60
|
+
})),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
const cents = (n) => Math.round(n * 100) / 100;
|
|
64
|
+
/** Roll per-day rows up into the figures the tile shows. `last7` includes today, as AdSense's own "Last 7 days" does. */
|
|
65
|
+
export function summarize(days, today) {
|
|
66
|
+
const by = new Map(days.map((d) => [d.date, d]));
|
|
67
|
+
const day = (date) => by.get(date) || { date, earnings: 0, pageViews: 0 };
|
|
68
|
+
const span = (n) => Array.from({ length: n }, (_, i) => day(shiftDate(today, i - n + 1)));
|
|
69
|
+
const week = span(7);
|
|
70
|
+
const last7 = week.reduce((s, d) => s + d.earnings, 0);
|
|
71
|
+
const pageViews7 = week.reduce((s, d) => s + d.pageViews, 0);
|
|
72
|
+
const month = today.slice(0, 7);
|
|
73
|
+
return {
|
|
74
|
+
today: cents(day(today).earnings),
|
|
75
|
+
yesterday: cents(day(shiftDate(today, -1)).earnings),
|
|
76
|
+
last7: cents(last7),
|
|
77
|
+
monthToDate: cents(days.filter((d) => d.date.startsWith(month)).reduce((s, d) => s + d.earnings, 0)),
|
|
78
|
+
pageViews7,
|
|
79
|
+
// Page RPM over the same 7 days: earnings per thousand page views.
|
|
80
|
+
rpm: pageViews7 ? cents((last7 / pageViews7) * 1000) : 0,
|
|
81
|
+
// Gap-filled so the sparkline has one point per day, oldest first.
|
|
82
|
+
daily: span(30),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
async function getJson(url, init, timeout) {
|
|
86
|
+
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeout) });
|
|
87
|
+
const body = await res.json().catch(() => ({}));
|
|
88
|
+
if (!res.ok) {
|
|
89
|
+
const e = new Error(body?.error_description || body?.error?.message || body?.error || `HTTP ${res.status}`);
|
|
90
|
+
e.code = typeof body?.error === "string" ? body.error : body?.error?.status;
|
|
91
|
+
throw e;
|
|
92
|
+
}
|
|
93
|
+
return body;
|
|
94
|
+
}
|
|
95
|
+
export function createAdsensePlugin() {
|
|
96
|
+
let refreshTimer = null;
|
|
97
|
+
// Resolved once: the account and its time zone do not change between polls.
|
|
98
|
+
let account = null;
|
|
99
|
+
const collect = async (cfg) => {
|
|
100
|
+
const timeout = cfg.timeout || 15000;
|
|
101
|
+
const tok = await getJson(TOKEN_URL, {
|
|
102
|
+
method: "POST",
|
|
103
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
104
|
+
body: new URLSearchParams({
|
|
105
|
+
grant_type: "refresh_token",
|
|
106
|
+
client_id: cfg.clientId || "",
|
|
107
|
+
client_secret: cfg.clientSecret || "",
|
|
108
|
+
refresh_token: cfg.refreshToken || "",
|
|
109
|
+
}).toString(),
|
|
110
|
+
}, timeout);
|
|
111
|
+
const auth = { headers: { Authorization: `Bearer ${tok.access_token}` } };
|
|
112
|
+
if (!account) {
|
|
113
|
+
const list = (await getJson(`${API}/accounts`, auth, timeout))?.accounts || [];
|
|
114
|
+
const a = cfg.accountId ? list.find((x) => x.name === cfg.accountId) : list[0];
|
|
115
|
+
if (!a)
|
|
116
|
+
throw new Error(cfg.accountId ? `account ${cfg.accountId} not visible to this token` : "no AdSense account visible to this token");
|
|
117
|
+
account = { name: a.name, timeZone: a.timeZone?.id };
|
|
118
|
+
}
|
|
119
|
+
const today = todayIn(account.timeZone);
|
|
120
|
+
const { currency, days } = parseReport(await getJson(reportUrl(account.name, reportStart(today), today), auth, timeout));
|
|
121
|
+
return { accountId: account.name, currency, asOf: today, ...summarize(days, today) };
|
|
122
|
+
};
|
|
123
|
+
const refreshFn = async (plugin) => {
|
|
124
|
+
const cfg = (plugin.config || {});
|
|
125
|
+
if (!cfg.clientId || !cfg.clientSecret || !cfg.refreshToken) {
|
|
126
|
+
await plugin.send({ error: "adsense plugin needs clientId, clientSecret and refreshToken" });
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
await plugin.send(await collect(cfg));
|
|
131
|
+
}
|
|
132
|
+
catch (e) {
|
|
133
|
+
// invalid_grant = the refresh token was revoked or expired. Nothing the
|
|
134
|
+
// next poll can fix, so it is flagged apart from a transient API error.
|
|
135
|
+
await plugin.send({
|
|
136
|
+
error: String(e?.message || e).slice(0, 160),
|
|
137
|
+
...(e?.code === "invalid_grant" ? { authExpired: true } : {}),
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
const monitorFn = async (plugin) => {
|
|
142
|
+
await refreshFn(plugin);
|
|
143
|
+
// AdSense figures lag by hours; 10 minutes keeps the row inside the
|
|
144
|
+
// server's 15-minute staleness window without spending API quota.
|
|
145
|
+
refreshTimer = setInterval(() => refreshFn(plugin), plugin.config?.refreshInterval || 600000);
|
|
146
|
+
};
|
|
147
|
+
const teardownFn = async () => {
|
|
148
|
+
if (refreshTimer)
|
|
149
|
+
clearInterval(refreshTimer);
|
|
150
|
+
refreshTimer = null;
|
|
151
|
+
};
|
|
152
|
+
return createMonitoringPlugin("adsense", "adsense", "Google AdSense earnings (today, yesterday, 7 days, month to date, page RPM)", async () => { }, monitorFn, refreshFn, teardownFn);
|
|
153
|
+
}
|
|
154
|
+
export default createAdsensePlugin;
|