Snake case

merge-requests/30/head
Bob Mottram 2021-12-26 14:42:21 +00:00
parent 47e648e516
commit 1c62dcd906
5 changed files with 67 additions and 67 deletions

View File

@ -90,13 +90,13 @@ def replaceTwitter(post_json_object: {}, replacementDomain: str,
replacementDomain, system_language) replacementDomain, system_language)
def _removeMetaData(imageFilename: str, outputFilename: str) -> None: def _removeMetaData(image_filename: str, outputFilename: str) -> None:
"""Attempts to do this with pure python didn't work well, """Attempts to do this with pure python didn't work well,
so better to use a dedicated tool if one is installed so better to use a dedicated tool if one is installed
""" """
copyfile(imageFilename, outputFilename) copyfile(image_filename, outputFilename)
if not os.path.isfile(outputFilename): if not os.path.isfile(outputFilename):
print('ERROR: unable to remove metadata from ' + imageFilename) print('ERROR: unable to remove metadata from ' + image_filename)
return return
if os.path.isfile('/usr/bin/exiftool'): if os.path.isfile('/usr/bin/exiftool'):
print('Removing metadata from ' + outputFilename + ' using exiftool') print('Removing metadata from ' + outputFilename + ' using exiftool')
@ -160,10 +160,10 @@ def _spoofMetaData(base_dir: str, nickname: str, domain: str,
return return
def convertImageToLowBandwidth(imageFilename: str) -> None: def convertImageToLowBandwidth(image_filename: str) -> None:
"""Converts an image to a low bandwidth version """Converts an image to a low bandwidth version
""" """
low_bandwidthFilename = imageFilename + '.low' low_bandwidthFilename = image_filename + '.low'
if os.path.isfile(low_bandwidthFilename): if os.path.isfile(low_bandwidthFilename):
try: try:
os.remove(low_bandwidthFilename) os.remove(low_bandwidthFilename)
@ -174,7 +174,7 @@ def convertImageToLowBandwidth(imageFilename: str) -> None:
cmd = \ cmd = \
'/usr/bin/convert +noise Multiplicative ' + \ '/usr/bin/convert +noise Multiplicative ' + \
'-evaluate median 10% -dither Floyd-Steinberg ' + \ '-evaluate median 10% -dither Floyd-Steinberg ' + \
'-monochrome ' + imageFilename + ' ' + low_bandwidthFilename '-monochrome ' + image_filename + ' ' + low_bandwidthFilename
print('Low bandwidth image conversion: ' + cmd) print('Low bandwidth image conversion: ' + cmd)
subprocess.call(cmd, shell=True) subprocess.call(cmd, shell=True)
# wait for conversion to happen # wait for conversion to happen
@ -188,43 +188,43 @@ def convertImageToLowBandwidth(imageFilename: str) -> None:
break break
if os.path.isfile(low_bandwidthFilename): if os.path.isfile(low_bandwidthFilename):
try: try:
os.remove(imageFilename) os.remove(image_filename)
except OSError: except OSError:
print('EX: convertImageToLowBandwidth unable to delete ' + print('EX: convertImageToLowBandwidth unable to delete ' +
imageFilename) image_filename)
os.rename(low_bandwidthFilename, imageFilename) os.rename(low_bandwidthFilename, image_filename)
if os.path.isfile(imageFilename): if os.path.isfile(image_filename):
print('Image converted to low bandwidth ' + imageFilename) print('Image converted to low bandwidth ' + image_filename)
else: else:
print('Low bandwidth converted image not found: ' + print('Low bandwidth converted image not found: ' +
low_bandwidthFilename) low_bandwidthFilename)
def processMetaData(base_dir: str, nickname: str, domain: str, def processMetaData(base_dir: str, nickname: str, domain: str,
imageFilename: str, outputFilename: str, image_filename: str, outputFilename: str,
city: str, content_license_url: str) -> None: city: str, content_license_url: str) -> None:
"""Handles image metadata. This tries to spoof the metadata """Handles image metadata. This tries to spoof the metadata
if possible, but otherwise just removes it if possible, but otherwise just removes it
""" """
# first remove the metadata # first remove the metadata
_removeMetaData(imageFilename, outputFilename) _removeMetaData(image_filename, outputFilename)
# now add some spoofed data to misdirect surveillance capitalists # now add some spoofed data to misdirect surveillance capitalists
_spoofMetaData(base_dir, nickname, domain, outputFilename, city, _spoofMetaData(base_dir, nickname, domain, outputFilename, city,
content_license_url) content_license_url)
def _isMedia(imageFilename: str) -> bool: def _isMedia(image_filename: str) -> bool:
"""Is the given file a media file? """Is the given file a media file?
""" """
if not os.path.isfile(imageFilename): if not os.path.isfile(image_filename):
print('WARN: Media file does not exist ' + imageFilename) print('WARN: Media file does not exist ' + image_filename)
return False return False
permittedMedia = get_media_extensions() permittedMedia = get_media_extensions()
for m in permittedMedia: for m in permittedMedia:
if imageFilename.endswith('.' + m): if image_filename.endswith('.' + m):
return True return True
print('WARN: ' + imageFilename + ' is not a permitted media type') print('WARN: ' + image_filename + ' is not a permitted media type')
return False return False
@ -295,20 +295,20 @@ def _updateEtag(mediaFilename: str) -> None:
def attachMedia(base_dir: str, http_prefix: str, def attachMedia(base_dir: str, http_prefix: str,
nickname: str, domain: str, port: int, nickname: str, domain: str, port: int,
postJson: {}, imageFilename: str, postJson: {}, image_filename: str,
mediaType: str, description: str, mediaType: str, description: str,
city: str, low_bandwidth: bool, city: str, low_bandwidth: bool,
content_license_url: str) -> {}: content_license_url: str) -> {}:
"""Attaches media to a json object post """Attaches media to a json object post
The description can be None The description can be None
""" """
if not _isMedia(imageFilename): if not _isMedia(image_filename):
return postJson return postJson
fileExtension = None fileExtension = None
acceptedTypes = get_media_extensions() acceptedTypes = get_media_extensions()
for mType in acceptedTypes: for mType in acceptedTypes:
if imageFilename.endswith('.' + mType): if image_filename.endswith('.' + mType):
if mType == 'jpg': if mType == 'jpg':
mType = 'jpeg' mType = 'jpeg'
if mType == 'mp3': if mType == 'mp3':
@ -344,7 +344,7 @@ def attachMedia(base_dir: str, http_prefix: str,
attachmentJson['blurhash'] = _getBlurHash() attachmentJson['blurhash'] = _getBlurHash()
# find the dimensions of the image and add them as metadata # find the dimensions of the image and add them as metadata
attachImageWidth, attachImageHeight = \ attachImageWidth, attachImageHeight = \
getImageDimensions(imageFilename) getImageDimensions(image_filename)
if attachImageWidth and attachImageHeight: if attachImageWidth and attachImageHeight:
attachmentJson['width'] = attachImageWidth attachmentJson['width'] = attachImageWidth
attachmentJson['height'] = attachImageHeight attachmentJson['height'] = attachImageHeight
@ -354,12 +354,12 @@ def attachMedia(base_dir: str, http_prefix: str,
if base_dir: if base_dir:
if mediaType.startswith('image/'): if mediaType.startswith('image/'):
if low_bandwidth: if low_bandwidth:
convertImageToLowBandwidth(imageFilename) convertImageToLowBandwidth(image_filename)
processMetaData(base_dir, nickname, domain, processMetaData(base_dir, nickname, domain,
imageFilename, mediaFilename, city, image_filename, mediaFilename, city,
content_license_url) content_license_url)
else: else:
copyfile(imageFilename, mediaFilename) copyfile(image_filename, mediaFilename)
_updateEtag(mediaFilename) _updateEtag(mediaFilename)
return postJson return postJson
@ -408,12 +408,12 @@ def pathIsAudio(path: str) -> bool:
return False return False
def getImageDimensions(imageFilename: str) -> (int, int): def getImageDimensions(image_filename: str) -> (int, int):
"""Returns the dimensions of an image file """Returns the dimensions of an image file
""" """
try: try:
result = subprocess.run(['identify', '-format', '"%wx%h"', result = subprocess.run(['identify', '-format', '"%wx%h"',
imageFilename], stdout=subprocess.PIPE) image_filename], stdout=subprocess.PIPE)
except BaseException: except BaseException:
print('EX: getImageDimensions unable to run identify command') print('EX: getImageDimensions unable to run identify command')
return None, None return None, None

View File

@ -93,19 +93,19 @@ def generateRSAKey() -> (str, str):
def setProfileImage(base_dir: str, http_prefix: str, def setProfileImage(base_dir: str, http_prefix: str,
nickname: str, domain: str, nickname: str, domain: str,
port: int, imageFilename: str, imageType: str, port: int, image_filename: str, imageType: str,
resolution: str, city: str, resolution: str, city: str,
content_license_url: str) -> bool: content_license_url: str) -> bool:
"""Saves the given image file as an avatar or background """Saves the given image file as an avatar or background
image for the given person image for the given person
""" """
imageFilename = imageFilename.replace('\n', '').replace('\r', '') image_filename = image_filename.replace('\n', '').replace('\r', '')
if not isImageFile(imageFilename): if not isImageFile(image_filename):
print('Profile image must be png, jpg, gif or svg format') print('Profile image must be png, jpg, gif or svg format')
return False return False
if imageFilename.startswith('~/'): if image_filename.startswith('~/'):
imageFilename = imageFilename.replace('~/', str(Path.home()) + '/') image_filename = image_filename.replace('~/', str(Path.home()) + '/')
domain = removeDomainPort(domain) domain = removeDomainPort(domain)
fullDomain = get_full_domain(domain, port) fullDomain = get_full_domain(domain, port)
@ -127,20 +127,20 @@ def setProfileImage(base_dir: str, http_prefix: str,
mediaType = 'image/png' mediaType = 'image/png'
iconFilename = iconFilenameBase + '.png' iconFilename = iconFilenameBase + '.png'
if imageFilename.endswith('.jpg') or \ if image_filename.endswith('.jpg') or \
imageFilename.endswith('.jpeg'): image_filename.endswith('.jpeg'):
mediaType = 'image/jpeg' mediaType = 'image/jpeg'
iconFilename = iconFilenameBase + '.jpg' iconFilename = iconFilenameBase + '.jpg'
elif imageFilename.endswith('.gif'): elif image_filename.endswith('.gif'):
mediaType = 'image/gif' mediaType = 'image/gif'
iconFilename = iconFilenameBase + '.gif' iconFilename = iconFilenameBase + '.gif'
elif imageFilename.endswith('.webp'): elif image_filename.endswith('.webp'):
mediaType = 'image/webp' mediaType = 'image/webp'
iconFilename = iconFilenameBase + '.webp' iconFilename = iconFilenameBase + '.webp'
elif imageFilename.endswith('.avif'): elif image_filename.endswith('.avif'):
mediaType = 'image/avif' mediaType = 'image/avif'
iconFilename = iconFilenameBase + '.avif' iconFilename = iconFilenameBase + '.avif'
elif imageFilename.endswith('.svg'): elif image_filename.endswith('.svg'):
mediaType = 'image/svg+xml' mediaType = 'image/svg+xml'
iconFilename = iconFilenameBase + '.svg' iconFilename = iconFilenameBase + '.svg'
profileFilename = base_dir + '/accounts/' + handle + '/' + iconFilename profileFilename = base_dir + '/accounts/' + handle + '/' + iconFilename
@ -154,7 +154,7 @@ def setProfileImage(base_dir: str, http_prefix: str,
saveJson(personJson, personFilename) saveJson(personJson, personFilename)
cmd = \ cmd = \
'/usr/bin/convert ' + imageFilename + ' -size ' + \ '/usr/bin/convert ' + image_filename + ' -size ' + \
resolution + ' -quality 50 ' + profileFilename resolution + ' -quality 50 ' + profileFilename
subprocess.call(cmd, shell=True) subprocess.call(cmd, shell=True)
processMetaData(base_dir, nickname, domain, processMetaData(base_dir, nickname, domain,

View File

@ -440,7 +440,7 @@ def postImage(session, attachImageFilename: str, federation_list: [],
def downloadImage(session, base_dir: str, url: str, def downloadImage(session, base_dir: str, url: str,
imageFilename: str, debug: bool, image_filename: str, debug: bool,
force: bool = False) -> bool: force: bool = False) -> bool:
"""Downloads an image with an expected mime type """Downloads an image with an expected mime type
""" """
@ -472,7 +472,7 @@ def downloadImage(session, base_dir: str, url: str,
print('downloadImage: no session headers') print('downloadImage: no session headers')
return False return False
if not os.path.isfile(imageFilename) or force: if not os.path.isfile(image_filename) or force:
try: try:
if debug: if debug:
print('Downloading image url: ' + url) print('Downloading image url: ' + url)
@ -485,14 +485,14 @@ def downloadImage(session, base_dir: str, url: str,
print('Image download failed with status ' + print('Image download failed with status ' +
str(result.status_code)) str(result.status_code))
# remove partial download # remove partial download
if os.path.isfile(imageFilename): if os.path.isfile(image_filename):
try: try:
os.remove(imageFilename) os.remove(image_filename)
except OSError: except OSError:
print('EX: downloadImage unable to delete ' + print('EX: downloadImage unable to delete ' +
imageFilename) image_filename)
else: else:
with open(imageFilename, 'wb') as f: with open(image_filename, 'wb') as f:
f.write(result.content) f.write(result.content)
if debug: if debug:
print('Image downloaded from ' + url) print('Image downloaded from ' + url)

View File

@ -302,7 +302,7 @@ def _indicateNewShareAvailable(base_dir: str, http_prefix: str,
def addShare(base_dir: str, def addShare(base_dir: str,
http_prefix: str, nickname: str, domain: str, port: int, http_prefix: str, nickname: str, domain: str, port: int,
displayName: str, summary: str, imageFilename: str, displayName: str, summary: str, image_filename: str,
itemQty: float, itemType: str, itemCategory: str, location: str, itemQty: float, itemType: str, itemCategory: str, location: str,
duration: str, debug: bool, city: str, duration: str, debug: bool, city: str,
price: str, currency: str, price: str, currency: str,
@ -336,20 +336,20 @@ def addShare(base_dir: str,
# has an image for this share been uploaded? # has an image for this share been uploaded?
imageUrl = None imageUrl = None
moveImage = False moveImage = False
if not imageFilename: if not image_filename:
sharesImageFilename = \ sharesImageFilename = \
acct_dir(base_dir, nickname, domain) + '/upload' acct_dir(base_dir, nickname, domain) + '/upload'
formats = get_image_extensions() formats = get_image_extensions()
for ext in formats: for ext in formats:
if os.path.isfile(sharesImageFilename + '.' + ext): if os.path.isfile(sharesImageFilename + '.' + ext):
imageFilename = sharesImageFilename + '.' + ext image_filename = sharesImageFilename + '.' + ext
moveImage = True moveImage = True
domain_full = get_full_domain(domain, port) domain_full = get_full_domain(domain, port)
# copy or move the image for the shared item to its destination # copy or move the image for the shared item to its destination
if imageFilename: if image_filename:
if os.path.isfile(imageFilename): if os.path.isfile(image_filename):
if not os.path.isdir(base_dir + '/sharefiles'): if not os.path.isdir(base_dir + '/sharefiles'):
os.mkdir(base_dir + '/sharefiles') os.mkdir(base_dir + '/sharefiles')
if not os.path.isdir(base_dir + '/sharefiles/' + nickname): if not os.path.isdir(base_dir + '/sharefiles/' + nickname):
@ -357,19 +357,19 @@ def addShare(base_dir: str,
itemIDfile = base_dir + '/sharefiles/' + nickname + '/' + itemID itemIDfile = base_dir + '/sharefiles/' + nickname + '/' + itemID
formats = get_image_extensions() formats = get_image_extensions()
for ext in formats: for ext in formats:
if not imageFilename.endswith('.' + ext): if not image_filename.endswith('.' + ext):
continue continue
if low_bandwidth: if low_bandwidth:
convertImageToLowBandwidth(imageFilename) convertImageToLowBandwidth(image_filename)
processMetaData(base_dir, nickname, domain, processMetaData(base_dir, nickname, domain,
imageFilename, itemIDfile + '.' + ext, image_filename, itemIDfile + '.' + ext,
city, content_license_url) city, content_license_url)
if moveImage: if moveImage:
try: try:
os.remove(imageFilename) os.remove(image_filename)
except OSError: except OSError:
print('EX: addShare unable to delete ' + print('EX: addShare unable to delete ' +
str(imageFilename)) str(image_filename))
imageUrl = \ imageUrl = \
http_prefix + '://' + domain_full + \ http_prefix + '://' + domain_full + \
'/sharefiles/' + nickname + '/' + itemID + '.' + ext '/sharefiles/' + nickname + '/' + itemID + '.' + ext
@ -555,7 +555,7 @@ def sendShareViaServer(base_dir, session,
fromNickname: str, password: str, fromNickname: str, password: str,
fromDomain: str, fromPort: int, fromDomain: str, fromPort: int,
http_prefix: str, displayName: str, http_prefix: str, displayName: str,
summary: str, imageFilename: str, summary: str, image_filename: str,
itemQty: float, itemType: str, itemCategory: str, itemQty: float, itemType: str, itemCategory: str,
location: str, duration: str, location: str, duration: str,
cached_webfingers: {}, person_cache: {}, cached_webfingers: {}, person_cache: {},
@ -647,13 +647,13 @@ def sendShareViaServer(base_dir, session,
authHeader = createBasicAuthHeader(fromNickname, password) authHeader = createBasicAuthHeader(fromNickname, password)
if imageFilename: if image_filename:
headers = { headers = {
'host': fromDomain, 'host': fromDomain,
'Authorization': authHeader 'Authorization': authHeader
} }
postResult = \ postResult = \
postImage(session, imageFilename, [], postImage(session, image_filename, [],
inboxUrl.replace('/' + postToBox, '/shares'), inboxUrl.replace('/' + postToBox, '/shares'),
headers) headers)
@ -775,7 +775,7 @@ def sendWantedViaServer(base_dir, session,
fromNickname: str, password: str, fromNickname: str, password: str,
fromDomain: str, fromPort: int, fromDomain: str, fromPort: int,
http_prefix: str, displayName: str, http_prefix: str, displayName: str,
summary: str, imageFilename: str, summary: str, image_filename: str,
itemQty: float, itemType: str, itemCategory: str, itemQty: float, itemType: str, itemCategory: str,
location: str, duration: str, location: str, duration: str,
cached_webfingers: {}, person_cache: {}, cached_webfingers: {}, person_cache: {},
@ -867,13 +867,13 @@ def sendWantedViaServer(base_dir, session,
authHeader = createBasicAuthHeader(fromNickname, password) authHeader = createBasicAuthHeader(fromNickname, password)
if imageFilename: if image_filename:
headers = { headers = {
'host': fromDomain, 'host': fromDomain,
'Authorization': authHeader 'Authorization': authHeader
} }
postResult = \ postResult = \
postImage(session, imageFilename, [], postImage(session, image_filename, [],
inboxUrl.replace('/' + postToBox, '/wanted'), inboxUrl.replace('/' + postToBox, '/wanted'),
headers) headers)
@ -1073,9 +1073,9 @@ def outboxShareUpload(base_dir: str, http_prefix: str,
location = '' location = ''
if message_json['object'].get('location'): if message_json['object'].get('location'):
location = message_json['object']['location'] location = message_json['object']['location']
imageFilename = None image_filename = None
if message_json['object'].get('imageFilename'): if message_json['object'].get('image_filename'):
imageFilename = message_json['object']['imageFilename'] image_filename = message_json['object']['image_filename']
if debug: if debug:
print('Adding shared item') print('Adding shared item')
pprint(message_json) pprint(message_json)
@ -1084,7 +1084,7 @@ def outboxShareUpload(base_dir: str, http_prefix: str,
http_prefix, nickname, domain, port, http_prefix, nickname, domain, port,
message_json['object']['displayName'], message_json['object']['displayName'],
message_json['object']['summary'], message_json['object']['summary'],
imageFilename, image_filename,
itemQty, itemQty,
message_json['object']['itemType'], message_json['object']['itemType'],
message_json['object']['category'], message_json['object']['category'],

View File

@ -360,7 +360,7 @@ def get_image_extensions() -> []:
return ('png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'svg', 'ico') return ('png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'svg', 'ico')
def get_image_mime_type(imageFilename: str) -> str: def get_image_mime_type(image_filename: str) -> str:
"""Returns the mime type for the given image """Returns the mime type for the given image
""" """
extensionsToMime = { extensionsToMime = {
@ -373,7 +373,7 @@ def get_image_mime_type(imageFilename: str) -> str:
'ico': 'x-icon' 'ico': 'x-icon'
} }
for ext, mimeExt in extensionsToMime.items(): for ext, mimeExt in extensionsToMime.items():
if imageFilename.endswith('.' + ext): if image_filename.endswith('.' + ext):
return 'image/' + mimeExt return 'image/' + mimeExt
return 'image/png' return 'image/png'