52 lines
1.4 KiB
Python
52 lines
1.4 KiB
Python
import httpx as h
|
|
import json
|
|
import random
|
|
|
|
import keys
|
|
|
|
|
|
class ImageGetException(Exception):
|
|
pass
|
|
|
|
|
|
class ImageGetter:
|
|
headers = {
|
|
"x-api-key": keys.immich_api_key
|
|
}
|
|
|
|
def __init__(self):
|
|
pass
|
|
|
|
|
|
def get_random_image(self) -> bytearray:
|
|
id = self.get_random_image_id()
|
|
bytes = self.get_image_file(id)
|
|
return bytes
|
|
|
|
|
|
def get_random_image_id(self) -> str:
|
|
url = keys.immich_api_root_url + "album/" + keys.immich_album_id
|
|
headers = self.headers | {"Accept": "application/json"}
|
|
|
|
response = h.request("GET", url, headers=headers, data={})
|
|
if response.status_code == 200:
|
|
response = json.loads(response.text)
|
|
else:
|
|
raise ImageGetException("Error in step get_random_image_id: " + str(response.status_code))
|
|
|
|
images = response['assets']
|
|
print(f"Picking random image out of {len(images)} album images")
|
|
image = random.choice(images)
|
|
return image["id"]
|
|
|
|
|
|
def get_image_file(self, image_id: str) -> bytearray:
|
|
url = keys.immich_api_root_url + "asset/download/" + image_id
|
|
|
|
headers = self.headers | {"Accept": "application/octet-stream"}
|
|
response = h.request("POST", url, headers=headers, data={})
|
|
if not response.status_code == 200:
|
|
raise ImageGetException("Error in step get_image_file: " + str(response.status_code))
|
|
|
|
return response.content
|