Advertisement
will9512

immich_asset_add_time_buckets

Mar 12th, 2024 (edited)
707
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.34 KB | None | 1 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 get_personId_time_bucket_assets(server_url, token, personId, time_bucket, size='MONTH'):
  21.     url = f"{server_url}/api/asset/time-bucket"
  22.     headers = {'Authorization': f'Bearer {token}', 'Accept': 'application/json'}
  23.     params = {
  24.         'personId': personId,
  25.         'timeBucket': time_bucket,
  26.         'size': size
  27.     }
  28.     response = requests.get(url, headers=headers, params=params)
  29.     if response.status_code == 200:
  30.         return response.json()
  31.     else:
  32.         print(f"Failed to fetch assets. Status code: {response.status_code}, Response text: {response.text}")
  33.         return []
  34.  
  35.  
  36. def get_time_buckets(server_url, token, user_id, size='MONTH'):
  37.     print("Fetching time buckets...")
  38.     url = f"{server_url}/api/asset/time-buckets"
  39.     headers = {'Authorization': f'Bearer {token}', 'Accept': 'application/json'}
  40.     params = {'userId': user_id, 'size': size}
  41.     response = requests.get(url, headers=headers, params=params)
  42.     if response.status_code == 200:
  43.         print("Time buckets fetched successfully.")
  44.         buckets = response.json()
  45.         print(f"Time buckets: {buckets}")
  46.         return buckets
  47.     else:
  48.         print(f"Failed to fetch time buckets. Status code: {response.status_code}, Response text: {response.text}")
  49.         return []
  50.  
  51. def add_assets_to_album(url, token, album_id, asset_ids, key=None):
  52.     url = f"{url}/api/album/{album_id}/assets"
  53.     headers = {
  54.         'Authorization': f'Bearer {token}',
  55.         'Content-Type': 'application/json',
  56.         'Accept': 'application/json'
  57.     }
  58.     payload = json.dumps({"ids": asset_ids})
  59.     params = {'key': key} if key else {}
  60.     print(f"Sending request to {url} with payload: {payload} and params: {params}")
  61.  
  62.     response = requests.put(url, headers=headers, data=payload, params=params)
  63.     print(response.text)
  64.     print(f"Add assets response: {response.status_code}, Body: {response.text}")
  65.  
  66.     if response.status_code == 200:
  67.         print("Assets successfully added to the album.")
  68.         return True
  69.     else:
  70.         try:
  71.             error_response = response.json()
  72.             print(f"Error adding assets to album: {error_response.get('error', 'Unknown error')}")
  73.         except json.JSONDecodeError:
  74.             print(f"Failed to decode JSON response. Status code: {response.status_code}, Response text: {response.text}")
  75.         return False
  76.  
  77. def chunker(seq, size):
  78.     return (seq[pos:pos + size] for pos in range(0, len(seq), size))
  79.  
  80. def main():    
  81.     server_url =     (https://localhost:port)
  82.     email =     (immich login)
  83.     password =    (immich pass)
  84.     person_id =    (https://localhost:port/people/**this number***)
  85.     album_id =   (https://localhost:port/albums/**this number***)
  86.    
  87.     login_response = login_to_api(server_url, email, password)
  88.     if login_response:
  89.         token = login_response['accessToken']
  90.         user_id = login_response['userId']
  91.         time_buckets = get_time_buckets(server_url, token, user_id, size='MONTH')
  92.  
  93.         unique_asset_ids = set()
  94.         for bucket in time_buckets:
  95.             assets =  get_personId_time_bucket_assets(server_url, token, person_id, bucket['timeBucket'])
  96.             for asset in assets:
  97.                 unique_asset_ids.add(asset['id'])
  98.  
  99.         print(f"Total unique assets: {len(unique_asset_ids)}")
  100.         asset_ids_list = list(unique_asset_ids)
  101.         # print(f"Total unique assets: {len(asset_ids_list)}")
  102.  
  103.         for asset_chunk in chunker(asset_ids_list, 500):
  104.             add_assets_to_album(server_url,token, album_id, asset_chunk, key=None)
  105.             time.sleep(2)
  106.     else:
  107.         print("Failed to log in; cannot proceed with fetching assets.")
  108.  
  109. if __name__ == "__main__":
  110.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement