mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-09-02 22:59:56 +08:00
feat(ios): improve share preview (#15538)
#### PR Dependency Tree * **PR #15538** 👈 This tree was auto-generated by [Charcoal](https://github.com/danerwilliams/charcoal) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added rich link previews to mobile and iOS sharing, including images, metadata, transcripts, and selected text. * Share imports can now create structured content blocks, embeds, bookmarks, and transcript callouts. * Added workspace-aware preview handling for cloud, self-hosted, and signed-out modes. * **Accessibility** * Improved collapse/expand controls with semantic buttons and ARIA relationships. * **Bug Fixes** * Enhanced URL and error sanitization in server logs. * Improved link-preview CORS support, validation, and request handling. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
@@ -10,5 +10,9 @@ enum ShareInboxConstants {
|
||||
static let inboxDirectoryName = "ShareInbox"
|
||||
static let attachmentsDirectoryName = "Attachments"
|
||||
static let invalidDirectoryName = "Invalid"
|
||||
static let workspaceModeFileName = "ShareWorkspaceMode.json"
|
||||
static let officialLinkPreviewURL = URL(
|
||||
string: "https://app.affine.pro/api/worker/link-preview"
|
||||
)!
|
||||
static let openInboxURL = URL(string: "affine://share-inbox")!
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ struct ShareInboxItem: Codable, Equatable, Identifiable {
|
||||
var createdAt: Date
|
||||
var title: String
|
||||
var content: ShareInboxContent
|
||||
var previewRoute: SharePreviewRoute?
|
||||
var target: ShareInboxTarget?
|
||||
var previewText: String?
|
||||
var attachments: [ShareInboxAttachment]
|
||||
@@ -48,6 +49,7 @@ struct ShareInboxItem: Codable, Equatable, Identifiable {
|
||||
createdAt: Date = Date(),
|
||||
title: String,
|
||||
content: ShareInboxContent,
|
||||
previewRoute: SharePreviewRoute? = nil,
|
||||
target: ShareInboxTarget? = nil,
|
||||
previewText: String? = nil,
|
||||
attachments: [ShareInboxAttachment] = [],
|
||||
@@ -59,6 +61,7 @@ struct ShareInboxItem: Codable, Equatable, Identifiable {
|
||||
self.createdAt = createdAt
|
||||
self.title = title
|
||||
self.content = content
|
||||
self.previewRoute = previewRoute
|
||||
self.target = target
|
||||
self.previewText = previewText
|
||||
self.attachments = attachments
|
||||
|
||||
@@ -1,6 +1,44 @@
|
||||
import Foundation
|
||||
|
||||
enum ShareWorkspaceMode: String, Codable {
|
||||
case selfHostedPresent
|
||||
case cloudOnly
|
||||
case signedOut
|
||||
case unknown
|
||||
}
|
||||
|
||||
enum SharePreviewRoute: String, Codable {
|
||||
case official
|
||||
case deferred
|
||||
}
|
||||
|
||||
struct ShareWorkspaceModeSnapshot: Codable, Equatable {
|
||||
static let schemaVersion = 1
|
||||
|
||||
var mode: ShareWorkspaceMode
|
||||
var schemaVersion: Int
|
||||
var updatedAt: Date
|
||||
|
||||
init(mode: ShareWorkspaceMode, updatedAt: Date = Date()) {
|
||||
self.mode = mode
|
||||
self.schemaVersion = Self.schemaVersion
|
||||
self.updatedAt = updatedAt
|
||||
}
|
||||
}
|
||||
|
||||
enum ShareInboxSafety {
|
||||
private static let workspaceModeMaxAge: TimeInterval = 24 * 60 * 60
|
||||
|
||||
static func manifestTitle(original: String, userEdited: String?) -> String {
|
||||
(userEdited ?? original).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
static func previewTitle(original: String, userEdited: String?, serverTitle: String?) -> String {
|
||||
if let userEdited { return userEdited }
|
||||
guard let serverTitle, !serverTitle.isEmpty else { return original }
|
||||
return serverTitle
|
||||
}
|
||||
|
||||
static func normalizedManifestID(_ value: String) -> String? {
|
||||
UUID(uuidString: value)?.uuidString
|
||||
}
|
||||
@@ -22,6 +60,56 @@ enum ShareInboxSafety {
|
||||
return url.absoluteString
|
||||
}
|
||||
|
||||
static func isOfficialPreviewURL(_ value: String) -> Bool {
|
||||
guard let normalized = normalizedWebURL(value), let url = URL(string: normalized) else {
|
||||
return false
|
||||
}
|
||||
let host = url.host?.lowercased()
|
||||
let components = url.pathComponents.filter { $0 != "/" }
|
||||
if ["x.com", "www.x.com", "twitter.com", "www.twitter.com"].contains(host) {
|
||||
return components.count == 3
|
||||
&& components[1] == "status"
|
||||
&& !components[2].isEmpty
|
||||
&& components[2].allSatisfy(\.isNumber)
|
||||
}
|
||||
if host == "youtu.be" {
|
||||
return components.count == 1 && !components[0].isEmpty
|
||||
}
|
||||
if ["youtube.com", "www.youtube.com", "m.youtube.com"].contains(host) {
|
||||
if url.path == "/watch" {
|
||||
return !(URLComponents(url: url, resolvingAgainstBaseURL: false)?
|
||||
.queryItems?.first(where: { $0.name == "v" })?.value?.isEmpty ?? true)
|
||||
}
|
||||
return components.count == 2
|
||||
&& ["shorts", "live", "embed"].contains(components[0])
|
||||
&& !components[1].isEmpty
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
static func previewRoute(mode: ShareWorkspaceMode, url: String) -> SharePreviewRoute {
|
||||
if isOfficialPreviewURL(url) { return .official }
|
||||
switch mode {
|
||||
case .cloudOnly, .signedOut:
|
||||
return .official
|
||||
case .selfHostedPresent, .unknown:
|
||||
return .deferred
|
||||
}
|
||||
}
|
||||
|
||||
static func workspaceMode(from data: Data?, now: Date = Date()) -> ShareWorkspaceMode {
|
||||
guard let data else { return .unknown }
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .iso8601
|
||||
guard let snapshot = try? decoder.decode(ShareWorkspaceModeSnapshot.self, from: data),
|
||||
snapshot.schemaVersion == ShareWorkspaceModeSnapshot.schemaVersion,
|
||||
(0...workspaceModeMaxAge).contains(now.timeIntervalSince(snapshot.updatedAt))
|
||||
else {
|
||||
return .unknown
|
||||
}
|
||||
return snapshot.mode
|
||||
}
|
||||
|
||||
static func detectRasterImageMimeType(_ data: Data) -> String? {
|
||||
let bytes = [UInt8](data.prefix(12))
|
||||
if bytes.starts(with: [0xFF, 0xD8, 0xFF]) {
|
||||
|
||||
@@ -102,6 +102,21 @@ final class ShareInboxStore {
|
||||
try encoder.encode(item).write(to: fileURL, options: .atomic)
|
||||
}
|
||||
|
||||
func updateWorkspaceMode(_ mode: ShareWorkspaceMode) throws {
|
||||
guard let containerURL else { throw ShareInboxError.containerUnavailable }
|
||||
let url = containerURL.appendingPathComponent(ShareInboxConstants.workspaceModeFileName)
|
||||
try encoder.encode(ShareWorkspaceModeSnapshot(mode: mode)).write(to: url, options: .atomic)
|
||||
}
|
||||
|
||||
func workspaceMode() -> ShareWorkspaceMode {
|
||||
guard let containerURL,
|
||||
let data = try? Data(
|
||||
contentsOf: containerURL.appendingPathComponent(ShareInboxConstants.workspaceModeFileName)
|
||||
)
|
||||
else { return .unknown }
|
||||
return ShareInboxSafety.workspaceMode(from: data)
|
||||
}
|
||||
|
||||
func pendingItems() -> [ShareInboxItem] {
|
||||
guard ensureDirectories(), let inboxDirectoryURL else { return [] }
|
||||
guard let urls = try? fileManager.contentsOfDirectory(
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
struct ShareLinkPreview: Decodable, Equatable {
|
||||
struct Author: Decodable, Equatable {
|
||||
var name: String
|
||||
var handle: String?
|
||||
var avatar: String?
|
||||
}
|
||||
|
||||
struct Transcript: Decodable, Equatable {
|
||||
struct Segment: Decodable, Equatable {
|
||||
var text: String
|
||||
var startSeconds: Double?
|
||||
var durationSeconds: Double?
|
||||
var speaker: String?
|
||||
}
|
||||
|
||||
struct Chapter: Decodable, Equatable {
|
||||
var title: String
|
||||
var startSeconds: Double
|
||||
}
|
||||
|
||||
var language: String?
|
||||
var segments: [Segment]
|
||||
var chapters: [Chapter]?
|
||||
var truncated: Bool?
|
||||
}
|
||||
|
||||
var url: String
|
||||
var title: String?
|
||||
var siteName: String?
|
||||
var description: String?
|
||||
var images: [String]?
|
||||
var favicons: [String]?
|
||||
var mediaType: String?
|
||||
var provider: String?
|
||||
var author: Author?
|
||||
var publishedAt: String?
|
||||
var durationSeconds: Double?
|
||||
var transcript: Transcript?
|
||||
}
|
||||
|
||||
extension ShareLinkPreview.Transcript {
|
||||
var previewText: String? {
|
||||
let text = segments
|
||||
.map { $0.text.split(whereSeparator: \.isWhitespace).joined(separator: " ") }
|
||||
.filter { !$0.isEmpty }
|
||||
.joined(separator: " ")
|
||||
guard !text.isEmpty else { return nil }
|
||||
guard text.count > 240 else { return text }
|
||||
return String(text.prefix(240)) + "…"
|
||||
}
|
||||
}
|
||||
|
||||
enum ShareLinkPreviewState: Equatable {
|
||||
case idle
|
||||
case deferred
|
||||
case loading
|
||||
case loaded(ShareLinkPreview)
|
||||
case failed
|
||||
}
|
||||
|
||||
struct ShareLinkPreviewClient {
|
||||
private let session: URLSession
|
||||
private let appVersion: String
|
||||
|
||||
init(session: URLSession? = nil, appVersion: String? = nil) {
|
||||
self.appVersion = appVersion ?? Self.bundledAppVersion
|
||||
if let session {
|
||||
self.session = session
|
||||
} else {
|
||||
let configuration = URLSessionConfiguration.ephemeral
|
||||
configuration.timeoutIntervalForRequest = 4
|
||||
configuration.timeoutIntervalForResource = 6
|
||||
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
|
||||
configuration.urlCache = nil
|
||||
self.session = URLSession(configuration: configuration)
|
||||
}
|
||||
}
|
||||
|
||||
func fetch(url: String) async throws -> ShareLinkPreview {
|
||||
guard let normalized = ShareInboxSafety.normalizedWebURL(url) else {
|
||||
throw URLError(.badURL)
|
||||
}
|
||||
var request = URLRequest(url: ShareInboxConstants.officialLinkPreviewURL)
|
||||
request.httpMethod = "POST"
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
addClientHeaders(to: &request)
|
||||
request.httpBody = try JSONEncoder().encode(
|
||||
Request(url: normalized, include: ["transcript"])
|
||||
)
|
||||
let (data, response) = try await session.data(for: request)
|
||||
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
|
||||
throw URLError(.badServerResponse)
|
||||
}
|
||||
return try JSONDecoder().decode(ShareLinkPreview.self, from: data)
|
||||
}
|
||||
|
||||
func fetchImage(url value: String) async throws -> UIImage {
|
||||
guard let candidate = URL(
|
||||
string: value,
|
||||
relativeTo: ShareInboxConstants.officialLinkPreviewURL
|
||||
) else {
|
||||
throw URLError(.badURL)
|
||||
}
|
||||
let resolved = candidate.absoluteURL
|
||||
guard
|
||||
let normalized = ShareInboxSafety.normalizedWebURL(resolved.absoluteString),
|
||||
let url = URL(string: normalized)
|
||||
else {
|
||||
throw URLError(.badURL)
|
||||
}
|
||||
var request = URLRequest(
|
||||
url: url,
|
||||
cachePolicy: .reloadIgnoringLocalCacheData,
|
||||
timeoutInterval: 3
|
||||
)
|
||||
addClientHeaders(to: &request)
|
||||
let (data, response) = try await session.data(for: request)
|
||||
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
|
||||
throw URLError(.badServerResponse)
|
||||
}
|
||||
guard let image = UIImage(data: data) else {
|
||||
throw URLError(.cannotDecodeContentData)
|
||||
}
|
||||
return image
|
||||
}
|
||||
|
||||
func fetchImageIfPresent(url: String?) async -> UIImage? {
|
||||
guard let url else { return nil }
|
||||
return try? await fetchImage(url: url)
|
||||
}
|
||||
|
||||
private func addClientHeaders(to request: inout URLRequest) {
|
||||
request.setValue("AFFiNE/\(appVersion)", forHTTPHeaderField: "User-Agent")
|
||||
request.setValue(appVersion, forHTTPHeaderField: "x-affine-version")
|
||||
}
|
||||
|
||||
private struct Request: Encodable {
|
||||
var url: String
|
||||
var include: [String]
|
||||
}
|
||||
|
||||
private struct AppConfig: Decodable {
|
||||
var affineVersion: String
|
||||
}
|
||||
|
||||
private static var bundledAppVersion: String {
|
||||
if let url = Bundle.main.url(forResource: "capacitor.config", withExtension: "json"),
|
||||
let data = try? Data(contentsOf: url),
|
||||
let version = try? JSONDecoder().decode(AppConfig.self, from: data).affineVersion,
|
||||
!version.isEmpty
|
||||
{
|
||||
return version
|
||||
}
|
||||
if let version = Bundle.main.object(
|
||||
forInfoDictionaryKey: "CFBundleShortVersionString"
|
||||
) as? String, !version.isEmpty {
|
||||
return version
|
||||
}
|
||||
return "0.2"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user