SPB Git

Repository Public

NotificationService.swift 5.5 KB 83 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/NotificationService/NotificationService.swift3// Description: The notification service extension. It fetches nothing: the server already wrote the notification at the account's preview4// level. Its two jobs: (1) privacy — while SP Mail is locked, or when this device hides senders and subjects, the text is replaced by the5// generic one before the system shows it; (2) presentation — a new-mail notification that may show its sender becomes a communication6// notification (sender monogram as avatar, grouped by conversation). Whatever fails, a notification is delivered — redacted when in doubt.7import CoreGraphics8import CoreText9import Foundation10import ImageIO11import Intents12import SPMailCore13import SPMailSystem14import UniformTypeIdentifiers15import UserNotifications1617final class NotificationService: UNNotificationServiceExtension, @unchecked Sendable {18    private var handler: ((UNNotificationContent) -> Void)?19    private var best: UNMutableNotificationContent?20    private let lock = NSLock()2122    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {23        guard let content = request.content.mutableCopy() as? UNMutableNotificationContent else { contentHandler(request.content); return }24        let kind = NotificationPayload(userInfo: content.userInfo)?.kind ?? .unknown25        // the shared state (keychain group): unreadable or never written means the most private level, never a failure26        let state = SharedStore.open().state()27        let text = NotificationText(title: content.title, subtitle: content.subtitle, body: content.body)28        if let redacted = NotificationRedactor.redact(text, kind: kind, state: state, french: ExtConfig.isFrench) {29            content.title = redacted.title; content.subtitle = redacted.subtitle; content.body = redacted.body30            contentHandler(content)31            return32        }33        lock.withLock { handler = contentHandler; best = content }34        // a sender may be shown: present it as a message from that person35        guard kind == .new, !content.title.isEmpty, content.title != "SP Mail" else { finish(content); return }36        let sender = content.title37        let person = INPerson(personHandle: INPersonHandle(value: nil, type: .unknown), nameComponents: nil, displayName: sender, image: Monogram.image(name: sender), contactIdentifier: nil, customIdentifier: nil)38        let intent = INSendMessageIntent(recipients: nil, outgoingMessageType: .outgoingMessageText, content: nil, speakableGroupName: nil,39                                         conversationIdentifier: content.threadIdentifier.isEmpty ? nil : content.threadIdentifier, serviceName: "SP Mail", sender: person, attachments: nil)40        let interaction = INInteraction(intent: intent, response: nil)41        interaction.direction = .incoming42        interaction.donate(completion: nil)43        if let updated = try? content.updating(from: intent) { finish(updated) } else { finish(content) }44    }4546    /// The system is about to give up on the extension: deliver what we have (already safe: redaction happens first).47    override func serviceExtensionTimeWillExpire() {48        if let best = lock.withLock({ best }) { finish(best) }49    }5051    private func finish(_ content: UNNotificationContent) {52        let h = lock.withLock { let h = handler; handler = nil; return h }53        h?(content)54    }55}5657/// The sender's initials on the stable colour the app uses for that correspondent (SPMailCore `AvatarStyle`), drawn with Core Graphics.58enum Monogram {59    static func image(name: String, size: Int = 120) -> INImage? {60        let style = AvatarStyle(name: name, address: name)61        guard let ctx = CGContext(data: nil, width: size, height: size, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }62        let (r, g, b) = rgb(style.lightHex)63        ctx.setFillColor(red: r, green: g, blue: b, alpha: 1)64        ctx.fillEllipse(in: CGRect(x: 0, y: 0, width: size, height: size))65        let font = CTFontCreateUIFontForLanguage(.system, CGFloat(size) * 0.42, nil) ?? CTFontCreateWithName("Helvetica" as CFString, CGFloat(size) * 0.42, nil)66        let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key(kCTFontAttributeName as String): font, NSAttributedString.Key(kCTForegroundColorAttributeName as String): CGColor(red: 1, green: 1, blue: 1, alpha: 1)]67        let line = CTLineCreateWithAttributedString(NSAttributedString(string: style.initials, attributes: attributes))68        let bounds = CTLineGetBoundsWithOptions(line, .useOpticalBounds)69        ctx.textPosition = CGPoint(x: (CGFloat(size) - bounds.width) / 2 - bounds.minX, y: (CGFloat(size) - bounds.height) / 2 - bounds.minY)70        CTLineDraw(line, ctx)71        guard let cg = ctx.makeImage() else { return nil }72        let data = NSMutableData()73        guard let dest = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil) else { return nil }74        CGImageDestinationAddImage(dest, cg, nil)75        guard CGImageDestinationFinalize(dest) else { return nil }76        return INImage(imageData: data as Data)77    }78    private static func rgb(_ hex: String) -> (CGFloat, CGFloat, CGFloat) {79        let v = UInt32(hex.trimmingCharacters(in: CharacterSet(charactersIn: "#")), radix: 16) ?? 0x2c5b4d80        return (CGFloat((v >> 16) & 0xff) / 255, CGFloat((v >> 8) & 0xff) / 255, CGFloat(v & 0xff) / 255)81    }82}83
Files main
Menu

Theme