File size: 8,412 Bytes
25f22bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4de23f
 
 
 
 
25f22bf
 
 
 
 
 
 
 
 
 
 
 
e4de23f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f22bf
 
 
 
 
 
 
 
 
 
 
e4de23f
 
 
 
 
25f22bf
 
 
 
 
e4de23f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f22bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
from flask import current_app
import requests
from requests_oauthlib import OAuth2Session
from urllib.parse import urlencode

class LinkedInService:
    """Service for LinkedIn API integration."""
    
    def __init__(self):
        self.client_id = current_app.config['CLIENT_ID']
        self.client_secret = current_app.config['CLIENT_SECRET']
        self.redirect_uri = current_app.config['REDIRECT_URL']
        self.scope = ['openid', 'profile', 'email', 'w_member_social']
        
    def get_authorization_url(self, state: str) -> str:
        """
        Get LinkedIn authorization URL.
        
        Args:
            state (str): State parameter for security
            
        Returns:
            str: Authorization URL
        """
        linkedin = OAuth2Session(
            self.client_id,
            redirect_uri=self.redirect_uri,
            scope=self.scope,
            state=state
        )
        
        authorization_url, _ = linkedin.authorization_url(
            'https://www.linkedin.com/oauth/v2/authorization'
        )
        
        return authorization_url
    
    def get_access_token(self, code: str) -> dict:
        """
        Exchange authorization code for access token.
        
        Args:
            code (str): Authorization code
            
        Returns:
            dict: Token response
        """
        import logging
        logger = logging.getLogger(__name__)
        
        logger.info(f"πŸ”— [LinkedIn] Starting token exchange for code: {code[:20]}...")
        
        url = "https://www.linkedin.com/oauth/v2/accessToken"
        headers = {
            "Content-Type": "application/x-www-form-urlencoded"
        }
        data = {
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": self.redirect_uri,
            "client_id": self.client_id,
            "client_secret": self.client_secret
        }
        
        logger.info(f"πŸ”— [LinkedIn] Making request to LinkedIn API...")
        logger.info(f"πŸ”— [LinkedIn] Request URL: {url}")
        logger.info(f"πŸ”— [LinkedIn] Request data: {data}")
        
        try:
            response = requests.post(url, headers=headers, data=data)
            logger.info(f"πŸ”— [LinkedIn] Response status: {response.status_code}")
            logger.info(f"πŸ”— [LinkedIn] Response headers: {dict(response.headers)}")
            
            response.raise_for_status()
            
            token_data = response.json()
            logger.info(f"πŸ”— [LinkedIn] Token response: {token_data}")
            
            return token_data
        except requests.exceptions.RequestException as e:
            logger.error(f"πŸ”— [LinkedIn] Token exchange failed: {str(e)}")
            logger.error(f"πŸ”— [LinkedIn] Error type: {type(e)}")
            raise e
    
    def get_user_info(self, access_token: str) -> dict:
        """
        Get user information from LinkedIn.
        
        Args:
            access_token (str): LinkedIn access token
            
        Returns:
            dict: User information
        """
        import logging
        logger = logging.getLogger(__name__)
        
        logger.info(f"πŸ”— [LinkedIn] Fetching user info with token length: {len(access_token)}")
        
        url = "https://api.linkedin.com/v2/userinfo"
        headers = {
            "Authorization": f"Bearer {access_token}"
        }
        
        logger.info(f"πŸ”— [LinkedIn] Making request to LinkedIn user info API...")
        logger.info(f"πŸ”— [LinkedIn] Request URL: {url}")
        logger.info(f"πŸ”— [LinkedIn] Request headers: {headers}")
        
        try:
            response = requests.get(url, headers=headers)
            logger.info(f"πŸ”— [LinkedIn] Response status: {response.status_code}")
            logger.info(f"πŸ”— [LinkedIn] Response headers: {dict(response.headers)}")
            
            response.raise_for_status()
            
            user_data = response.json()
            logger.info(f"πŸ”— [LinkedIn] User info response: {user_data}")
            
            return user_data
        except requests.exceptions.RequestException as e:
            logger.error(f"πŸ”— [LinkedIn] User info fetch failed: {str(e)}")
            logger.error(f"πŸ”— [LinkedIn] Error type: {type(e)}")
            raise e
    
    def publish_post(self, access_token: str, user_id: str, text_content: str, image_url: str = None) -> dict:
        """
        Publish a post to LinkedIn.
        
        Args:
            access_token (str): LinkedIn access token
            user_id (str): LinkedIn user ID
            text_content (str): Post content
            image_url (str, optional): Image URL
            
        Returns:
            dict: Publish response
        """
        url = "https://api.linkedin.com/v2/ugcPosts"
        headers = {
            "Authorization": f"Bearer {access_token}",
            "X-Restli-Protocol-Version": "2.0.0",
            "Content-Type": "application/json"
        }
        
        if image_url:
            # Handle image upload
            register_body = {
                "registerUploadRequest": {
                    "recipes": ["urn:li:digitalmediaRecipe:feedshare-image"],
                    "owner": f"urn:li:person:{user_id}",
                    "serviceRelationships": [{
                        "relationshipType": "OWNER",
                        "identifier": "urn:li:userGeneratedContent"
                    }]
                }
            }
            
            r = requests.post(
                "https://api.linkedin.com/v2/assets?action=registerUpload",
                headers=headers,
                json=register_body
            )
            
            if r.status_code not in (200, 201):
                raise Exception(f"Failed to register upload: {r.status_code} {r.text}")
            
            datar = r.json()["value"]
            upload_url = datar["uploadMechanism"]["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"]["uploadUrl"]
            asset_urn = datar["asset"]
            
            # Upload image
            upload_headers = {
                "Authorization": f"Bearer {access_token}",
                "X-Restli-Protocol-Version": "2.0.0",
                "Content-Type": "application/octet-stream"
            }
            
            # Download image and upload to LinkedIn
            image_response = requests.get(image_url)
            if image_response.status_code == 200:
                upload_response = requests.put(upload_url, headers=upload_headers, data=image_response.content)
                if upload_response.status_code not in (200, 201):
                    raise Exception(f"Failed to upload image: {upload_response.status_code} {upload_response.text}")
            
            # Create post with image
            post_body = {
                "author": f"urn:li:person:{user_id}",
                "lifecycleState": "PUBLISHED",
                "specificContent": {
                    "com.linkedin.ugc.ShareContent": {
                        "shareCommentary": {"text": text_content},
                        "shareMediaCategory": "IMAGE",
                        "media": [{
                            "status": "READY",
                            "media": asset_urn,
                            "description": {"text": "Post image"},
                            "title": {"text": "Post image"}
                        }]
                    }
                },
                "visibility": {"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"}
            }
        else:
            # Create text-only post
            post_body = {
                "author": f"urn:li:person:{user_id}",
                "lifecycleState": "PUBLISHED",
                "specificContent": {
                    "com.linkedin.ugc.ShareContent": {
                        "shareCommentary": {
                            "text": text_content
                        },
                        "shareMediaCategory": "NONE"
                    }
                },
                "visibility": {
                    "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
                }
            }
        
        response = requests.post(url, headers=headers, json=post_body)
        response.raise_for_status()
        return response.json()