auto-archiver/auto_archive.py

124 wiersze
4.0 KiB
Python
Czysty Zwykły widok Historia

import os
2022-02-21 13:19:09 +00:00
import datetime
import argparse
import requests
2022-02-21 13:19:09 +00:00
import gspread
from loguru import logger
2022-02-21 13:19:09 +00:00
from dotenv import load_dotenv
import archivers
from storages import S3Storage, S3Config
2022-02-23 08:54:03 +00:00
from gworksheet import GWorksheet
load_dotenv()
2021-05-03 12:16:09 +00:00
2022-02-23 08:54:03 +00:00
def update_sheet(gw, row, result: archivers.ArchiveResult):
update = []
2021-05-03 12:16:09 +00:00
2022-02-23 08:54:03 +00:00
def batch_if_valid(col, val, final_value=None):
final_value = final_value or val
if val and gw.col_exists(col) and gw.cell(row, col) == '':
update.append((row, col, final_value))
2021-03-18 10:03:13 +00:00
2022-02-23 08:54:03 +00:00
update.append((row, 'status', result.status))
2021-03-15 09:08:02 +00:00
2022-02-23 08:54:03 +00:00
batch_if_valid('archive', result.cdn_url)
batch_if_valid('archive', True, datetime.datetime.now().isoformat())
batch_if_valid('thumbnail', result.thumbnail, f'=IMAGE("{result.thumbnail}")')
batch_if_valid('thumbnail_index', result.thumbnail_index)
batch_if_valid('title', result.title)
batch_if_valid('duration', result.duration, str(result.duration))
2022-02-23 08:54:03 +00:00
if result.timestamp and type(result.timestamp) != str:
result.timestamp = datetime.datetime.fromtimestamp(result.timestamp).isoformat()
batch_if_valid('timestamp', result.timestamp)
2021-03-15 09:08:02 +00:00
2022-02-23 08:54:03 +00:00
gw.update_batch(update)
2021-03-15 09:08:02 +00:00
2021-06-01 09:00:40 +00:00
2021-03-25 12:42:42 +00:00
def process_sheet(sheet):
2021-06-01 09:05:13 +00:00
gc = gspread.service_account(filename='service_account.json')
2021-03-25 12:42:42 +00:00
sh = gc.open(sheet)
s3_config = S3Config(
bucket=os.getenv('DO_BUCKET'),
region=os.getenv('DO_SPACES_REGION'),
key=os.getenv('DO_SPACES_KEY'),
secret=os.getenv('DO_SPACES_SECRET')
)
# loop through worksheets to check
for ii, wks in enumerate(sh.worksheets()):
logger.info(f'Opening worksheet {ii}: "{wks.title}"')
2022-02-23 08:54:03 +00:00
gw = GWorksheet(wks)
2021-03-15 09:08:02 +00:00
2022-02-23 08:57:04 +00:00
if not gw.col_exists('url'):
logger.warning(f'No "Media URL" column found, skipping worksheet {wks.title}')
2021-03-25 12:42:42 +00:00
continue
2022-02-23 08:57:04 +00:00
if not gw.col_exists('status'):
logger.warning("No 'Archive status' column found, skipping")
2021-03-25 12:42:42 +00:00
continue
# archives will be in a folder 'doc_name/worksheet_name'
s3_config.folder = f'{sheet}/{wks.title}/'
s3_client = S3Storage(s3_config)
2022-02-21 13:19:09 +00:00
# order matters, first to succeed excludes remaining
active_archivers = [
archivers.TelegramArchiver(s3_client),
archivers.TiktokArchiver(s3_client),
archivers.YoutubeDLArchiver(s3_client),
archivers.WaybackArchiver(s3_client)
]
# loop through rows in worksheet
2022-02-23 08:54:03 +00:00
for i in range(2, gw.count_rows() + 1):
row = gw.get_row(i)
url = gw.cell(row, 'url')
status = gw.cell(row, 'status')
if url != '' and status in ['', None]:
gw.update(i, 'status', 'Archive in progress')
# expand short URL links
if 'https://t.co/' in url:
r = requests.get(url)
url = r.url
for archiver in active_archivers:
logger.debug(f'Trying {archiver} on row {i}')
2022-02-23 08:57:44 +00:00
# TODO: add support for multiple videos/images
2022-02-23 08:54:03 +00:00
result = archiver.download(url, check_if_exists=True)
if result:
2022-02-23 08:54:03 +00:00
logger.success(f'{archiver} succeeded on row {i}')
break
if result:
update_sheet(gw, i, result)
else:
gw.update(i, 'status', 'failed: no archiver')
2022-02-23 08:54:03 +00:00
# # except:
# # if any unexpected errors occured, log these into the Google Sheet
# # t, value, traceback = sys.exc_info()
2022-02-23 08:54:03 +00:00
# # update_sheet(wks, i, str(
# # value), {}, columns, v)
2021-03-15 09:08:02 +00:00
2021-03-25 12:42:42 +00:00
def main():
parser = argparse.ArgumentParser(
2022-02-23 08:57:04 +00:00
description='Automatically archive social media videos from a Google Sheets document')
parser.add_argument('--sheet', action='store', dest='sheet')
2021-03-25 12:42:42 +00:00
args = parser.parse_args()
2022-02-23 08:57:04 +00:00
logger.info(f'Opening document {args.sheet}')
2021-03-25 12:42:42 +00:00
process_sheet(args.sheet)
2021-03-15 09:08:02 +00:00
2021-06-01 09:00:40 +00:00
2022-02-23 08:57:04 +00:00
if __name__ == '__main__':
main()