Skip to content

Commit

Permalink
feat: some proper data about user ip and location
Browse files Browse the repository at this point in the history
  • Loading branch information
tm26a21p committed Jun 15, 2024
1 parent 0a88378 commit 691d9ba
Show file tree
Hide file tree
Showing 13 changed files with 625 additions and 48 deletions.
505 changes: 482 additions & 23 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ tower = "0.4.13"
octocrab = "0.38.0"
dotenv = "0.15.0"
chrono = "0.4.38"
reqwest = { version = "0.12.4", features = ["json"] }
ipgeolocate = "0.3.5"

[profile.dev.package.askama_derive]
opt-level = 3

60 changes: 60 additions & 0 deletions src/htmx_routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,63 @@ pub async fn set_theme(
state.set_theme(payload.theme);
(StatusCode::OK, "Theme set".into_response())
}

async fn get_ip() -> String
{
reqwest::get("https://api.ipify.org")
.await
.expect("Failed to get ip")
.text()
.await
.expect("Failed to get ip")
}

pub async fn ip_adress(
Extension(state): Extension<Common>
) -> impl IntoResponse
{
let ip = get_ip().await;

let mut metrics = state.metrics.write().unwrap();
metrics.ip = ip.clone();
drop(metrics);
(StatusCode::OK, ip.into_response())
}

use ipgeolocate::{Locator, Service};

async fn get_location(ip: &str) -> Option<GeoLocation>
{
let service = Service::IpApi;
match Locator::get(ip, service).await {
Ok(response) => {
Some(GeoLocation {
latitude: response.latitude,
longitude: response.longitude,
city: response.city,
region: response.region,
country: response.country,
timezone: response.timezone,
})
}
Err(error) => {
eprintln!("Failed to get location: {:?}", error);
None
}
}
}

pub async fn location(
Extension(_state): Extension<Common>
) -> impl IntoResponse
{
let ip = get_ip().await;

let location = get_location(&ip).await.unwrap();
// let's acually return a jinja template with the location

let reply_html = LocationT { location }
.render()
.expect("Failed to render template");
(StatusCode::OK, Html(reply_html).into_response())
}
23 changes: 21 additions & 2 deletions src/htmx_templates.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,28 @@
use askama_axum::Template;

use crate::project::Project;

#[derive(Template)]
#[template(path = "htmx/tabs.html")]
pub struct TabsT {
pub struct TabsT
{
pub liked: bool,
pub projects: Vec<Project>,
}
}

#[derive(Template)]
#[template(path = "htmx/location.html")]
pub struct LocationT
{
pub location: GeoLocation,
}

pub struct GeoLocation
{
pub latitude: String,
pub longitude: String,
pub city: String,
pub region: String,
pub country: String,
pub timezone: String,
}
2 changes: 2 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ async fn main()
.route("/api/projects", get(projects))
.route("/api/projects-liked", get(projects_liked))
.route("/api/set-theme", post(set_theme))
.route("/api/ip", get(ip_adress))
.route("/api/location", get(location))
.nest("/public", using_serve_dir())
.layer(Extension(state.clone()));

Expand Down
6 changes: 4 additions & 2 deletions src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub struct Project

impl Project
{
pub fn new(url: &str) -> Self
pub fn _new(url: &str) -> Self
{
Self {
url: url.to_string(),
Expand Down Expand Up @@ -104,7 +104,9 @@ impl Project
.collect()
}

pub async fn get_repositories_liked(octo: Octocrab) -> octocrab::Result<Vec<Project>>
pub async fn get_repositories_liked(
octo: Octocrab
) -> octocrab::Result<Vec<Project>>
{
let repos = Project::fetch_user_repositories(octo).await?;
let projects = Project::process_repositories(repos);
Expand Down
13 changes: 8 additions & 5 deletions src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,20 @@ pub async fn metrics_page(
title: state.name.clone() + " - Metrics",
daisy_theme: state.get_theme(),
};

let mut metrics = state.metrics.write().unwrap();
metrics.visited += 1;
let metrics_clone = metrics.clone();
drop(metrics);

let template = MetricsT {
base,
likes: 0,
likes_ratio_over_last_month: 0.0,
views: 0,
view_ratio_over_last_month: 0.0,
metrics: metrics_clone,
};

let reply_html = template.render().expect("Failed to render template");
(StatusCode::OK, Html(reply_html).into_response())
}

pub async fn projects_page(
Extension(state): Extension<Common>
) -> impl IntoResponse
Expand Down
22 changes: 22 additions & 0 deletions src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub struct Common
pub daisy_theme: Arc<RwLock<String>>,
pub _github_token: String,
pub octocrab: octocrab::Octocrab,
pub metrics: Arc<RwLock<Metrics>>,
}

impl Common
Expand All @@ -27,6 +28,7 @@ impl Common
.personal_token(github_token)
.build()
.expect("Failed to create Octocrab instance."),
metrics: Arc::new(RwLock::new(Metrics::new())),
}
}

Expand All @@ -44,3 +46,23 @@ impl Common
*theme = new_theme;
}
}

#[derive(Debug, Clone)]
pub struct Metrics
{
pub visited: usize,
pub ip: String,
pub location: String,
}

impl Metrics
{
pub fn new() -> Self
{
Self {
visited: 1,
ip: "Unknown".to_string(),
location: "Unknown".to_string(),
}
}
}
9 changes: 3 additions & 6 deletions src/templates.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use askama_axum::Template;

use crate::project::Project;
use crate::{htmx_templates::GeoLocation, project::Project, state::Metrics};

#[derive(Template)]
#[template(path = "base.html")]
Expand All @@ -23,10 +23,7 @@ pub struct IndexT
pub struct MetricsT
{
pub base: BaseT,
pub likes: usize,
pub likes_ratio_over_last_month: f64,
pub views: usize,
pub view_ratio_over_last_month: f64,
pub metrics: Metrics,
}

#[derive(Template)]
Expand All @@ -42,4 +39,4 @@ pub struct ProjectsT
pub struct PlaygroundT
{
pub base: BaseT,
}
}
1 change: 1 addition & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ pub fn read_daisy_theme_config(file_path: &str) -> Vec<String>
}

use rand::Rng;

// Function to return a random number between 0 and `range`
pub fn random_number(range: u32) -> u32
{
Expand Down
8 changes: 4 additions & 4 deletions templates/components/stats.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
</svg>
</div>
<div class="stat-title">Total Likes</div>
<div class="stat-value text-primary"> {{ likes }} </div>
<div class="stat-desc"> {{ likes_ratio_over_last_month }}% more than last month</div>
<div class="stat-value text-primary"> data </div>
<div class="stat-desc"> data more than last month</div>
</div>

<div class="stat">
Expand All @@ -23,8 +23,8 @@
</svg>
</div>
<div class="stat-title">Website Views</div>
<div class="stat-value text-secondary">{{ views }} </div>
<div class="stat-desc"> {{ view_ratio_over_last_month }}% more than last month</div>
<div class="stat-value text-secondary">data </div>
<div class="stat-desc"> data more than last month</div>
</div>

<div class="stat">
Expand Down
12 changes: 12 additions & 0 deletions templates/htmx/location.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<tr class="border px-4 py-2">
<td class="border px-4 py-2">Location</td>
<td class="border px-4 py-2">{{ location.country }}, {{ location.city }}, {{ location.region }}</td>
</tr>
<tr>
<td class="border px-4 py-2">Latitude & Longitude</td>
<td class="border px-4 py-2">{{location.latitude}} | {{location.longitude}}</td>
</tr>
<tr>
<td class="border px-4 py-2">Timezone</td>
<td class="border px-4 py-2">{{location.timezone}}</td>
</tr>
9 changes: 4 additions & 5 deletions templates/pages/metrics.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,11 @@ <h2 class="text-2xl font-bold mb-4 text-primary text-center">What I Know About Y
<tbody>
<tr>
<td class="border px-4 py-2">IP Address</td>
<td class="border px-4 py-2">192.168.1.1</td>
</tr>
<tr>
<td class="border px-4 py-2">Location</td>
<td class="border px-4 py-2">San Francisco, CA, USA</td>
<td hx-get="/api/ip" hx-swap="innerHTML" hx-trigger="load" class="border px-4 py-2">Unknown
address</td>
</tr>
<tr hx-get="/api/location" hx-swap="outerHTML" hx-trigger="load">

<tr>
<td class="border px-4 py-2">Device Type</td>
<td class="border px-4 py-2">Desktop</td>
Expand Down

0 comments on commit 691d9ba

Please sign in to comment.