#!/usr/bin/python # import requests import sys import magic import time import string import random import mimetypes import logging import config from glob import glob # logging.basicConfig(filename='mau.log',level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # Set up log file and level logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') message = sys.argv[1] description = sys.argv[2] visibility = sys.argv[3] pics_path = sys.argv[4] def get_pics(): imgfiles = [] for file in glob(f'{pics_path}/*.jpg'): imgfiles.append(file) for file in glob(f'{pics_path}/*.png'): imgfiles.append(file) logging.debug(f'{imgfiles}') return imgfiles def do_upload(msg, media_ids): logging.info(f'Posting to Mastodon...') auth_data = f'\"Bearer {config.access_token}' response = requests.post(f'{config.instance_url}/api/v1/statuses', params={'status': msg, 'media_ids[]': media_ids}, headers={'Authorization': auth_data, 'visibility': 'public'}) json_response = response.json() def img_upload(description, media_info): # Upload the image, return the media id logging.info(f'Uploading image {media_info}') auth_data = f'\"Bearer {config.access_token}' response = requests.post(f'{config.instance_url}/api/v2/media', files={'file': media_info}, params={'description': description}, headers={'Authorization': auth_data}) json_response = response.json() id = json_response['id'] logging.debug(f'{id}') return id def guess_type(media_file): # Get the mime type of the file mime_type = None try: mime_type = magic.from_file(media_file, mime=True) except AttributeError: mime_type = mimetypes.guess_type(media_file)[0] logging.debug(f'It looks like this is a {mime_type}.') return mime_type media_ids = [] for image in get_pics(): mime_type = guess_type(image) # Get the mime type random_suffix = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) # Create a random suffix for our file name so we don't upload the same file name more than once file_name = "mau_upload_" + str(time.time()) + "_" + str(random_suffix) + mimetypes.guess_extension(mime_type) info = (file_name, open(image, 'rb'), mime_type) # Get the image, and create multipart form data logging.info(f'{image}...\n') media_id = img_upload(description,info) # Upload the image, get the id media_ids.append(media_id) # Append to the media_ids list logging.info(f'Current list: {media_ids}') logging.info(f'Pausing, so the server has time to process the image\n') time.sleep(10) if len(sys.argv) < 5: print('Usage: python mau.py \"\" \"\" \"\" \"