Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Modules/Sources/BBPanelFeature/BBPanelFeature.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public struct BBPanelFeature: Reducer, Sendable {
var alertInput = ""
var textSize = 1

var isUploading = false
public internal(set) var isUploading = false
var uploadedFiles = 0
var showUploadBox = false

Expand All @@ -83,6 +83,7 @@ public struct BBPanelFeature: Reducer, Sendable {
self.supportsUpload = supportsUpload
self.allowedExtensions = allowedExtensions
self.existsFiles = existsFiles
self.upload.isQms = panelType == .qms
}
}

Expand Down Expand Up @@ -192,6 +193,8 @@ public struct BBPanelFeature: Reducer, Sendable {
return .send(.delegate(.tagTapped(tag)))

case let .upload(.delegate(.fileHasBeenTapped(id, name))):
// QMS sends files as message attachments, not inline tags
guard state.panelWith != .qms else { return .none }
return .send(.delegate(.tagTapped(("[attachment=\"\(id):\(name)\"]", ""))))

case .upload(.delegate(.someFileUploading)):
Expand Down
2 changes: 1 addition & 1 deletion Modules/Sources/ParsingClient/Parsers/QMSParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public struct QMSChatParser {
senderId: message[1] as! Int,
date: Date(timeIntervalSince1970: message[2] as! TimeInterval),
text: message[3] as! String,
attachments: try! AttachmentParser.parseAttachment(message[4] as! [[Any]])
attachments: (try? AttachmentParser.parseAttachment(message[4] as? [[Any]] ?? [])) ?? []
)
}
}
Expand Down
10 changes: 5 additions & 5 deletions Modules/Sources/QMSClient/QMSClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public struct QMSClient: Sendable {
public var createChat: @Sendable (_ opponentId: Int, _ title: String, _ message: String) async throws -> String
public var deleteAllChats: @Sendable (_ userId: Int) async throws -> String
public var deleteChat: @Sendable (_ chatId: Int) async throws -> String
public var sendMessage: @Sendable (_ chatId: Int, _ message: String) async throws -> Void
public var sendMessage: @Sendable (_ chatId: Int, _ message: String, _ attachments: [Int]) async throws -> Void
public var deleteMessage: @Sendable (_ chatId: Int, _ messageId: Int, _ forAll: Bool) async throws -> String
public var blacklist: @Sendable () async throws -> String
public var addToBlacklist: @Sendable (_ id: Int, _ add: Bool) async throws -> String
Expand Down Expand Up @@ -69,8 +69,8 @@ extension QMSClient: DependencyKey {
return response
},

sendMessage: { chatId, message in
let _ = try await api.send(QMSCommand.Message.send(message: message, dialogId: chatId, attaches: []))
sendMessage: { chatId, message, attachments in
let _ = try await api.send(QMSCommand.Message.send(message: message, dialogId: chatId, attaches: attachments))
},

deleteMessage: { chatId, messageId, forAll in
Expand Down Expand Up @@ -117,7 +117,7 @@ extension QMSClient: DependencyKey {
deleteChat: { _ in
return ""
},
sendMessage: { chatId, message in
sendMessage: { chatId, message, _ in
return try await mock.sendQMSMessage(chatId: chatId, message: message)
},
deleteMessage: { _, _, _ in
Expand Down Expand Up @@ -146,7 +146,7 @@ extension QMSClient: DependencyKey {
createChat: unimplemented(),
deleteAllChats: unimplemented(),
deleteChat: unimplemented(),
sendMessage: { chatId, message in
sendMessage: { chatId, message, _ in
return try await mock.sendQMSMessage(chatId: chatId, message: message)
},
deleteMessage: unimplemented(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ extension QMSFeature {
@Dependency(\.analyticsClient) var analytics

var body: some Reducer<State, Action> {
Reduce<State, Action> { _, action in
Reduce<State, Action> { state, action in
switch action {
case .view(.onAppear), .internal, .delegate, .binding, .alert:
case .view(.onAppear), .view(.bbPanelButtonTapped), .internal, .delegate, .binding, .alert, .bbPanel:
break

case let .view(.sendMessageButtonTapped(draft)):
analytics.log(QMSEvent.sendMessageTapped(isEmpty: draft.text.isEmpty))
case .view(.sendMessageButtonTapped):
analytics.log(QMSEvent.sendMessageTapped(isEmpty: state.draftText.isEmpty))

case .view(.loadMoreTriggered):
analytics.log(QMSEvent.loadMoreTriggered)
Expand Down
139 changes: 129 additions & 10 deletions Modules/Sources/QMSFeature/QMSFeature.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import AnalyticsClient
import NotificationsClient
import TCAExtensions
import ExyteChat
import BBPanelFeature
import SharedUI
import TopicBuilder

@Reducer
public struct QMSFeature: Reducer, Sendable {
Expand All @@ -41,7 +44,17 @@ public struct QMSFeature: Reducer, Sendable {

public let chatId: Int
public var chat: QMSChat?
public var messages: [Message] = []
public var messages: [ExyteChat.Message] = []

/// BB-code trees for each message, keyed by message id
var nodes: [String: [UITopicType]] = [:]
/// Non-image attachments for each message, keyed by message id
var files: [String: [Models.Attachment]] = [:]

var bbPanel = BBPanelFeature.State(for: .qms, supportsUpload: true)
var textRange: NSRange?
var isInputFocused = false
var isBBPanelShown = false

var hasMoreOlderMessages = true
var isLoadingMore = false
Expand All @@ -50,6 +63,15 @@ public struct QMSFeature: Reducer, Sendable {
var draftText = ""
var draftSnapshot = ""

var attachmentIds: [Int] {
bbPanel.existsFiles.compactMap(\.serverId)
}

var canSend: Bool {
let hasText = !draftText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
return !isSending && !bbPanel.isUploading && (hasText || !attachmentIds.isEmpty)
}

public var title: String {
if let chat {
return chat.partnerName + " - " + chat.name
Expand All @@ -67,6 +89,7 @@ public struct QMSFeature: Reducer, Sendable {

public enum Action: BindableAction, ViewAction {
case binding(BindingAction<State>)
case bbPanel(BBPanelFeature.Action)

case alert(PresentationAction<Alert>)
public enum Alert {
Expand All @@ -76,7 +99,8 @@ public struct QMSFeature: Reducer, Sendable {
case view(View)
public enum View {
case onAppear
case sendMessageButtonTapped(DraftMessage)
case sendMessageButtonTapped
case bbPanelButtonTapped
case loadMoreTriggered
case urlTapped(URL)
}
Expand All @@ -85,6 +109,7 @@ public struct QMSFeature: Reducer, Sendable {
public enum Internal {
case loadChat
case chatLoaded(Result<QMSChat, any Error>, LoadKind)
case messageSent
case messageSendError(any Error)
}

Expand All @@ -107,11 +132,27 @@ public struct QMSFeature: Reducer, Sendable {
public var body: some Reducer<State, Action> {
BindingReducer()

Scope(\.bbPanel, action: \.bbPanel) {
BBPanelFeature()
}

Reduce<State, Action> { state, action in
switch action {
case .alert, .delegate:
return .none

case .view(.bbPanelButtonTapped):
state.isBBPanelShown.toggle()
return .none

case let .bbPanel(.delegate(.tagTapped(tag))):
insertTag(tag, state: &state)
state.isInputFocused = true
return .none

case .bbPanel:
return .none

case .view(.onAppear):
return .merge([
.send(.internal(.loadChat)),
Expand All @@ -129,19 +170,31 @@ public struct QMSFeature: Reducer, Sendable {
}
])

case let .view(.sendMessageButtonTapped(draftMessage)):
guard !state.isSending, !draftMessage.text.isEmpty else { return .none }
case .view(.sendMessageButtonTapped):
guard state.canSend else { return .none }

let message = state.draftText
state.draftText = ""
state.draftSnapshot = draftMessage.text
state.textRange = nil
state.draftSnapshot = message
state.isSending = true

return .run { [chatId = state.chatId, message = draftMessage.text] send in
try await qmsClient.sendMessage(chatId: chatId, message: message)
return .run { [chatId = state.chatId, attachments = state.attachmentIds] send in
try await qmsClient.sendMessage(chatId: chatId, message: message, attachments: attachments)
await send(.internal(.messageSent))
} catch: { error, send in
await send(.internal(.messageSendError(error)))
}

case .internal(.messageSent):
// Fresh panel drops already sent files from the upload box
state.bbPanel = BBPanelFeature.State(for: .qms, supportsUpload: true)
state.isBBPanelShown = false
return .merge(
.send(.bbPanel(.view(.onAppear))),
.send(.internal(.loadChat))
)

case .view(.loadMoreTriggered):
guard !state.isLoadingMore else { return .none }
guard state.hasMoreOlderMessages else { return .none }
Expand Down Expand Up @@ -207,6 +260,19 @@ public struct QMSFeature: Reducer, Sendable {
var mergedChat = chat
mergedChat.messages = mergeResult.messages

for message in mergeResult.messages {
let id = String(message.id)
guard state.nodes[id] == nil else { continue }
// Attachments not referenced in text are shown separately as images/files,
// so builder gets only inline ones (otherwise it adds an extra spoiler with them)
let inline = message.inlineAttachmentIds
let inlineAttachments = message.attachments.filter { inline.contains($0.id) }
state.nodes[id] = message.text.isEmpty
? []
: TopicNodeBuilder(text: message.text, attachments: inlineAttachments).build()
state.files[id] = message.attachments.filter { $0.type == .file && !inline.contains($0.id) }
}

state.messages = makeLocalMessages(
from: mergeResult.messages,
chat: mergedChat,
Expand Down Expand Up @@ -285,7 +351,7 @@ public struct QMSFeature: Reducer, Sendable {
from remoteMessages: [QMSMessage],
chat: QMSChat,
currentUserId: Int
) -> [Message] {
) -> [ExyteChat.Message] {
var localMessages = remoteMessages.map { remoteMessage in
let isCurrentUser = currentUserId == remoteMessage.senderId
let user = User(
Expand All @@ -295,12 +361,27 @@ public struct QMSFeature: Reducer, Sendable {
isCurrentUser: isCurrentUser
)

return Message(
// Images go to the chat's own media grid with fullscreen viewer
let inline = remoteMessage.inlineAttachmentIds
let images: [ExyteChat.Attachment] = remoteMessage.attachments.compactMap { attachment in
guard attachment.type == .image,
!inline.contains(attachment.id),
let metadata = attachment.metadata else { return nil }
return ExyteChat.Attachment(
id: String(attachment.id),
thumbnail: metadata.url,
full: metadata.fullUrl ?? metadata.url,
type: .image
)
}

return ExyteChat.Message(
id: String(remoteMessage.id),
user: user,
status: .none,
createdAt: remoteMessage.date,
text: remoteMessage.processedText
text: remoteMessage.text,
attachments: images
)
}

Expand All @@ -316,4 +397,42 @@ public struct QMSFeature: Reducer, Sendable {

return localMessages
}

// MARK: - BB Tags

private func insertTag(_ tag: (String, String), state: inout State) {
if let nsRange = state.textRange,
let range = Range(nsRange, in: state.draftText),
!state.draftText.isEmpty {
if range.isEmpty {
let location = nsRange.location + tag.0.utf16.count
state.draftText.insert(contentsOf: "\(tag.0)\(tag.1)", at: range.lowerBound)
state.textRange = NSRange(location: location, length: 0)
} else {
// Wrap selected text into the tag
state.draftText.insert(contentsOf: tag.1, at: range.upperBound)
state.draftText.insert(contentsOf: tag.0, at: range.lowerBound)
state.textRange = NSRange(location: nsRange.location + tag.0.utf16.count, length: nsRange.length)
}
} else {
state.draftText += "\(tag.0)\(tag.1)"
state.textRange = NSRange(location: state.draftText.utf16.count - tag.1.utf16.count, length: 0)
}
}
}

// MARK: - Helpers

private extension QMSMessage {
/// Ids of attachments that are already referenced in text via `[attachment="id:name"]`
var inlineAttachmentIds: Set<Int> {
guard text.contains("attachment") else { return [] }
let regex = try? NSRegularExpression(pattern: #"\[attachment=(?:"|&quot;)?(\d+)"#, options: .caseInsensitive)
let range = NSRange(text.startIndex..., in: text)
let ids = regex?.matches(in: text, range: range).compactMap { match -> Int? in
guard let idRange = Range(match.range(at: 1), in: text) else { return nil }
return Int(text[idRange])
} ?? []
return Set(ids)
}
}
Loading