1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
//! 好友列表。
//!
//! 更多信息参考 [`FriendList`]。

use std::{collections::HashMap, sync::Arc};

use anyhow::Result;
use futures_util::Future;
use pyo3::{prelude::*, types::*};
use ricq::structs::{FriendGroupInfo, FriendInfo};

use super::{
    client_impl::{Cacheable, ClientImpl},
    friend::Friend,
    friend_group::FriendGroup,
};

/// 好友列表。
///
/// # Python
/// ```python
/// class FriendList:
///     @property
///     def total_count(self) -> int: ...
///     @property
///     def online_count(self) -> int: ...
/// ```
#[pyclass]
#[derive(Clone)]
pub struct FriendList {
    pub(crate) client: Arc<ClientImpl>,
    /// 好友信息。
    pub(crate) friends: Vec<FriendInfo>,
    /// 好友分组信息。
    pub(crate) friend_groups: HashMap<u8, FriendGroupInfo>,
    /// 好友数量。
    #[pyo3(get)]
    pub total_count: i16,
    /// 在线好友数量。
    #[pyo3(get)]
    pub online_count: i16,
}

#[pymethods]
impl FriendList {
    /// 遍历好友信息的迭代器。
    ///
    /// 参考 [`Friend`]。
    ///
    /// # Examples
    /// ```python
    /// friend_list = await client.get_friend_list()
    /// for friend in friend_list.friends():
    ///     print(friend.nickname)
    /// ```
    ///
    /// # Python
    /// ```python
    /// def friends(self) -> Iterator[Friend]:
    /// ```
    pub fn friends(self_: Py<Self>, py: Python) -> FriendIter {
        FriendIter {
            list: self_.clone_ref(py),
            curr: 0,
            end: self_.borrow(py).friends.len(),
        }
    }

    /// 查找指定的好友。
    ///
    /// 参考 [`Friend`]。
    ///
    /// # Examples
    /// ```python
    /// friend_list = await client.get_friend_list()
    /// friend = friend_list.find_friend(12345678)
    /// if friend:
    ///     print(friend.nickname)
    /// else:
    ///     print("未找到好友 12345678")
    /// ```
    ///
    /// # Python
    /// ```python
    /// def find_friend(self, uin: int) -> Friend | None:
    /// ```
    pub fn find_friend(&self, uin: i64) -> Option<Friend> {
        self.friends
            .iter()
            .find(|info| info.uin == uin)
            .map(|info| Friend {
                client: self.client.clone(),
                info: info.clone(),
            })
    }

    /// 获取所有好友分组信息。
    ///
    /// 参考 [`FriendGroup`]。
    ///
    /// # Examples
    /// ```python
    /// friend_list = await client.get_friend_list()
    /// for group in friend_list.friend_groups():
    ///     print(group.name)
    /// ```
    ///
    /// # Python
    /// ```python
    /// def friend_groups(self) -> list[FriendGroup]:
    /// ```
    pub fn friend_groups<'py>(&self, py: Python<'py>) -> PyResult<&'py PyList> {
        let friend_groups = self
            .friend_groups
            .values()
            .map(|info| {
                PyCell::new(
                    py,
                    FriendGroup {
                        client: self.client.clone(),
                        info: info.clone(),
                    },
                )
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(PyList::new(py, friend_groups))
    }

    /// 查找好友分组。
    ///
    /// 参考 [`FriendGroup`]。
    ///
    /// # Examples
    /// ```python
    /// friend_list = await client.get_friend_list()
    /// friend = friend_list.find_friend(12345678)
    /// if friend:
    ///     group = friend_list.find_friend_group(friend.group_id)
    ///     if group:
    ///         print("好友 12345678 位于分组", group.name)
    /// ```
    ///
    /// # Python
    /// ```python
    /// def find_friend_group(self, group_id: int) -> FriendGroup | None:
    /// ```
    pub fn find_friend_group(&self, group_id: u8) -> Option<FriendGroup> {
        self.friend_groups
            .get(&group_id)
            .cloned()
            .map(|info| FriendGroup {
                client: self.client.clone(),
                info,
            })
    }
}

impl Cacheable for FriendList {
    type FetchFuture = impl Future<Output = Result<Self>>;

    /// 请求获取好友列表。
    fn fetch(client: Arc<ClientImpl>) -> Self::FetchFuture {
        async { client.get_friend_list().await }
    }
}

#[pyclass]
#[doc(hidden)]
pub struct FriendIter {
    list: Py<FriendList>,
    curr: usize,
    end: usize,
}

#[pymethods]
impl FriendIter {
    fn __iter__(self_: PyRef<'_, Self>) -> PyRef<'_, Self> {
        self_
    }

    fn __next__(&mut self, py: Python) -> Option<Friend> {
        if self.curr < self.end {
            let info = self.list.borrow(py).friends[self.curr].clone();
            self.curr += 1;
            Some(Friend {
                client: self.list.borrow(py).client.clone(),
                info,
            })
        } else {
            None
        }
    }
}