Hexbear is the engine that powers Chapochat. It is a customization of the Lemmy project.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

143 lines
4.2 KiB

3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. #[macro_use]
  2. extern crate diesel_migrations;
  3. #[macro_use]
  4. pub extern crate lazy_static;
  5. use actix::prelude::*;
  6. use actix_cors::Cors;
  7. use actix_web::{*, body::Body, dev::{Service, ServiceRequest, ServiceResponse}, http::{
  8. header::{CACHE_CONTROL, CONTENT_TYPE},
  9. HeaderValue,
  10. }, web::Data};
  11. use diesel::{
  12. r2d2::{ConnectionManager, Pool},
  13. PgConnection,
  14. };
  15. use futures::Future;
  16. use lemmy_db::get_database_url_from_env;
  17. use lemmy_rate_limit::{rate_limiter::RateLimiter, RateLimit};
  18. use lemmy_server::{
  19. apub::activity_queue::create_activity_queue, blocking, routes::*, twofactor::CodeCacheHandler,
  20. websocket::chat_server::ChatServer, LemmyContext,
  21. };
  22. use lemmy_utils::{
  23. settings::Settings, LemmyError, CACHE_CONTROL_APPLICATION_REGEX, CACHE_CONTROL_IMAGE_REGEX,
  24. };
  25. use reqwest::Client;
  26. use std::sync::{Arc, Mutex};
  27. lazy_static! {
  28. // static ref CACHE_CONTROL_VALUE: String = format!("public, max-age={}", 365 * 24 * 60 * 60);
  29. // Test out 1 hour here, this is breaking some things
  30. static ref CACHE_CONTROL_IMAGE_VALUE: String = format!("public, max-age={}", 12 * 60 * 60);
  31. static ref CACHE_CONTROL_APPLICATION_VALUE: String = format!("public, no-cache, max-age={}", 0);
  32. }
  33. embed_migrations!();
  34. #[actix_rt::main]
  35. async fn main() -> Result<(), LemmyError> {
  36. env_logger::init();
  37. let settings = Settings::get();
  38. // Set up the r2d2 connection pool
  39. let db_url = match get_database_url_from_env() {
  40. Ok(url) => url,
  41. Err(_) => settings.get_database_url(),
  42. };
  43. let manager = ConnectionManager::<PgConnection>::new(&db_url);
  44. let pool = Pool::builder()
  45. .max_size(settings.database.pool_size)
  46. .build(manager)
  47. .unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
  48. // Run the migrations from code
  49. blocking(&pool, move |conn| {
  50. embedded_migrations::run(conn)?;
  51. // uncomment if there's an advanced migration we need to run
  52. // run_advanced_migrations(conn)?;
  53. Ok(()) as Result<(), LemmyError>
  54. })
  55. .await??;
  56. // Set up the rate limiter
  57. let rate_limiter = RateLimit {
  58. rate_limiter: Arc::new(Mutex::new(RateLimiter::default())),
  59. };
  60. println!(
  61. "Starting http server at {}:{}",
  62. settings.bind, settings.port
  63. );
  64. let activity_queue = create_activity_queue();
  65. let cache_handler = Arc::new(CodeCacheHandler::new());
  66. let chat_server = ChatServer::startup(
  67. pool.clone(),
  68. rate_limiter.clone(),
  69. Client::default(),
  70. activity_queue.clone(),
  71. cache_handler.clone(),
  72. )
  73. .start();
  74. // Create Http server with websocket support
  75. HttpServer::new(move || {
  76. let context = LemmyContext::create(
  77. pool.clone(),
  78. chat_server.to_owned(),
  79. Client::default(),
  80. activity_queue.to_owned(),
  81. cache_handler.clone(),
  82. );
  83. let cors = Cors::default()
  84. .allow_any_origin()
  85. .supports_credentials()
  86. .allowed_methods(vec!["GET", "POST", "PUT", "OPTIONS"])
  87. .allow_any_header()
  88. .max_age(3600);
  89. let rate_limiter = rate_limiter.clone();
  90. App::new()
  91. .wrap_fn(add_cache_headers)
  92. .wrap(cors)
  93. .wrap(middleware::Logger::default())
  94. .app_data(Data::new(context))
  95. // The routes
  96. .configure(|cfg| api::config(cfg, &rate_limiter))
  97. .configure(federation::config)
  98. .configure(feeds::config)
  99. .configure(|cfg| images::config(cfg, &rate_limiter))
  100. .configure(nodeinfo::config)
  101. .configure(webfinger::config)
  102. })
  103. .bind((settings.bind, settings.port))?
  104. .run()
  105. .await?;
  106. Ok(())
  107. }
  108. fn add_cache_headers<S>(
  109. req: ServiceRequest,
  110. srv: &S,
  111. ) -> impl Future<Output = Result<ServiceResponse, Error>>
  112. where
  113. S: Service<ServiceRequest, Response = ServiceResponse<Body>, Error = Error>
  114. {
  115. let fut = srv.call(req);
  116. async move {
  117. let mut res = fut.await?;
  118. if let Some(content_type) = res.headers().get(CONTENT_TYPE) {
  119. if CACHE_CONTROL_IMAGE_REGEX.is_match(content_type.to_str().unwrap()) {
  120. let header_val = HeaderValue::from_static(&CACHE_CONTROL_IMAGE_VALUE);
  121. res.headers_mut().insert(CACHE_CONTROL, header_val);
  122. } else if CACHE_CONTROL_APPLICATION_REGEX.is_match(content_type.to_str().unwrap()) {
  123. let header_val = HeaderValue::from_static(&CACHE_CONTROL_APPLICATION_VALUE);
  124. res.headers_mut().insert(CACHE_CONTROL, header_val);
  125. }
  126. }
  127. Ok(res)
  128. }
  129. }