Spaces:
Running
Running
Update Data_Fetching_and_Rendering.py
Browse files- Data_Fetching_and_Rendering.py +86 -303
Data_Fetching_and_Rendering.py
CHANGED
|
@@ -1,357 +1,140 @@
|
|
| 1 |
import json
|
| 2 |
import requests
|
| 3 |
-
from sessions import create_session
|
| 4 |
import html
|
| 5 |
-
from datetime import datetime
|
| 6 |
|
|
|
|
| 7 |
from error_handling import display_error
|
| 8 |
|
| 9 |
API_V2_BASE = 'https://api.linkedin.com/v2'
|
| 10 |
API_REST_BASE = "https://api.linkedin.com/rest"
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
def fetch_org_urn(comm_client_id, comm_token_dict):
|
| 16 |
-
"""
|
| 17 |
-
Fetches the user's administrated organization URN and name using the Marketing token.
|
| 18 |
-
Expects comm_token_dict to be the full token dictionary.
|
| 19 |
-
Raises ValueError on failure.
|
| 20 |
-
"""
|
| 21 |
-
print("--- Fetching Organization URN ---")
|
| 22 |
if not comm_token_dict or 'access_token' not in comm_token_dict:
|
| 23 |
-
|
| 24 |
-
raise ValueError("Marketing token is missing or invalid.")
|
| 25 |
-
|
| 26 |
-
ln_mkt = create_session(comm_client_id, token=comm_token_dict)
|
| 27 |
|
| 28 |
-
|
| 29 |
url = (
|
| 30 |
f"{API_V2_BASE}/organizationalEntityAcls"
|
| 31 |
-
"?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED"
|
| 32 |
-
"&projection=(elements*(*,organizationalTarget~(id,localizedName)))"
|
| 33 |
)
|
| 34 |
-
|
| 35 |
try:
|
| 36 |
-
|
| 37 |
-
|
| 38 |
except requests.exceptions.RequestException as e:
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
details = f" Details: {e.response.json()}"
|
| 46 |
-
except json.JSONDecodeError:
|
| 47 |
-
details = f" Response: {e.response.text[:200]}..." # Show partial text
|
| 48 |
-
raise ValueError(f"Failed to fetch Organization details (Status: {status}). Check Marketing App permissions (r_organization_admin) and ensure the user is an admin of an org page.{details}") from e
|
| 49 |
-
|
| 50 |
-
data = r.json()
|
| 51 |
-
print(f"Org URN Response Data: {json.dumps(data, indent=2)}")
|
| 52 |
-
elements = data.get('elements')
|
| 53 |
|
|
|
|
| 54 |
if not elements:
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
# Extract Full URN ('organizationalTarget' field contains the URN string)
|
| 65 |
-
org_urn_full = org_element.get('organizationalTarget')
|
| 66 |
-
if not org_urn_full or not isinstance(org_urn_full, str) or not org_urn_full.startswith("urn:li:organization:"):
|
| 67 |
-
print(f"ERROR: Could not extract valid Organization URN ('organizationalTarget') from API response element: {org_element}")
|
| 68 |
-
raise ValueError("Could not extract a valid Organization URN from the API response.")
|
| 69 |
-
|
| 70 |
-
# Extract Name (from the projected 'organizationalTarget~' field)
|
| 71 |
-
org_name = None
|
| 72 |
-
# The key might be exactly 'organizationalTarget~' or something similar depending on projection syntax variations
|
| 73 |
-
org_target_details_key = next((k for k in org_element if k.endswith('organizationalTarget~')), None)
|
| 74 |
-
|
| 75 |
-
if org_target_details_key and isinstance(org_element.get(org_target_details_key), dict):
|
| 76 |
-
org_name = org_element[org_target_details_key].get('localizedName')
|
| 77 |
-
|
| 78 |
if not org_name:
|
| 79 |
-
|
| 80 |
-
org_id = org_urn_full.split(':')[-1]
|
| 81 |
org_name = f"Organization ({org_id})"
|
| 82 |
-
print(f"WARN: Could not find localizedName, using fallback: {org_name}")
|
| 83 |
-
|
| 84 |
-
print(f"Found Org: {org_name} ({org_urn_full})")
|
| 85 |
-
return org_urn_full, org_name
|
| 86 |
-
|
| 87 |
-
|
| 88 |
|
|
|
|
| 89 |
|
| 90 |
def fetch_posts_and_stats(comm_client_id, community_token, count=10):
|
| 91 |
-
"""Fetches posts using Marketing token and stats using Marketing token."""
|
| 92 |
-
print("--- Fetching Posts and Stats ---")
|
| 93 |
-
|
| 94 |
if not community_token:
|
| 95 |
-
|
| 96 |
-
raise ValueError("Community token is missing.") # Don't raise if not needed
|
| 97 |
-
|
| 98 |
-
# Ensure tokens are in the correct format (dict)
|
| 99 |
-
comm_token_dict = community_token if isinstance(community_token, dict) else {'access_token': community_token, 'token_type': 'Bearer'} # Process if needed later
|
| 100 |
|
| 101 |
-
|
|
|
|
| 102 |
|
| 103 |
-
#
|
| 104 |
-
#org_urn, org_name = fetch_org_urn(comm_token_dict) # Reuses the function
|
| 105 |
org_urn, org_name = "urn:li:organization:19010008", "GRLS"
|
| 106 |
-
|
| 107 |
-
# 2) Fetch latest posts (using Marketing Token via REST API)
|
| 108 |
-
# Endpoint requires r_organization_social permission
|
| 109 |
posts_url = f"{API_REST_BASE}/posts?author={org_urn}&q=author&count={count}&sortBy=LAST_MODIFIED"
|
| 110 |
|
| 111 |
-
print(f"Attempting to fetch posts from: {posts_url} using Marketing token")
|
| 112 |
try:
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
# Limit printing large response bodies
|
| 117 |
-
print(f"β POSTS Response Body (first 500 chars): {resp_posts.text[:500]}")
|
| 118 |
-
resp_posts.raise_for_status()
|
| 119 |
-
print("Fetched posts using Marketing token.")
|
| 120 |
except requests.exceptions.RequestException as e:
|
| 121 |
-
status = e.response
|
| 122 |
-
|
| 123 |
-
if e.response is not None:
|
| 124 |
-
try:
|
| 125 |
-
details = f" Details: {e.response.json()}"
|
| 126 |
-
except json.JSONDecodeError:
|
| 127 |
-
details = f" Response: {e.response.text[:200]}..."
|
| 128 |
-
print(f"ERROR: Fetching posts failed with Marketing token (Status: {status}).{details}")
|
| 129 |
-
raise ValueError(f"Failed to fetch posts using Marketing token (Status: {status}). Check permissions (r_organization_social).") from e
|
| 130 |
-
|
| 131 |
-
raw_posts_data = resp_posts.json()
|
| 132 |
-
raw_posts = raw_posts_data.get("elements", [])
|
| 133 |
-
print(f"Fetched {len(raw_posts)} raw posts.")
|
| 134 |
|
| 135 |
if not raw_posts:
|
| 136 |
-
return [], org_name
|
| 137 |
|
| 138 |
-
|
| 139 |
-
post_urns = [p.get("id") for p in raw_posts if p.get("id") and (":share:" in p.get("id") or ":ugcPost:" in p.get("id"))]
|
| 140 |
if not post_urns:
|
| 141 |
-
print("WARN: No post URNs (share or ugcPost) found in the fetched posts.")
|
| 142 |
return [], org_name
|
| 143 |
|
| 144 |
-
print(f"Post URNs to fetch stats for: {post_urns}")
|
| 145 |
-
|
| 146 |
-
# 4) Fetch stats (using Comm session via REST API)
|
| 147 |
-
# Endpoint requires r_organization_social permission
|
| 148 |
stats_map = {}
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
for batch in urn_batches:
|
| 153 |
-
if not batch: continue
|
| 154 |
-
|
| 155 |
-
stats_url = f"{API_REST_BASE}/organizationalEntityShareStatistics"
|
| 156 |
-
# Parameters need to be structured correctly: q=organizationalEntity, organizationalEntity=orgURN, shares[0]=shareURN1, ugcPosts[0]=ugcURN1 etc.
|
| 157 |
params = {'q': 'organizationalEntity', 'organizationalEntity': org_urn}
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
params[f'shares[{share_idx}]'] = urn
|
| 162 |
-
share_idx += 1
|
| 163 |
-
elif ':ugcPost:' in urn:
|
| 164 |
-
params[f'ugcPosts[{ugc_idx}]'] = urn
|
| 165 |
-
ugc_idx += 1
|
| 166 |
-
else:
|
| 167 |
-
print(f"WARN: Skipping unknown URN type for stats: {urn}")
|
| 168 |
-
|
| 169 |
-
if share_idx == 0 and ugc_idx == 0:
|
| 170 |
-
print("WARN: Skipping stats fetch for batch as no valid share/ugcPost URNs found.")
|
| 171 |
-
continue
|
| 172 |
|
| 173 |
-
print(f"Fetching stats for batch from: {stats_url} with {len(params)-2} URNs using Marketing token")
|
| 174 |
try:
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
# Map stats back to their URNs
|
| 185 |
-
for elem in stats_data:
|
| 186 |
-
# Key in response is 'share' or 'ugcPost' containing the URN
|
| 187 |
-
urn_key = elem.get('share') or elem.get('ugcPost')
|
| 188 |
-
if urn_key:
|
| 189 |
-
# Store the whole 'totalShareStatistics' object
|
| 190 |
-
stats_map[urn_key] = elem.get('totalShareStatistics', {})
|
| 191 |
-
else:
|
| 192 |
-
print(f"WARN: Stats element missing 'share' or 'ugcPost' key: {elem}")
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
except requests.exceptions.RequestException as e:
|
| 196 |
-
status = e.response.status_code if e.response is not None else "N/A"
|
| 197 |
-
details = ""
|
| 198 |
-
if e.response is not None:
|
| 199 |
-
try:
|
| 200 |
-
details = f" Details: {e.response.json()}"
|
| 201 |
-
except json.JSONDecodeError:
|
| 202 |
-
details = f" Response: {e.response.text[:200]}..."
|
| 203 |
-
print(f"ERROR fetching stats batch using Marketing token (Status: {status}).{details}")
|
| 204 |
-
print("WARN: Skipping stats for this batch due to error.")
|
| 205 |
-
# Optionally raise an error here if stats are critical, or continue with partial data
|
| 206 |
-
# raise ValueError(f"Failed to fetch stats batch (Status: {status}).") from e
|
| 207 |
-
|
| 208 |
-
print(f"Fetched stats for {len(stats_map)} posts in total.")
|
| 209 |
|
| 210 |
-
|
| 211 |
-
combined_posts = []
|
| 212 |
for post in raw_posts:
|
| 213 |
post_id = post.get("id")
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
specific_content = post.get("specificContent", {})
|
| 233 |
-
share_content = specific_content.get("com.linkedin.ugc.ShareContent", {})
|
| 234 |
-
share_commentary_v2 = share_content.get("shareCommentaryV2", {}).get("text")
|
| 235 |
-
if share_commentary_v2:
|
| 236 |
-
text = share_commentary_v2
|
| 237 |
-
else:
|
| 238 |
-
# Check top-level commentaryV2 (less common?)
|
| 239 |
-
commentary_v2 = post.get("commentaryV2", {}).get("text")
|
| 240 |
-
if commentary_v2:
|
| 241 |
-
text = commentary_v2
|
| 242 |
-
else:
|
| 243 |
-
# Check for article titles if it's an article share
|
| 244 |
-
article_content = specific_content.get("com.linkedin.ugc.ArticleContent", {})
|
| 245 |
-
article_title = article_content.get("title")
|
| 246 |
-
if article_title:
|
| 247 |
-
text = f"Article: {article_title}"
|
| 248 |
-
else:
|
| 249 |
-
# Check older 'content' field (might be deprecated)
|
| 250 |
-
content_text = post.get("content", {}).get("text", {}).get("text")
|
| 251 |
-
if content_text:
|
| 252 |
-
text = content_text
|
| 253 |
-
else:
|
| 254 |
-
# Final fallback
|
| 255 |
-
text = "[Media post or share without text]"
|
| 256 |
-
|
| 257 |
-
# Escape and truncate text for HTML display
|
| 258 |
-
display_text = html.escape(text[:250]).replace("\n", "<br>") + ("..." if len(text) > 250 else "")
|
| 259 |
-
|
| 260 |
-
# --- Stats Extraction ---
|
| 261 |
-
# Use .get with default 0 for robustness
|
| 262 |
-
impressions = stats.get("impressionCount", 0) or 0
|
| 263 |
-
likes = stats.get("likeCount", 0) or 0
|
| 264 |
-
comments = stats.get("commentCount", 0) or 0
|
| 265 |
-
clicks = stats.get("clickCount", 0) or 0
|
| 266 |
-
shares = stats.get("shareCount", 0) or 0
|
| 267 |
-
|
| 268 |
-
# Calculate engagement rate manually if 'engagement' field isn't present or reliable
|
| 269 |
-
engagement_num = likes + comments + clicks + shares # Sum of interactions
|
| 270 |
-
engagement_rate_manual = (engagement_num / impressions * 100) if impressions > 0 else 0.0
|
| 271 |
-
|
| 272 |
-
# Check if API provides 'engagement' field (usually rate as decimal)
|
| 273 |
-
engagement_api = stats.get('engagement')
|
| 274 |
-
if engagement_api is not None:
|
| 275 |
-
try:
|
| 276 |
-
# API provides rate as decimal (e.g., 0.02 for 2%)
|
| 277 |
-
engagement_str = f"{float(engagement_api) * 100:.2f}%"
|
| 278 |
-
except (ValueError, TypeError):
|
| 279 |
-
# Fallback to manual calculation if API value is invalid
|
| 280 |
-
engagement_str = f"{engagement_rate_manual:.2f}%"
|
| 281 |
-
else:
|
| 282 |
-
# Use manual calculation if API field is missing
|
| 283 |
-
engagement_str = f"{engagement_rate_manual:.2f}%"
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
combined_posts.append({
|
| 287 |
-
"id": post_id, "when": when, "text": display_text,
|
| 288 |
-
"likes": likes, "comments": comments, "impressions": impressions,
|
| 289 |
-
"clicks": clicks, "shares": shares, # Added shares to dict
|
| 290 |
-
"engagement": engagement_str,
|
| 291 |
})
|
| 292 |
|
| 293 |
-
return
|
| 294 |
|
| 295 |
def render_post_cards(posts, org_name):
|
| 296 |
-
|
| 297 |
-
safe_org_name = html.escape(org_name) if org_name else "Your Organization"
|
| 298 |
if not posts:
|
| 299 |
-
return f"<h2 style='text-align:
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
<div style=
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
</div>
|
| 312 |
-
<div style="font-size: 0.9em; color: #333; border-top: 1px solid #eee; padding-top: 10px; margin-top: auto; line-height: 1.6;">
|
| 313 |
-
<span title="Impressions">ποΈ {p.get('impressions', 0):,}</span> |
|
| 314 |
-
<span title="Likes">π {p.get('likes', 0):,}</span> |
|
| 315 |
-
<span title="Comments">π¬ {p.get('comments', 0):,}</span> |
|
| 316 |
-
<span title="Shares">π {p.get('shares', 0):,}</span> |
|
| 317 |
-
<span title="Clicks">π±οΈ {p.get('clicks', 0):,}</span><br>
|
| 318 |
-
<span title="Engagement Rate" style="font-weight: bold;">π {p.get('engagement', '0.00%')}</span>
|
| 319 |
-
</div>
|
| 320 |
-
</div>
|
| 321 |
-
"""
|
| 322 |
-
cards_html += "</div>"
|
| 323 |
-
return cards_html
|
| 324 |
|
| 325 |
def fetch_and_render_dashboard(comm_client_id, community_token):
|
| 326 |
-
"""Orchestrates fetching post data and rendering the dashboard."""
|
| 327 |
-
print("--- Rendering Dashboard ---")
|
| 328 |
-
if not comm_client_id: # Community token not strictly needed for this fetch anymore
|
| 329 |
-
print("ERROR: comm_client_id missing for dashboard rendering.")
|
| 330 |
-
return "<p style='color: red; text-align: center; font-weight: bold;'>β Error: Missing LinkedIn Marketing token. Please complete the login process on the 'Login' tab.</p>"
|
| 331 |
try:
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
posts_data, org_name = fetch_posts_and_stats(comm_client_id, community_token) # community_token kept for signature consistency
|
| 335 |
-
print(f"Rendering {len(posts_data)} posts for {org_name}.")
|
| 336 |
-
if not org_name:
|
| 337 |
-
org_name = "[Organization Name Not Found]" # Handle case where org name wasn't fetched
|
| 338 |
-
return render_post_cards(posts_data, org_name)
|
| 339 |
-
except ValueError as ve: # Catch specific errors like missing orgs or token issues
|
| 340 |
-
print(f"VALUE ERROR during dashboard fetch: {ve}")
|
| 341 |
-
# Use display_error to format the message for HTML/Markdown
|
| 342 |
-
error_update = display_error(f"Configuration or API Error: {ve}", ve)
|
| 343 |
-
return error_update.get('value', "<p style='color: red; text-align: center;'>β A configuration or API error occurred.</p>")
|
| 344 |
-
except requests.exceptions.RequestException as re:
|
| 345 |
-
print(f"HTTP ERROR during dashboard fetch: {re}")
|
| 346 |
-
status_code = re.response.status_code if re.response else "N/A"
|
| 347 |
-
error_update = display_error(f"API Request Failed (Status: {status_code}). Check permissions/scopes or API status.", re)
|
| 348 |
-
return error_update.get('value', f"<p style='color: red; text-align: center;'>β API Error: {status_code}. Check console logs.</p>")
|
| 349 |
except Exception as e:
|
| 350 |
-
|
| 351 |
-
error_update = display_error("Failed to fetch or render dashboard data.", e)
|
| 352 |
-
error_html = error_update.get('value', "<p style='color: red; text-align: center;'>β An unexpected error occurred. Check console logs.</p>")
|
| 353 |
-
# Ensure the error message is HTML-safe
|
| 354 |
-
if isinstance(error_html, str) and not error_html.strip().startswith("<"):
|
| 355 |
-
error_html = f"<pre style='color: red; white-space: pre-wrap;'>{html.escape(error_html)}</pre>"
|
| 356 |
-
return error_html
|
| 357 |
-
|
|
|
|
| 1 |
import json
|
| 2 |
import requests
|
|
|
|
| 3 |
import html
|
| 4 |
+
from datetime import datetime
|
| 5 |
|
| 6 |
+
from sessions import create_session
|
| 7 |
from error_handling import display_error
|
| 8 |
|
| 9 |
API_V2_BASE = 'https://api.linkedin.com/v2'
|
| 10 |
API_REST_BASE = "https://api.linkedin.com/rest"
|
| 11 |
|
|
|
|
|
|
|
|
|
|
| 12 |
def fetch_org_urn(comm_client_id, comm_token_dict):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
if not comm_token_dict or 'access_token' not in comm_token_dict:
|
| 14 |
+
raise ValueError("Marketing token is missing or invalid.")
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
session = create_session(comm_client_id, token=comm_token_dict)
|
| 17 |
url = (
|
| 18 |
f"{API_V2_BASE}/organizationalEntityAcls"
|
| 19 |
+
"?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED"
|
| 20 |
+
"&projection=(elements*(*,organizationalTarget~(id,localizedName)))"
|
| 21 |
)
|
| 22 |
+
|
| 23 |
try:
|
| 24 |
+
response = session.get(url)
|
| 25 |
+
response.raise_for_status()
|
| 26 |
except requests.exceptions.RequestException as e:
|
| 27 |
+
status = getattr(e.response, 'status_code', 'N/A')
|
| 28 |
+
try:
|
| 29 |
+
details = e.response.json()
|
| 30 |
+
except Exception:
|
| 31 |
+
details = str(e)
|
| 32 |
+
raise ValueError(f"Failed to fetch Organization details (Status: {status}): {details}") from e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
elements = response.json().get('elements')
|
| 35 |
if not elements:
|
| 36 |
+
raise ValueError("No organizations found with ADMINISTRATOR role.")
|
| 37 |
+
|
| 38 |
+
org = elements[0]
|
| 39 |
+
org_urn = org.get('organizationalTarget')
|
| 40 |
+
org_name = org.get(next((k for k in org if k.endswith('organizationalTarget~')), {}), {}).get('localizedName')
|
| 41 |
+
|
| 42 |
+
if not org_urn or not org_urn.startswith("urn:li:organization:"):
|
| 43 |
+
raise ValueError("Invalid Organization URN.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
if not org_name:
|
| 45 |
+
org_id = org_urn.split(":")[-1]
|
|
|
|
| 46 |
org_name = f"Organization ({org_id})"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
return org_urn, org_name
|
| 49 |
|
| 50 |
def fetch_posts_and_stats(comm_client_id, community_token, count=10):
|
|
|
|
|
|
|
|
|
|
| 51 |
if not community_token:
|
| 52 |
+
raise ValueError("Community token is missing.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
token_dict = community_token if isinstance(community_token, dict) else {'access_token': community_token, 'token_type': 'Bearer'}
|
| 55 |
+
session = create_session(comm_client_id, token=token_dict)
|
| 56 |
|
| 57 |
+
#org_urn, org_name = fetch_org_urn(comm_token_dict)
|
|
|
|
| 58 |
org_urn, org_name = "urn:li:organization:19010008", "GRLS"
|
|
|
|
|
|
|
|
|
|
| 59 |
posts_url = f"{API_REST_BASE}/posts?author={org_urn}&q=author&count={count}&sortBy=LAST_MODIFIED"
|
| 60 |
|
|
|
|
| 61 |
try:
|
| 62 |
+
resp = session.get(posts_url)
|
| 63 |
+
resp.raise_for_status()
|
| 64 |
+
raw_posts = resp.json().get("elements", [])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
except requests.exceptions.RequestException as e:
|
| 66 |
+
status = getattr(e.response, 'status_code', 'N/A')
|
| 67 |
+
raise ValueError(f"Failed to fetch posts (Status: {status})") from e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
if not raw_posts:
|
| 70 |
+
return [], org_name
|
| 71 |
|
| 72 |
+
post_urns = [p["id"] for p in raw_posts if ":share:" in p["id"] or ":ugcPost:" in p["id"]]
|
|
|
|
| 73 |
if not post_urns:
|
|
|
|
| 74 |
return [], org_name
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
stats_map = {}
|
| 77 |
+
for i in range(0, len(post_urns), 20):
|
| 78 |
+
batch = post_urns[i:i+20]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
params = {'q': 'organizationalEntity', 'organizationalEntity': org_urn}
|
| 80 |
+
for idx, urn in enumerate(batch):
|
| 81 |
+
key = f"shares[{idx}]" if ":share:" in urn else f"ugcPosts[{idx}]"
|
| 82 |
+
params[key] = urn
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
|
|
|
| 84 |
try:
|
| 85 |
+
stat_resp = session.get(f"{API_REST_BASE}/organizationalEntityShareStatistics", params=params)
|
| 86 |
+
stat_resp.raise_for_status()
|
| 87 |
+
for stat in stat_resp.json().get("elements", []):
|
| 88 |
+
urn = stat.get("share") or stat.get("ugcPost")
|
| 89 |
+
if urn:
|
| 90 |
+
stats_map[urn] = stat.get("totalShareStatistics", {})
|
| 91 |
+
except:
|
| 92 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
+
posts = []
|
|
|
|
| 95 |
for post in raw_posts:
|
| 96 |
post_id = post.get("id")
|
| 97 |
+
stats = stats_map.get(post_id, {})
|
| 98 |
+
timestamp = post.get("publishedAt") or post.get("createdAt")
|
| 99 |
+
when = datetime.fromtimestamp(timestamp / 1000).strftime("%Y-%m-%d %H:%M") if timestamp else "Unknown"
|
| 100 |
+
|
| 101 |
+
text = post.get("commentary") or post.get("specificContent", {}).get("com.linkedin.ugc.ShareContent", {}).get("shareCommentaryV2", {}).get("text") or "[No text]"
|
| 102 |
+
text = html.escape(text[:250]).replace("\n", "<br>") + ("..." if len(text) > 250 else "")
|
| 103 |
+
|
| 104 |
+
likes = stats.get("likeCount", 0)
|
| 105 |
+
comments = stats.get("commentCount", 0)
|
| 106 |
+
clicks = stats.get("clickCount", 0)
|
| 107 |
+
shares = stats.get("shareCount", 0)
|
| 108 |
+
impressions = stats.get("impressionCount", 0)
|
| 109 |
+
engagement = stats.get("engagement", likes + comments + clicks + shares) / impressions * 100 if impressions else 0.0
|
| 110 |
+
|
| 111 |
+
posts.append({
|
| 112 |
+
"id": post_id, "when": when, "text": text, "likes": likes,
|
| 113 |
+
"comments": comments, "clicks": clicks, "shares": shares,
|
| 114 |
+
"impressions": impressions, "engagement": f"{engagement:.2f}%"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
})
|
| 116 |
|
| 117 |
+
return posts, org_name
|
| 118 |
|
| 119 |
def render_post_cards(posts, org_name):
|
| 120 |
+
safe_name = html.escape(org_name or "Your Organization")
|
|
|
|
| 121 |
if not posts:
|
| 122 |
+
return f"<h2 style='text-align:center;color:#555;'>No recent posts found for {safe_name}.</h2>"
|
| 123 |
+
|
| 124 |
+
cards = [
|
| 125 |
+
f"<div style='border:1px solid #ccc;border-radius:8px;padding:15px;width:280px;background:#fff;'>"
|
| 126 |
+
f"<div style='font-size:0.8em;color:#666;margin-bottom:8px;'>{p['when']}</div>"
|
| 127 |
+
f"<div style='font-size:0.95em;margin-bottom:12px;max-height:120px;overflow:auto'>{p['text']}</div>"
|
| 128 |
+
f"<div style='font-size:0.9em;color:#333;border-top:1px solid #eee;padding-top:10px;'>"
|
| 129 |
+
f"ποΈ {p['impressions']:,} | π {p['likes']:,} | π¬ {p['comments']:,} | π {p['shares']:,} | π±οΈ {p['clicks']:,}<br>"
|
| 130 |
+
f"<strong>π {p['engagement']}</strong></div></div>"
|
| 131 |
+
for p in posts
|
| 132 |
+
]
|
| 133 |
+
return f"<h2 style='text-align:center;margin-bottom:20px;'>Recent Posts for {safe_name}</h2><div style='display:flex;flex-wrap:wrap;gap:15px;justify-content:center;'>" + "".join(cards) + "</div>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
def fetch_and_render_dashboard(comm_client_id, community_token):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
try:
|
| 137 |
+
posts, org_name = fetch_posts_and_stats(comm_client_id, community_token)
|
| 138 |
+
return render_post_cards(posts, org_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
except Exception as e:
|
| 140 |
+
return display_error("Dashboard Error", e).get('value', '<p style="color:red;text-align:center;">β An error occurred.</p>')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|