Skip to content

Commit

Permalink
feat: display whether or not the instance is up to date on error (#310)
Browse files Browse the repository at this point in the history
  • Loading branch information
sigaloid authored Nov 1, 2024
1 parent 2fd358f commit f03bdcf
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/instance_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ fn info_html(req: &Request<Body>) -> Result<Response<Body>, Error> {
pub struct InstanceInfo {
package_name: String,
crate_version: String,
git_commit: String,
pub git_commit: String,
deploy_date: String,
compile_mode: String,
deploy_unix_ts: i64,
Expand Down
31 changes: 28 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
#![forbid(unsafe_code)]
#![allow(clippy::cmp_owned)]

// Import Crates
use cached::proc_macro::cached;
use clap::{Arg, ArgAction, Command};
use std::str::FromStr;

use futures_lite::FutureExt;
use hyper::Uri;
use hyper::{header::HeaderValue, Body, Request, Response};

use log::info;
use once_cell::sync::Lazy;
use redlib::client::{canonical_path, proxy};
use redlib::client::{canonical_path, proxy, CLIENT};
use redlib::server::{self, RequestExt};
use redlib::utils::{error, redirect, ThemeAssets};
use redlib::{config, duplicates, headers, instance_info, post, search, settings, subreddit, user};
Expand Down Expand Up @@ -217,6 +218,11 @@ async fn main() {
app
.at("/highlighted.js")
.get(|_| resource(include_str!("../static/highlighted.js"), "text/javascript", false).boxed());
app
.at("/check_update.js")
.get(|_| resource(include_str!("../static/check_update.js"), "text/javascript", false).boxed());

app.at("/commits.atom").get(|_| async move { proxy_commit_info().await }.boxed());

// Proxy media through Redlib
app.at("/vid/:id/:size").get(|r| proxy(r, "https://v.redd.it/{id}/DASH_{size}").boxed());
Expand Down Expand Up @@ -374,3 +380,22 @@ async fn main() {
eprintln!("Server error: {e}");
}
}

pub async fn proxy_commit_info() -> Result<Response<Body>, String> {
Ok(
Response::builder()
.status(200)
.header("content-type", "application/atom+xml")
.body(Body::from(fetch_commit_info().await))
.unwrap_or_default(),
)
}

#[cached(time = 600)]
async fn fetch_commit_info() -> String {
let uri = Uri::from_str("https://github.com/redlib-org/redlib/commits/main.atom").expect("Invalid URI");

let resp: Body = CLIENT.get(uri).await.expect("Failed to request GitHub").into_body();

hyper::body::to_bytes(resp).await.expect("Failed to read body").iter().copied().map(|x| x as char).collect()
}
38 changes: 38 additions & 0 deletions static/check_update.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
async function checkInstanceUpdateStatus() {
try {
const response = await fetch('/commits.atom');
const text = await response.text();
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(text, "application/xml");
const entries = xmlDoc.getElementsByTagName('entry');
const localCommit = document.getElementById('git_commit').dataset.value;

let statusMessage = '';

if (entries.length > 0) {
const commitHashes = Array.from(entries).map(entry => {
const id = entry.getElementsByTagName('id')[0].textContent;
return id.split('/').pop();
});

const commitIndex = commitHashes.indexOf(localCommit);

if (commitIndex === 0) {
statusMessage = '✅ Instance is up to date.';
} else if (commitIndex > 0) {
statusMessage = `⚠️ This instance is not up to date and is ${commitIndex} commits old. Test and confirm on an up-to-date instance before reporting.`;
} else {
statusMessage = `⚠️ This instance is not up to date and is at least ${commitHashes.length} commits old. Test and confirm on an up-to-date instance before reporting.`;
}
} else {
statusMessage = '⚠️ Unable to fetch commit information.';
}

document.getElementById('update-status').innerText = statusMessage;
} catch (error) {
console.error('Error fetching commits:', error);
document.getElementById('update-status').innerText = '⚠️ Error checking update status.';
}
}

checkInstanceUpdateStatus();
7 changes: 6 additions & 1 deletion templates/error.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@
<h1>{{ msg }}</h1>
<h3><a href="https://www.redditstatus.com/">Reddit Status</a></h3>
<br />
<h3 id="update-status"></h3>
<br>
<div id="git_commit" data-value="{{ crate::instance_info::INSTANCE_INFO.git_commit }}"></div>
<script src="/check_update.js"></script>

<h3>Expected something to work? <a
href="https://github.com/redlib-org/redlib/issues/new?assignees=&labels=bug&projects=&template=bug_report.md&title=%F0%9F%90%9B+Bug+Report%3A+{{ msg }}">Report
an issue</a></h3>
<br />
<h3>Head back <a href="/">home</a>?</h3>
</div>
{% endblock %}
{% endblock %}

0 comments on commit f03bdcf

Please sign in to comment.