Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / LinkedInPages.swift

Raw 5.8 KB on 3299148fb8af57afc73c4a39f59b66f2ac2bca32
1import Foundation
2
3struct LinkedInDestination: Codable, Identifiable, Equatable, Sendable {
4 let kind: String
5 let urn: String
6 let memberId: String
7 let name: String
8
9 var id: String { urn }
10
11 var fields: [String: String] { ["kind": kind, "urn": urn, "memberId": memberId, "name": name] }
12
13 init(kind: String, urn: String, memberId: String, name: String) {
14 self.kind = kind
15 self.urn = urn
16 self.memberId = memberId
17 self.name = name
18 }
19
20 init?(fields: [String: Any]?) {
21 guard let fields, let kind = fields["kind"] as? String, let urn = fields["urn"] as? String,
22 let member = fields["memberId"] as? String, let name = fields["name"] as? String,
23 !name.isEmpty, name.utf16.count <= 300,
24 member.range(of: #"\A[A-Za-z0-9_-]{1,200}\z"#, options: .regularExpression) != nil else { return nil }
25 if kind == "personal" {
26 guard urn == "urn:li:person:" + member else { return nil }
27 } else {
28 guard kind == "organization", Self.validOrganization(urn) else { return nil }
29 }
30 self.init(kind: kind, urn: urn, memberId: member, name: name)
31 }
32
33 static func personal(_ account: ManagedSocialAccount) -> Self {
34 Self(kind: "personal", urn: "urn:li:person:" + account.id, memberId: account.id, name: account.name)
35 }
36
37 static func validOrganization(_ urn: String) -> Bool {
38 urn.range(of: #"\Aurn:li:organization:[0-9]{1,24}\z"#, options: .regularExpression) != nil
39 }
40}
41
42enum LinkedInPages {
43 static let headers = ["LinkedIn-Version": "202609", "X-Restli-Protocol-Version": "2.0.0"]
44 private static let roles: Set<String> = ["ADMINISTRATOR", "CONTENT_ADMINISTRATOR", "CONTENT_ADMIN"]
45
46 static func available(_ account: ManagedSocialAccount) -> Bool {
47 let scopes = (account.session.scopes ?? "").split { $0.isWhitespace || $0 == "," }
48 return scopes.contains("w_organization_social")
49 && (scopes.contains("r_organization_admin") || scopes.contains("rw_organization_admin"))
50 }
51
52 static func schedulingDestination(for draft: WorkspaceRecord, account: ManagedSocialAccount,
53 selected: LinkedInDestination? = nil) throws -> LinkedInDestination {
54 let personal = LinkedInDestination.personal(account)
55 let saved = LinkedInDestination(fields: draft.fields["linkedinDestination"] as? [String: Any])
56 guard selected != nil || draft.fields["linkedinDestination"] == nil || saved != nil else {
57 throw WorkspaceError("Choose a valid LinkedIn destination before scheduling.")
58 }
59 let requested = selected ?? saved ?? personal
60 let destinations = [personal] + (available(account) ? account.linkedInPages ?? [] : [])
61 guard requested.memberId == account.id,
62 let destination = destinations.first(where: { $0.urn == requested.urn && $0.memberId == account.id }) else {
63 throw WorkspaceError("Choose your current LinkedIn profile or refresh the company pages in Connections before scheduling.")
64 }
65 let scopes = (account.session.scopes ?? "").split { $0.isWhitespace || $0 == "," }
66 guard destination.kind != "personal" || scopes.isEmpty || scopes.contains("w_member_social") else {
67 throw WorkspaceError("Reconnect LinkedIn with permission to publish to your profile.")
68 }
69 return destination
70 }
71
72 @MainActor
73 static func refresh(_ account: ManagedSocialAccount, transport: SocialTransport) async throws -> [LinkedInDestination] {
74 guard available(account) else { throw WorkspaceError("Reconnect a LinkedIn developer app with company-page access.") }
75 var organizations: Set<String> = []
76 let acl = URL(string: "https://api.linkedin.com/rest/organizationAcls")!
77 for start in stride(from: 0, to: 1000, by: 100) {
78 let url = acl.appending(queryItems: [
79 .init(name: "q", value: "roleAssignee"), .init(name: "state", value: "APPROVED"),
80 .init(name: "start", value: String(start)), .init(name: "count", value: "100")
81 ])
82 let (result, _) = try await transport.request(url, token: account.session.accessToken, headers: headers)
83 guard let entries = result["elements"] as? [[String: Any]], entries.count <= 100 else {
84 throw WorkspaceError("LinkedIn returned an unreadable company-page list.")
85 }
86 for row in entries {
87 if row["state"] as? String == "APPROVED", row["roleAssignee"] as? String == "urn:li:person:" + account.id,
88 let role = row["role"] as? String, roles.contains(role),
89 let urn = row["organization"] as? String, LinkedInDestination.validOrganization(urn) {
90 organizations.insert(urn)
91 }
92 }
93 if entries.count < 100 { break }
94 if start == 900 { throw WorkspaceError("LinkedIn returned too many company-page roles.") }
95 }
96 var pages: [LinkedInDestination] = []
97 for urn in organizations.sorted() {
98 let id = urn.split(separator: ":").last.map(String.init) ?? ""
99 let url = URL(string: "https://api.linkedin.com/rest/organizations/")!.appending(path: id)
100 let (value, _) = try await transport.request(url, token: account.session.accessToken, headers: headers)
101 let returnedID = value["id"] as? String ?? (value["id"] as? NSNumber)?.stringValue
102 guard returnedID == id, let name = value["localizedName"] as? String,
103 !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
104 throw WorkspaceError("LinkedIn didn’t identify the company page.")
105 }
106 pages.append(LinkedInDestination(kind: "organization", urn: urn, memberId: account.id, name: String(name.prefix(300))))
107 }
108 return pages
109 }
110}