Skip to content

Commit 91d2e78

Browse files
fix: various smaller bugfixes
Signed-off-by: Henry Gressmann <[email protected]>
1 parent d49e3ce commit 91d2e78

File tree

9 files changed

+33
-17
lines changed

9 files changed

+33
-17
lines changed

scripts/deploy-demo.sh

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#!/usr/bin/env bash
2+
cd "$(dirname "$0")" && cd ..
3+
cargo zigbuild --release --target x86_64-unknown-linux-musl
4+
rsync -avzP target/x86_64-unknown-linux-musl/release/liwan pegasus:~/.local/bin/liwan

src/web/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,11 @@ fn save_spec() -> Result<()> {
5252
}
5353

5454
pub fn create_router(app: Liwan, events: Sender<Event>) -> impl IntoEndpoint {
55-
let handle_events =
56-
event_service().with(Cors::new().allow_origin("*").allow_method("POST").allow_credentials(false));
55+
let handle_events = event_service().with(Cors::new().allow_method("POST").allow_credentials(false));
5756

5857
let serve_script = EmbeddedFileEndpoint::<Script>::new("script.min.js")
59-
.with(Cors::new().allow_origin("*").allow_method("GET").allow_credentials(false));
58+
.with(Cors::new().allow_method("GET").allow_credentials(false))
59+
.with(SetHeader::new().appending("Content-Type", "application/javascript"));
6060

6161
let headers = SetHeader::new()
6262
.appending("X-Frame-Options", "DENY")

src/web/routes/dashboard.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use crate::utils::validate::{self, can_access_project};
44
use crate::web::session::SessionUser;
55
use crate::web::webext::{http_bail, ApiResult, PoemErrExt};
66

7+
use maxminddb::geoip2::city;
78
use poem::http::StatusCode;
89
use poem::web::Data;
910
use poem_openapi::param::Path;
@@ -169,6 +170,7 @@ impl DashboardAPI {
169170
.split_at_checked(2)
170171
.map(|(a, b)| (Some(a.to_string()), Some(b.to_string())))
171172
.unwrap_or((None, None));
173+
let city = city.filter(|city| !city.is_empty());
172174
data.push(DimensionTableRow { dimension_value: key, value, display_name: city, icon: country });
173175
}
174176
_ => {

src/web/routes/event.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use poem::web::{headers, Data, RealIp, TypedHeader};
1212
use poem_openapi::payload::Json;
1313
use poem_openapi::{Object, OpenApi};
1414
use std::cell::RefCell;
15+
use std::net::{IpAddr, Ipv4Addr};
1516
use std::str::FromStr;
1617

1718
#[derive(Object)]
@@ -66,13 +67,15 @@ impl EventApi {
6667
};
6768

6869
let (country, city) = match (&app.geoip, ip) {
69-
(Some(geoip), Some(ip)) => match geoip.lookup(&ip) {
70+
(Some(geoip), Some(ip)) => match geoip.lookup(&IpAddr::V4(Ipv4Addr::new(46, 114, 18, 156))) {
7071
Ok(lookup) => (lookup.country_code, lookup.city),
7172
Err(_) => (None, None),
7273
},
7374
_ => (None, None),
7475
};
7576

77+
tracing::error!("country: {:?}, city: {:?}", country, city);
78+
7679
let event = Event {
7780
visitor_id,
7881
referrer,

tracker/script.d.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ declare module "script" {
2424
* Required in server-side environments.
2525
*/
2626
endpoint?: string;
27+
/**
28+
* The entity that the event is associated with.
29+
*
30+
* If not provided, the `data-entity` attribute will be used.
31+
* Required for custom events.
32+
*/
33+
entity?: string;
2734
};
2835
/**
2936
* Sends an event to the Liwan API.

tracker/script.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tracker/script.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,15 @@ let entity: string | null = null;
4848
let referrer: string | null = null;
4949

5050
if (typeof document !== "undefined") {
51-
scriptEl = document.currentScript as HTMLScriptElement;
51+
scriptEl = document.querySelector(`script[src^="${import.meta.url}"]`);
5252
endpoint = scriptEl?.getAttribute("data-api") || (scriptEl && `${new URL(scriptEl.src).origin}/api/event`);
5353
entity = scriptEl?.getAttribute("data-entity") || null;
5454
referrer = document.referrer;
5555
}
5656

5757
const LOCALHOST_REGEX = /^localhost$|^127(\.[0-9]+){0,2}\.[0-9]+$|^\[::1?\]$/;
58-
const ignoreEvent = (reason: string) => console.info(`[liwan]: ignoring event: ${reason}`);
58+
const log = (message: string) => console.info(`[liwan]: ${message}`);
59+
const ignore = (reason: string) => log(`Ignoring event: ${reason}`);
5960

6061
/**
6162
* Sends an event to the Liwan API.
@@ -80,10 +81,9 @@ const ignoreEvent = (reason: string) => console.info(`[liwan]: ignoring event: $
8081
export async function event(name = "pageview", options?: EventOptions) {
8182
if (typeof window === "undefined" && !options?.endpoint)
8283
return Promise.reject(new Error("endpoint is required in server-side environments"));
83-
if (typeof localStorage !== "undefined" && localStorage.getItem("disable-liwan"))
84-
return ignoreEvent("localStorage flag");
85-
if (LOCALHOST_REGEX.test(location.hostname) || location.protocol === "file:") return ignoreEvent("localhost");
86-
if (!endpoint && !options?.endpoint) return ignoreEvent("no endpoint");
84+
if (typeof localStorage !== "undefined" && localStorage.getItem("disable-liwan")) return ignore("localStorage flag");
85+
if (LOCALHOST_REGEX.test(location.hostname) || location.protocol === "file:") return ignore("localhost");
86+
if (!endpoint && !options?.endpoint) return ignore("no endpoint");
8787

8888
// biome-ignore lint/style/noNonNullAssertion: we know that endpoint is not null
8989
return fetch((options?.endpoint || endpoint)!, {
@@ -96,7 +96,7 @@ export async function event(name = "pageview", options?: EventOptions) {
9696
url: options?.url || `${location.origin}${location.pathname}`,
9797
}),
9898
}).then((response) => {
99-
if (!response.ok) console.error("[liwan]: failed to send event: ", response);
99+
if (!response.ok) log(`Failed to send event: ${response.statusText}`);
100100
return { status: response.status };
101101
});
102102
}

web/src/components/dimensions/index.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ const dimensionLabels: Record<Dimension, (value: DimensionTableRow) => React.Rea
239239
<>
240240
{countryCodeToFlag(value.icon || "XX")}
241241
&nbsp;
242-
{value.displayName ?? value.dimensionValue ?? "Unknown"}
242+
{value.displayName ?? "Unknown"}
243243
</>
244244
),
245245
referrer: (value) => (

web/src/components/projects.tsx

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ export const ProjectOverview = ({
201201
title="Total Views"
202202
value={stats?.stats.totalViews}
203203
prevValue={stats?.statsPrev.totalViews}
204-
metric={metric}
204+
metric={"views"}
205205
onSelect={() => setMetric("views")}
206206
selected={metric === "views"}
207207
/>
@@ -210,23 +210,23 @@ export const ProjectOverview = ({
210210
title="Total Sessions"
211211
value={stats?.stats.totalSessions}
212212
prevValue={stats?.statsPrev.totalSessions}
213-
metric={metric}
213+
metric={"sessions"}
214214
onSelect={() => setMetric("sessions")}
215215
selected={metric === "sessions"}
216216
/>
217217
<Stat
218218
title="Unique Visitors"
219219
value={stats?.stats.uniqueVisitors}
220220
prevValue={stats?.statsPrev.uniqueVisitors}
221-
metric={metric}
221+
metric={"unique_visitors"}
222222
onSelect={() => setMetric("unique_visitors")}
223223
selected={metric === "unique_visitors"}
224224
/>
225225
<Stat
226226
title="Avg. Views Per Session"
227227
value={stats?.stats.avgViewsPerSession}
228228
prevValue={stats?.statsPrev.avgViewsPerSession}
229-
metric={metric}
229+
metric={"avg_views_per_session"}
230230
onSelect={() => setMetric("avg_views_per_session")}
231231
selected={metric === "avg_views_per_session"}
232232
/>

0 commit comments

Comments
 (0)