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
use super::{
MediaType, PhotoInitRequest, PhotoInitRequestBuilder, PostInfo, PostMode, PostStatusData,
PostStatusResponse, Source, SourceInfoBuilder, VideoInitRequest, VideoInitRequestBuilder,
VideoInitResponse, VideoInitResponseData,
};
use crate::error::{ErrorResponse, TikTokApiError};
use reqwest::Client;
use serde_json::json;
use tokio::{fs::File, io::AsyncReadExt};
pub struct Service {
base_url: String,
}
impl Service {
/// Creates a new instance of the Service.
pub fn new() -> Self {
Self {
base_url: String::from("https://open.tiktokapis.com"),
}
}
/// Sets a custom base URL for the Service.
///
/// # Arguments
///
/// * `base_url` - A string slice that holds the custom base URL.
pub fn with_base_url(mut self, base_url: &str) -> Self {
self.base_url = base_url.into();
self
}
/// Initializes a video post on TikTok.
///
/// # Arguments
///
/// * `token` - The API token.
/// * `video_init_request` - The request data for initializing the video post.
///
/// # Returns
///
/// * `Result<VideoInitResponseData, TikTokApiError>` - The response data or an error.
pub async fn post_video(
&self,
token: &str,
video_init_request: VideoInitRequest,
) -> Result<VideoInitResponseData, TikTokApiError> {
let url = format!("{}/v2/post/publish/video/init/", self.base_url);
let client = Client::new();
let response = client
.post(&url)
.header("Authorization", format!("Bearer {}", token))
.header("Content-Type", "application/json; charset=UTF-8")
.json(&video_init_request)
.send()
.await
.map_err(|e| TikTokApiError::RequestFailed(e.to_string()))?;
let status = response.status();
let body = response
.text()
.await
.map_err(|e| TikTokApiError::ResponseReadFailed(e.to_string()))?;
let video_init_response: VideoInitResponse =
serde_json::from_str(&body).map_err(|e| TikTokApiError::ParseFailed(e.to_string()))?;
if status.is_success() && video_init_response.error.code == "ok" {
Ok(video_init_response.data)
} else {
Err(TikTokApiError::from(video_init_response.error))
}
}
/// Uploads a video file to the provided upload URL.
///
/// # Arguments
///
/// * `upload_url` - The URL to which the video file should be uploaded.
/// * `file_path` - The path to the video file on the local filesystem.
///
/// # Returns
///
/// * `Result<(), TikTokApiError>` - An empty result or an error.
pub async fn upload_video(
&self,
upload_url: &str,
file_path: &str,
) -> Result<(), TikTokApiError> {
let mut file = File::open(file_path)
.await
.map_err(|e| TikTokApiError::RequestFailed(e.to_string()))?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)
.await
.map_err(|e| TikTokApiError::ResponseReadFailed(e.to_string()))?;
let client = Client::new();
let response = client
.put(upload_url)
.header(
"Content-Range",
format!("bytes 0-{}/{}", buffer.len() - 1, buffer.len()),
)
.header("Content-Type", "video/mp4")
.body(buffer)
.send()
.await
.map_err(|e| TikTokApiError::RequestFailed(e.to_string()))?;
if response.status().is_success() {
Ok(())
} else {
let body = response
.text()
.await
.map_err(|e| TikTokApiError::ResponseReadFailed(e.to_string()))?;
let error_response: ErrorResponse = serde_json::from_str(&body)
.map_err(|e| TikTokApiError::ParseFailed(e.to_string()))?;
Err(TikTokApiError::from(error_response))
}
}
/// Retrieves the status of a post using the publish ID.
///
/// # Arguments
///
/// * `token` - The API token.
/// * `publish_id` - The ID of the post whose status is to be retrieved.
///
/// # Returns
///
/// * `Result<PostStatusData, TikTokApiError>` - The status data or an error.
pub async fn get_post_status(
&self,
token: &str,
publish_id: &str,
) -> Result<PostStatusData, TikTokApiError> {
let url = format!("{}/v2/post/publish/status/fetch/", self.base_url);
let client = Client::new();
let response = client
.post(&url)
.header("Authorization", format!("Bearer {}", token))
.header("Content-Type", "application/json; charset=UTF-8")
.json(&json!({ "publish_id": publish_id }))
.send()
.await
.map_err(|e| TikTokApiError::RequestFailed(e.to_string()))?;
let status = response.status();
let body = response
.text()
.await
.map_err(|e| TikTokApiError::ResponseReadFailed(e.to_string()))?;
let post_status_response: PostStatusResponse =
serde_json::from_str(&body).map_err(|e| TikTokApiError::ParseFailed(e.to_string()))?;
if status.is_success() && post_status_response.error.code == "ok" {
Ok(post_status_response.data)
} else {
Err(TikTokApiError::from(post_status_response.error))
}
}
/// Simplified function to upload a video from a file.
///
/// This function combines the steps of initializing a video post, uploading the video file,
/// and checking the post status into a single function call.
///
/// # Arguments
///
/// * `token` - The API token.
/// * `post_info` - The post information.
/// * `file_path` - The path to the video file on the local filesystem.
/// * `video_size` - The size of the video file in bytes.
/// * `chunk_size` - The size of each chunk to be uploaded in bytes.
/// * `total_chunk_count` - The total number of chunks to be uploaded.
///
/// # Returns
///
/// * `Result<PostStatusData, TikTokApiError>` - The status data or an error.
pub async fn upload_video_from_file(
&self,
token: &str,
post_info: PostInfo,
file_path: &str,
video_size: u64,
chunk_size: u64,
total_chunk_count: u32,
) -> Result<PostStatusData, TikTokApiError> {
let source_info = SourceInfoBuilder::default()
.source(Source::FileUpload)
.video_size(Some(video_size))
.chunk_size(Some(chunk_size))
.total_chunk_count(Some(total_chunk_count))
.build()
.unwrap();
let video_init_request = VideoInitRequestBuilder::default()
.post_info(post_info)
.source_info(source_info)
.build()
.unwrap();
// Call the post_video function
let response_data = self.post_video(token, video_init_request).await?;
// Upload the video file
if let Some(upload_url) = response_data.upload_url {
self.upload_video(&upload_url, file_path).await?;
}
// Check the post status
self.get_post_status(token, &response_data.publish_id).await
}
/// Simplified function to upload a video from a URL.
///
/// This function combines the steps of initializing a video post and checking the post status
/// into a single function call.
///
/// # Arguments
///
/// * `token` - The API token.
/// * `post_info` - The post information.
/// * `video_url` - The URL of the video to be uploaded.
///
/// # Returns
///
/// * `Result<PostStatusData, TikTokApiError>` - The status data or an error.
pub async fn upload_video_from_url(
&self,
token: &str,
post_info: PostInfo,
video_url: &str,
) -> Result<PostStatusData, TikTokApiError> {
// Create SourceInfo for PULL_FROM_URL
let source_info = SourceInfoBuilder::default()
.source(Source::PullFromUrl)
.video_url(Some(video_url.to_string()))
.build()
.unwrap();
// Create VideoInitRequest using the generated builder
let video_init_request = VideoInitRequestBuilder::default()
.post_info(post_info)
.source_info(source_info)
.build()
.unwrap();
// Call the post_video function
let response_data = self.post_video(token, video_init_request).await?;
// Check the post status
self.get_post_status(token, &response_data.publish_id).await
}
/// Initializes a photo post on TikTok.
///
/// # Arguments
///
/// * `token` - The API token.
/// * `photo_init_request` - The request data for initializing the photo post.
///
/// # Returns
///
/// * `Result<VideoInitResponseData, TikTokApiError>` - The response data or an error.
pub async fn post_photo(
&self,
token: &str,
photo_init_request: PhotoInitRequest,
) -> Result<VideoInitResponseData, TikTokApiError> {
let url = format!("{}/v2/post/publish/content/init/", self.base_url);
let client = Client::new();
let response = client
.post(&url)
.header("Authorization", format!("Bearer {}", token))
.header("Content-Type", "application/json; charset=UTF-8")
.json(&photo_init_request)
.send()
.await
.map_err(|e| TikTokApiError::RequestFailed(e.to_string()))?;
let status = response.status();
let body = response
.text()
.await
.map_err(|e| TikTokApiError::ResponseReadFailed(e.to_string()))?;
let photo_init_response: VideoInitResponse =
serde_json::from_str(&body).map_err(|e| TikTokApiError::ParseFailed(e.to_string()))?;
if status.is_success() && photo_init_response.error.code == "ok" {
Ok(photo_init_response.data)
} else {
Err(TikTokApiError::from(photo_init_response.error))
}
}
/// Simplified function to upload a photo from URLs.
///
/// This function combines the steps of initializing a photo post and checking the post status
/// into a single function call.
///
/// The first photo will be the cover
///
/// # Arguments
///
/// * `token` - The API token.
/// * `post_info` - The post information.
/// * `photo_urls` - The URLs of the photos to be uploaded.
///
/// # Returns
///
/// * `Result<PostStatusData, TikTokApiError>` - The status data or an error.
pub async fn upload_photo_from_urls(
&self,
token: &str,
post_info: PostInfo,
photo_urls: Vec<String>,
) -> Result<PostStatusData, TikTokApiError> {
// Create SourceInfo for PULL_FROM_URL
let source_info = SourceInfoBuilder::default()
.source(Source::PullFromUrl)
.photo_images(Some(photo_urls))
.photo_cover_index(Some(1)) // Assuming the first photo is the cover
.build()
.unwrap();
// Create PhotoInitRequest using the generated builder
let photo_init_request = PhotoInitRequestBuilder::default()
.post_info(post_info)
.source_info(source_info)
.post_mode(PostMode::DirectPost)
.media_type(MediaType::Photo)
.build()
.unwrap();
// Call the post_photo function
let response_data = self.post_photo(token, photo_init_request).await?;
// Check the post status
self.get_post_status(token, &response_data.publish_id).await
}
}