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
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ Copyright: (c) 2023, Mike 'PhiSyX' S. (https://github.com/PhiSyX)         ┃
// ┃ SPDX-License-Identifier: MPL-2.0                                          ┃
// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
// ┃                                                                           ┃
// ┃  This Source Code Form is subject to the terms of the Mozilla Public      ┃
// ┃  License, v. 2.0. If a copy of the MPL was not distributed with this      ┃
// ┃  file, You can obtain one at https://mozilla.org/MPL/2.0/.                ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

mod error;
pub mod settings;

use std::net;

use console::style;

pub use self::error::Error;

// -------- //
// Constant //
// -------- //

pub const PORT_PLAINTEXT: u16 = 80;
pub const PORT_ENCRYPT: u16 = 443;

// --------- //
// Structure //
// --------- //

pub struct Server<UserState> {
	state: crate::state::State<UserState>,
	pub application_settings: crate::application::Settings,
	pub(crate) settings: settings::Settings,
	global_router: axum::Router<()>,
	pub(crate) router: axum::Router<crate::state::State<UserState>>,
	pub(crate) routes: crate::routing::RouteCollection<UserState>,
	static_resources: Vec<settings::SettingsStaticResource>,
}

// -------------- //
// Implémentation //
// -------------- //

impl<US> Server<US>
where
	US: 'static,
	US: crate::state::StateInterface,
{
	/// Instancie un serveur.
	pub fn new(
		application_settings: crate::application::Settings,
	) -> Result<Self, Error> {
		let state = crate::state::State { user_state: None };

		let settings = settings::Settings::fetch_or_default(
			&application_settings.config_dir,
			&application_settings.loader_extension,
		);

		let static_resources = settings
			.static_resources
			.iter()
			.cloned()
			.map(|mut sr| {
				sr.dir_path = if sr.dir_path.is_relative() {
					application_settings.root_dir.join(&sr.dir_path)
				} else {
					sr.dir_path.to_owned()
				};
				sr
			})
			.collect();

		Ok(Self {
			application_settings,
			state,
			settings,
			global_router: axum::Router::new(),
			router: axum::Router::new(),
			routes: crate::routing::RouteCollection::new(),
			static_resources,
		})
	}

	/// Ajoute une collection de routes au serveur.
	fn define_routes(
		mut self,
		routes: crate::routing::RouteCollection<US>,
	) -> Self {
		let mut scoped_router = axum::Router::<crate::state::State<US>>::new();

		for route in routes.all() {
			scoped_router =
				scoped_router.route(&route.fullpath, route.action.to_owned());
		}

		self.router = self.router.merge(scoped_router);
		self.routes.extend(routes);

		self
	}

	/// Crée une application pour le serveur.
	pub fn make_application<A>(self) -> Self
	where
		A: crate::Application<State = US>,
	{
		let mut this = self.define_routes(
			<A::Router as crate::routing::interface::RouterExt>::routes(),
		);

		this.router = A::register_extension(&this.state, this.router);
		this.router = A::register_layer(&this.state, this.router);
		this.router = A::register_middleware(&this.state, this.router);

		A::register_service(this)
	}

	/// Démarre le serveur WEB.
	pub async fn run(mut self) -> Result<(), Error>
	where
		US: 'static,
	{
		log::info!("Tentative de lancement du serveur web...");

		println!();
		println!("Liste des routes du serveur web:");
		for route in self.routes.all() {
			let methods = route
				.methods
				.iter()
				.map(|m| style(&m).yellow().to_string())
				.collect::<Vec<String>>()
				.join(" | ");

			println!(
				"\t[{}]: {} {}",
				methods,
				style(&route.fullpath).bright().green(),
				if let Some(name) = route.name.as_deref() {
					format!("as {}", style(name).bright().black())
				} else {
					String::new()
				}
			);
		}
		println!();

		for static_resource in self.static_resources.iter() {
			println!(
				"\t[{}]: {} -> {}",
				style("STATIC RESOURCE").magenta(),
				style(&static_resource.url_path).bright().green(),
				style(static_resource.dir_path.display()).bright().black(),
			);

			self.global_router = self.global_router.nest_service(
				&static_resource.url_path,
				tower_http::services::ServeDir::new(&static_resource.dir_path),
			);
		}

		self.global_router =
			self.global_router.merge(self.router.with_state(self.state));

		// Ouverture de la connexion du serveur.

		let protocol = if self.settings.tls.is_some() {
			"https"
		} else {
			"http"
		};
		let host = self.settings.host;
		let port = self.settings.port;

		let server_socket_addr =
			<_ as Into<net::SocketAddr>>::into((host, port));

		let port_with_prefix = if port == PORT_PLAINTEXT || port == PORT_ENCRYPT
		{
			String::new()
		} else {
			format!(":{}", port)
		};

		let url = format!("{protocol}://{host}{port_with_prefix}");
		type S = net::SocketAddr;
		println!("URL: {url}");

		if let Some(settings_tls) = self.settings.tls {
			let tls_config =
				axum_server::tls_rustls::RustlsConfig::from_pem_file(
					&settings_tls.cert,
					&settings_tls.key,
				)
				.await?;

			let http_config =
				axum_server::HttpConfig::new().http2_only(true).build();

			axum_server::bind_rustls(server_socket_addr, tls_config)
				.http_config(http_config)
				.serve(
					self.global_router
						.into_make_service_with_connect_info::<S>(),
				)
				.await?;
		} else {
			axum::Server::bind(&server_socket_addr)
				.serve(
					self.global_router
						.into_make_service_with_connect_info::<S>(),
				)
				.await?;
		}

		Ok(())
	}

	/// Définit les paramètres utilisateur de l'état.
	pub fn with_user_state(mut self, data: US::UserData) -> Self {
		self.state.user_state.replace(US::new(data));
		self
	}
}