open_lark/client/
mod.rs

1#[cfg(any(
2    feature = "attendance",
3    feature = "authentication",
4    feature = "im",
5    feature = "search",
6    feature = "cloud-docs"
7))]
8use std::sync::Arc;
9use std::time::Duration;
10
11use crate::core::{config::Config, constants::AppType};
12
13// 条件导入服务
14#[cfg(feature = "acs")]
15use crate::service::acs::AcsService;
16#[cfg(feature = "admin")]
17use crate::service::admin::AdminService;
18#[cfg(feature = "ai")]
19use crate::service::ai::AiService;
20#[cfg(feature = "aily")]
21use crate::service::aily::AilyService;
22#[cfg(feature = "apass")]
23use crate::service::apass::ApassService;
24#[cfg(feature = "application")]
25use crate::service::application::ApplicationService;
26#[cfg(feature = "approval")]
27use crate::service::approval::ApprovalService;
28#[cfg(feature = "attendance")]
29use crate::service::attendance::AttendanceService;
30#[cfg(feature = "authentication")]
31use crate::service::authentication::AuthenService;
32#[cfg(feature = "bot")]
33use crate::service::bot::BotService;
34#[cfg(feature = "calendar")]
35use crate::service::calendar::CalendarService;
36#[cfg(feature = "cardkit")]
37use crate::service::cardkit::CardkitService;
38#[cfg(feature = "cloud-docs")]
39use crate::service::cloud_docs::CloudDocsService;
40#[cfg(feature = "contact")]
41use crate::service::contact::ContactService;
42#[cfg(feature = "corehr")]
43use crate::service::corehr::CoreHRService;
44#[cfg(feature = "directory")]
45use crate::service::directory::DirectoryService;
46#[cfg(feature = "ehr")]
47use crate::service::ehr::EhrService;
48#[cfg(feature = "elearning")]
49use crate::service::elearning::ELearningService;
50#[cfg(feature = "group")]
51use crate::service::group::GroupService;
52#[cfg(feature = "helpdesk")]
53use crate::service::helpdesk::HelpdeskService;
54#[cfg(feature = "hire")]
55use crate::service::hire::HireService;
56#[cfg(feature = "human-authentication")]
57use crate::service::human_authentication::HumanAuthenticationService;
58#[cfg(feature = "im")]
59use crate::service::im::ImService;
60#[cfg(feature = "lingo")]
61use crate::service::lingo::LingoService;
62#[cfg(feature = "mail")]
63use crate::service::mail::MailService;
64#[cfg(feature = "mdm")]
65use crate::service::mdm::MdmService;
66#[cfg(feature = "minutes")]
67use crate::service::minutes::MinutesService;
68#[cfg(feature = "moments")]
69use crate::service::moments::MomentsService;
70#[cfg(feature = "okr")]
71use crate::service::okr::OkrService;
72#[cfg(feature = "payroll")]
73use crate::service::payroll::PayrollService;
74#[cfg(feature = "performance")]
75use crate::service::performance::PerformanceService;
76#[cfg(feature = "personal-settings")]
77use crate::service::personal_settings::PersonalSettingsService;
78#[cfg(feature = "report")]
79use crate::service::report::ReportService;
80#[cfg(feature = "search")]
81use crate::service::search::SearchService;
82#[cfg(feature = "security-and-compliance")]
83use crate::service::security_and_compliance::SecurityAndComplianceService;
84#[cfg(feature = "task")]
85use crate::service::task::TaskV2Service;
86#[cfg(feature = "tenant")]
87use crate::service::tenant::TenantService;
88#[cfg(feature = "tenant-tag")]
89use crate::service::tenant_tag::TenantTagService;
90#[cfg(feature = "trust-party")]
91use crate::service::trust_party::TrustPartyService;
92#[cfg(feature = "vc")]
93use crate::service::vc::VcService;
94#[cfg(feature = "verification")]
95use crate::service::verification::VerificationService;
96#[cfg(feature = "workplace")]
97use crate::service::workplace::WorkplaceService;
98
99// 向后兼容的导入
100#[cfg(feature = "cloud-docs")]
101use crate::service::{
102    AssistantService, BitableService, BoardService, CommentsService, DocsService, DriveService,
103    PermissionService, SheetsService, WikiService,
104};
105
106#[cfg(feature = "websocket")]
107pub mod ws_client;
108
109/// 飞书开放平台SDK主客户端
110///
111/// 提供对所有飞书开放平台API的统一访问接口。支持自建应用和商店应用两种类型,
112/// 自动处理认证、令牌管理、请求重试等核心功能。
113///
114/// # 主要功能
115///
116/// - 🔐 自动令牌管理和刷新
117/// - 🚀 支持所有飞书开放平台API
118/// - 🔄 内置请求重试机制
119/// - 📡 WebSocket长连接支持(需开启websocket特性)
120/// - 🎯 类型安全的API调用
121///
122/// # 快速开始
123///
124/// ```rust
125/// use open_lark::prelude::*;
126///
127/// // 创建自建应用客户端
128/// let client = LarkClient::builder("your_app_id", "your_app_secret")
129///     .with_app_type(AppType::SelfBuild)
130///     .with_enable_token_cache(true)
131///     .build();
132///
133/// // 发送文本消息
134/// let message = CreateMessageRequestBody::builder()
135///     .receive_id("ou_xxx")
136///     .msg_type("text")
137///     .content("{\"text\":\"Hello from Rust!\"}")
138///     .build();
139///
140/// let request = CreateMessageRequest::builder()
141///     .receive_id_type("open_id")
142///     .request_body(message)
143///     .build();
144///
145/// // let result = client.im.message.create(request, None).await?;
146/// ```
147///
148/// # 服务模块
149///
150/// 客户端包含以下主要服务模块:
151/// - `im`: 即时消息
152/// - `drive`: 云盘文件
153/// - `sheets`: 电子表格
154/// - `calendar`: 日历
155/// - `contact`: 通讯录
156/// - `hire`: 招聘
157/// - 更多服务请参考各字段文档
158pub struct LarkClient {
159    pub config: Config,
160    // 核心服务 - 使用条件编译
161    #[cfg(feature = "acs")]
162    pub acs: AcsService,
163    #[cfg(feature = "admin")]
164    pub admin: AdminService,
165    #[cfg(feature = "ai")]
166    pub ai: AiService,
167    #[cfg(feature = "aily")]
168    pub aily: AilyService,
169    #[cfg(feature = "apass")]
170    pub apass: ApassService,
171    #[cfg(feature = "application")]
172    pub application: ApplicationService,
173    #[cfg(feature = "approval")]
174    pub approval: ApprovalService,
175    #[cfg(feature = "attendance")]
176    pub attendance: AttendanceService,
177    #[cfg(feature = "authentication")]
178    pub auth: AuthenService,
179    #[cfg(feature = "bot")]
180    pub bot: BotService,
181    #[cfg(feature = "calendar")]
182    pub calendar: CalendarService,
183    #[cfg(feature = "cardkit")]
184    pub cardkit: CardkitService,
185    #[cfg(feature = "contact")]
186    pub contact: ContactService,
187    #[cfg(feature = "corehr")]
188    pub corehr: CoreHRService,
189    #[cfg(feature = "directory")]
190    pub directory: DirectoryService,
191    #[cfg(feature = "ehr")]
192    pub ehr: EhrService,
193    #[cfg(feature = "elearning")]
194    pub elearning: ELearningService,
195    #[cfg(feature = "group")]
196    pub group: GroupService,
197    #[cfg(feature = "helpdesk")]
198    pub helpdesk: HelpdeskService,
199    #[cfg(feature = "hire")]
200    pub hire: HireService,
201    #[cfg(feature = "human-authentication")]
202    pub human_authentication: HumanAuthenticationService,
203    #[cfg(feature = "im")]
204    pub im: ImService,
205    #[cfg(feature = "lingo")]
206    pub lingo: LingoService,
207    #[cfg(feature = "mail")]
208    pub mail: MailService,
209    #[cfg(feature = "mdm")]
210    pub mdm: MdmService,
211    #[cfg(feature = "minutes")]
212    pub minutes: MinutesService,
213    #[cfg(feature = "moments")]
214    pub moments: MomentsService,
215    #[cfg(feature = "okr")]
216    pub okr: OkrService,
217    #[cfg(feature = "payroll")]
218    pub payroll: PayrollService,
219    #[cfg(feature = "performance")]
220    pub performance: PerformanceService,
221    #[cfg(feature = "personal-settings")]
222    pub personal_settings: PersonalSettingsService,
223    #[cfg(feature = "report")]
224    pub report: ReportService,
225    #[cfg(feature = "search")]
226    pub search: SearchService,
227    #[cfg(feature = "security-and-compliance")]
228    pub security_and_compliance: SecurityAndComplianceService,
229    #[cfg(feature = "task")]
230    pub task: TaskV2Service,
231    #[cfg(feature = "tenant")]
232    pub tenant: TenantService,
233    #[cfg(feature = "tenant-tag")]
234    pub tenant_tag: TenantTagService,
235    #[cfg(feature = "trust-party")]
236    pub trust_party: TrustPartyService,
237    #[cfg(feature = "vc")]
238    pub vc: VcService,
239    #[cfg(feature = "verification")]
240    pub verification: VerificationService,
241    #[cfg(feature = "workplace")]
242    pub workplace: WorkplaceService,
243    // 云文档服务聚合
244    #[cfg(feature = "cloud-docs")]
245    pub cloud_docs: CloudDocsService,
246    // 向后兼容的字段
247    #[cfg(feature = "cloud-docs")]
248    pub assistant: AssistantService,
249    #[cfg(feature = "cloud-docs")]
250    pub docs: DocsService,
251    #[cfg(feature = "cloud-docs")]
252    pub drive: DriveService,
253    #[cfg(feature = "cloud-docs")]
254    pub sheets: SheetsService,
255    #[cfg(feature = "cloud-docs")]
256    pub bitable: BitableService,
257    #[cfg(feature = "cloud-docs")]
258    pub wiki: WikiService,
259    #[cfg(feature = "cloud-docs")]
260    pub comments: CommentsService,
261    #[cfg(feature = "cloud-docs")]
262    pub permission: PermissionService,
263    #[cfg(feature = "cloud-docs")]
264    pub board: BoardService,
265}
266
267/// 飞书客户端构建器
268///
269/// 使用构建器模式配置和创建LarkClient实例。支持链式调用配置各种选项。
270///
271/// # 示例
272///
273/// ```rust
274/// use open_lark::prelude::*;
275///
276/// let client = LarkClient::builder("app_id", "app_secret")
277///     .with_app_type(AppType::SelfBuild)
278///     .with_enable_token_cache(true)
279///     .with_req_timeout(Some(30.0))
280///     .build();
281/// ```
282pub struct LarkClientBuilder {
283    config: Config,
284}
285
286impl LarkClientBuilder {
287    /// 设置应用类型
288    ///
289    /// # 参数
290    /// - `app_type`: 应用类型,`AppType::SelfBuild`(自建应用)或`AppType::Marketplace`(商店应用)
291    pub fn with_app_type(mut self, app_type: AppType) -> Self {
292        self.config.app_type = app_type;
293        self
294    }
295
296    /// 设置为商店应用(等同于 `with_app_type(AppType::Marketplace)`)
297    pub fn with_marketplace_app(mut self) -> Self {
298        self.config.app_type = AppType::Marketplace;
299        self
300    }
301
302    /// 设置自定义API基础URL
303    ///
304    /// # 参数
305    /// - `base_url`: 自定义的API基础URL,默认为官方地址
306    pub fn with_open_base_url(mut self, base_url: String) -> Self {
307        self.config.base_url = base_url;
308        self
309    }
310
311    /// 启用或禁用令牌缓存
312    ///
313    /// # 参数
314    /// - `enable`: 是否启用令牌缓存,建议启用以提高性能
315    pub fn with_enable_token_cache(mut self, enable: bool) -> Self {
316        self.config.enable_token_cache = enable;
317        self
318    }
319
320    /// 设置请求超时时间
321    ///
322    /// # 参数
323    /// - `timeout`: 超时时间(秒),None表示使用默认值
324    pub fn with_req_timeout(mut self, timeout: Option<f32>) -> Self {
325        self.config.req_timeout = timeout.map(Duration::from_secs_f32);
326        self
327    }
328
329    /// 构建LarkClient实例
330    ///
331    /// 根据配置的参数创建最终的客户端实例。
332    pub fn build(mut self) -> LarkClient {
333        if let Some(req_timeout) = self.config.req_timeout {
334            self.config.http_client = reqwest::Client::builder()
335                .timeout(req_timeout)
336                .build()
337                .expect("Failed to build HTTP client with timeout")
338        }
339
340        LarkClient {
341            config: self.config.clone(),
342            // 核心服务 - 使用条件编译
343            #[cfg(feature = "acs")]
344            acs: AcsService::new(self.config.clone()),
345            #[cfg(feature = "admin")]
346            admin: AdminService::new(self.config.clone()),
347            #[cfg(feature = "ai")]
348            ai: AiService::new(self.config.clone()),
349            #[cfg(feature = "aily")]
350            aily: AilyService::new(self.config.clone()),
351            #[cfg(feature = "apass")]
352            apass: ApassService::new(self.config.clone()),
353            #[cfg(feature = "application")]
354            application: ApplicationService::new(self.config.clone()),
355            #[cfg(feature = "approval")]
356            approval: ApprovalService::new(self.config.clone()),
357            #[cfg(feature = "attendance")]
358            attendance: AttendanceService::new(Arc::new(self.config.clone())),
359            #[cfg(feature = "authentication")]
360            auth: AuthenService::new(Arc::new(self.config.clone())),
361            #[cfg(feature = "bot")]
362            bot: BotService::new(self.config.clone()),
363            #[cfg(feature = "calendar")]
364            calendar: CalendarService::new(self.config.clone()),
365            #[cfg(feature = "cardkit")]
366            cardkit: CardkitService::new(self.config.clone()),
367            #[cfg(feature = "contact")]
368            contact: ContactService::new(self.config.clone()),
369            #[cfg(feature = "corehr")]
370            corehr: CoreHRService::new(self.config.clone()),
371            #[cfg(feature = "directory")]
372            directory: DirectoryService::new(self.config.clone()),
373            #[cfg(feature = "ehr")]
374            ehr: EhrService::new(self.config.clone()),
375            #[cfg(feature = "elearning")]
376            elearning: ELearningService::new(self.config.clone()),
377            #[cfg(feature = "group")]
378            group: GroupService::new(self.config.clone()),
379            #[cfg(feature = "helpdesk")]
380            helpdesk: HelpdeskService::new(self.config.clone()),
381            #[cfg(feature = "hire")]
382            hire: HireService::new(self.config.clone()),
383            #[cfg(feature = "human-authentication")]
384            human_authentication: HumanAuthenticationService::new(self.config.clone()),
385            #[cfg(feature = "im")]
386            im: ImService::new(Arc::new(self.config.clone())),
387            #[cfg(feature = "lingo")]
388            lingo: LingoService::new(self.config.clone()),
389            #[cfg(feature = "mail")]
390            mail: MailService::new(self.config.clone()),
391            #[cfg(feature = "mdm")]
392            mdm: MdmService::new(self.config.clone()),
393            #[cfg(feature = "minutes")]
394            minutes: MinutesService::new(self.config.clone()),
395            #[cfg(feature = "moments")]
396            moments: MomentsService::new(self.config.clone()),
397            #[cfg(feature = "okr")]
398            okr: OkrService::new(self.config.clone()),
399            #[cfg(feature = "payroll")]
400            payroll: PayrollService::new(self.config.clone()),
401            #[cfg(feature = "performance")]
402            performance: PerformanceService::new(self.config.clone()),
403            #[cfg(feature = "personal-settings")]
404            personal_settings: PersonalSettingsService::new(self.config.clone()),
405            #[cfg(feature = "report")]
406            report: ReportService::new(self.config.clone()),
407            #[cfg(feature = "search")]
408            search: SearchService::new(Arc::new(self.config.clone())),
409            #[cfg(feature = "security-and-compliance")]
410            security_and_compliance: SecurityAndComplianceService::new(self.config.clone()),
411            #[cfg(feature = "task")]
412            task: TaskV2Service::new(self.config.clone()),
413            #[cfg(feature = "tenant")]
414            tenant: TenantService::new(self.config.clone()),
415            #[cfg(feature = "tenant-tag")]
416            tenant_tag: TenantTagService::new(self.config.clone()),
417            #[cfg(feature = "trust-party")]
418            trust_party: TrustPartyService::new(self.config.clone()),
419            #[cfg(feature = "vc")]
420            vc: VcService::new(self.config.clone()),
421            #[cfg(feature = "verification")]
422            verification: VerificationService::new(self.config.clone()),
423            #[cfg(feature = "workplace")]
424            workplace: WorkplaceService::new(self.config.clone()),
425            // 云文档服务聚合
426            #[cfg(feature = "cloud-docs")]
427            cloud_docs: CloudDocsService::new(Arc::new(self.config.clone())),
428            // 向后兼容的字段(重新创建实例)
429            #[cfg(feature = "cloud-docs")]
430            assistant: AssistantService::new(Arc::new(self.config.clone())),
431            #[cfg(feature = "cloud-docs")]
432            docs: DocsService::new(Arc::new(self.config.clone())),
433            #[cfg(feature = "cloud-docs")]
434            drive: DriveService::new(Arc::new(self.config.clone())),
435            #[cfg(feature = "cloud-docs")]
436            sheets: SheetsService::new(Arc::new(self.config.clone())),
437            #[cfg(feature = "cloud-docs")]
438            bitable: BitableService::new(Arc::new(self.config.clone())),
439            #[cfg(feature = "cloud-docs")]
440            wiki: WikiService::new(Arc::new(self.config.clone())),
441            #[cfg(feature = "cloud-docs")]
442            comments: CommentsService::new(Arc::new(self.config.clone())),
443            #[cfg(feature = "cloud-docs")]
444            permission: PermissionService::new(Arc::new(self.config.clone())),
445            #[cfg(feature = "cloud-docs")]
446            board: BoardService::new(Arc::new(self.config.clone())),
447        }
448    }
449}
450
451impl LarkClient {
452    /// 创建客户端构建器
453    ///
454    /// # 参数
455    /// - `app_id`: 应用ID,从飞书开放平台获取
456    /// - `app_secret`: 应用密钥,从飞书开放平台获取
457    ///
458    /// # 示例
459    /// ```rust
460    /// use open_lark::prelude::*;
461    ///
462    /// let client = LarkClient::builder("cli_xxx", "xxx")
463    ///     .with_app_type(AppType::SelfBuild)
464    ///     .build();
465    /// ```
466    pub fn builder(app_id: &str, app_secret: &str) -> LarkClientBuilder {
467        LarkClientBuilder {
468            config: Config {
469                app_id: app_id.to_string(),
470                app_secret: app_secret.to_string(),
471                ..Default::default()
472            },
473        }
474    }
475}