Skip to content
1 change: 1 addition & 0 deletions TypeTypeIOS/App/AppDependencies+Live.swift
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ extension AppDependencies {
serverStore.selectedServer()?.baseURL
}
),
liveChatService: LiveChatService(transport: URLSessionLiveChatTransport(client: client)),
platform: platform,
crashReports: crashReports
)
Expand Down
3 changes: 3 additions & 0 deletions TypeTypeIOS/App/AppDependencies.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ final class AppDependencies {
let versionService: LiveVersionServiceProtocol
let youtubeSessionService: LiveYouTubeSessionServiceProtocol?
let playbackService: LivePlaybackServiceProtocol?
let liveChatService: LiveChatService?
let watchProgress: LiveWatchProgressStore
let imagePipeline: TypeTypeImagePipeline
let platform: LivePlatformServices
Expand Down Expand Up @@ -150,6 +151,7 @@ final class AppDependencies {
versionService: LiveVersionServiceProtocol = LiveVersionUnavailableService(),
youtubeSessionService: LiveYouTubeSessionServiceProtocol? = nil,
playbackService: LivePlaybackServiceProtocol? = nil,
liveChatService: LiveChatService? = nil,
watchProgress: LiveWatchProgressStore = LiveWatchProgressStore(),
imagePipeline: TypeTypeImagePipeline = TypeTypeImagePipeline(),
platform: LivePlatformServices,
Expand Down Expand Up @@ -193,6 +195,7 @@ final class AppDependencies {
self.versionService = versionService
self.youtubeSessionService = youtubeSessionService
self.playbackService = playbackService
self.liveChatService = liveChatService
self.watchProgress = watchProgress
self.imagePipeline = imagePipeline
self.platform = platform
Expand Down
58 changes: 58 additions & 0 deletions TypeTypeIOS/Core/Networking/URLSessionLiveChatTransport.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import Foundation

// Carries the live chat stream over URLSession. It has a session of its own: the API and media sessions end a
// transfer after 120 to 180 seconds, and a live can run for hours.
struct URLSessionLiveChatTransport: LiveChatTransport, @unchecked Sendable {
let client: URLSessionAPIClient
var session: URLSession = Self.makeSession()

// The server sends a keep-alive every 15 seconds; a minute without a byte means the connection is dead.
static let idleTimeout: TimeInterval = 60

func open(videoURL: String) async throws -> AsyncThrowingStream<UInt8, Error> {
try DebugNetworkOutage.check()
// The stream is public on an open instance; a signed-in session sends its token like every other request.
let signedIn = client.accessTokenProvider() != nil
var request = try client.makeURLRequest(
APIEndpoint(
path: "/live-chat",
method: .get,
queryItems: [URLQueryItem(name: "url", value: videoURL)],
requiresAuth: signedIn,
timeoutInterval: Self.idleTimeout
)
)
// JSON too: the server writes its refusals as JSON, and a request that accepts only the stream gets every one of
// them as 406, which hides a 429 or a 502 that waiting would solve.
request.setValue("text/event-stream, application/json", forHTTPHeaderField: "Accept")
let (bytes, response) = try await session.bytes(for: request)
guard let http = response as? HTTPURLResponse else { throw NetworkError.invalidResponse }
guard (200...299).contains(http.statusCode) else {
throw LiveChatRefused(
status: http.statusCode,
retryAfter: http.value(forHTTPHeaderField: "Retry-After").flatMap(TimeInterval.init)
)
}
return AsyncThrowingStream { continuation in
let pump = Task {
do {
for try await byte in bytes { continuation.yield(byte) }
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
continuation.onTermination = { _ in pump.cancel() }
}
}

static func makeSession() -> URLSession {
let configuration = URLSessionConfiguration.default
configuration.urlCache = nil
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
configuration.timeoutIntervalForRequest = idleTimeout
configuration.timeoutIntervalForResource = 24 * 60 * 60
configuration.waitsForConnectivity = false
return URLSession(configuration: configuration)
}
}
54 changes: 54 additions & 0 deletions TypeTypeIOS/Features/Watch/Models/LiveChatBuffer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import Foundation

// What the chat column shows: the newest messages and where the connection stands. Replayed messages (a
// reconnect may deliver the last batch again) are shown once.
struct LiveChatBuffer: Equatable {
enum Status: Equatable {
case connecting
case connected
case ended
case unavailable
}

// Android TV keeps 30: a column of a TV shows fewer lines than that.
static let keptMessages = 30
static let rememberedIDs = 400

private(set) var messages: [LiveChatMessage] = []
private(set) var status: Status = .connecting
private var remembered: [String] = []
private var rememberedSet: Set<String> = []

mutating func apply(_ events: [LiveChatEvent]) {
for event in events {
switch event {
case .connected:
if status == .connecting { status = .connected }
case let .message(message):
append(message)
case .ended:
status = .ended
case .unavailable:
status = .unavailable
}
}
if messages.count > Self.keptMessages { messages.removeFirst(messages.count - Self.keptMessages) }
}

private mutating func append(_ message: LiveChatMessage) {
guard rememberedSet.insert(message.id).inserted else { return }
remembered.append(message.id)
if remembered.count > Self.rememberedIDs {
rememberedSet.remove(remembered.removeFirst())
}
messages.append(message)
}
}

enum LiveChatSupport {
// The server only serves the chat of YouTube lives.
static func supports(videoURL: String) -> Bool {
guard let host = URL(string: videoURL)?.host?.lowercased() else { return false }
return host == "youtube.com" || host.hasSuffix(".youtube.com") || host == "youtu.be"
}
}
55 changes: 55 additions & 0 deletions TypeTypeIOS/Features/Watch/Models/LiveChatEventDecoder.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import Foundation

enum LiveChatEventDecoder {
// nil for an event that carries nothing to show: an unknown name, a message without text, a payload that is
// not a message. Only an `error` event throws, so the caller reconnects.
static func decode(_ event: LiveSSEEvent) throws -> LiveChatEvent? {
switch event.name {
case "message": return message(from: event.data).map(LiveChatEvent.message)
case "ended": return .ended
case "error": throw LiveChatStreamError.server(errorText(event.data))
default: return nil
}
}

static func message(from data: String) -> LiveChatMessage? {
guard let payload = try? JSONDecoder().decode(Payload.self, from: Data(data.utf8)) else { return nil }
let text = clean(payload.text ?? "")
guard !text.isEmpty else { return nil }
let id = payload.id.flatMap { $0.isEmpty ? nil : $0 } ?? UUID().uuidString
return LiveChatMessage(
id: id,
author: clean(payload.authorName ?? ""),
text: text,
moderator: payload.moderator ?? false
)
}

// One line of text: U+FFFC (YouTube's placeholder for an inline emoji, drawn as a boxed "OBJ"), zero-width
// spaces and the byte order mark are dropped, runs of whitespace and line breaks become one space. The
// zero-width joiner stays: it holds emoji like a family together.
static func clean(_ raw: String) -> String {
let dropped: Set<Character> = ["\u{FFFC}", "\u{200B}", "\u{2060}", "\u{FEFF}"]
let kept = raw.filter { !dropped.contains($0) }
return kept.split(whereSeparator: \.isWhitespace).joined(separator: " ")
}

private struct Payload: Decodable {
let id: String?
let text: String?
let authorName: String?
let moderator: Bool?
}

private struct ErrorPayload: Decodable {
let error: String?
}

private static func errorText(_ data: String) -> String {
if let payload = try? JSONDecoder().decode(ErrorPayload.self, from: Data(data.utf8)),
let message = payload.error, !message.isEmpty {
return message
}
return String(data.prefix(200))
}
}
23 changes: 23 additions & 0 deletions TypeTypeIOS/Features/Watch/Models/LiveChatModels.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import Foundation

struct LiveChatMessage: Equatable, Identifiable, Sendable {
let id: String
let author: String
let text: String
let moderator: Bool
}

enum LiveChatEvent: Equatable, Sendable {
// The stream is open; the first message may take a while on a quiet chat.
case connected
case message(LiveChatMessage)
// The live is over, the server says so.
case ended
// The video has no chat, or the connection kept failing: stop asking.
case unavailable
}

// The server reports a failure inside an open stream as an `error` event: the stream is dropped and retried.
enum LiveChatStreamError: Error, Equatable {
case server(String)
}
70 changes: 70 additions & 0 deletions TypeTypeIOS/Features/Watch/Models/LiveSSEParser.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import Foundation

struct LiveSSEEvent: Equatable, Sendable {
let name: String
let data: String
}

// Server-sent events, fed one byte at a time. Lines are split on the newline byte before any UTF-8 is read, so a
// character cut between two network reads is never decoded half. Lines end with "\n" or "\r\n", as the server
// writes them; a blank line ends an event, a line starting with ":" is a comment (the server's keep-alive).
struct LiveSSEParser {
private var line: [UInt8] = []
private var name = "message"
private var data: [String] = []

mutating func feed(_ byte: UInt8) -> LiveSSEEvent? {
guard byte == 0x0A else {
line.append(byte)
return nil
}
return endLine()
}

mutating func feed<Bytes: Sequence>(_ bytes: Bytes) -> [LiveSSEEvent] where Bytes.Element == UInt8 {
var events: [LiveSSEEvent] = []
for byte in bytes {
if let event = feed(byte) { events.append(event) }
}
return events
}

// The stream ended: an event whose blank line never came is still delivered, as the web client does.
mutating func finish() -> LiveSSEEvent? {
if !line.isEmpty { _ = endLine() }
return dispatch()
}

private mutating func endLine() -> LiveSSEEvent? {
var bytes = line
line.removeAll(keepingCapacity: true)
if bytes.last == 0x0D { bytes.removeLast() }
guard !bytes.isEmpty else { return dispatch() }
guard bytes[0] != 0x3A else { return nil }
let text = String(decoding: bytes, as: UTF8.self)
let field: String
var value = Substring("")
if let colon = text.firstIndex(of: ":") {
field = String(text[..<colon])
value = text[text.index(after: colon)...]
if value.first == " " { value = value.dropFirst() }
} else {
field = text
}
switch field {
case "event": name = value.isEmpty ? "message" : String(value)
case "data": data.append(String(value))
default: break
}
return nil
}

private mutating func dispatch() -> LiveSSEEvent? {
defer {
name = "message"
data.removeAll()
}
guard !data.isEmpty else { return nil }
return LiveSSEEvent(name: name, data: data.joined(separator: "\n"))
}
}
Loading