File size: 13,271 Bytes
25f22bf
 
 
 
40a3caf
 
 
25f22bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4de23f
 
 
 
 
25f22bf
 
 
 
 
 
 
 
 
 
 
 
e4de23f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f22bf
 
 
 
 
 
 
 
 
 
 
e4de23f
 
 
 
 
25f22bf
 
 
 
 
e4de23f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f22bf
40a3caf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f22bf
 
 
 
 
 
 
 
40a3caf
25f22bf
 
 
 
40a3caf
25f22bf
 
 
 
 
 
 
40a3caf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f22bf
40a3caf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f22bf
 
40a3caf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f22bf
 
40a3caf
 
 
 
 
 
 
 
 
 
 
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
from flask import current_app
import requests
from requests_oauthlib import OAuth2Session
from urllib.parse import urlencode
import tempfile
import os
import logging

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 _create_temp_image_file(self, image_bytes: bytes) -> str:
        """
        Create a temporary file from image bytes.
        
        Args:
            image_bytes: Image data as bytes
            
        Returns:
            Path to the temporary file
        """
        # Create a temporary file
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
        temp_file_path = temp_file.name
        
        try:
            # Write image bytes to the temporary file
            temp_file.write(image_bytes)
            temp_file.flush()
        finally:
            temp_file.close()
        
        return temp_file_path
    
    def _cleanup_temp_file(self, file_path: str) -> None:
        """
        Safely remove a temporary file.
        
        Args:
            file_path: Path to the temporary file to remove
        """
        try:
            if file_path and os.path.exists(file_path):
                os.unlink(file_path)
        except Exception as e:
            # Log the error but don't fail the operation
            logging.error(f"Failed to cleanup temporary file {file_path}: {str(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 or bytes, optional): Image URL or image bytes
            
        Returns:
            dict: Publish response
        """
        temp_file_path = None
        url = "https://api.linkedin.com/v2/ugcPosts"
        headers = {
            "Authorization": f"Bearer {access_token}",
            "X-Restli-Protocol-Version": "2.0.0",
            "Content-Type": "application/json"
        }
        
        try:
            if image_url and isinstance(image_url, bytes):
                # Handle bytes data - create temporary file and upload
                temp_file_path = self._create_temp_image_file(image_url)
                
                # Register 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 from temporary file
                upload_headers = {
                    "Authorization": f"Bearer {access_token}",
                    "X-Restli-Protocol-Version": "2.0.0",
                    "Content-Type": "application/octet-stream"
                }
                
                with open(temp_file_path, 'rb') as f:
                    image_data = f.read()
                    upload_response = requests.put(upload_url, headers=upload_headers, data=image_data)
                    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"}
                }
            elif image_url and isinstance(image_url, str):
                # Handle image upload for URL-based images
                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()
        except Exception as e:
            # Re-raise the exception to maintain existing behavior
            raise e
        finally:
            # Clean up temporary file if it was created
            if temp_file_path:
                self._cleanup_temp_file(temp_file_path)