PixelfedImporter/PixelfedImporter.py

201 lines
5.8 KiB
Python
Raw Normal View History

2023-10-29 03:25:04 +01:00
import os
import json
import requests
import glob
import exifread
2023-11-01 16:09:32 +01:00
from PIL import Image
2023-10-29 03:25:04 +01:00
from PIL.ExifTags import TAGS
from PIL.PngImagePlugin import PngImageFile, PngInfo
2023-11-01 16:09:32 +01:00
def confirm():
confirmMsg = input("[y]es or [n]o ")
if confirmMsg == 'y' or confirmMsg == 'yes':
return True
elif confirmMsg == 'n' or confirmMsg == 'no':
return False
else:
print("\n Invalid Option. Please Enter a Valid Option.")
return confirm()
return False
2023-10-29 03:25:04 +01:00
def load_config(file_path):
with open(file_path, "r") as config_file:
config_data = json.load(config_file)
return config_data
def getTags(file_path):
try:
file = open(file_path,'r')
fileContent = file.read()
file.close
except:
fileContent = ''
return fileContent
def getImages(dir):
result = glob.glob(dir + '/*.jpg')
return result
def getItemDescription(filename):
2023-11-01 16:09:32 +01:00
img = Image.open(filename)
exif_data = img._getexif()
imageDescription = ""
if exif_data:
for tag, value in exif_data.items():
tag_name = TAGS.get(tag, tag)
if tag_name == "ImageDescription":
imageDescription = value
else:
imageDescription = "This image has no description. Please let me know so that I can update it."
else:
raise ValueError("No EXIF data found.")
return imageDescription
2023-10-29 03:25:04 +01:00
2023-11-01 16:09:32 +01:00
def getPostText(filename):
postText = ""
tags = getTags("tags.txt")
date = ""
cam = ""
title = ""
img = Image.open(filename)
exif_data = img._getexif()
if exif_data:
for tag, value in exif_data.items():
tag_name = TAGS.get(tag, tag)
if tag_name == "DateTimeOriginal":
dateTime = value
year = dateTime[:4]
month = dateTime[5:7]
date = "🗓 " + year + "-" + month
if tag_name == "Make":
cam += "📸 " + value
if cam != "" and tag_name == "Model":
cam += " " + value
if tag_name == "Object Name":
title = value
else:
raise ValueError("No EXIF data found.")
if date != "":
postText = date
if cam != "":
if postText != "":
postText += " || "
postText += cam
if title != "":
postText += "\n\r\n\r" + title
elif title == "":
print(f"No post Text found. Do you want to add a post text for file " + os.path.basename(filename) + "?")
if confirm():
ownPostText = input("Post text:")
ownPostText.encode('utf-8')
postText += "\n\r\n\r" + ownPostText
postText += "\n\r\n\r" + tags
return postText
def mediaUpload(access_token, url, file, itemDescription):
2023-10-29 03:25:04 +01:00
api_url = url + "/api/v1/media"
headers = {
"Authorization": f"Bearer {access_token}"
}
try:
with open(file, "rb") as imageFile:
2023-11-01 16:09:32 +01:00
f = {
"file": (file, imageFile)
}
2023-10-30 12:45:37 +01:00
data = {
2023-11-01 16:09:32 +01:00
"description": itemDescription.encode('utf-8')
2023-10-30 12:45:37 +01:00
}
2023-11-01 16:09:32 +01:00
response = requests.post(api_url, headers=headers, files=f, data=data)
response.raise_for_status()
2023-10-29 03:25:04 +01:00
try:
data = response.json()
return(data)
except json.decoder.JSONDecodeError:
print("API response contains non-valid JSON data:")
print(response.text)
except requests.exceptions.RequestException as e:
print(f"An error occurred during the API call: {e}")
def createNewPost(access_token, url, ImageID, ImageDescription):
api_url = url + "/api/v1/statuses"
ImageIDs = ImageID.split(",")
ImageIDsInt = list(map(int, ImageIDs))
headers = {
"Authorization": f"Bearer {access_token}"
}
data = {
"status": ImageDescription,
"media_ids": ImageIDsInt
}
try:
response = requests.post(api_url, headers=headers, json=data)
try:
responsedata = response.json()
return(responsedata)
except json.decoder.JSONDecodeError:
print("API response contains non-valid JSON data:")
print(response.text)
except requests.exceptions.RequestException as e:
print(f"An error occurred during the API call: {e}")
def sendImages(Token, url, imagedir, uploadType, deleteFile):
2023-10-29 03:25:04 +01:00
files = getImages(imagedir)
if not files:
raise ValueError("No file found.")
2023-11-01 16:09:32 +01:00
postText = ""
2023-10-29 03:25:04 +01:00
newFileID = ""
2023-11-01 16:09:32 +01:00
itemDescription = ""
postText = ""
2023-10-29 03:25:04 +01:00
for f in files:
2023-11-01 16:09:32 +01:00
itemDescription = getItemDescription(f)
newFile = mediaUpload(Token, url, f, itemDescription)
2023-10-29 03:25:04 +01:00
if uploadType == 0:
2023-11-01 16:09:32 +01:00
postText = getPostText(f)
2023-10-29 03:25:04 +01:00
newFileID = newFile.get("id")
2023-11-01 16:09:32 +01:00
createNewPost(Token, url, newFileID, postText)
2023-10-29 03:25:04 +01:00
else:
2023-11-01 16:09:32 +01:00
if postText == "":
postText = getPostText(f)
2023-10-29 03:25:04 +01:00
if newFileID != "":
newFileID = newFileID + "," + newFile.get("id")
else:
newFileID = newFile.get("id")
if uploadType == 1:
2023-11-01 16:09:32 +01:00
createNewPost(Token, url, newFileID, postText)
if deleteFile:
for f in files:
if os.path.exists(f):
os.remove(f)
2023-11-01 16:09:32 +01:00
2023-10-29 03:25:04 +01:00
return True
if __name__ == "__main__":
config_file_path = "config.json"
config = load_config(config_file_path)
url = config.get("server_url")
accessToken = config.get("access_token")
imagedir = config.get("image_path")
uploadType = config.get("upload_type")
deleteFile = config.get("delete_file")
try:
sendImages(accessToken, url, imagedir, uploadType, deleteFile)
except ValueError as e:
print(f"Error while uploading the image: {e}")