auto-archiver/archivers/tiktok_archiver.py

65 wiersze
2.2 KiB
Python
Czysty Zwykły widok Historia

2022-02-21 13:19:09 +00:00
import os, traceback
import tiktok_downloader
from loguru import logger
from .base_archiver import Archiver, ArchiveResult
2022-05-09 15:45:54 +00:00
from storages import Storage
2022-02-21 13:19:09 +00:00
class TiktokArchiver(Archiver):
name = "tiktok"
2022-02-21 13:19:09 +00:00
def download(self, url, check_if_exists=False):
if 'tiktok.com' not in url:
return False
status = 'success'
try:
info = tiktok_downloader.info_post(url)
key = self.get_key(f'{info.id}.mp4')
2022-02-23 08:54:03 +00:00
cdn_url = self.storage.get_cdn_url(key)
2022-05-09 15:45:54 +00:00
filename = Storage.TMP_FOLDER + key
2022-02-21 13:19:09 +00:00
if check_if_exists and self.storage.exists(key):
status = 'already archived'
2022-02-21 13:19:09 +00:00
media = tiktok_downloader.snaptik(url).get_media()
2022-02-21 13:19:09 +00:00
if len(media) <= 0:
if status == 'already archived':
return ArchiveResult(status='Could not download media, but already archived', cdn_url=cdn_url)
else:
return ArchiveResult(status='Could not download media')
2022-02-21 13:19:09 +00:00
media[0].download(filename)
2022-02-21 13:19:09 +00:00
if status != 'already archived':
self.storage.upload(filename, key)
2022-02-21 13:19:09 +00:00
try:
2022-02-23 15:07:58 +00:00
key_thumb, thumb_index = self.get_thumbnails(filename, key, duration=info.duration)
except Exception as e:
logger.error(e)
2022-02-21 13:19:09 +00:00
key_thumb = ''
thumb_index = 'error creating thumbnails'
hash = self.get_hash(filename)
screenshot = self.get_screenshot(url)
2022-02-21 13:19:09 +00:00
try: os.remove(filename)
except FileNotFoundError:
logger.info(f'tmp file not found thus not deleted {filename}')
return ArchiveResult(status=status, cdn_url=cdn_url, thumbnail=key_thumb,
thumbnail_index=thumb_index, duration=info.duration, title=info.caption, timestamp=info.create.isoformat(),
hash=hash, screenshot=screenshot)
2022-02-21 13:19:09 +00:00
except tiktok_downloader.Except.InvalidUrl:
status = 'Invalid URL'
return ArchiveResult(status=status)
except:
error = traceback.format_exc()
status = 'Other Tiktok error: ' + str(error)
return ArchiveResult(status=status)