Spaces:
Sleeping
Sleeping
File size: 3,421 Bytes
fb07b17 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | from dotenv import load_dotenv, find_dotenv
import requests
import os
# Constants
LINKEDIN_ACCESS_TOKEN = os.getenv("LINKEDIN_ACCESS_TOKEN")
load_dotenv(find_dotenv())
HEADERS = {
"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}",
"Content-Type": "application/json",
}
def get_user_id():
"""
Retrieve LinkedIn user profile information using the /userinfo endpoint.
Returns:
dict: User profile information or None if an error occurs.
"""
url = "https://api.linkedin.com/v2/userinfo"
try:
response = requests.get(url, headers=HEADERS)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching user info: {e}")
return None
def get_user_info():
"""Retrieve the authenticated user's LinkedIn information."""
url = "https://api.linkedin.com/v2/userinfo"
response = requests.get(url, headers=HEADERS)
if response.status_code == 200:
return response.json()
else:
print(f"Error fetching user info: {response.status_code}")
return None
def register_image_upload():
"""Register an image upload with LinkedIn."""
user_info = get_user_info()
if not user_info:
print("Failed to retrieve user information.")
return None, None
url = "https://api.linkedin.com/v2/assets?action=registerUpload"
payload = {
"registerUploadRequest": {
"recipes": ["urn:li:digitalmediaRecipe:feedshare-image"],
"owner": f"urn:li:person:{user_info['sub']}",
"serviceRelationships": [
{
"relationshipType": "OWNER",
"identifier": "urn:li:userGeneratedContent",
}
],
}
}
response = requests.post(url, headers=HEADERS, json=payload)
if response.status_code == 200:
return response.json().get("value", {}).get("uploadMechanism", {}).get(
"com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest", {}
).get("uploadUrl"), response.json().get("value", {}).get("asset")
else:
print(f"Error registering image upload: {response.status_code}")
return None, None
def upload_image(upload_url, image_source):
"""
Upload the image to LinkedIn.
Args:
upload_url (str): The LinkedIn upload URL
image_source (str): Either a local file path or a URL to the image
"""
if image_source.startswith(("http://", "https://")):
# Handle URL
response = requests.get(image_source)
if response.status_code != 200:
print(f"Error fetching image from URL: {response.status_code}")
return False
image_data = response.content
else:
# Handle local file
try:
with open(image_source, "rb") as image_file:
image_data = image_file.read()
except FileNotFoundError:
print(f"Error: Image file not found at {image_source}")
return False
response = requests.post(
upload_url,
headers={"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}"},
data=image_data,
)
if response.status_code == 201:
print("Image uploaded successfully.")
return True
else:
print(f"Error uploading image: {response.status_code}")
return False
|