From b2cb33faea74db21730ed345851f45aa5932b5ac Mon Sep 17 00:00:00 2001 From: Asuna Date: Fri, 19 Jul 2024 05:26:44 +0800 Subject: [PATCH] Return error if sending request timeout --- src/helper.rs | 17 +++++++++++++++++ src/lib.rs | 1 + src/notify/qq/lagrange.rs | 3 ++- src/notify/telegram/request.rs | 17 ++++++++++++----- src/source/bilibili/live.rs | 3 ++- src/source/bilibili/space.rs | 3 ++- src/source/bilibili/video.rs | 3 ++- src/source/twitter/request.rs | 4 +++- src/task/reporter.rs | 7 +++++-- 9 files changed, 46 insertions(+), 12 deletions(-) create mode 100644 src/helper.rs diff --git a/src/helper.rs b/src/helper.rs new file mode 100644 index 0000000..bce8224 --- /dev/null +++ b/src/helper.rs @@ -0,0 +1,17 @@ +use std::time::Duration; + +use anyhow::anyhow; + +pub fn reqwest_client() -> anyhow::Result { + reqwest_client_with(|_| {}) +} + +pub fn reqwest_client_with( + configure: impl FnOnce(&mut reqwest::ClientBuilder), +) -> anyhow::Result { + let mut builder = reqwest::ClientBuilder::new().timeout(Duration::from_secs(30)); + configure(&mut builder); + builder + .build() + .map_err(|err| anyhow!("failed to build reqwest client: {err}")) +} diff --git a/src/lib.rs b/src/lib.rs index 1ad83fc..c887496 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ pub mod cli; mod config; +mod helper; mod notify; mod platform; pub mod prop; diff --git a/src/notify/qq/lagrange.rs b/src/notify/qq/lagrange.rs index 6c8454f..fb2f33c 100644 --- a/src/notify/qq/lagrange.rs +++ b/src/notify/qq/lagrange.rs @@ -6,6 +6,7 @@ use serde_json::{self as json, json}; use tokio::time::timeout; use super::ConfigChat; +use crate::helper; #[derive(Clone, Debug, PartialEq, Deserialize)] pub struct ConfigLagrange { @@ -39,7 +40,7 @@ impl<'a> LagrangeOnebot<'a> { arguments: Option, ) -> anyhow::Result> { async { - let mut resp = reqwest::Client::new() + let mut resp = helper::reqwest_client()? .post(format!( "http://{}:{}/{method}", self.config.http_host, self.config.http_port diff --git a/src/notify/telegram/request.rs b/src/notify/telegram/request.rs index 14dd636..74af249 100644 --- a/src/notify/telegram/request.rs +++ b/src/notify/telegram/request.rs @@ -14,7 +14,10 @@ use serde_json::{self as json, json}; use spdlog::prelude::*; use super::ConfigChat; -use crate::source::{PostAttachmentImage, PostAttachmentVideo}; +use crate::{ + helper, + source::{PostAttachmentImage, PostAttachmentVideo}, +}; pub struct Request<'a> { token: &'a str, @@ -43,7 +46,7 @@ impl<'a> Request<'a> { ) -> anyhow::Result> { let url = format!("https://api.telegram.org/bot{}/{}", self.token, method); - let mut client = reqwest::Client::new().post(url); + let mut client = helper::reqwest_client()?.post(url); if let Some(file_urls) = file_urls { let form = form_append_json(Form::new(), body.as_object().unwrap()); @@ -54,9 +57,13 @@ impl<'a> Request<'a> { .try_fold(form, |form, (i, file_url)| async move { trace!("downloading media from url '{}'", file_url.url); - let file = reqwest::get(file_url.url).await.map_err(|err| { - anyhow!("failed to download file: {err} from url '{}'", file_url.url) - })?; + let file = helper::reqwest_client()? + .get(file_url.url) + .send() + .await + .map_err(|err| { + anyhow!("failed to download file: {err} from url '{}'", file_url.url) + })?; let status = file.status(); anyhow::ensure!( diff --git a/src/source/bilibili/live.rs b/src/source/bilibili/live.rs index 43331ed..2a83c04 100644 --- a/src/source/bilibili/live.rs +++ b/src/source/bilibili/live.rs @@ -8,6 +8,7 @@ use tokio::sync::Mutex; use super::{upgrade_to_https, Response}; use crate::{ + helper, platform::{PlatformMetadata, PlatformTrait}, source::{ FetcherTrait, LiveStatus, LiveStatusKind, Status, StatusKind, StatusSource, @@ -134,7 +135,7 @@ impl Fetcher { async fn fetch_live_info(user_id: u64) -> anyhow::Result { let body = json!({ "uids": [user_id] }); - let resp = reqwest::Client::new() + let resp = helper::reqwest_client()? .post(BILIBILI_LIVE_API) .json(&body) .send() diff --git a/src/source/bilibili/space.rs b/src/source/bilibili/space.rs index 4588f38..563c82f 100644 --- a/src/source/bilibili/space.rs +++ b/src/source/bilibili/space.rs @@ -11,6 +11,7 @@ use tokio::sync::{Mutex, OnceCell}; use super::{upgrade_to_https, Response}; use crate::{ + helper, platform::{PlatformMetadata, PlatformTrait}, source::{ FetcherTrait, Notification, NotificationKind, Post, PostAttachment, PostAttachmentImage, @@ -378,7 +379,7 @@ fn fetch_space_history_impl( .map(|(name, value)| format!("{}={}", name, value)) .collect::>() .join("; "); - let resp = reqwest::Client::new() + let resp = helper::reqwest_client()? .get(format!( "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space?host_mid={}", user_id diff --git a/src/source/bilibili/video.rs b/src/source/bilibili/video.rs index 1ed91a7..f4fe0bc 100644 --- a/src/source/bilibili/video.rs +++ b/src/source/bilibili/video.rs @@ -6,6 +6,7 @@ use serde_json as json; use super::{upgrade_to_https, Response}; use crate::{ + helper, platform::{PlatformMetadata, PlatformTrait}, source::{ FetcherTrait, Post, PostAttachment, PostAttachmentImage, PostUrl, Posts, Status, @@ -90,7 +91,7 @@ impl Fetcher { } async fn fetch_series_archives(user_id: u64, series_id: u64) -> anyhow::Result { - let resp = reqwest::Client::new() + let resp = helper::reqwest_client()? .get(format!( "https://api.bilibili.com/x/series/archives?mid={user_id}&series_id={series_id}" )) diff --git a/src/source/twitter/request.rs b/src/source/twitter/request.rs index 8d21c1e..a7dd226 100644 --- a/src/source/twitter/request.rs +++ b/src/source/twitter/request.rs @@ -1,6 +1,8 @@ use anyhow::{anyhow, ensure}; use reqwest::header::COOKIE; +use crate::helper; + pub struct TwitterCookies { pub raw: String, pub ct0: String, @@ -52,7 +54,7 @@ impl TwitterRequester { } async fn request(&self, url: impl AsRef) -> anyhow::Result { - let resp = reqwest::Client::new() + let resp = helper::reqwest_client()? .get(url.as_ref()) .bearer_auth(BEARER_TOKEN) .header(COOKIE, &self.cookies.raw) diff --git a/src/task/reporter.rs b/src/task/reporter.rs index d9d26ac..9d4508b 100644 --- a/src/task/reporter.rs +++ b/src/task/reporter.rs @@ -5,7 +5,10 @@ use spdlog::prelude::*; use tokio::time::MissedTickBehavior; use super::{Task, TaskKind}; -use crate::reporter::{ConfigHeartbeat, ConfigHeartbeatKind, ReporterParams}; +use crate::{ + helper, + reporter::{ConfigHeartbeat, ConfigHeartbeatKind, ReporterParams}, +}; pub struct TaskReporter { params: ReporterParams, @@ -35,7 +38,7 @@ impl TaskReporter { async fn run_once(heartbeat: &ConfigHeartbeat) -> anyhow::Result<()> { match &heartbeat.kind { ConfigHeartbeatKind::HttpGet(http_get) => { - let response = reqwest::get(http_get.url()).await?; + let response = helper::reqwest_client()?.get(http_get.url()).send().await?; let status = response.status(); ensure!( status.is_success(),