Likendin-Agent / mcp_server_tools /raw_function.py
Coding-With's picture
Refactor application structure by removing backend directory and integrating main.py directly. Update Dockerfile to reflect new entry point and streamline dependencies. Implement FastAPI with CORS support and asynchronous agent handling for improved functionality.
01038c9
Raw History Blame
3.42 kB
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