Echo Writes Code

main.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
mod content;
mod errors;
mod handlers;
mod renderer;
mod state;

use tracing_subscriber::prelude::{ * };

use crate::errors::{ Error, Result };
use crate::state::{ ServerState };
use axum::{ Router };
use axum::routing::{ get, post };
use axum_messages::{ MessagesManagerLayer };
use clap::{ Parser };
use directories::{ ProjectDirs };
use include_dir::{ Dir, include_dir };
use kdl::{ KdlDocument };
use tokio::net::{ TcpListener };
use tower_http::services::{ ServeDir };
use tower_http::trace::{ TraceLayer };
use tower_sessions::{ Expiry, MemoryStore, SessionManagerLayer };
use tracing_subscriber::filter::{ EnvFilter, LevelFilter };
use tracing_subscriber::reload::{ Layer as ReloadableFilterLayer };
use std::path::{ Path, PathBuf };
use std::process::{ ExitCode };
use std::sync::{ Arc };

static DEFAULT_CONFIGURATION_TEXT: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/limetree.kdl"));
static DEFAULT_THEME: Dir = include_dir!("themes/simple");
static LIMETREE_DEVELOPMENT_MODE: Option<&'static str> = option_env!("LIMETREE_DEVELOPMENT_MODE");

/// The server program for the Limetree CMS.
#[derive(Debug, Parser)]
#[command(about, version)]
struct CommandLine {
  /// Path to the limetree.kdl configuration file. The default location is in your platform-specific
  /// local application data directory (%LocalAppData%\echowritescode\limetree\limetree.kdl on
  /// Windows, ${HOME}/Library/Application Support/dev.echowritescode.limetree/limetree.kdl on
  /// macOS, or ${XDG_CONFIG_HOME}/limetree/limetree.kdl on Linux).
  #[arg(short, long)]
  configuration_file: Option<PathBuf>,

  /// The site title is displayed in several prominent locations, including tabs, bookmarks, and the
  /// site header.
  #[arg(short, long)]
  site_title: Option<String>,

  /// Your theme controls how your pages look and any additional features. The "simple" theme is
  /// bundled within the Limetree executable (i.e., it does not need to be installed; Limetree will
  /// extract and use it automatically).
  #[arg(short, long)]
  theme_name: Option<String>,

  /// This is the host port that Limetree will bind to. If you already have another service running
  /// on port 8080, you can change it to anything between 1024 and 65535.
  #[arg(short = 'H', long)]
  host: Option<String>,

  /// This is the host port that Limetree will bind to. If you already have another service running
  /// on port 8080, you can change it to anything between 1024 and 65535.
  #[arg(short = 'P', long)]
  port: Option<u16>,

  /// This is an alternate location for Limetree to store its data files. By default this folder is
  /// placed in the current user's local persistent application data directory, which is
  /// "%LocalAppData%\echowritescode\limetree" on Windows,
  /// "${HOME}/Library/Application Support/dev.echowritescode.limetree" on macOS, or
  /// "${XDG_DATA_HOME}/limetree" on Linux.
  #[arg(short = 'R', long)]
  root_path: Option<PathBuf>,

  /// This is an alternate location for Limetree to store content files specifically (i.e., the pages
  /// you create and edit, as well as file uploads). Normally, these go in a folder called "content"
  /// under the Limetree root directory.
  #[arg(short = 'C', long)]
  content_path: Option<PathBuf>,

  /// This is an alternate location for Limetree to store its metadata file, which stores things like
  /// page titles and tag associations. Normally, this is a file called "metadata.json" under the
  /// Limetree root directory.
  #[arg(short = 'M', long)]
  metadata_path: Option<PathBuf>,

  /// This is an alternate location for theme files. Normally, these go in a folder called "themes"
  /// under the Limetree root directory.
  #[arg(short = 'T', long)]
  themes_path: Option<PathBuf>,

  /// The filter for log messages. You can also set this parameter via the RUST_LOG environment
  /// variable, which is overridden by this switch. The filter syntax is available at:
  /// https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
  #[arg(short, long)]
  logging: Option<String>,
}

#[tokio::main]
async fn main() -> ExitCode {
  let result = run_server().await;

  match result {
    Ok(_) => ExitCode::SUCCESS,
    Err(e) => {
      tracing::error!("{}", e);
      ExitCode::FAILURE
    },
  }
}

async fn run_server() -> Result<()> {
  // This is the default tracing layer, which is configurable via the RUST_LOG environment variable.
  // It defaults to the INFO level, which should be reasonable for reporting any very-early issues
  // but not spamming the log with TRACE or DEBUG level messages.
  let filter_layer = EnvFilter::builder()
    .with_default_directive(LevelFilter::INFO.into())
    .with_regex(false)
    .from_env()?;

  // We wrap the layer in a ReloadableFilterLayer, so that after parsing the command line and
  // configuration file we can adjust the filtering to whatever the user configured.
  let (filter_layer, filter_handle) = ReloadableFilterLayer::new(filter_layer);

  tracing_subscriber::registry()
    .with(tracing_subscriber::fmt::layer())
    .with(filter_layer)
    .init();

  // NOTE: From this point on we can use `tracing::*` macros

  let command_line = CommandLine::parse();

  // If we got a logging override on the command line, apply it as early as possible (i.e., before
  // even reading the config file)
  if let Some(ref new_filter_text) = command_line.logging {
    let new_filter_layer = EnvFilter::builder()
      .with_default_directive(LevelFilter::INFO.into())
      .with_regex(false)
      .parse(new_filter_text)?;

    filter_handle.reload(new_filter_layer)?;
  }

  // NOTE: the `directories` crate has Opinions(tm) about what our bundle ID should be on macOS, so
  // this line forces us to make it "dev.echowritescode.limetree"
  let project_dirs = ProjectDirs::from("dev", "echowritescode", "limetree")
    .ok_or(Error::NoHomeDirectoryAvailable)?;

  let default_configuration_file = project_dirs
    .config_local_dir()
    .join("limetree.kdl");

  let configuration_file = command_line.configuration_file
    .as_ref()
    .unwrap_or(&default_configuration_file);

  let configuration_text = std::fs::read_to_string(configuration_file)
    .or_else(|e| if e.kind() == std::io::ErrorKind::NotFound {
      // It's okay to not have a config file, we'll just use the defaults
      tracing::info!("No configuration file found; using default values");
      std::fs::write(&default_configuration_file, DEFAULT_CONFIGURATION_TEXT)?;
      Ok("".to_string())
    } else {
      Err(e)
    })?;

  let configuration = KdlDocument::parse(&configuration_text)?;

  let site_title = command_line.site_title
    .unwrap_or_else(|| configuration
      .get_arg("title")
      .and_then(|value| value.as_string())
      .unwrap_or("Limetree CMS")
      .to_string());

  let theme_name = command_line.theme_name
    .unwrap_or_else(|| configuration
      .get_arg("theme_name")
      .and_then(|value| value.as_string())
      .unwrap_or("simple")
      .to_string());

  let host = command_line.host
    .unwrap_or_else(|| configuration
      .get_arg("host")
      .and_then(|value| value.as_string())
      .unwrap_or("127.0.0.1")
      .to_string());

  let port = command_line.port
    .unwrap_or_else(|| configuration
      .get_arg("port")
      .and_then(|value| value.as_integer())
      .and_then(|integer| integer.try_into().ok())
      .unwrap_or(8080));

  let root_path = command_line.root_path
    .unwrap_or_else(|| PathBuf::from(configuration
      .get_arg("root_path")
      .and_then(|value| value.as_string())
      .map(Path::new)
      .unwrap_or(project_dirs.data_local_dir())));

  let content_path = command_line.content_path
    .unwrap_or_else(|| configuration
      .get_arg("content_path")
      .and_then(|value| value.as_string())
      .map(PathBuf::from)
      .unwrap_or(root_path.join("content")));

  let metadata_path = command_line.metadata_path
    .unwrap_or_else(|| configuration
      .get_arg("metadata_path")
      .and_then(|value| value.as_string())
      .map(PathBuf::from)
      .unwrap_or(root_path.join("metadata.json")));

  let themes_path = command_line.themes_path
    .unwrap_or_else(|| configuration
      .get_arg("themes_path")
      .and_then(|value| value.as_string())
      .map(PathBuf::from)
      .unwrap_or(root_path.join("themes")));

  // Only override logging filter if we didn't have an environment variable filter or a command line
  // filter
  if std::env::var("RUST_LOG").is_err() && command_line.logging.is_none() {
    let new_filter_text = configuration
      .get_arg("logging")
      .and_then(|value| value.as_string())
      .unwrap_or("info")
      .to_string();

    let new_filter_layer = EnvFilter::builder()
      .with_default_directive(LevelFilter::INFO.into())
      .with_regex(false)
      .parse(new_filter_text)?;

    filter_handle.reload(new_filter_layer)?;
  }

  let theme_path = themes_path.join(&theme_name);
  let theme_static_path = theme_path.join("static");

  // Avoid having to delete the bundled `simple` theme every time we `cargo run`
  let is_development_mode = "true" == LIMETREE_DEVELOPMENT_MODE
    .unwrap_or("true")
    .to_lowercase();

  if is_development_mode && theme_name == "simple" && std::fs::exists(&theme_path)? {
    std::fs::remove_dir_all(&theme_path)?;
  }

  if theme_name == "simple" && !theme_path.is_dir() {
    DEFAULT_THEME.extract(&theme_path)?;
  }

  let session_store = MemoryStore::default();
  let session_layer = SessionManagerLayer::new(session_store)
    .with_secure(false)
    .with_expiry(Expiry::OnSessionEnd);

  let server_state = ServerState::new(&site_title, &content_path, &metadata_path, &theme_path)?;

  let router = Router::new()
    .layer(TraceLayer::new_for_http())
    .route("/", get(handlers::index))
    .route("/administration", get(handlers::administration))
    .route("/authentication", get(handlers::authentication))
    .route("/page/new", get(handlers::new_page))
    .route("/page/edit/{slug}", get(handlers::edit_page))
    .route("/page/view/{slug}", get(handlers::view_page))
    .route("/tags/all", get(handlers::all_tags))
    .route("/tags/in/{tag}", get(handlers::in_tags))
    .route("/user/new", get(handlers::new_user))
    .route("/api/deauthenticate", get(handlers::deauthenticate_api))
    .route("/api/authenticate", post(handlers::authenticate_api))
    .route("/api/page/new", post(handlers::new_page_api))
    .route("/api/page/edit/{slug}", post(handlers::edit_page_api))
    .route("/api/user/new", post(handlers::new_user_api))
    .layer(MessagesManagerLayer)
    .layer(session_layer)
    .with_state(Arc::new(server_state))
    .nest_service("/static", ServeDir::new(theme_static_path));

  let address = format!("{}:{}", host, port);
  let listener = TcpListener::bind(address).await?;

  let bound_address = listener.local_addr()?;
  tracing::info!("{} now listening on {}", env!("CARGO_BIN_NAME"), bound_address);

  axum::serve(listener, router).await?;
  Ok(())
}