Skip to content

Commit

Permalink
Merge pull request #452 from lxl66566/2.x
Browse files Browse the repository at this point in the history
Fix clippy issues, remove some dep
  • Loading branch information
iovxw authored Dec 22, 2024
2 parents 182d5da + b27ab89 commit a0eae53
Show file tree
Hide file tree
Showing 10 changed files with 100 additions and 99 deletions.
2 changes: 0 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ rustls = [
ctl10n = "0.2.0"

[dependencies]
lazy_static = "1.4"
once_cell = "1.18"
anyhow = "1.0"
structopt = "0.3"
futures = "0.3"
Expand Down
2 changes: 0 additions & 2 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use std::env;
use std::path::Path;

use ctl10n;

const LOCALES: &[&str] = &["zh", "en"];

fn main() {
Expand Down
15 changes: 7 additions & 8 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use std::env;
use std::time::Duration;

use once_cell::sync::OnceCell;
use reqwest::{
self,
header::{HeaderValue, CONTENT_TYPE},
};
use std::sync::OnceLock;
use thiserror::Error;

use crate::feed::Rss;

static RESP_SIZE_LIMIT: OnceCell<u64> = OnceCell::new();
static CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
static RESP_SIZE_LIMIT: OnceLock<u64> = OnceLock::new();
static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();

#[derive(Error, Debug)]
pub enum FeedError {
Expand All @@ -28,10 +28,9 @@ impl FeedError {
match self {
Self::Network(source) => tr!("network_error", source = source),
Self::Parsing(source) => tr!("parsing_error", source = source),
Self::TooLarge(limit) => tr!(
"rss_size_limit_exceeded",
size = format_byte_size((*limit).into())
),
Self::TooLarge(limit) => {
tr!("rss_size_limit_exceeded", size = format_byte_size(*limit))
}
}
}
}
Expand Down Expand Up @@ -153,7 +152,7 @@ mod test {

#[test]
fn max_format_byte_size() {
assert_eq!(format_byte_size(std::u64::MAX), "16EiB");
assert_eq!(format_byte_size(u64::MAX), "16EiB");
}

#[test]
Expand Down
7 changes: 3 additions & 4 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub async fn check_command(opt: &crate::Opt, cmd: &Command) -> bool {
let reply_target = &mut MsgTarget::new(cmd.chat.id, cmd.message_id);

// Private mode
if !opt.admin.is_empty() && !is_from_bot_admin(&cmd, &opt.admin) {
if !opt.admin.is_empty() && !is_from_bot_admin(cmd, &opt.admin) {
eprintln!(
"Unauthenticated request from user/channel: {:?}, command: {}, args: {}",
cmd.from, cmd.command, cmd.text.value
Expand All @@ -62,7 +62,7 @@ pub async fn check_command(opt: &crate::Opt, cmd: &Command) -> bool {
}
// Restrict mode: bot commands are only accessible to admins.
Group { .. } | Supergroup { .. } if opt.restricted => {
let user_is_admin = is_from_chat_admin(&cmd).await;
let user_is_admin = is_from_chat_admin(cmd).await;
if !user_is_admin {
let _ignore_result = update_response(
&cmd.bot,
Expand Down Expand Up @@ -226,8 +226,7 @@ async fn check_channel_permission(
}
let bot_is_admin = admins
.iter()
.find(|member| member.user.id == *crate::BOT_ID.get().unwrap())
.is_some();
.any(|member| member.user.id == *crate::BOT_ID.get().unwrap());
if !bot_is_admin {
update_response(
bot,
Expand Down
18 changes: 7 additions & 11 deletions src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use std::time::{Duration, SystemTime};

use atomicwrites::{AtomicFile, OverwriteBehavior};
use serde::{Deserialize, Serialize};
use serde_json;
use thiserror::Error;

use crate::feed;
Expand Down Expand Up @@ -94,11 +93,11 @@ impl Database {
}

pub fn all_feeds(&self) -> Vec<Feed> {
self.feeds.iter().map(|(_, v)| v.clone()).collect()
self.feeds.values().cloned().collect()
}

pub fn all_subscribers(&self) -> Vec<SubscriberId> {
self.subscribers.iter().map(|(k, _)| *k).collect()
self.subscribers.keys().copied().collect()
}

pub fn subscribed_feeds(&self, subscriber: SubscriberId) -> Option<Vec<Feed>> {
Expand Down Expand Up @@ -144,10 +143,7 @@ impl Database {
pub fn subscribe(&mut self, subscriber: SubscriberId, rss_link: &str, rss: &feed::Rss) -> bool {
let feed_id = gen_hash(&rss_link);
{
let subscribed_feeds = self
.subscribers
.entry(subscriber)
.or_insert_with(HashSet::default);
let subscribed_feeds = self.subscribers.entry(subscriber).or_default();
if !subscribed_feeds.insert(feed_id) {
return false;
}
Expand Down Expand Up @@ -218,7 +214,7 @@ impl Database {
.remove(&from)
.map(|feeds| {
for feed_id in &feeds {
let feed = self.feeds.get_mut(&feed_id).unwrap();
let feed = self.feeds.get_mut(feed_id).unwrap();
feed.subscribers.remove(&from);
feed.subscribers.insert(to);
}
Expand Down Expand Up @@ -273,7 +269,7 @@ impl Database {
}

pub fn save(&self) -> Result<(), DataError> {
let feeds_list: Vec<&Feed> = self.feeds.iter().map(|(_id, feed)| feed).collect();
let feeds_list: Vec<&Feed> = self.feeds.values().collect();
let file = AtomicFile::new(&self.path, OverwriteBehavior::AllowOverwrite);
file.write(|file| serde_json::to_writer(file, &feeds_list))
.map_err(|e| match e {
Expand All @@ -294,8 +290,8 @@ pub enum FeedUpdate {

fn gen_item_hash(item: &feed::Item) -> u64 {
item.id.as_ref().map(|id| gen_hash(&id)).unwrap_or_else(|| {
let title = item.title.as_ref().map(|s| s.as_str()).unwrap_or_default();
let link = item.link.as_ref().map(|s| s.as_str()).unwrap_or_default();
let title = item.title.as_deref().unwrap_or_default();
let link = item.link.as_deref().unwrap_or_default();
gen_hash(&format!("{}{}", title, link))
})
}
Expand Down
80 changes: 34 additions & 46 deletions src/feed.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
use std::borrow::Cow;
use std::cell::RefCell;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::str;

use lazy_static::lazy_static;
use quick_xml::events::attributes::Attributes;
use quick_xml::events::BytesStart;
use quick_xml::events::Event as XmlEvent;
use quick_xml::Reader as XmlReader;
use regex::Regex;
use serde::Deserialize;
use std::sync::LazyLock;

trait FromXml: Sized {
fn from_xml<B: std::io::BufRead>(
Expand Down Expand Up @@ -76,12 +75,11 @@ impl FromXml for SkipThisElement {
let mut buf = bufs.pop();
let mut depth = 1u64;
loop {
match reader.read_event(&mut buf) {
Ok(XmlEvent::Start(_)) => depth += 1,
Ok(XmlEvent::End(_)) if depth == 1 => break,
Ok(XmlEvent::End(_)) => depth -= 1,
Ok(XmlEvent::Eof) => break, // just ignore EOF
Err(err) => return Err(err.into()),
match reader.read_event(&mut buf)? {
XmlEvent::Start(_) => depth += 1,
XmlEvent::End(_) if depth == 1 => break,
XmlEvent::End(_) => depth -= 1,
XmlEvent::Eof => break, // just ignore EOF
_ => (),
}
buf.clear();
Expand All @@ -99,16 +97,15 @@ impl FromXml for Option<u32> {
let mut buf = bufs.pop();
let mut output = None;
loop {
match reader.read_event(&mut buf) {
Ok(XmlEvent::Start(ref e)) => {
match reader.read_event(&mut buf)? {
XmlEvent::Start(ref e) => {
SkipThisElement::from_xml(bufs, reader, e)?;
}
Ok(XmlEvent::Text(ref e)) => {
XmlEvent::Text(ref e) => {
let text = reader.decode(e);
output = text.parse().ok();
}
Ok(XmlEvent::End(_)) | Ok(XmlEvent::Eof) => break,
Err(err) => return Err(err.into()),
XmlEvent::End(_) | XmlEvent::Eof => break,
_ => (),
}
buf.clear();
Expand All @@ -126,20 +123,19 @@ impl FromXml for Option<String> {
let mut buf = bufs.pop();
let mut content: Option<String> = None;
loop {
match reader.read_event(&mut buf) {
Ok(XmlEvent::Start(ref e)) => {
match reader.read_event(&mut buf)? {
XmlEvent::Start(ref e) => {
SkipThisElement::from_xml(bufs, reader, e)?;
}
Ok(XmlEvent::Text(ref e)) => {
XmlEvent::Text(ref e) => {
let text = e.unescape_and_decode(reader)?;
content = Some(text);
}
Ok(XmlEvent::CData(ref e)) => {
XmlEvent::CData(ref e) => {
let text = reader.decode(e).to_string();
content = Some(text);
}
Ok(XmlEvent::End(_)) | Ok(XmlEvent::Eof) => break,
Err(err) => return Err(err.into()),
XmlEvent::End(_) | XmlEvent::Eof => break,
_ => (),
}
buf.clear();
Expand Down Expand Up @@ -174,8 +170,8 @@ impl FromXml for Rss {
let mut sy_freq: Option<u32> = None;

loop {
match reader.read_event(&mut buf) {
Ok(XmlEvent::Empty(ref e)) => {
match reader.read_event(&mut buf)? {
XmlEvent::Empty(ref e) => {
if reader.decode(e.local_name()) == "link" {
match parse_atom_link(reader, e.attributes())? {
Some(AtomLink::Alternate(link)) => rss.link = link,
Expand All @@ -184,7 +180,7 @@ impl FromXml for Rss {
}
}
}
Ok(XmlEvent::Start(ref e)) => {
XmlEvent::Start(ref e) => {
match &*reader.decode(e.local_name()) {
"channel" => {
// RSS 0.9 1.0
Expand Down Expand Up @@ -229,12 +225,11 @@ impl FromXml for Rss {
}
}
}
Ok(XmlEvent::End(_)) if reading_rss_1_0_head => {
XmlEvent::End(_) if reading_rss_1_0_head => {
// reader.decode(e.local_name())? == "channel";
reading_rss_1_0_head = false;
}
Ok(XmlEvent::End(_)) | Ok(XmlEvent::Eof) => break,
Err(err) => return Err(err.into()),
XmlEvent::End(_) | XmlEvent::Eof => break,
_ => (),
}
buf.clear();
Expand Down Expand Up @@ -271,8 +266,8 @@ impl FromXml for Item {
let mut buf = bufs.pop();
let mut item = Item::default();
loop {
match reader.read_event(&mut buf) {
Ok(XmlEvent::Empty(ref e)) => {
match reader.read_event(&mut buf)? {
XmlEvent::Empty(ref e) => {
if reader.decode(e.name()) == "link" {
if let Some(AtomLink::Alternate(link)) =
parse_atom_link(reader, e.attributes())?
Expand All @@ -281,7 +276,7 @@ impl FromXml for Item {
}
}
}
Ok(XmlEvent::Start(ref e)) => {
XmlEvent::Start(ref e) => {
match &*reader.decode(e.name()) {
"title" => {
item.title = <Option<String> as FromXml>::from_xml(bufs, reader, e)?;
Expand All @@ -307,8 +302,7 @@ impl FromXml for Item {
}
}
}
Ok(XmlEvent::End(_)) | Ok(XmlEvent::Eof) => break,
Err(err) => return Err(err.into()),
XmlEvent::End(_) | XmlEvent::Eof => break,
_ => (),
}
buf.clear();
Expand All @@ -335,11 +329,11 @@ impl FromXml for Option<SyPeriod> {
let mut buf = bufs.pop();
let mut output = None;
loop {
match reader.read_event(&mut buf) {
Ok(XmlEvent::Start(ref e)) => {
match reader.read_event(&mut buf)? {
XmlEvent::Start(ref e) => {
SkipThisElement::from_xml(bufs, reader, e)?;
}
Ok(XmlEvent::Text(ref e)) => {
XmlEvent::Text(ref e) => {
let period = match &*reader.decode(e) {
"hourly" => SyPeriod::Hourly,
"daily" => SyPeriod::Daily,
Expand All @@ -350,8 +344,7 @@ impl FromXml for Option<SyPeriod> {
};
output = Some(period);
}
Ok(XmlEvent::End(_)) | Ok(XmlEvent::Eof) => break,
Err(err) => return Err(err.into()),
XmlEvent::End(_) | XmlEvent::Eof => break,
_ => (),
}
buf.clear();
Expand All @@ -367,8 +360,8 @@ pub fn parse<B: std::io::BufRead>(reader: B) -> quick_xml::Result<Rss> {
let bufs = BufPool::new(4, 512);
let mut buf = bufs.pop();
loop {
match reader.read_event(&mut buf) {
Ok(XmlEvent::Start(ref e)) => match &*reader.decode(e.name()) {
match reader.read_event(&mut buf)? {
XmlEvent::Start(ref e) => match &*reader.decode(e.name()) {
"rss" => continue,
"channel" | "feed" | "rdf:RDF" => {
return Rss::from_xml(&bufs, &mut reader, e);
Expand All @@ -377,8 +370,7 @@ pub fn parse<B: std::io::BufRead>(reader: B) -> quick_xml::Result<Rss> {
SkipThisElement::from_xml(&bufs, &mut reader, e)?;
}
},
Ok(XmlEvent::Eof) => return Err(quick_xml::Error::UnexpectedEof("feed".to_string())),
Err(err) => return Err(err.into()),
XmlEvent::Eof => return Err(quick_xml::Error::UnexpectedEof("feed".to_string())),
_ => (),
}
buf.clear();
Expand All @@ -402,9 +394,7 @@ fn url_relative_to_absolute(link: &mut String, host: &str) {
}

pub fn fix_relative_url(mut rss: Rss, rss_link: &str) -> Rss {
lazy_static! {
static ref HOST: Regex = Regex::new(r"^(https?://[^/]+)").unwrap();
}
static HOST: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(https?://[^/]+)").unwrap());
let rss_host = HOST
.captures(rss_link)
.map_or(rss_link, |r| r.get(0).unwrap().as_str());
Expand Down Expand Up @@ -453,9 +443,7 @@ struct Buffer {

impl Drop for Buffer {
fn drop(&mut self) {
self.pool
.borrow_mut()
.push(mem::replace(&mut self.inner, Vec::new()))
self.pool.borrow_mut().push(std::mem::take(&mut self.inner))
}
}

Expand Down Expand Up @@ -736,7 +724,7 @@ mod test {

#[test]
fn atom_link_parsing() {
let data = vec![
let data = [
r#"<link href="alternate href" />"#,
r#"<link href="alternate href" rel="alternate" />"#,
r#"<link href="self href" rel="self" />"#,
Expand Down
Loading

0 comments on commit a0eae53

Please sign in to comment.