#!/usr/bin/python3 from datetime import datetime as dt from lib.setup import import_config_file from lib.authentication import authenticate_nextcloud def setup_archive_data(config, timestamp): """ Set up the data necessary for media archival to Nextcloud Arguments: config {dict} -- Configuration dictionary object timestamp {str} -- String describing the timestamp of the tweet Returns: obj -- WebDAV client object str -- String formatted date timestamp str -- String formatted time timestamp """ if(config['webdav_hostname'] and config['webdav_login'] and config['webdav_password']): client = authenticate_nextcloud(config) else: print('Nextcloud WebDAV information missing/incomplete, skipping...') return ts = dt.fromtimestamp(int(int(timestamp)/1000)) date_ts = ts.strftime('%Y_%m_%d') time_ts = ts.strftime('%H_%M_%S') return client, date_ts, time_ts def setup_archive_dir(client, upload_path, date_ts): """ Set up Nextcloud directory path for file upload Arguments: client {obj} -- WebDAV client object upload_path {str} -- Intended path to set up directories for upload archival date_ts {str} -- String formatted date timestamp """ if(not client.check(upload_path)): client.mkdir(f'{upload_path}') client.mkdir(f'{upload_path}/{date_ts}') else: if(not client.check(f'{upload_path}/{date_ts}')): client.mkdir(f'{upload_path}/{date_ts}') def attempt_upload_media(client, upload_dir, upload_filename, upload_filetype, archive_filename): """ Attempt to upload archived media to Nextcloud with WebDAV client Arguments: client {obj} -- WebDAV client object upload_dir {str} -- String formatted directory path for Nextcloud archival upload_filename {str} -- String formatted filename for Nextcloud archival upload_filetype {str} -- File extension of archived media archive_filename {str} -- String formatted filename of the local archive """ file_dne = True count = 1 while(file_dne): temp_filename = f'{upload_dir}/{upload_filename}_{count}.{upload_filetype}' if(not client.check(temp_filename)): client.upload_file(temp_filename, f'{archive_filename}') file_dne = False else: count += 1 def nextcloud_upload_media(config, upload_path, archive_filename, timestamp): """ Upload archived media file to Nextcloud with WebDAV client Arguments: config {obj} -- Configuration dictionary object upload_path {str} -- Nextcloud upload directory path archive_filename {str} -- String formatted filename of the local archive timestamp {str} -- String describing the timestamp of the tweet """ client, date_ts, time_ts = setup_archive_data(config, timestamp) setup_archive_dir(client, upload_path, date_ts) attempt_upload_media(client, f'{upload_path}/{date_ts}', f'{date_ts}_{time_ts}', f'{archive_filename.split(".")[1]}', f'data/{archive_filename}')