use crate::app::AppConfig;
use crate::app::AppState;
use crate::error::WebError;
use adapter_onlyoffice::{prepare_proxy_request, sign_config, OnlyOfficeProxyPreparationInput};
use axum::body::{Body, Bytes};
use axum::extract::{Path, Query, State};
use axum::http::{header, HeaderMap, HeaderValue, Method, Request, Uri};
use axum::response::{Html, IntoResponse, Response};
use axum::Json;
use serde::Deserialize;
use serde_json::{json, Value};
use std::env;
use std::fs;
use std::time::Duration;
const ONLYOFFICE_PROBE_PATH: &str = "/web-apps/apps/api/documents/api.js";
const DEFAULT_ONLYOFFICE_INTERNAL_URL: &str = "http://127.0.0.1:8082";
const ONLYOFFICE_RUNTIME_REWRITE_SNIPPET: &str = r#""#;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OnlyOfficePageQuery {
file_url: Option,
file_name: Option,
file_type: Option,
asset_id: Option,
document_id: Option,
user_id: Option,
mode: Option,
}
#[derive(Debug, Deserialize)]
pub struct OnlyOfficeProxyQuery {
u: Option,
}
#[derive(Debug, Deserialize)]
pub struct OnlyOfficeCallbackQuery {
#[serde(rename = "assetId")]
asset_id: Option,
#[serde(rename = "userId")]
user_id: Option,
}
#[derive(Debug, Deserialize)]
pub struct OnlyOfficeForcesaveQuery {
#[serde(rename = "assetId")]
asset_id: Option,
key: Option,
}
#[derive(Debug, Deserialize)]
pub struct OnlyOfficeSignPayload {
config: Option,
}
fn env_or_dotenv(key: &str) -> Option {
if let Ok(value) = env::var(key) {
let trimmed = value.trim().trim_matches('"').to_string();
if !trimmed.is_empty() {
return Some(trimmed);
}
}
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../..")
.join(".env.all");
let content = fs::read_to_string(root).ok()?;
for line in content.lines() {
let line = line.trim_end_matches('\r');
if line.starts_with('#') || line.trim().is_empty() {
continue;
}
let Some((k, v)) = line.split_once('=') else {
continue;
};
if k.trim() != key {
continue;
}
let trimmed = v.trim().trim_matches('"').to_string();
if !trimmed.is_empty() {
return Some(trimmed);
}
}
None
}
fn normalize_http_origin(raw: &str) -> Option {
let value = raw.trim().trim_end_matches('/');
if value.is_empty() || value == "/onlyoffice-server" {
return None;
}
let url = reqwest::Url::parse(value).ok()?;
if url.scheme() != "http" && url.scheme() != "https" {
return None;
}
Some(url.to_string().trim_end_matches('/').to_string())
}
fn onlyoffice_internal_candidates() -> Vec {
let mut candidates = Vec::new();
let mut push = |value: Option| {
let Some(value) = value else {
return;
};
let Some(normalized) = normalize_http_origin(&value) else {
return;
};
if !candidates.contains(&normalized) {
candidates.push(normalized);
}
};
push(env_or_dotenv("ONLYOFFICE_INTERNAL_URL"));
if let Some(raw) = env_or_dotenv("ONLYOFFICE_INTERNAL_URL_CANDIDATES") {
for value in raw.split(',') {
push(Some(value.to_string()));
}
}
push(Some(DEFAULT_ONLYOFFICE_INTERNAL_URL.into()));
push(Some("http://127.0.0.1:8081".into()));
push(Some("http://localhost:8082".into()));
push(Some("http://localhost:8081".into()));
if candidates.is_empty() {
candidates.push(DEFAULT_ONLYOFFICE_INTERNAL_URL.into());
}
candidates
}
async fn resolve_onlyoffice_internal_url() -> String {
let client = reqwest::Client::builder()
.timeout(Duration::from_millis(2_500))
.build()
.unwrap_or_else(|_| reqwest::Client::new());
let candidates = onlyoffice_internal_candidates();
for candidate in &candidates {
let probe_url = format!("{candidate}{ONLYOFFICE_PROBE_PATH}");
if client
.head(probe_url)
.send()
.await
.map(|response| response.status().is_success())
.unwrap_or(false)
{
return candidate.clone();
}
}
candidates
.first()
.cloned()
.unwrap_or_else(|| DEFAULT_ONLYOFFICE_INTERNAL_URL.into())
}
fn escape_html(value: &str) -> String {
value
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
fn json_string(value: &str) -> String {
serde_json::to_string(value).unwrap_or_else(|_| "\"\"".into())
}
fn header_value(headers: &HeaderMap, name: &str) -> Option {
headers
.get(name)
.and_then(|value| value.to_str().ok())
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
}
fn forwarded_public_origin(headers: &HeaderMap) -> (String, String, String) {
let origin_like = header_value(headers, "origin")
.or_else(|| header_value(headers, "referer"))
.and_then(|value| reqwest::Url::parse(&value).ok());
let forwarded_host_raw = header_value(headers, "x-forwarded-host")
.or_else(|| header_value(headers, header::HOST.as_str()))
.or_else(|| {
origin_like.as_ref().map(|url| match url.port() {
Some(port) => format!("{}:{port}", url.host_str().unwrap_or_default()),
None => url.host_str().unwrap_or_default().to_string(),
})
})
.unwrap_or_else(|| "127.0.0.1:3000".into());
let forwarded_host = forwarded_host_raw
.split(',')
.next()
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or("127.0.0.1:3000")
.to_string();
let forwarded_proto = header_value(headers, "x-forwarded-proto")
.and_then(|value| {
value
.split(',')
.next()
.map(str::trim)
.map(ToOwned::to_owned)
})
.filter(|value| !value.is_empty())
.or_else(|| origin_like.as_ref().map(|url| url.scheme().to_string()))
.unwrap_or_else(|| "http".into());
let forwarded_port = header_value(headers, "x-forwarded-port")
.and_then(|value| {
value
.split(',')
.next()
.map(str::trim)
.map(ToOwned::to_owned)
})
.filter(|value| !value.is_empty())
.or_else(|| {
forwarded_host
.rsplit(':')
.next()
.filter(|value| value.chars().all(|ch| ch.is_ascii_digit()))
.map(ToOwned::to_owned)
})
.unwrap_or_else(|| {
if forwarded_proto == "https" {
"443".into()
} else {
"80".into()
}
});
(forwarded_host, forwarded_proto, forwarded_port)
}
pub async fn page(Query(query): Query) -> Result {
let file_url = query.file_url.unwrap_or_default();
let file_name = query.file_name.unwrap_or_else(|| "附件".into());
let file_type = query.file_type.unwrap_or_else(|| "docx".into());
let asset_id = query.asset_id.unwrap_or_default();
let document_id = query.document_id.unwrap_or_default();
let user_id = query.user_id.unwrap_or_default();
let mode = match query.mode.as_deref() {
Some("view") => "view",
_ => "edit",
};
let html = format!(
r#"
{title}
"#,
title = escape_html(&file_name),
file_url = json_string(&file_url),
file_name = json_string(&file_name),
file_type = json_string(&file_type),
asset_id = json_string(&asset_id),
document_id = json_string(&document_id),
user_id = json_string(&user_id),
mode = json_string(mode),
);
Ok(Html(html).into_response())
}
pub async fn sign(Json(payload): Json) -> Result {
let config = payload.config.ok_or_else(|| {
WebError::bad_request_code("onlyoffice_sign_config_missing", "缺少 config")
})?;
let secret = env_or_dotenv("ONLYOFFICE_JWT_SECRET").unwrap_or_default();
let tokens = sign_config(&config, &secret)
.map_err(|error| WebError::internal(format!("OnlyOffice 签名失败: {error}")))?;
Ok(Json(tokens).into_response())
}
fn proxy_origin_env(key: &str) -> Option {
env_or_dotenv(key).and_then(|value| normalize_http_origin(&value))
}
pub async fn proxy(
Query(query): Query,
headers: HeaderMap,
method: Method,
) -> Result {
let encoded_url = query
.u
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or_else(|| WebError::bad_request_code("onlyoffice_proxy_url_missing", "缺少 u"))?;
let prepared = prepare_proxy_request(OnlyOfficeProxyPreparationInput {
encoded_url: encoded_url.to_string(),
method: method.as_str().to_string(),
range: headers
.get(header::RANGE)
.and_then(|value| value.to_str().ok())
.map(ToOwned::to_owned),
supabase_url: proxy_origin_env("NEXT_PUBLIC_SUPABASE_URL")
.or_else(|| proxy_origin_env("SUPABASE_URL")),
supabase_internal_url: proxy_origin_env("SUPABASE_INTERNAL_URL"),
onlyoffice_storage_host_override: env_or_dotenv(
"NEXT_PUBLIC_ONLYOFFICE_STORAGE_HOST_OVERRIDE",
),
convex_origin: proxy_origin_env("CONVEX_SELF_HOSTED_URL")
.or_else(|| proxy_origin_env("NEXT_PUBLIC_CONVEX_URL")),
supabase_anon_key: env_or_dotenv("NEXT_PUBLIC_SUPABASE_ANON_KEY")
.or_else(|| env_or_dotenv("SUPABASE_ANON_KEY")),
})
.map_err(|error| WebError::bad_request_code("onlyoffice_proxy_prepare_failed", error))?;
let client = reqwest::Client::new();
let mut request = client.request(
reqwest::Method::from_bytes(method.as_str().as_bytes()).unwrap_or(reqwest::Method::GET),
&prepared.target_url,
);
for item in prepared.forward_headers {
request = request.header(item.name, item.value);
}
let upstream = request.send().await.map_err(|error| {
WebError::bad_gateway_code(
"onlyoffice_proxy_fetch_failed",
format!("回源下载失败: {error}"),
)
})?;
let status = upstream.status();
let mut response_headers = HeaderMap::new();
for (name, value) in upstream.headers() {
if name == header::SET_COOKIE {
continue;
}
response_headers.insert(name, value.clone());
}
if method == Method::HEAD {
let mut response = Response::new(Body::empty());
*response.status_mut() = status;
*response.headers_mut() = response_headers;
return Ok(response);
}
let bytes = upstream.bytes().await.map_err(|error| {
WebError::bad_gateway_code(
"onlyoffice_proxy_body_failed",
format!("读取回源文件失败: {error}"),
)
})?;
let mut response = Response::new(Body::from(bytes));
*response.status_mut() = status;
*response.headers_mut() = response_headers;
Ok(response)
}
pub async fn callback(
State(state): State,
uri: Uri,
Query(query): Query,
Json(body): Json,
) -> Response {
let status = body
.get("status")
.and_then(Value::as_i64)
.unwrap_or_default();
tracing::info!(
asset_id = query.asset_id.as_deref().unwrap_or(""),
user_id = query.user_id.as_deref().unwrap_or(""),
status,
"OnlyOffice callback received by mnote-web"
);
match proxy_legacy_onlyoffice_json(
state.config(),
"/api/onlyoffice/callback",
uri.query(),
Some(body),
)
.await
{
Ok(response) => response,
Err(error) if error.status() == axum::http::StatusCode::NOT_IMPLEMENTED => (
axum::http::StatusCode::NOT_IMPLEMENTED,
Json(json!({
"error": 1,
"degraded": true,
"code": "onlyoffice_legacy_writeback_unavailable",
"message": error.message(),
})),
)
.into_response(),
Err(error) => (
axum::http::StatusCode::BAD_GATEWAY,
Json(json!({
"error": 1,
"degraded": true,
"code": "onlyoffice_legacy_writeback_failed",
"message": error.message(),
})),
)
.into_response(),
}
}
pub async fn forcesave(
State(state): State,
uri: Uri,
Query(query): Query,
) -> Result {
let asset_id = query
.asset_id
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or_else(|| {
WebError::bad_request_code("onlyoffice_forcesave_asset_missing", "缺少 assetId")
})?;
let key = query
.key
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or_else(|| {
WebError::bad_request_code("onlyoffice_forcesave_key_missing", "缺少 key")
})?;
let response = proxy_legacy_onlyoffice_json(
state.config(),
"/api/onlyoffice/forcesave",
uri.query(),
None,
)
.await
.map_err(|error| {
if error.status() == axum::http::StatusCode::NOT_IMPLEMENTED {
return WebError::new(
axum::http::StatusCode::NOT_IMPLEMENTED,
"onlyoffice_legacy_writeback_unavailable",
format!(
"OnlyOffice forcesave 未配置 legacy Next 写回链: assetId={asset_id}, key={key}"
),
);
}
error
})?;
Ok(response)
}
fn legacy_onlyoffice_writeback_base(config: &AppConfig) -> Option {
config
.legacy_next_base_url
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.map(|value| value.trim_end_matches('/').to_string())
}
async fn proxy_legacy_onlyoffice_json(
config: &AppConfig,
path: &str,
query: Option<&str>,
body: Option,
) -> Result {
let base = legacy_onlyoffice_writeback_base(config).ok_or_else(|| {
WebError::new(
axum::http::StatusCode::NOT_IMPLEMENTED,
"onlyoffice_legacy_writeback_unavailable",
"OnlyOffice Rust route 暂未直接写回,且未配置 legacy Next 写回链",
)
})?;
let target = append_path_and_query(&base, path, query);
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(30))
.build()
.map_err(|error| {
WebError::internal(format!(
"OnlyOffice legacy proxy HTTP 客户端创建失败: {error}"
))
})?;
let mut request = client
.post(target)
.header(header::CONTENT_TYPE, "application/json");
if let Some(body) = body {
request = request.json(&body);
} else {
request = request.body("{}");
}
let upstream = request.send().await.map_err(|error| {
WebError::bad_gateway_code(
"onlyoffice_legacy_writeback_failed",
format!("OnlyOffice legacy 写回请求失败: {error}"),
)
})?;
let status = upstream.status();
let content_type = upstream
.headers()
.get(header::CONTENT_TYPE)
.cloned()
.unwrap_or_else(|| HeaderValue::from_static("application/json"));
let bytes = upstream.bytes().await.map_err(|error| {
WebError::bad_gateway_code(
"onlyoffice_legacy_writeback_failed",
format!("OnlyOffice legacy 写回响应读取失败: {error}"),
)
})?;
let mut response = Response::new(Body::from(bytes));
*response.status_mut() = status;
response
.headers_mut()
.insert(header::CONTENT_TYPE, content_type);
Ok(response)
}
fn append_path_and_query(base: &str, path: &str, query: Option<&str>) -> String {
let mut target = format!(
"{}/{}",
base.trim_end_matches('/'),
path.trim_start_matches('/')
);
if let Some(query) = query.filter(|value| !value.is_empty()) {
target.push('?');
target.push_str(query);
}
target
}
fn request_body_bytes(
request: Request,
) -> impl std::future::Future