Skip to content

Commit

Permalink
HAPPY NEW YEAR
Browse files Browse the repository at this point in the history
  • Loading branch information
strawmelonjuice committed Dec 31, 2023
1 parent 422e750 commit f45d255
Show file tree
Hide file tree
Showing 10 changed files with 80 additions and 96 deletions.
1 change: 1 addition & 0 deletions .github/workflows/rust-clippy.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#file: noinspection GrazieInspection
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
Expand Down
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ serde_json = "1.0.107"
serde_yaml = "0.9.29"
colored = "2.0.4"
dotenv = "0.15.0"
handlebars = "4.5.0"
handlebars = "5.0.0"
jsonc-parser = { version = "0.23.0", features = ["serde"] }
markdown = "1.0.0-alpha.16"
curl = "0.4.44"
Expand Down
6 changes: 3 additions & 3 deletions docs/jsr.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
_Cynthia doesn't need one, but most of its plugins do!_

## Supported runtimes
- Cynthia supports **_Node.js_ everywhere**, and **_Bun_ on Linux and MacOS**. If you have Bun working on Windows through WSL, it'll try that but most likely fail (and fall back on Node.JS).
- Cynthia supports **_Node.js_ everywhere**, and **_Bun_ on Linux and macOS**. If you have Bun working on Windows through WSL, it'll try that but most likely fail (and fall back on Node.js).

- Any available Bun instance is prefered over Node.js by Cynthia, this because Cynthia assumes Bun will start faster.
- Cynthia (plv2) plugins are rapidly iterated over, giving each a chance to modify or enhance outputs. This makes starting times **very** important, as a single action might mean 30 scripts being ran and returned from. This said, in testing, no serious issues have been seen, yet.
- Cynthia (plv2) plugins are rapidly iterated over, giving each a chance to modify or enhance outputs. This makes starting times **very** important, as a single action might mean 30 scripts being run and returned from. This said, in testing, no serious issues have been seen, yet.
- Cynthia finds runtimes through the _path_.

## Downloads
I'll link you to these, and you should be able to download and install them according to their own websites.
- Node.JS: <https://nodejs.org/en/download/> (`LTS / v20.x.x` is used in tests, too.)
- Node.js: <https://nodejs.org/en/download/> (`LTS / v20.x.x` is used in tests, too.)
- Bun: <https://bun.sh> (`current` is used in tests, too.)
23 changes: 11 additions & 12 deletions src/contentservers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,9 @@ pub(crate) fn p_content(pgid: String) -> String {
)
}
None => String::from("unknownexeception"),
}
};
};
let rawcontent: String;
match post.content.location.to_owned().as_str() {
let rawcontent = match post.content.location.to_owned().as_str() {
"external" => {
let mut data = Vec::new();
let mut c = Easy::new();
Expand Down Expand Up @@ -159,17 +158,14 @@ pub(crate) fn p_content(pgid: String) -> String {
return "contentlocationerror".to_owned();
}
};
rawcontent = resp.to_owned();
resp.to_owned()
}
"local" => {
let contentpath_ = std::path::Path::new("./cynthiaFiles/pages/");
let contentpath = &contentpath_.join(post.content.data.to_owned().as_str());
rawcontent =
std::fs::read_to_string(contentpath).unwrap_or("contenterror".to_string());
}
"inline" => {
rawcontent = post.content.data.to_owned();
std::fs::read_to_string(contentpath).unwrap_or("contenterror".to_string())
}
"inline" => post.content.data.to_owned(),
&_ => {
return "contentlocationerror".to_owned();
}
Expand Down Expand Up @@ -285,7 +281,10 @@ pub(crate) fn generate_menus(pgid: String, probableurl: &String) -> Menulist {
ele.href, ele.name
)
} else {
format!(r#"<a href="{0}" class="menulink">{1}</a>"#, ele.href, ele.name)
format!(
r#"<a href="{0}" class="menulink">{1}</a>"#,
ele.href, ele.name
)
};
mlist1.push_str(link.as_str());
}
Expand Down Expand Up @@ -324,7 +323,7 @@ pub(crate) fn generate_menus(pgid: String, probableurl: &String) -> Menulist {
pub(crate) fn fetcher(uri: String) -> String {
let mut data = Vec::new();
let mut c = Easy::new();
c.url(&(&uri)).unwrap();
c.url(&uri).unwrap();
{
let mut transfer = c.transfer();
match transfer.write_function(|new_data| {
Expand Down Expand Up @@ -355,5 +354,5 @@ pub(crate) fn fetcher(uri: String) -> String {
return "contentlocationerror".to_owned();
}
};
return resp.to_owned();
resp.to_owned()
}
4 changes: 2 additions & 2 deletions src/contentservers/postlists.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ pub(crate) fn postlist_table_gen(postlistobject: Postlist) -> String {
.unwrap(),
category,
to_html_with_options(
&description,
description,
&Options {
compile: CompileOptions {
allow_dangerous_html: false,
Expand All @@ -135,7 +135,7 @@ pub(crate) fn postlist_table_gen(postlistobject: Postlist) -> String {
table_html.push_str(addition.as_str());
}
table_html.push_str("</table>");
if fullpostlist.len() == 0 {
if fullpostlist.is_empty() {
table_html = String::from("<p>No results.</p>");
}
table_html
Expand Down
46 changes: 16 additions & 30 deletions src/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,12 @@ pub(crate) fn cacheretriever(file: String, max_age: u64) -> Result<PathBuf, Erro
if f.fileid == file {
if (now - f.timestamp) < max_age {
return Ok(f.cachepath);
} else {
if Path::new(&f.cachepath).exists() {
fs::remove_file(Path::new(&f.cachepath)).unwrap();
}
} else if Path::new(&f.cachepath).exists() {
fs::remove_file(Path::new(&f.cachepath)).unwrap();
};
}
}
return Err(Error::from(ErrorKind::Other));
Err(Error::from(ErrorKind::Other))
}

pub(crate) fn cacheplacer(fileid: String, contents: String) -> String {
Expand Down Expand Up @@ -77,11 +75,11 @@ pub(crate) fn cacheplacer(fileid: String, contents: String) -> String {
let line = serde_json::to_string(&cacheindex).unwrap();
let linestr = line.as_str();
write!(cacheindexfile, "{}", linestr).unwrap();
return contents;
contents
}

pub(crate) fn import_js_minified(scriptfile: String) -> String {
return match cacheretriever((&scriptfile).to_string(), 120) {
return match cacheretriever(scriptfile.to_string(), 120) {
Ok(o) => fs::read_to_string(o).expect("Couldn't find or open a JS file."),
Err(_) => match jsruntime(true) {
BUNJSR => {
Expand Down Expand Up @@ -114,9 +112,7 @@ pub(crate) fn import_js_minified(scriptfile: String) -> String {
"Bunx".purple()
),
);
let output =
fs::read_to_string(scriptfile).expect("Couldn't find or open a JS file.");
output
fs::read_to_string(scriptfile).expect("Couldn't find or open a JS file.")
}
}
NODEJSR => {
Expand All @@ -137,17 +133,15 @@ pub(crate) fn import_js_minified(scriptfile: String) -> String {
std::process::exit(1);
}
};
if !(output.status.success()) {
if !output.status.success() {
logger(
5,
format!(
"Failed running Terser in {}, couldn't minify to embed JS.",
"NPX".purple()
),
);
let output =
fs::read_to_string(scriptfile).expect("Couldn't find or open a JS file.");
output
fs::read_to_string(scriptfile).expect("Couldn't find or open a JS file.")
} else {
let res: String = String::from_utf8_lossy(&output.stdout).parse().unwrap();
cacheplacer(scriptfile, format!(
Expand All @@ -157,16 +151,14 @@ pub(crate) fn import_js_minified(scriptfile: String) -> String {
}
_ => {
logger(15, String::from("Couldn't minify inlined javascript because there is no found javascript run time, may incre ase bandwidth and slow down served web pages."));
let output =
fs::read_to_string(scriptfile).expect("Couldn't find or open a JS file.");
output
fs::read_to_string(scriptfile).expect("Couldn't find or open a JS file.")
}
},
};
}

pub(crate) fn import_css_minified(stylefile: String) -> String {
return match cacheretriever((&stylefile).to_string(), 120) {
return match cacheretriever(stylefile.to_string(), 120) {
Ok(o) => fs::read_to_string(o).expect("Couldn't find or open a JS file."),
Err(_) => match jsruntime(true) {
BUNJSR => {
Expand All @@ -189,7 +181,7 @@ pub(crate) fn import_css_minified(stylefile: String) -> String {
if output.status.success() {
let res: String = String::from_utf8_lossy(&output.stdout).parse().unwrap();
cacheplacer(stylefile, format!(
"\n\r/* Minified internally by Cynthia using cleas-css */\n\n{res}\n\n\r/* Cached after minifying, so might be ~2 minutes behind. */\n\r"
"\n\r/* Minified internally by Cynthia using clean-css */\n\n{res}\n\n\r/* Cached after minifying, so might be ~2 minutes behind. */\n\r"
))
} else {
logger(
Expand All @@ -199,9 +191,7 @@ pub(crate) fn import_css_minified(stylefile: String) -> String {
"Bunx".purple()
),
);
let output =
fs::read_to_string(stylefile).expect("Couldn't find or open a JS file.");
output
fs::read_to_string(stylefile).expect("Couldn't find or open a JS file.")
}
}
NODEJSR => {
Expand All @@ -222,29 +212,25 @@ pub(crate) fn import_css_minified(stylefile: String) -> String {
std::process::exit(1);
}
};
if !(output.status.success()) {
if !output.status.success() {
logger(
5,
format!(
"Failed running clean-css in {}, couldn't minify to embed CSS.",
"NPX".purple()
),
);
let output =
fs::read_to_string(stylefile).expect("Couldn't find or open a CSS file.");
output
fs::read_to_string(stylefile).expect("Couldn't find or open a CSS file.")
} else {
let res: String = String::from_utf8_lossy(&output.stdout).parse().unwrap();
cacheplacer(stylefile, format!(
"\n\r/* Minified internally by Cynthia using cleas-css */\n\n{res}\n\n\r/* Cached after minifying, so might be ~2 minutes behind. */\n\r"
"\n\r/* Minified internally by Cynthia using clean-css */\n\n{res}\n\n\r/* Cached after minifying, so might be ~2 minutes behind. */\n\r"
))
}
}
_ => {
logger(15, String::from("Couldn't minify inlined javascript because there is no found javascript run time, may incre ase bandwidth and slow down served web pages."));
let output =
fs::read_to_string(stylefile).expect("Couldn't find or open a CSS file.");
output
fs::read_to_string(stylefile).expect("Couldn't find or open a CSS file.")
}
},
};
Expand Down
2 changes: 1 addition & 1 deletion src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ pub(crate) fn logger(act: i32, msg: String) {
let preq = format!("{0}{2}{1}", title, " ".repeat(spaceleft), tabs);
println!("{0}❕ {1}", preq, msg.bright_green());
}
1 | _ => {
_ => {
let name = format!("[{} - [LOG]", times).blue();
let spaceleft = if name.chars().count() < spaces {
spaces - name.chars().count()
Expand Down
20 changes: 10 additions & 10 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ async fn serves_e(id: web::Path<String>, pluginsmex: Data<Mutex<Vec<PluginMeta>>
let fileb = format!("./plugins/{}/{}/{fid}", plugin.name, s[0]);
let file = Path::new(&fileb);
mime = find_mimetype(&format!("{:?}", file.file_name().unwrap()));
body = std::fs::read_to_string(file)
body = fs::read_to_string(file)
.unwrap_or(String::from("Couldn't serve file."));
};
}
Expand All @@ -149,7 +149,7 @@ async fn serves_es(req: HttpRequest, pluginsmex: Data<Mutex<Vec<PluginMeta>>>) -
Some(p) => {
for s in p {
// println!("{} == {}?", en , s[1].to_string());
if en == s[1].to_string() {
if en == s[1] {
body = contentservers::fetcher(format!("{}/{}", s[0], id));
};
}
Expand All @@ -158,7 +158,7 @@ async fn serves_es(req: HttpRequest, pluginsmex: Data<Mutex<Vec<PluginMeta>>>) -
}
}

return HttpResponse::Ok().body(body);
HttpResponse::Ok().body(body)
}

async fn root(pluginsmex: Data<Mutex<Vec<PluginMeta>>>) -> impl Responder {
Expand All @@ -170,12 +170,12 @@ fn read_published_jsonc() -> Vec<CynthiaContentMetaData> {
let res: Vec<CynthiaContentMetaData> = if Path::new("./cynthiaFiles/published.yaml").exists() {
let file = "./cynthiaFiles/published.yaml".to_owned();
let unparsed_yaml =
std::fs::read_to_string(file).expect("Couldn't find or load that file.");
serde_yaml::from_str(&*unparsed_yaml).unwrap()
fs::read_to_string(file).expect("Couldn't find or load that file.");
serde_yaml::from_str(&unparsed_yaml).unwrap()
} else {
let file = "./cynthiaFiles/published.jsonc".to_owned();
let unparsed_json =
std::fs::read_to_string(file).expect("Couldn't find or load that file.");
fs::read_to_string(file).expect("Couldn't find or load that file.");
// println!("{}", unparsed_json);
let parsed_json: Option<serde_json::Value> =
parse_to_serde_value(unparsed_json.as_str(), &Default::default())
Expand All @@ -187,11 +187,11 @@ fn read_published_jsonc() -> Vec<CynthiaContentMetaData> {

fn load_mode(mode_name: String) -> CynthiaModeObject {
let file = format!("./cynthiaFiles/modes/{}.jsonc", mode_name).to_owned();
let unparsed_json = match std::fs::read_to_string(file){
let unparsed_json = match fs::read_to_string(file){
Ok(s) => s,
Err(f) => {
if f.kind() == ErrorKind::NotFound {
if mode_name != String::from("default") {
if mode_name != *"default" {
logger(15, format!("Cynthia is missing the `{}´ mode for a page to be served. It will retry using the `default´ mode.", mode_name));
return load_mode(String::from("default"));
} else {
Expand Down Expand Up @@ -420,12 +420,12 @@ As of now, Cynthia has only 4 commands:
}
let mut pluginlist: Vec<PluginMeta> = [].to_vec();
if Path::new("./plugins").exists() {
for entry in std::fs::read_dir("./plugins").unwrap() {
for entry in fs::read_dir("./plugins").unwrap() {
if entry.is_ok() {
let name = entry.unwrap().file_name().to_string_lossy().into_owned();
let p = format!("./plugins/{}/cynthiaplugin.json", name);
let pluginmetafile = Path::new(&p);
match std::fs::read_to_string(pluginmetafile) {
match fs::read_to_string(pluginmetafile) {
Ok(e) => {
let mut f: PluginMeta = serde_json::from_str(&e).unwrap();
if f.cyntia_plugin_compat != CYNTHIAPLUGINCOMPAT {
Expand Down
Loading

0 comments on commit f45d255

Please sign in to comment.