iOS/Sources/Shared/Notifications/NotificationAttachments/NotificationAttachmentParserURL.swift
Zac West 85b5ec4579
Support attachments which aren't downloaded in advance (#1610)
## Summary
Allows attachments to be loaded on-the-fly in the content extension if they are not present.

## Link to pull request in Documentation repository
Documentation: home-assistant/companion.home-assistant#510

## Any other notes
- Adds `lazy` as an option to the `attachment` dictionary. When true, this prevents the attachment from being downloaded except when displayed in the content extension.  
  
This is similar, but not identical, to hide-thumbnail. Hiding the thumbnail still uses the internal storage of the notifications which are limited to e.g. 50mb. However, we'd still want to pre-load those attachments even if the thumbnail is hidden.
- Retries non-lazy attachments which failed due to a network error when the content extension opens.
2021-05-01 12:58:30 -07:00

45 lines
1.5 KiB
Swift

import Foundation
import PromiseKit
import UserNotifications
final class NotificationAttachmentParserURL: NotificationAttachmentParser {
enum URLError: LocalizedError {
case noURL
case invalidURL
var errorDescription: String? {
switch self {
case .noURL: return L10n.NotificationService.Parser.Url.noUrl
case .invalidURL: return L10n.NotificationService.Parser.Url.invalidUrl
}
}
}
func attachmentInfo(from content: UNNotificationContent) -> Guarantee<NotificationAttachmentParserResult> {
guard let attachment = content.userInfo["attachment"] as? [String: Any] else {
return .value(.missing)
}
guard let urlString = attachment["url"] as? String else {
return .value(.rejected(URLError.noURL))
}
guard let url = URL(string: urlString) else {
return .value(.rejected(URLError.invalidURL))
}
let needsAuth: Bool = urlString.hasPrefix("/")
let contentType = (attachment["content-type"] as? String).flatMap(NotificationAttachmentInfo.contentType(for:))
let hideThumbnail = attachment["hide-thumbnail"] as? Bool
let lazy = attachment["lazy"] as? Bool == true
return .value(.fulfilled(.init(
url: url,
needsAuth: needsAuth,
typeHint: contentType,
hideThumbnail: hideThumbnail,
lazy: lazy
)))
}
}