open-lark 0.14.0

Enterprise-grade Lark/Feishu Open API SDK with comprehensive Chinese documentation and advanced error handling
Documentation
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::core::{
    api_req::ApiRequest,
    api_resp::{ApiResponseTrait, BaseResponse, ResponseFormat},
    config::Config,
    constants::AccessTokenType,
    endpoints::{cloud_docs::*, EndpointBuilder},
    http::Transport,
    req_option::RequestOption,
    trait_system::Service,
    SDKResult,
};

/// 文档块服务
pub struct DocumentBlockService {
    config: Config,
}

impl DocumentBlockService {
    pub fn new(config: Config) -> Self {
        Self { config }
    }

    /// 创建块
    ///
    /// 该接口用于在文档中创建一个新的块。
    ///
    /// <https://open.feishu.cn/document/server-docs/docs/docs/docx-v1/document-block/create>
    pub async fn create(
        &self,
        document_id: impl Into<String>,
        request: CreateBlockRequest,
        option: Option<RequestOption>,
    ) -> SDKResult<BaseResponse<CreateBlockRespData>> {
        let api_req = ApiRequest {
            http_method: Method::POST,
            api_path: DOCX_V1_DOCUMENT_BLOCKS.replace("{}", &document_id.into()),
            supported_access_token_types: vec![AccessTokenType::User, AccessTokenType::Tenant],
            body: serde_json::to_vec(&request)?,
            ..Default::default()
        };

        let api_resp = Transport::request(api_req, &self.config, option).await?;
        Ok(api_resp)
    }

    /// 获取块的内容
    ///
    /// 该接口用于获取块的详细内容。
    ///
    /// <https://open.feishu.cn/document/server-docs/docs/docs/docx-v1/document-block/get>
    pub async fn get(
        &self,
        document_id: impl Into<String>,
        block_id: impl Into<String>,
        option: Option<RequestOption>,
    ) -> SDKResult<BaseResponse<GetBlockRespData>> {
        let api_req = ApiRequest {
            http_method: Method::GET,
            api_path: DOCX_V1_DOCUMENT_BLOCK_GET
                .replace("{document_id}", &document_id.into())
                .replace("{block_id}", &block_id.into()),
            supported_access_token_types: vec![AccessTokenType::User, AccessTokenType::Tenant],
            ..Default::default()
        };

        let api_resp = Transport::request(api_req, &self.config, option).await?;
        Ok(api_resp)
    }

    /// 更新块的内容
    ///
    /// 该接口用于更新块的内容。
    ///
    /// <https://open.feishu.cn/document/server-docs/docs/docs/docx-v1/document-block/patch>
    pub async fn patch(
        &self,
        document_id: impl Into<String>,
        block_id: impl Into<String>,
        request: PatchBlockRequest,
        option: Option<RequestOption>,
    ) -> SDKResult<BaseResponse<PatchBlockRespData>> {
        let api_req = ApiRequest {
            http_method: Method::PATCH,
            api_path: DOCX_V1_DOCUMENT_BLOCK_GET
                .replace("{document_id}", &document_id.into())
                .replace("{block_id}", &block_id.into()),
            supported_access_token_types: vec![AccessTokenType::User, AccessTokenType::Tenant],
            body: serde_json::to_vec(&request)?,
            ..Default::default()
        };

        let api_resp = Transport::request(api_req, &self.config, option).await?;
        Ok(api_resp)
    }

    /// 批量更新块的内容
    ///
    /// 该接口用于批量更新多个块的内容。
    ///
    /// <https://open.feishu.cn/document/server-docs/docs/docs/docx-v1/document-block/batch_update>
    pub async fn batch_update(
        &self,
        document_id: impl Into<String>,
        request: BatchUpdateBlockRequest,
        option: Option<RequestOption>,
    ) -> SDKResult<BaseResponse<BatchUpdateBlockRespData>> {
        let mut api_req = ApiRequest {
            http_method: Method::PATCH,
            api_path: DOCX_V1_DOCUMENT_BLOCKS_BATCH_UPDATE
                .replace("{document_id}", &document_id.into()),
            ..Default::default()
        };
        api_req.supported_access_token_types = vec![AccessTokenType::User, AccessTokenType::Tenant];
        api_req.body = serde_json::to_vec(&request)?;

        let api_resp = Transport::request(api_req, &self.config, option).await?;
        Ok(api_resp)
    }

    /// 删除块
    ///
    /// 该接口用于批量删除块。
    ///
    /// <https://open.feishu.cn/document/server-docs/docs/docs/docx-v1/document-block/batch_delete>
    pub async fn batch_delete(
        &self,
        document_id: impl Into<String>,
        request: BatchDeleteBlockRequest,
        option: Option<RequestOption>,
    ) -> SDKResult<BaseResponse<BatchDeleteBlockRespData>> {
        let mut api_req = ApiRequest {
            http_method: Method::DELETE,
            api_path: EndpointBuilder::replace_param(
                DOCX_V1_DOCUMENT_BLOCKS_BATCH_DELETE,
                "document_id",
                &document_id.into(),
            ),
            ..Default::default()
        };
        api_req.supported_access_token_types = vec![AccessTokenType::User, AccessTokenType::Tenant];
        api_req.body = serde_json::to_vec(&request)?;

        let api_resp = Transport::request(api_req, &self.config, option).await?;
        Ok(api_resp)
    }

    /// 获取所有子块
    ///
    /// 该接口用于获取指定块的所有子块。
    ///
    /// <https://open.feishu.cn/document/server-docs/docs/docs/docx-v1/document-block/get-2>
    pub async fn list_children(
        &self,
        document_id: impl Into<String>,
        block_id: impl Into<String>,
        request: ListChildrenRequest,
        option: Option<RequestOption>,
    ) -> SDKResult<BaseResponse<ListChildrenRespData>> {
        let document_id_str = document_id.into();
        let block_id_str = block_id.into();
        let mut api_req = ApiRequest {
            http_method: Method::GET,
            api_path: EndpointBuilder::replace_params_from_array(
                DOCX_V1_DOCUMENT_BLOCK_CHILDREN,
                &[
                    ("document_id", &document_id_str),
                    ("block_id", &block_id_str),
                ],
            ),
            supported_access_token_types: vec![AccessTokenType::User, AccessTokenType::Tenant],
            ..Default::default()
        };

        // 添加查询参数
        if let Some(page_size) = request.page_size {
            api_req
                .query_params
                .insert("page_size", page_size.to_string());
        }
        if let Some(page_token) = request.page_token {
            api_req.query_params.insert("page_token", page_token);
        }

        let api_resp = Transport::request(api_req, &self.config, option).await?;
        Ok(api_resp)
    }
}

// === 数据结构定义 ===

/// 创建块请求参数
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CreateBlockRequest {
    /// 父块ID,如果创建在文档根级,传document_id
    pub parent_id: String,
    /// 块索引位置
    pub index: Option<i32>,
    /// 块数据列表
    pub blocks: Vec<BlockData>,
}

impl CreateBlockRequest {
    pub fn builder() -> CreateBlockRequestBuilder {
        CreateBlockRequestBuilder::default()
    }

    pub fn new(parent_id: impl Into<String>, blocks: Vec<BlockData>) -> Self {
        Self {
            parent_id: parent_id.into(),
            index: None,
            blocks,
        }
    }

    pub fn with_index(mut self, index: i32) -> Self {
        self.index = Some(index);
        self
    }
}

/// 创建块请求构建器
#[derive(Default)]
pub struct CreateBlockRequestBuilder {
    request: CreateBlockRequest,
    document_id: String,
}

impl CreateBlockRequestBuilder {
    pub fn document_id(mut self, document_id: impl Into<String>) -> Self {
        self.document_id = document_id.into();
        self
    }

    pub fn parent_id(mut self, parent_id: impl Into<String>) -> Self {
        self.request.parent_id = parent_id.into();
        self
    }

    pub fn index(mut self, index: i32) -> Self {
        self.request.index = Some(index);
        self
    }

    pub fn blocks(mut self, blocks: Vec<BlockData>) -> Self {
        self.request.blocks = blocks;
        self
    }

    pub fn add_block(mut self, block: BlockData) -> Self {
        self.request.blocks.push(block);
        self
    }

    pub fn build(self) -> (String, CreateBlockRequest) {
        (self.document_id, self.request)
    }
}

/// 块数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlockData {
    /// 块类型
    pub block_type: i32,
    /// 块内容(根据不同类型有不同结构)
    pub block: Value,
}

/// 创建块响应数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateBlockRespData {
    /// 创建的块列表
    pub blocks: Vec<BlockInfo>,
    /// 文档版本ID
    pub document_revision_id: i64,
}

impl ApiResponseTrait for CreateBlockRespData {
    fn data_format() -> ResponseFormat {
        ResponseFormat::Data
    }
}

/// 块信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlockInfo {
    /// 块ID
    pub block_id: String,
    /// 父块ID
    pub parent_id: String,
    /// 子块ID列表
    pub children: Vec<String>,
    /// 块类型
    pub block_type: i32,
    /// 块索引
    pub index: i32,
}

/// 获取块响应数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetBlockRespData {
    /// 块信息
    pub block: DetailedBlock,
}

impl ApiResponseTrait for GetBlockRespData {
    fn data_format() -> ResponseFormat {
        ResponseFormat::Data
    }
}

/// 详细块信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetailedBlock {
    /// 块ID
    pub block_id: String,
    /// 父块ID
    pub parent_id: String,
    /// 子块ID列表
    pub children: Vec<String>,
    /// 块类型
    pub block_type: i32,
    /// 块索引
    pub index: i32,
    /// 块内容
    pub block: Value,
}

/// 更新块请求参数
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatchBlockRequest {
    /// 要更新的块内容
    pub block: Value,
}

impl PatchBlockRequest {
    pub fn new(block: Value) -> Self {
        Self { block }
    }
}

/// 更新块响应数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatchBlockRespData {
    /// 更新后的块信息
    pub block: DetailedBlock,
    /// 文档版本ID
    pub document_revision_id: i64,
}

impl ApiResponseTrait for PatchBlockRespData {
    fn data_format() -> ResponseFormat {
        ResponseFormat::Data
    }
}

/// 批量更新块请求参数
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BatchUpdateBlockRequest {
    /// 要更新的块列表
    pub requests: Vec<UpdateBlockItem>,
}

/// 更新块项
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateBlockItem {
    /// 块ID
    pub block_id: String,
    /// 要更新的块内容
    pub block: Value,
}

impl BatchUpdateBlockRequest {
    pub fn builder() -> BatchUpdateBlockRequestBuilder {
        BatchUpdateBlockRequestBuilder::default()
    }

    pub fn new(requests: Vec<UpdateBlockItem>) -> Self {
        Self { requests }
    }
}

/// 批量更新块请求构建器
#[derive(Default)]
pub struct BatchUpdateBlockRequestBuilder {
    request: BatchUpdateBlockRequest,
    document_id: String,
}

impl BatchUpdateBlockRequestBuilder {
    pub fn document_id(mut self, document_id: impl Into<String>) -> Self {
        self.document_id = document_id.into();
        self
    }

    pub fn requests(mut self, requests: Vec<UpdateBlockItem>) -> Self {
        self.request.requests = requests;
        self
    }

    pub fn add_request(mut self, block_id: impl Into<String>, block: Value) -> Self {
        self.request.requests.push(UpdateBlockItem {
            block_id: block_id.into(),
            block,
        });
        self
    }

    pub fn build(self) -> (String, BatchUpdateBlockRequest) {
        (self.document_id, self.request)
    }
}

/// 批量更新块响应数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchUpdateBlockRespData {
    /// 更新的块列表
    pub blocks: Vec<DetailedBlock>,
    /// 文档版本ID
    pub document_revision_id: i64,
}

impl ApiResponseTrait for BatchUpdateBlockRespData {
    fn data_format() -> ResponseFormat {
        ResponseFormat::Data
    }
}

/// 批量删除块请求参数
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BatchDeleteBlockRequest {
    /// 要删除的块ID列表
    pub block_ids: Vec<String>,
}

impl BatchDeleteBlockRequest {
    pub fn builder() -> BatchDeleteBlockRequestBuilder {
        BatchDeleteBlockRequestBuilder::default()
    }

    pub fn new(block_ids: Vec<String>) -> Self {
        Self { block_ids }
    }
}

/// 批量删除块请求构建器
#[derive(Default)]
pub struct BatchDeleteBlockRequestBuilder {
    request: BatchDeleteBlockRequest,
    document_id: String,
}

impl BatchDeleteBlockRequestBuilder {
    pub fn document_id(mut self, document_id: impl Into<String>) -> Self {
        self.document_id = document_id.into();
        self
    }

    pub fn block_ids(mut self, block_ids: Vec<String>) -> Self {
        self.request.block_ids = block_ids;
        self
    }

    pub fn add_block_id(mut self, block_id: impl Into<String>) -> Self {
        self.request.block_ids.push(block_id.into());
        self
    }

    pub fn build(self) -> (String, BatchDeleteBlockRequest) {
        (self.document_id, self.request)
    }
}

/// 批量删除块响应数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchDeleteBlockRespData {
    /// 文档版本ID
    pub document_revision_id: i64,
}

impl ApiResponseTrait for BatchDeleteBlockRespData {
    fn data_format() -> ResponseFormat {
        ResponseFormat::Data
    }
}

/// 获取子块请求参数
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListChildrenRequest {
    /// 分页大小
    pub page_size: Option<i32>,
    /// 分页标记
    pub page_token: Option<String>,
}

impl ListChildrenRequest {
    pub fn new() -> Self {
        Self {
            page_size: None,
            page_token: None,
        }
    }

    pub fn with_page_size(mut self, page_size: i32) -> Self {
        self.page_size = Some(page_size);
        self
    }

    pub fn with_page_token(mut self, page_token: impl Into<String>) -> Self {
        self.page_token = Some(page_token.into());
        self
    }
}

impl Default for ListChildrenRequest {
    fn default() -> Self {
        Self::new()
    }
}

/// 获取子块响应数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListChildrenRespData {
    /// 子块列表
    pub items: Vec<DetailedBlock>,
    /// 是否还有更多数据
    pub has_more: bool,
    /// 下一页标记
    pub page_token: Option<String>,
}

impl ApiResponseTrait for ListChildrenRespData {
    fn data_format() -> ResponseFormat {
        ResponseFormat::Data
    }
}

// === Builder execute方法实现 ===
// 为需要路径参数的Builder提供统一的execute方法

macro_rules! impl_execute_with_path {
    ($builder:ty, $response:ty, $method:ident) => {
        impl $builder {
            /// 执行请求
            pub async fn execute(
                self,
                service: &DocumentBlockService,
                option: Option<RequestOption>,
            ) -> SDKResult<$response> {
                let (document_id, request) = self.build();
                service.$method(document_id, request, option).await
            }

            /// 执行请求(带选项)
            pub async fn execute_with_options(
                self,
                service: &DocumentBlockService,
                option: RequestOption,
            ) -> SDKResult<$response> {
                self.execute(service, Some(option)).await
            }
        }
    };
}

impl_execute_with_path!(
    CreateBlockRequestBuilder,
    BaseResponse<CreateBlockRespData>,
    create
);

impl_execute_with_path!(
    BatchUpdateBlockRequestBuilder,
    BaseResponse<BatchUpdateBlockRespData>,
    batch_update
);

impl_execute_with_path!(
    BatchDeleteBlockRequestBuilder,
    BaseResponse<BatchDeleteBlockRespData>,
    batch_delete
);

// === Service trait 实现 ===

impl Service for DocumentBlockService {
    fn config(&self) -> &Config {
        &self.config
    }

    fn service_name() -> &'static str {
        "document_block"
    }

    fn service_version() -> &'static str {
        "v1"
    }
}