Jobley / app · jobley.ai / Sources / JobleyKit / APIClient.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// Which app is calling. The API records it in the audit log, and refuses people-only actions |
| 4 | /// (approve, reject, publish, unpublish, anything about candidates) from `mcp`. |
| 5 | public enum ClientKind: String, Sendable { |
| 6 | case mac, iphone, mcp |
| 7 | } |
| 8 | |
| 9 | /// Every error the API sends: `{ok:false, error, message, fields?, status?}`. |
| 10 | public struct APIError: Error, LocalizedError, Equatable, Sendable { |
| 11 | public var code: String |
| 12 | public var message: String |
| 13 | public var fields: [String: String] |
| 14 | public var status: String? |
| 15 | public var httpStatus: Int |
| 16 | |
| 17 | public init(code: String, message: String, fields: [String: String] = [:], status: String? = nil, httpStatus: Int = 0) { |
| 18 | self.code = code; self.message = message; self.fields = fields; self.status = status; self.httpStatus = httpStatus |
| 19 | } |
| 20 | |
| 21 | public var errorDescription: String? { |
| 22 | if fields.isEmpty { return message } |
| 23 | return message + " " + fields.sorted { $0.key < $1.key }.map(\.value).joined(separator: " ") |
| 24 | } |
| 25 | |
| 26 | public static let signedOut = APIError(code: "unauthorized", message: "Sign in with your passkey in Settings first.", httpStatus: 401) |
| 27 | } |
| 28 | |
| 29 | /// A job post from the "Post a job" form (`POST /api/jobs`). |
| 30 | public struct JobDraft: Equatable, Sendable { |
| 31 | public var title = "", company = "", companyURL = "", location = "" |
| 32 | public var workplace = "", employmentType = "", category = "" |
| 33 | public var payMin = "", payMax = "", payPeriod = "hour", payCurrency = "USD" |
| 34 | public var description = "", applyURL = "", contactName = "", contactEmail = "" |
| 35 | |
| 36 | public init() {} |
| 37 | |
| 38 | func body(turnstileToken: String?) -> [String: Any] { |
| 39 | var body: [String: Any] = [ |
| 40 | "title": title, "company": company, "location": location, "workplace": workplace, |
| 41 | "employment_type": employmentType, "category": category, "pay_period": payPeriod, |
| 42 | "pay_currency": payCurrency.uppercased(), "description": description, |
| 43 | "contact_name": contactName, "contact_email": contactEmail, |
| 44 | "pay_min": Int(payMin.filter(\.isNumber)) ?? payMin, "pay_max": Int(payMax.filter(\.isNumber)) ?? payMax |
| 45 | ] |
| 46 | if !companyURL.isEmpty { body["company_url"] = companyURL } |
| 47 | if !applyURL.isEmpty { body["apply_url"] = applyURL } |
| 48 | if let turnstileToken { body["turnstile_token"] = turnstileToken } |
| 49 | return body |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | /// "Put me forward" (`POST /api/candidates`), for one job or for a kind of job. |
| 54 | public struct CandidateDraft: Equatable, Sendable { |
| 55 | public var jobID: String? |
| 56 | public var name = "", email = "", headline = "", location = "", lookingFor = "", about = "" |
| 57 | public var links = "", resumeURL = "" |
| 58 | public var consent = false |
| 59 | |
| 60 | public init(jobID: String? = nil) { self.jobID = jobID } |
| 61 | |
| 62 | func body(turnstileToken: String?) -> [String: Any] { |
| 63 | var body: [String: Any] = ["name": name, "email": email, "headline": headline, "consent": consent] |
| 64 | if let jobID { body["job_id"] = jobID } |
| 65 | if !location.isEmpty { body["location"] = location } |
| 66 | if !lookingFor.isEmpty { body["looking_for"] = lookingFor } |
| 67 | if !about.isEmpty { body["about"] = about } |
| 68 | if !resumeURL.isEmpty { body["resume_url"] = resumeURL } |
| 69 | let list = links.split(whereSeparator: { $0.isNewline || $0 == " " || $0 == "," }).map(String.init).filter { !$0.isEmpty } |
| 70 | if !list.isEmpty { body["links"] = list } |
| 71 | if let turnstileToken { body["turnstile_token"] = turnstileToken } |
| 72 | return body |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /// The fields an edit may change (`PATCH /api/admin/jobs/:id`). Contact and status never change here. |
| 77 | public struct JobEdit: Equatable, Sendable { |
| 78 | public var title: String, company: String, companyURL: String, location: String |
| 79 | public var workplace: String, employmentType: String, category: String |
| 80 | public var payMin: Int, payMax: Int, payPeriod: String, payCurrency: String |
| 81 | public var description: String, applyURL: String |
| 82 | |
| 83 | public init(_ job: Job) { |
| 84 | title = job.title; company = job.company; companyURL = job.companyURL ?? ""; location = job.location |
| 85 | workplace = job.workplace; employmentType = job.employmentType; category = job.category |
| 86 | payMin = job.pay.min; payMax = job.pay.max; payPeriod = job.pay.period; payCurrency = job.pay.currency |
| 87 | description = job.description; applyURL = job.applyURL ?? "" |
| 88 | } |
| 89 | |
| 90 | /// Only the fields that differ from the job, so the audit log shows what really changed. |
| 91 | public func changes(from job: Job) -> [String: Any] { |
| 92 | let before = JobEdit(job) |
| 93 | var out: [String: Any] = [:] |
| 94 | if title != before.title { out["title"] = title } |
| 95 | if company != before.company { out["company"] = company } |
| 96 | if companyURL != before.companyURL { out["company_url"] = companyURL } |
| 97 | if location != before.location { out["location"] = location } |
| 98 | if workplace != before.workplace { out["workplace"] = workplace } |
| 99 | if employmentType != before.employmentType { out["employment_type"] = employmentType } |
| 100 | if category != before.category { out["category"] = category } |
| 101 | if payMin != before.payMin || payMax != before.payMax { out["pay_min"] = payMin; out["pay_max"] = payMax } |
| 102 | if payPeriod != before.payPeriod { out["pay_period"] = payPeriod } |
| 103 | if payCurrency != before.payCurrency { out["pay_currency"] = payCurrency } |
| 104 | if description != before.description { out["description"] = description } |
| 105 | if applyURL != before.applyURL { out["apply_url"] = applyURL } |
| 106 | return out |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /// The Jobley API (PRD section 7). Public calls need no token; admin calls send |
| 111 | /// `Authorization: Bearer <session token from a passkey sign-in>` and `X-Client`. |
| 112 | public struct APIClient: Sendable { |
| 113 | public let base: URL |
| 114 | public let client: ClientKind |
| 115 | public let token: String? |
| 116 | let session: URLSession |
| 117 | |
| 118 | /// Production until jobley.ai is connected. `JOBLEY_API_BASE` (tests, local work) and the |
| 119 | /// "Server" setting override it. |
| 120 | public static let productionBase = URL(string: "https://jobley.ai")! |
| 121 | public static let serverDefaultsKey = "jobley.server" |
| 122 | |
| 123 | public static var configuredBase: URL { |
| 124 | if let env = ProcessInfo.processInfo.environment["JOBLEY_API_BASE"], let url = URL(string: env) { return url } |
| 125 | if let saved = UserDefaults.standard.string(forKey: serverDefaultsKey), let url = URL(string: saved), url.scheme != nil { return url } |
| 126 | return productionBase |
| 127 | } |
| 128 | |
| 129 | public init(base: URL = APIClient.configuredBase, client: ClientKind, token: String? = nil, session: URLSession = .shared) { |
| 130 | self.base = base; self.client = client; self.token = token?.trimmingCharacters(in: .whitespacesAndNewlines); self.session = session |
| 131 | } |
| 132 | |
| 133 | public var hasToken: Bool { !(token ?? "").isEmpty } |
| 134 | public var turnstilePage: URL { base.appending(path: "app/turnstile/") } |
| 135 | public func withToken(_ token: String?) -> APIClient { APIClient(base: base, client: client, token: token, session: session) } |
| 136 | |
| 137 | // MARK: Public |
| 138 | |
| 139 | public func meta() async throws -> Meta { try await get("api/meta") } |
| 140 | |
| 141 | public func jobs(query: String = "", workplace: String = "", type: String = "", category: String = "", |
| 142 | limit: Int = 30, cursor: String? = nil) async throws -> JobPage { |
| 143 | var items = [URLQueryItem(name: "limit", value: String(limit))] |
| 144 | if !query.isEmpty { items.append(.init(name: "q", value: String(query.prefix(80)))) } |
| 145 | if !workplace.isEmpty { items.append(.init(name: "workplace", value: workplace)) } |
| 146 | if !type.isEmpty { items.append(.init(name: "type", value: type)) } |
| 147 | if !category.isEmpty { items.append(.init(name: "category", value: category)) } |
| 148 | if let cursor { items.append(.init(name: "cursor", value: cursor)) } |
| 149 | return try await get("api/jobs", query: items) |
| 150 | } |
| 151 | |
| 152 | public func job(_ id: String) async throws -> Job { |
| 153 | let reply: JobReply = try await get("api/jobs/\(id)") |
| 154 | return reply.job |
| 155 | } |
| 156 | |
| 157 | public func post(_ draft: JobDraft, turnstileToken: String?) async throws -> PostedJob { |
| 158 | try await send("POST", "api/jobs", body: draft.body(turnstileToken: turnstileToken), admin: false) |
| 159 | } |
| 160 | |
| 161 | public func close(job id: String, manageToken: String) async throws { |
| 162 | let _: Received = try await send("POST", "api/jobs/\(id)/close", body: ["manage_token": manageToken], admin: false) |
| 163 | } |
| 164 | |
| 165 | public func putForward(_ draft: CandidateDraft, turnstileToken: String?) async throws -> Received { |
| 166 | try await send("POST", "api/candidates", body: draft.body(turnstileToken: turnstileToken), admin: false) |
| 167 | } |
| 168 | |
| 169 | // MARK: Admin: jobs |
| 170 | |
| 171 | public func me() async throws -> Me { try await get("api/admin/me", admin: true) } |
| 172 | public func stats() async throws -> Stats { try await get("api/admin/stats", admin: true) } |
| 173 | |
| 174 | public func adminJobs(status: String, limit: Int = 100) async throws -> [Job] { |
| 175 | let reply: JobsReply = try await get("api/admin/jobs", query: [.init(name: "status", value: status), .init(name: "limit", value: String(limit))], admin: true) |
| 176 | return reply.jobs |
| 177 | } |
| 178 | |
| 179 | public func reviewItem(_ id: String) async throws -> JobReviewItem { try await get("api/admin/jobs/\(id)", admin: true) } |
| 180 | |
| 181 | public func edit(job id: String, changes: [String: Any]) async throws -> Job { |
| 182 | let reply: JobReply = try await send("PATCH", "api/admin/jobs/\(id)", body: changes) |
| 183 | return reply.job |
| 184 | } |
| 185 | |
| 186 | @discardableResult |
| 187 | public func addNote(job id: String, note: String) async throws -> String { |
| 188 | let reply: IDReply = try await send("POST", "api/admin/jobs/\(id)/notes", body: ["note": note]) |
| 189 | return reply.id |
| 190 | } |
| 191 | |
| 192 | /// The normal one-step "Publish" is `approve(publish: true)`. |
| 193 | public func approve(job id: String, publish: Bool, reason: String? = nil) async throws -> Job { |
| 194 | var body: [String: Any] = ["publish": publish] |
| 195 | if let reason, !reason.isEmpty { body["reason"] = reason } |
| 196 | let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/approve", body: body) |
| 197 | return reply.job |
| 198 | } |
| 199 | |
| 200 | /// "Send back": the reason is required and goes to the poster. |
| 201 | public func reject(job id: String, reason: String) async throws -> Job { |
| 202 | let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/reject", body: ["reason": reason]) |
| 203 | return reply.job |
| 204 | } |
| 205 | |
| 206 | public func publish(job id: String) async throws -> Job { |
| 207 | let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/publish", body: [:]) |
| 208 | return reply.job |
| 209 | } |
| 210 | |
| 211 | public func unpublish(job id: String, reason: String? = nil) async throws -> Job { |
| 212 | var body: [String: Any] = [:] |
| 213 | if let reason, !reason.isEmpty { body["reason"] = reason } |
| 214 | let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/unpublish", body: body) |
| 215 | return reply.job |
| 216 | } |
| 217 | |
| 218 | // MARK: Admin: candidates (people only, never agents) |
| 219 | |
| 220 | /// `jobID` nil lists everyone; "none" lists people who asked about a kind of job. Oldest first. |
| 221 | public func candidates(jobID: String? = nil, status: String? = nil, limit: Int = 200) async throws -> [Candidate] { |
| 222 | var items = [URLQueryItem(name: "limit", value: String(limit))] |
| 223 | if let jobID { items.append(.init(name: "job_id", value: jobID)) } |
| 224 | if let status, !status.isEmpty { items.append(.init(name: "status", value: status)) } |
| 225 | let reply: CandidatesReply = try await get("api/admin/candidates", query: items, admin: true) |
| 226 | return reply.candidates |
| 227 | } |
| 228 | |
| 229 | public func candidate(_ id: String) async throws -> CandidateDetail { try await get("api/admin/candidates/\(id)", admin: true) } |
| 230 | |
| 231 | public func introduce(candidate id: String, jobID: String?, note: String?) async throws -> IntroductionResult { |
| 232 | var body: [String: Any] = [:] |
| 233 | if let jobID { body["job_id"] = jobID } |
| 234 | if let note, !note.isEmpty { body["note"] = note } |
| 235 | return try await send("POST", "api/admin/candidates/\(id)/introduce", body: body) |
| 236 | } |
| 237 | |
| 238 | public func setStatus(candidate id: String, status: String, note: String? = nil) async throws -> Candidate { |
| 239 | var body: [String: Any] = ["status": status] |
| 240 | if let note, !note.isEmpty { body["note"] = note } |
| 241 | let reply: CandidateReply = try await send("POST", "api/admin/candidates/\(id)/status", body: body) |
| 242 | return reply.candidate |
| 243 | } |
| 244 | |
| 245 | // MARK: Admin: moderators (curator only) |
| 246 | |
| 247 | public func moderatorApplications(status: String = "new") async throws -> [ModeratorApplication] { |
| 248 | let reply: ApplicationsReply = try await get("api/admin/moderator-applications", query: [.init(name: "status", value: status)], admin: true) |
| 249 | return reply.applications |
| 250 | } |
| 251 | |
| 252 | public func approve(application id: String, canSeeCandidates: Bool) async throws -> NewModerator { |
| 253 | try await send("POST", "api/admin/moderator-applications/\(id)/approve", body: ["can_see_candidates": canSeeCandidates]) |
| 254 | } |
| 255 | |
| 256 | public func decline(application id: String, note: String? = nil) async throws { |
| 257 | var body: [String: Any] = [:] |
| 258 | if let note, !note.isEmpty { body["note"] = note } |
| 259 | let _: IDReply = try await send("POST", "api/admin/moderator-applications/\(id)/decline", body: body) |
| 260 | } |
| 261 | |
| 262 | public func moderators() async throws -> [Moderator] { |
| 263 | let reply: ModeratorsReply = try await get("api/admin/moderators", admin: true) |
| 264 | return reply.moderators |
| 265 | } |
| 266 | |
| 267 | public func setAccess(moderator id: String, canSeeCandidates: Bool) async throws { |
| 268 | let _: IDReply = try await send("POST", "api/admin/moderators/\(id)/access", body: ["can_see_candidates": canSeeCandidates]) |
| 269 | } |
| 270 | |
| 271 | public func revoke(moderator id: String) async throws { |
| 272 | let _: IDReply = try await send("POST", "api/admin/moderators/\(id)/revoke", body: [:]) |
| 273 | } |
| 274 | |
| 275 | /// Deletes what is past the retention period. The Mac app calls it when the curator opens it. |
| 276 | public func purge() async throws -> PurgeResult { try await send("POST", "api/admin/purge", body: [:]) } |
| 277 | |
| 278 | // MARK: Transport |
| 279 | |
| 280 | func get<T: Decodable>(_ path: String, query: [URLQueryItem] = [], admin: Bool = false) async throws -> T { |
| 281 | try await perform(request("GET", path, query: query, admin: admin)) |
| 282 | } |
| 283 | |
| 284 | func send<T: Decodable>(_ method: String, _ path: String, body: [String: Any], admin: Bool = true) async throws -> T { |
| 285 | var request = try request(method, path, admin: admin) |
| 286 | request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 287 | request.httpBody = try JSONSerialization.data(withJSONObject: body) |
| 288 | return try await perform(request) |
| 289 | } |
| 290 | |
| 291 | func request(_ method: String, _ path: String, query: [URLQueryItem] = [], admin: Bool) throws -> URLRequest { |
| 292 | var components = URLComponents(url: base.appending(path: path), resolvingAgainstBaseURL: false)! |
| 293 | if !query.isEmpty { components.queryItems = query } |
| 294 | // Always fresh: the board answers with cache-control max-age=60, and a curator must see a |
| 295 | // post disappear the moment it is unpublished. |
| 296 | var request = URLRequest(url: components.url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 30) |
| 297 | request.httpMethod = method |
| 298 | request.setValue("application/json", forHTTPHeaderField: "Accept") |
| 299 | request.setValue(client.rawValue, forHTTPHeaderField: "X-Client") |
| 300 | if admin { |
| 301 | guard let token, !token.isEmpty else { throw APIError.signedOut } |
| 302 | request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") |
| 303 | } |
| 304 | return request |
| 305 | } |
| 306 | |
| 307 | func perform<T: Decodable>(_ request: URLRequest) async throws -> T { |
| 308 | let data: Data, response: URLResponse |
| 309 | do { (data, response) = try await session.data(for: request) } |
| 310 | catch { throw APIError(code: "offline", message: "We couldn't reach Jobley. Check your connection and try again.") } |
| 311 | let status = (response as? HTTPURLResponse)?.statusCode ?? 0 |
| 312 | guard (200..<300).contains(status) else { throw Self.error(from: data, status: status) } |
| 313 | do { return try JSONDecoder().decode(T.self, from: data) } |
| 314 | catch { throw APIError(code: "bad_reply", message: "Jobley sent a reply we couldn't read.", httpStatus: status) } |
| 315 | } |
| 316 | |
| 317 | static func error(from data: Data, status: Int) -> APIError { |
| 318 | guard let reply = try? JSONDecoder().decode(ErrorReply.self, from: data) else { |
| 319 | return APIError(code: "http_\(status)", message: "Jobley answered with an error (\(status)). Please try again.", httpStatus: status) |
| 320 | } |
| 321 | return APIError(code: reply.error, message: reply.message, fields: reply.fields ?? [:], status: reply.status, httpStatus: status) |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | struct ErrorReply: Decodable { |
| 326 | var error: String |
| 327 | var message: String |
| 328 | var fields: [String: String]? |
| 329 | var status: String? |
| 330 | } |
| 331 | struct JobReply: Decodable { var job: Job } |
| 332 | struct JobsReply: Decodable { var jobs: [Job] } |
| 333 | struct IDReply: Decodable { var id: String } |
| 334 | struct CandidatesReply: Decodable { var candidates: [Candidate] } |
| 335 | struct CandidateReply: Decodable { var candidate: Candidate } |
| 336 | struct ApplicationsReply: Decodable { var applications: [ModeratorApplication] } |
| 337 | struct ModeratorsReply: Decodable { var moderators: [Moderator] } |