Skip to content

Commit

Permalink
refactor: sync feed api
Browse files Browse the repository at this point in the history
  • Loading branch information
zhanglun committed Oct 27, 2023
1 parent fb6a7b2 commit ef9e469
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 28 deletions.
46 changes: 32 additions & 14 deletions src-tauri/src/feed/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -667,10 +667,12 @@ pub async fn fetch_site_favicon(url: &str) -> Option<String> {
favicon_url
}

pub async fn sync_articles(uuid: String) -> Vec<(usize, String, String)> {
pub async fn sync_articles(uuid: String) -> HashMap<String, (usize, String)> {
let mut result = HashMap::new();

let channel = match feed::channel::get_feed_by_uuid(&uuid) {
Some(channel) => channel,
None => return vec![(0, uuid, "feed not found".to_string())],
None => return HashMap::new(),
};

let res = match feed::parse_feed(&channel.feed_url).await {
Expand All @@ -680,34 +682,48 @@ pub async fn sync_articles(uuid: String) -> Vec<(usize, String, String)> {
}
Err(err) => {
feed::channel::update_health_status(&uuid, 1, err.to_string());
return vec![(0, uuid, err.to_string())];
result.insert(uuid, (0, err.to_string()));

return result;
}
};

let articles = create_article_models(&channel.uuid, &channel.feed_url, &res);
let result = feed::article::Article::add_articles(channel.uuid, articles);
let record = feed::article::Article::add_articles(channel.uuid, articles);

result.insert(uuid, (record, "".to_string()));

return result;

vec![(result, uuid, "".to_string())]
}

pub async fn sync_article_in_folder(uuid: String) -> Vec<(usize, String, String)> {
pub async fn sync_article_in_folder(uuid: String) -> HashMap<String, (usize, String)> {
let connection = db::establish_connection();
let feeds = feed::folder::get_channels_in_folders(connection, vec![uuid]);
let feeds = feed::folder::get_channels_in_folders(connection, vec![uuid.clone()]);
let mut result: HashMap<String, (usize, String)> = HashMap::new();
let mut count = 0;

println!("{:?}", feeds);
let mut res = vec![];

log::debug!("sync_article_in_folder: feeds {:?}", feeds);

for feed in feeds {
res.extend(sync_articles(feed.uuid).await);
let record = sync_articles(feed.uuid.clone()).await;
let (num, _message) = record.get(&String::from(feed.uuid)).unwrap();
result.extend(record.clone());
count += num;
}

res
result.insert(uuid, (count, String::from("")));

result
}

pub async fn sync_feed(uuid: String, feed_type: String) -> Vec<(usize, String, String)> {
// pub struct SyncFeedResult {}
pub async fn sync_feed(uuid: String, feed_type: String) -> HashMap<String, (usize, String)> {
if feed_type == "folder" {
return feed::channel::sync_article_in_folder(uuid.to_string()).await;
} else {
log::debug!("start sync feed ===>");
return feed::channel::sync_articles(uuid.to_string()).await;
}
}
Expand Down Expand Up @@ -755,10 +771,12 @@ mod tests {

#[tokio::test]
async fn test_sync_feed() {
sync_feed(
"1e2dbbcd-5f44-4811-a907-0b6320b3ee9e".to_string(),
let a = sync_feed(
"efc718b5-14a8-45ce-8d0b-975013198ac1".to_string(),
"feed".to_string(),
)
.await;

println!("a {:?}", a);
}
}
2 changes: 1 addition & 1 deletion src-tauri/src/feed/folder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub fn get_channels_in_folders(
uuids: Vec<String>,
) -> Vec<models::FeedMeta> {
let result = schema::feed_metas::dsl::feed_metas
.filter(schema::feed_metas::uuid.eq_any(&uuids))
.filter(schema::feed_metas::folder_uuid.eq_any(&uuids))
.load::<models::FeedMeta>(&mut connection)
.expect("Expect get feed meta");

Expand Down
2 changes: 0 additions & 2 deletions src-tauri/src/server/handlers/article.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ pub async fn handle_mark_as_read(
is_all: body.is_all,
});

println!("=========> {:?}", body);

Ok(web::Json(res))
}

Expand Down
2 changes: 1 addition & 1 deletion src/components/Subscribes/ItemView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const ItemView: FC<CardProps> = ({
>
<div
className={clsx(
"w-full h-8 px-4 rounded-md flex items-center cursor-pointer group text-foreground hover:bg-accent",
"w-full h-9 px-4 rounded-md flex items-center cursor-pointer group text-foreground hover:bg-accent",
{
"hover:bg-primary bg-primary text-primary-foreground": isActive,
"shadow-[inset_0_0_0_2px_var(--color-primary)]":
Expand Down
38 changes: 32 additions & 6 deletions src/components/Subscribes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ import {useRefresh} from "./useRefresh";
import {TooltipBox} from "../TooltipBox";
import {ListContainer} from "./ListContainer";
import {copyText} from "@/helpers/copyText";
import {useToast} from "../ui/use-toast";
import { ToastAction } from "@/components/ui/toast";
import {useToast} from "@/components/ui/use-toast";
import {DialogDeleteFolder} from "@/components/SettingPanel/Content/DialogDeleteFolder";

const ChannelList = (): JSX.Element => {
Expand All @@ -49,7 +50,7 @@ const ChannelList = (): JSX.Element => {
setRefreshing,
done,
setDone,
startFresh,
startRefresh,
] = useRefresh();
const store = useBearStore((state) => ({
feed: state.feed,
Expand All @@ -64,7 +65,9 @@ const ChannelList = (): JSX.Element => {
setViewMeta: state.setViewMeta,
collectionMeta: state.collectionMeta,
initCollectionMetas: state.initCollectionMetas,
syncArticles: state.syncArticles,
}));

const [, , channelUuid] = useQuery();

useEffect(() => {
Expand All @@ -91,6 +94,29 @@ const ChannelList = (): JSX.Element => {
};

const reloadFeedData = (feed: FeedResItem | null) => {
if (feed) {
store.syncArticles(feed?.uuid, feed?.item_type)
.then(([,, message ]) => {
if (message) {
toast({
title: "Something wrong!",
variant: "destructive",
description: message,
action: (
<ToastAction altText="Goto schedule to undo">Close</ToastAction>
),
});
} else {
toast({
title: "Success",
description: message,
action: (
<ToastAction altText="Goto schedule to undo">Close</ToastAction>
),
});
}
});
}
console.log("TODO");
};

Expand Down Expand Up @@ -210,7 +236,7 @@ const ChannelList = (): JSX.Element => {
}
/>
<TooltipBox content="Update">
<Icon onClick={startFresh}>
<Icon onClick={startRefresh}>
<RefreshCw
size={16}
className={`${refreshing ? "spinning" : ""}`}
Expand All @@ -226,7 +252,7 @@ const ChannelList = (): JSX.Element => {
</div>
</div>
<div
className="flex-1 overflow-y-auto pb-2 px-2 height-[calc(100% - var(--app-toolbar-height))]"
className="flex-1 overflow-y-auto pb-2 px-1 height-[calc(100% - var(--app-toolbar-height))]"
ref={listRef}
>
<h2 className="mt-6 mb-2 px-4 text-lg font-semibold tracking-tight">
Expand Down Expand Up @@ -353,8 +379,8 @@ const ChannelList = (): JSX.Element => {
<ContextMenuSeparator/>
<ContextMenuItem
onClick={() =>
store.feedContextMenuTarget?.link &&
copyText(store.feedContextMenuTarget?.link).then(() =>
store.feedContextMenuTarget?.feed_url &&
copyText(store.feedContextMenuTarget?.feed_url).then(() =>
toast({
title: "Current URL copied to clipboard",
description: "Paste it wherever you like",
Expand Down
2 changes: 1 addition & 1 deletion src/components/Subscribes/useRefresh.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const useRefresh = () => {

setRefreshing(true);

dataAgent.getUserConfig().then((config) => {
dataAgent.getUserConfig().then(({ data: config }) => {
const { threads = 5 } = config;
const limit = pLimit(threads);
const fns = (store.feedList || []).map((channel: any) => {
Expand Down
19 changes: 16 additions & 3 deletions src/stores/createFeedSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export interface FeedSlice {

openFolder: (uuid: string) => void;
closeFolder: (uuid: string) => void;

syncArticles: (uuid: string, type: string) => Promise<[number, string, string]>;
}

export const createFeedSlice: StateCreator<FeedSlice> = (
Expand Down Expand Up @@ -192,10 +194,7 @@ export const createFeedSlice: StateCreator<FeedSlice> = (
};
return Promise.all([dataAgent.getFeeds(), dataAgent.getUnreadTotal()]).then(
([{ data: feedList }, { data: unreadTotal }]) => {
console.log("%c Line:188 🍡 unreadTotal", "color:#4fff4B", unreadTotal);
console.log("%c Line:185 🍺 feedList", "color:#7f2b82", feedList);
feedList = initUnreadCount(feedList, unreadTotal);
console.log("%c Line:191 🥐 feedList", "color:#2eafb0", feedList);
set(() => ({
feedList: feedList || [],
}));
Expand Down Expand Up @@ -242,5 +241,19 @@ export const createFeedSlice: StateCreator<FeedSlice> = (
set(() => ({
feedList: [...list]
}))
},

syncArticles(uuid: string, type: string) {
return dataAgent.syncFeed(type, uuid)
.then(({ data }) => {
const [num, , message] = data[0];

if (num > 0) {
get().initCollectionMetas();
get().getFeedList();
}

return data[0];
})
}
});

0 comments on commit ef9e469

Please sign in to comment.