Skip to content

Commit

Permalink
[수정] PR 리뷰 반영 및 프로덕션 서버 에러 수정 (#213)
Browse files Browse the repository at this point in the history
  • Loading branch information
wonniiii committed Aug 19, 2024
1 parent 204fabe commit b7b7670
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 73 deletions.
14 changes: 4 additions & 10 deletions package-kuring/Sources/Features/BotFeatures/BotFeature.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,7 @@ public struct BotFeature {
do {
SSEClient.shared.sessionStart(question: question)

/// 작업이 취소되거나 완료되기 전까지 send가 호출되지 않도록 보장
await withTaskCancellationHandler {
let continuation = AsyncStream<String>.Continuation.self

///서버로부터 받은 메시지들을 비동기 스트림으로 처리
let stream = AsyncStream<String> { continuation in
SSEClient.shared.sendMessage = { message in
continuation.yield(message)
Expand All @@ -97,10 +93,6 @@ public struct BotFeature {
for await message in stream {
await send(.messageResponse(.success(message)))
}

} onCancel: {
SSEClient.shared.task?.cancel()
}

} catch {
await send(.messageResponse(.failure(.serverError(error))))
Expand All @@ -120,6 +112,8 @@ public struct BotFeature {
return .none

case let .addQuestion(question):
state.chatInfo.text = question

let newQuestion = ChatInfo(
index: state.chatHistory.count,
text: question,
Expand All @@ -140,8 +134,8 @@ public struct BotFeature {
state.chatHistory.append(newResponse)
do { try context.add(newResponse) } catch {}

return .none
return .send(.sendMessage)

case .queryChanged(let newMessage):
state.chatHistory = newMessage
return .none
Expand Down
12 changes: 4 additions & 8 deletions package-kuring/Sources/Networks/Depdencies/SSEClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ import Combine
import OSLog

public class SSEClient: NSObject, ObservableObject, URLSessionDataDelegate {
@Published public var botMessage: String = ""
@Published public var error: Error?
public var sendMessage: ((String) -> Void)?
public static let shared = SSEClient()
public var task: URLSessionDataTask?
private var url: URL
private var session: URLSession?
private var testableFCMToken: String = Date().description
@AppStorage("com.kuring.sdk.v2.token.fcm")
private var fcmToken: String = ""
private let logger = Logger(subsystem: "Network", category: "SSEClient")

public override init() {
Expand Down Expand Up @@ -45,24 +45,20 @@ public class SSEClient: NSObject, ObservableObject, URLSessionDataDelegate {

request.httpMethod = "GET"
request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
request.setValue(testableFCMToken, forHTTPHeaderField: "User-Token")
request.setValue(fcmToken, forHTTPHeaderField: "User-Token")
request.setValue("no-cache", forHTTPHeaderField: "Cache-Control")

task = session?.dataTask(with: request)
task?.resume()
}

public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
self.botMessage = ""
if let message = String(data: data, encoding: .utf8) {
let processedMessage = message
.components(separatedBy: .newlines)
.map { $0.replacingOccurrences(of: "data:", with: "") }
.joined()

DispatchQueue.main.sync {
self.sendMessage?(processedMessage)
}
self.sendMessage?(processedMessage)
}
}

Expand Down
3 changes: 0 additions & 3 deletions package-kuring/Sources/Networks/KuringLink/API.Path.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ enum Path {
case searchStaffs
case sendFeedback
case registerAuthorization
case getBotMessage

var path: String {
switch self {
Expand All @@ -43,8 +42,6 @@ enum Path {
return "api/v2/users/feedbacks"
case .registerAuthorization:
return "api/v2/users"
case .getBotMessage:
return "api/v2/ai/messages"
}
}
}
46 changes: 21 additions & 25 deletions package-kuring/Sources/UIKit/BotUI/BotView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
//

import SwiftUI
import ComposableArchitecture
import ColorSet
import Networks
import ColorSet
import SwiftData
import BotFeatures
import ComposableArchitecture

public struct BotView: View {
@Bindable var store: StoreOf<BotFeature>
Expand All @@ -22,13 +22,15 @@ public struct BotView: View {
ZStack {
Color.Kuring.bg
.ignoresSafeArea()

VStack(alignment: .center) {
Group {
headerView
chatView
}
.onTapGesture {
isInputFocused = false
}

VStack(alignment: .center) {
headerView
chatView
inputView
infoText
}
Expand Down Expand Up @@ -87,11 +89,12 @@ public struct BotView: View {

private var popoverContent: some View {
VStack(spacing: 10) {
Text("• 쿠링봇은 2024년 6월 이후의 공지\n 사항 내용을 기준으로 답변할 수 \n 어요.")
Text("• 테스트 기간인 관계로 한 달에 2회\n 까지만 질문 가능해요.")
Text("• 쿠링봇은 2024년 6월 이후의 공지사항 내용을 기준으로 답변할 수 있어요.")
Text("• 테스트 기간인 관계로 한 달에 2회까지만 질문 가능해요.")
}
.lineSpacing(5)
.font(.system(size: 15, weight: .medium))
.frame(width: 250)
.padding(20)
.presentationBackground(Color.Kuring.gray100)
.presentationCompactAdaptation(.popover)
Expand All @@ -108,17 +111,23 @@ public struct BotView: View {

private var inputView: some View {
HStack(alignment: .bottom, spacing: 12) {
TextField("질문을 입력해주세요", text: $tempInputText.limit(to: 300), axis: .vertical)
TextField("질문을 입력해주세요", text: $tempInputText, axis: .vertical)
.lineLimit(5)
.focused($isInputFocused)
.padding(.horizontal)
.padding(.vertical, 12)
.overlay(RoundedRectangle(cornerRadius: 20).strokeBorder(Color.Kuring.gray200, style: StrokeStyle(lineWidth: 1.0)))

.overlay(
RoundedRectangle(cornerRadius: 20)
.strokeBorder(Color.Kuring.gray200, style: StrokeStyle(lineWidth: 1.0))
)
.onChange(of: tempInputText) { _, newValue in
if newValue.count > 300 {
tempInputText = String(newValue.prefix(300))
}
}
sendButton
}
.padding(.horizontal, 20)
.disabled(store.chatHistory.count >= 4)
}

private var sendButton: some View {
Expand All @@ -132,7 +141,6 @@ public struct BotView: View {
.scaledToFit()
.frame(width: 40, height: 40)
}
.disabled(store.chatHistory.count >= 4)
}

private var infoText: some View {
Expand All @@ -146,7 +154,6 @@ public struct BotView: View {
SendPopup(isVisible: $isSendPopupVisible) {
store.send(.addQuestion(tempInputText))
tempInputText = ""
store.send(.sendMessage)
}
}

Expand All @@ -155,14 +162,3 @@ public struct BotView: View {
}
}

/// 글자 수 max 판단
extension Binding where Value == String {
func limit(to maxLength: Int) -> Self {
if self.wrappedValue.count > maxLength {
DispatchQueue.main.async {
self.wrappedValue = String(self.wrappedValue.prefix(maxLength))
}
}
return self
}
}
6 changes: 2 additions & 4 deletions package-kuring/Sources/UIKit/BotUI/Bundle.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
//
// File.swift
//
//
// Created by 최효원 on 8/5/24.
// Copyright (c) 2024 쿠링
// See the 'License.txt' file for licensing information.
//

import Foundation
Expand Down
3 changes: 1 addition & 2 deletions package-kuring/Sources/UIKit/BotUI/ChatView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import SwiftData
struct ChatView: View {
@Bindable var store: StoreOf<BotFeature>
@Query(FetchDescriptor<ChatInfo>()) var chatQuery: [ChatInfo]
@State private var limit = 2

var body: some View {
ScrollView {
Expand Down Expand Up @@ -62,7 +61,7 @@ struct ChatView: View {

private var lottieView: some View {
LottieView(animation: .named("animation_loading.json", bundle: Bundle.bots))
.playing()
.looping()
.resizable()
.frame(width: 70, alignment: .leading)
}
Expand Down
4 changes: 2 additions & 2 deletions package-kuring/Sources/UIKit/BotUI/SendPopup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ struct SendPopup: View {
Text("전송하시면 횟수 차감이 인정돼요.\n전송할까요?")
.foregroundStyle(Color.Kuring.body)
.multilineTextAlignment(.center)
.padding(40)
.padding(.bottom, 0)
.padding([.horizontal, .bottom], 30)
.padding(.top, 43)
}

private var actionButtons: some View {
Expand Down
38 changes: 19 additions & 19 deletions package-kuring/Sources/UIKit/NoticeUI/BotFloatButton.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,26 @@ public struct BotFloatButton: View {
)
.toolbar(.hidden, for: .tabBar)
) {
ZStack {
Circle()
.fill(Color.Kuring.primary)
.frame(width: 64, height: 64)
.shadow(radius: 5)

VStack(alignment: .center) {
Image("kuring_app_white", bundle: Bundle.bots)
.font(.system(size: 24))
.foregroundColor(.white)
Text("쿠링봇")
.font(.system(size: 10, weight: .medium))
.foregroundColor(.white)
}
.padding(.top, 5)
}
.padding(.bottom, 20)
.padding(.trailing, 16)
ZStack {
Circle()
.fill(Color.Kuring.primary)
.frame(width: 64, height: 64)
.shadow(radius: 5)

VStack(alignment: .center) {
Image("kuring_app_white", bundle: Bundle.bots)
.font(.system(size: 24))
.foregroundColor(.white)
Text("쿠링봇")
.font(.system(size: 10, weight: .medium))
.foregroundColor(.white)
}

.padding(.top, 5)
}
.padding(.bottom, 20)
.padding(.trailing, 16)
}

}
}

0 comments on commit b7b7670

Please sign in to comment.