Advertisement
will9512

immich_asset_add_time_buckets_061324

Jun 13th, 2024
578
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.73 KB | None | 0 0
  1. import requests
  2. import json
  3. import time
  4.  
  5. def login_to_api(server_url, email, password):
  6.     print("Attempting to log in...")
  7.     login_url = f"{server_url}/api/auth/login"
  8.     login_payload = json.dumps({"email": email, "password": password})
  9.     login_headers = {'Content-Type': 'application/json'}
  10.     response = requests.post(login_url, headers=login_headers, data=login_payload)
  11.     print(response.text)
  12.  
  13.     if response.status_code in [200, 201]:
  14.         print(f"Login successful: {response.status_code}")
  15.         return response.json()
  16.     else:
  17.         print(f"Failed to login. Status code: {response.status_code}")
  18.         return None
  19.  
  20. def validate_token(server_url, token):
  21.     url = f"{server_url}/api/auth/validateToken"
  22.     headers = {'Authorization': f'Bearer {token}', 'Accept': 'application/json'}
  23.     response = requests.post(url, headers=headers)
  24.     if response.status_code == 200:
  25.         return response.json().get('authStatus', False)
  26.     else:
  27.         print(f"Failed to validate token. Status code: {response.status_code}, Response text: {response.text}")
  28.         return False
  29.  
  30. def get_person_assets(server_url, token, person_id):
  31.     url = f"{server_url}/api/people/{person_id}/assets"
  32.     headers = {'Authorization': f'Bearer {token}', 'Accept': 'application/json'}
  33.     response = requests.get(url, headers=headers)
  34.     if response.status_code == 200:
  35.         return response.json()
  36.     else:
  37.         print(f"Failed to fetch assets. Status code: {response.status_code}, Response text: {response.text}")
  38.         return []
  39.  
  40. def get_time_buckets(server_url, token, user_id, size='MONTH'):
  41.     print("Fetching time buckets...")
  42.     url = f"{server_url}/api/timeline/buckets"
  43.     headers = {'Authorization': f'Bearer {token}', 'Accept': 'application/json'}
  44.     params = {'userId': user_id, 'size': size}
  45.     response = requests.get(url, headers=headers, params=params)
  46.     if response.status_code == 200:
  47.         print("Time buckets fetched successfully.")
  48.         buckets = response.json()
  49.         print(f"Time buckets: {buckets}")
  50.         return buckets
  51.     else:
  52.         print(f"Failed to fetch time buckets. Status code: {response.status_code}, Response text: {response.text}")
  53.         return []
  54.  
  55. def add_assets_to_album(server_url, token, album_id, asset_ids, key=None):
  56.     url = f"{server_url}/api/albums/{album_id}/assets"
  57.     headers = {
  58.         'Authorization': f'Bearer {token}',
  59.         'Content-Type': 'application/json',
  60.         'Accept': 'application/json'
  61.     }
  62.     payload = json.dumps({"ids": asset_ids})
  63.     params = {'key': key} if key else {}
  64.     print(f"Sending request to {url} with payload: {payload} and params: {params}")
  65.  
  66.     response = requests.put(url, headers=headers, data=payload, params=params)
  67.     print(response.text)
  68.     print(f"Add assets response: {response.status_code}, Body: {response.text}")
  69.  
  70.     if response.status_code == 200:
  71.         print("Assets successfully added to the album.")
  72.         return True
  73.     else:
  74.         try:
  75.             error_response = response.json()
  76.             print(f"Error adding assets to album: {error_response.get('error', 'Unknown error')}")
  77.         except json.JSONDecodeError:
  78.             print(f"Failed to decode JSON response. Status code: {response.status_code}, Response text: {response.text}")
  79.         return False
  80.  
  81. def chunker(seq, size):
  82.     return (seq[pos:pos + size] for pos in range(0, len(seq), size))
  83.  
  84. def main():    
  85.     #dont forget to change the entries:
  86.     server_url = "https://immich.yurserver.xy"
  87.     email = "test@test.xy"
  88.     password = "yuorpassword"
  89.     person_id = "1dde757d-00c5-4aab-b610-934a1105f1f0"
  90.     album_id = "c5cb853e-ae21-48c3-aeea-b8efe72da9c0"
  91.  
  92.     login_response = login_to_api(server_url, email, password)
  93.     if login_response:
  94.         token = login_response['accessToken']
  95.         user_id = login_response['userId']
  96.        
  97.         if validate_token(server_url, token):
  98.             time_buckets = get_time_buckets(server_url, token, user_id, size='MONTH')
  99.  
  100.             unique_asset_ids = set()
  101.             for bucket in time_buckets:
  102.                 assets = get_person_assets(server_url, token, person_id)
  103.                 for asset in assets:
  104.                     unique_asset_ids.add(asset['id'])
  105.  
  106.             print(f"Total unique assets: {len(unique_asset_ids)}")
  107.             asset_ids_list = list(unique_asset_ids)
  108.  
  109.             for asset_chunk in chunker(asset_ids_list, 500):
  110.                 add_assets_to_album(server_url, token, album_id, asset_chunk, key=None)
  111.                 time.sleep(2)
  112.         else:
  113.             print("Invalid token; cannot proceed with fetching assets.")
  114.     else:
  115.         print("Failed to log in; cannot proceed with fetching assets.")
  116.  
  117. if __name__ == "__main__":
  118.     main()
  119.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement