@xbibzlibrary/tiktokscrap
Version:
Powerful TikTok Scraper and Downloader Library
108 lines (83 loc) • 3.21 kB
text/typescript
import BaseScraper from './base';
import { TikTokVideo, TikTokScrapOptions, TikTokScrapResult } from '../types';
import { ValidationError, NotFoundError } from '../errors';
export class VideoScraper extends BaseScraper {
constructor(options: TikTokScrapOptions = {}) {
super(options);
}
public async getVideoByUrl(url: string): Promise<TikTokScrapResult<TikTokVideo>> {
return this.executeRequest(async () => {
if (!this.validator.validateTikTokUrl(url)) {
throw new ValidationError('Invalid TikTok URL');
}
const videoId = this.extractVideoIdFromUrl(url);
if (!videoId) {
throw new ValidationError('Could not extract video ID from URL');
}
return this.getVideoById(videoId);
}, `Get video by URL: ${url}`);
}
public async getVideoById(id: string): Promise<TikTokVideo> {
this.validator.validateId(id);
const url = this.buildUrl('https://www.tiktok.com', `//video/${id}`);
const response = await this.http.get(url);
if (response.status !== 200) {
throw new NotFoundError('Video not found');
}
return this.parser.parseVideoData(response.data);
}
public async getVideoTrends(count: number = 20): Promise<TikTokScrapResult<TikTokVideo[]>> {
return this.executeRequest(async () => {
if (count <= 0 || count > 100) {
throw new ValidationError('Count must be between 1 and 100');
}
const url = this.buildUrl('https://www.tiktok.com', '/api/item_list/', {
count,
id: 1,
type: 5,
secUid: '',
maxCursor: 0,
minCursor: 0,
retryType: 0,
isWeb: 1
});
const response = await this.http.get(url);
if (response.status !== 200) {
throw new NotFoundError('Could not fetch trending videos');
}
const data = response.data;
if (!data.body || !data.body.itemListData) {
return [];
}
return data.body.itemListData.map((item: any) => this.parser.parseVideoObject(item));
}, `Get trending videos: ${count}`);
}
public async getRecommendedVideos(videoId: string, count: number = 10): Promise<TikTokScrapResult<TikTokVideo[]>> {
return this.executeRequest(async () => {
this.validator.validateId(videoId);
if (count <= 0 || count > 50) {
throw new ValidationError('Count must be between 1 and 50');
}
const url = this.buildUrl('https://www.tiktok.com', '/api/recommend/item_list/', {
count,
id: videoId,
type: 0,
secUid: '',
maxCursor: 0,
minCursor: 0,
retryType: 0,
isWeb: 1
});
const response = await this.http.get(url);
if (response.status !== 200) {
throw new NotFoundError('Could not fetch recommended videos');
}
const data = response.data;
if (!data.body || !data.body.itemListData) {
return [];
}
return data.body.itemListData.map((item: any) => this.parser.parseVideoObject(item));
}, `Get recommended videos for ${videoId}: ${count}`);
}
}
export default VideoScraper;