fix userId

This commit is contained in:
anlicheng 2025-02-25 13:50:47 +08:00
parent bae2eb607a
commit ba79ba08cf
8 changed files with 120 additions and 137 deletions

View File

@ -38,14 +38,14 @@ struct API {
// //
static let baseUrl = "http://39.98.184.67:8500" static let baseUrl = "http://39.98.184.67:8500"
static func getIndexData<T: Codable>(userId: Int, as: T.Type) async -> APIResponse<T> { static func getIndexData<T: Codable>(userId: String, as: T.Type) async -> APIResponse<T> {
let request = URLRequest(url: URL(string: baseUrl + "/api/index?user_id=\(userId)")!) let request = URLRequest(url: URL(string: baseUrl + "/api/index?user_id=\(userId)")!)
return await doRequest(request: request, as: T.self) return await doRequest(request: request, as: T.self)
} }
// //
static func loadMoreUpdateDramas<T: Codable>(userId: Int, mode: LoadMode, id: Int, as: T.Type) async -> APIResponse<T> { static func loadMoreUpdateDramas<T: Codable>(userId: String, mode: LoadMode, id: Int, as: T.Type) async -> APIResponse<T> {
// TODO // TODO
let request = URLRequest(url: URL(string: baseUrl + "/api/load_more_dramas?user_id=\(userId)&mode=\(mode.rawValue)&id=8030")!) let request = URLRequest(url: URL(string: baseUrl + "/api/load_more_dramas?user_id=\(userId)&mode=\(mode.rawValue)&id=8030")!)
print(request) print(request)
@ -54,25 +54,25 @@ struct API {
} }
// //
static func loadDateUpdateDramas<T: Codable>(userId: Int, date: String, as: T.Type) async -> APIResponse<T> { static func loadDateUpdateDramas<T: Codable>(userId: String, date: String, as: T.Type) async -> APIResponse<T> {
let request = URLRequest(url: URL(string: baseUrl + "/api/load_date_dramas?user_id=\(userId)&date=\(date)")!) let request = URLRequest(url: URL(string: baseUrl + "/api/load_date_dramas?user_id=\(userId)&date=\(date)")!)
return await doRequest(request: request, as: T.self) return await doRequest(request: request, as: T.self)
} }
static func getDateIndex<T: Codable>(as: T.Type) async -> APIResponse<T> { static func getDateIndex<T: Codable>(userId: String, as: T.Type) async -> APIResponse<T> {
let request = URLRequest(url: URL(string: baseUrl + "date_index")!) let request = URLRequest(url: URL(string: baseUrl + "/api/date_index?user_id=\(userId)")!)
return await doRequest(request: request, as: T.self) return await doRequest(request: request, as: T.self)
} }
static func getDramaDetail<T: Codable>(userId: Int, id: Int, as: T.Type) async -> APIResponse<T> { static func getDramaDetail<T: Codable>(userId: String, id: Int, as: T.Type) async -> APIResponse<T> {
let request = URLRequest(url: URL(string: baseUrl + "/api/detail?user_id=\(userId)&id=\(id)")!) let request = URLRequest(url: URL(string: baseUrl + "/api/detail?user_id=\(userId)&id=\(id)")!)
return await doRequest(request: request, as: T.self) return await doRequest(request: request, as: T.self)
} }
static func followDrama<T: Codable>(userId: Int, id: Int, status: String, as: T.Type) async -> APIResponse<T> { static func followDrama<T: Codable>(userId: String, id: Int, status: String, as: T.Type) async -> APIResponse<T> {
let request = URLRequest(url: URL(string: baseUrl + "/api/follow?user_id=\(userId)&id=\(id)&status=\(status)")!) let request = URLRequest(url: URL(string: baseUrl + "/api/follow?user_id=\(userId)&id=\(id)&status=\(status)")!)
return await doRequest(request: request, as: T.self) return await doRequest(request: request, as: T.self)
@ -88,6 +88,7 @@ struct API {
return .error(-1, "http status error") return .error(-1, "http status error")
} }
print("request url: \(request.url!.absoluteString)")
// let x = String(data: data, encoding: .utf8)! // let x = String(data: data, encoding: .utf8)!
// print("url: \(request.url!.path()), data is: \(x)") // print("url: \(request.url!.path()), data is: \(x)")
do { do {

View File

@ -5,6 +5,7 @@
// Created by on 2025/2/25. // Created by on 2025/2/25.
// //
import Foundation import Foundation
import UIKit
struct Utils { struct Utils {
@ -25,4 +26,12 @@ struct Utils {
return attributedString.string return attributedString.string
} }
static func defaultUserId() -> String {
if let uuid = UIDevice.current.identifierForVendor?.uuidString {
return uuid.lowercased()
} else {
return UUID().uuidString.lowercased()
}
}
} }

View File

@ -1,35 +0,0 @@
//
// UserModel.swift
// dimensionhub
//
// Created by on 2025/2/24.
//
import Foundation
import SwiftData
import UIKit
@Model
final class UserModel {
var userId: String
var username: String
init(userId: String, username: String) {
self.userId = userId
self.username = username
}
static func defaultUser() -> UserModel {
return UserModel(userId: getUserId(), username: "")
}
//
private static func getUserId() -> String {
if let uuid = UIDevice.current.identifierForVendor?.uuidString {
return uuid.lowercased()
} else {
return UUID().uuidString.lowercased()
}
}
}

View File

@ -9,7 +9,62 @@ import Foundation
import SwiftUI import SwiftUI
import Observation import Observation
@Observable
final class DateNavModel {
struct DateModel: Codable, Identifiable {
struct Month: Codable {
let id: String
let name: String
let disabled: Bool
}
let id = UUID().uuidString
let year: String
let months: [Month]
enum CodingKeys: String, CodingKey {
case year
case months
}
}
var dateModels: [DateModel]
init() {
self.dateModels = []
}
@MainActor
func loadDateCells(userId: String) async {
self.dateModels = await getDateModelData(userId: userId)
}
private func getDateModelData(userId: String) async -> [DateModel] {
let models = await DataCache.shared.getDateModelCache()
if models.count > 0 {
return models
} else {
let response = await API.getDateIndex(userId: userId, as: [DateModel].self)
print(response)
switch response {
case .error(let code, let message):
print(code)
print(message)
return []
case .result(let models):
print(models)
await DataCache.shared.setDateModelCache(models)
return models
}
}
}
}
struct DateNavView: View { struct DateNavView: View {
@AppStorage("userId") private var userId: String = Utils.defaultUserId()
@State var navModel = DateNavModel() @State var navModel = DateNavModel()
@Binding var selectGroupId: String @Binding var selectGroupId: String
@ -18,20 +73,22 @@ struct DateNavView: View {
var onSelected: (String) -> Void var onSelected: (String) -> Void
var body: some View { var body: some View {
VStack(alignment: .center) { ScrollView(.vertical, showsIndicators: false) {
ForEach(navModel.dateModels) { model in VStack(alignment: .center) {
VStack(alignment: .leading, spacing: 10) { ForEach(navModel.dateModels) { model in
Text(model.year) VStack(alignment: .leading, spacing: 10) {
HStack { Text(model.year)
ForEach(model.months, id: \.id) { month in HStack {
if month.disabled { ForEach(model.months, id: \.id) { month in
DateDisabledItemView(datetime: month.name) if month.disabled {
} else { DateDisabledItemView(datetime: month.name)
DateItemView(id: month.id, } else {
datetime: month.name, DateItemView(id: month.id,
selected: month.id == selectGroupId, datetime: month.name,
showDateNavPopover: $showDateNavPopover, selected: month.id == selectGroupId,
onSelected: onSelected) showDateNavPopover: $showDateNavPopover,
onSelected: onSelected)
}
} }
} }
} }
@ -39,7 +96,7 @@ struct DateNavView: View {
} }
} }
.task { .task {
await self.navModel.loadDateCells() await self.navModel.loadDateCells(userId: self.userId)
} }
.onAppear { .onAppear {
print("group_id is: \(selectGroupId)") print("group_id is: \(selectGroupId)")
@ -104,58 +161,6 @@ extension DateNavView {
} }
@Observable
final class DateNavModel {
struct DateModel: Codable, Identifiable {
struct Month: Codable {
let id: String
let name: String
let disabled: Bool
}
let id = UUID().uuidString
let year: String
let months: [Month]
enum CodingKeys: String, CodingKey {
case year
case months
}
}
var dateModels: [DateModel]
init() {
self.dateModels = []
}
@MainActor
func loadDateCells() async {
self.dateModels = await getDateModelData()
}
private func getDateModelData() async -> [DateModel] {
let models = await DataCache.shared.getDateModelCache()
if models.count > 0 {
return models
} else {
let response = await API.getDateIndex(as: [DateModel].self)
print(response)
switch response {
case .error(let code, let message):
print(code)
print(message)
return []
case .result(let models):
print(models)
await DataCache.shared.setDateModelCache(models)
return models
}
}
}
}
//#Preview { //#Preview {
// DateNavView() // DateNavView()

View File

@ -87,7 +87,7 @@ final class DetailModel {
var selectedEpisodes: [Episode] = [] var selectedEpisodes: [Episode] = []
@MainActor @MainActor
func loadData(userId: Int, id: Int) async { func loadData(userId: String, id: Int) async {
let response = await API.getDramaDetail(userId: userId, id: id, as: DramaDetailResponse.self) let response = await API.getDramaDetail(userId: userId, id: id, as: DramaDetailResponse.self)
switch response { switch response {
case .error(let code, let message): case .error(let code, let message):
@ -118,10 +118,10 @@ final class DetailModel {
} }
@MainActor @MainActor
func onTapFollowButton(userId: Int, id: Int, status: String) async -> FollowResult { func onTapFollowButton(userId: String, id: Int, status: String) async -> FollowResult {
let response = await API.followDrama(userId: userId, id: id, status: status, as: [String].self) let response = await API.followDrama(userId: userId, id: id, status: status, as: [String].self)
switch response { switch response {
case .error(let code, let message): case .error(_, let message):
return .error("错误", message) return .error("错误", message)
case .result(let newStatuses): case .result(let newStatuses):
self.statuses = newStatuses.flatMap({ s in self.statuses = newStatuses.flatMap({ s in
@ -138,6 +138,8 @@ final class DetailModel {
} }
struct DetailView: View { struct DetailView: View {
@AppStorage("userId") private var userId: String = Utils.defaultUserId()
@State var detailModel = DetailModel() @State var detailModel = DetailModel()
@State var showAllSummary: Bool = false @State var showAllSummary: Bool = false
@ -185,7 +187,7 @@ struct DetailView: View {
ForEach(detailModel.statuses, id: \.status) { status in ForEach(detailModel.statuses, id: \.status) { status in
FollowButtonView(dramaStatus: status) { followStatus in FollowButtonView(dramaStatus: status) { followStatus in
Task { Task {
let result = await detailModel.onTapFollowButton(userId: 1, id: id, status: followStatus) let result = await detailModel.onTapFollowButton(userId: self.userId, id: id, status: followStatus)
switch result { switch result {
case .success: case .success:
() ()
@ -267,7 +269,7 @@ struct DetailView: View {
Alert(title: Text(self.errorInfo.0), message: Text(self.errorInfo.1), dismissButton: .default(Text("OK"))) Alert(title: Text(self.errorInfo.0), message: Text(self.errorInfo.1), dismissButton: .default(Text("OK")))
} }
.task { .task {
await detailModel.loadData(userId: 1, id: self.id) await detailModel.loadData(userId: self.userId, id: self.id)
print(detailModel.summary) print(detailModel.summary)
} }
} }

View File

@ -78,8 +78,8 @@ final class IndexModel {
} }
@MainActor @MainActor
func loadData() async { func loadData(userId: String) async {
let response = await API.getIndexData(userId: 1, as: IndexResponse.self) let response = await API.getIndexData(userId: userId, as: IndexResponse.self)
switch response { switch response {
case .error(let code, let message): case .error(let code, let message):
print(code) print(code)
@ -92,7 +92,7 @@ final class IndexModel {
} }
@MainActor @MainActor
func loadMoreUpdateDramas(userId: Int, mode: API.LoadMode) async { func loadMoreUpdateDramas(userId: String, mode: API.LoadMode) async {
let id: Int = 8030 let id: Int = 8030
// TODO id // TODO id
switch mode { switch mode {
@ -114,7 +114,7 @@ final class IndexModel {
// //
@MainActor @MainActor
func loadDateUpdateDramas(userId: Int, date: String) async { func loadDateUpdateDramas(userId: String, date: String) async {
self.showUpdateDramas.removeAll() self.showUpdateDramas.removeAll()
let response = await API.loadDateUpdateDramas(userId: userId, date: date, as: [UpdateDramaGroup].self) let response = await API.loadDateUpdateDramas(userId: userId, date: date, as: [UpdateDramaGroup].self)
if case let .result(groups) = response { if case let .result(groups) = response {
@ -174,6 +174,8 @@ final class IndexModel {
struct IndexView: View { struct IndexView: View {
@Environment(\.modelContext) private var modelContext @Environment(\.modelContext) private var modelContext
@AppStorage("userId") private var userId: String = Utils.defaultUserId()
//@Query private var items: [Item] //@Query private var items: [Item]
//@Query private var userModel: [UserModel] = [] //@Query private var userModel: [UserModel] = []
@ -273,7 +275,7 @@ struct IndexView: View {
if screenBounds.height - frame.minY > 50 && contextFrame.minY > 0 && !isMoreLoading { if screenBounds.height - frame.minY > 50 && contextFrame.minY > 0 && !isMoreLoading {
Task { Task {
self.isMoreLoading = true self.isMoreLoading = true
await self.indexModel.loadMoreUpdateDramas(userId: 1, mode: .next) await self.indexModel.loadMoreUpdateDramas(userId: self.userId, mode: .next)
self.isMoreLoading = false self.isMoreLoading = false
} }
} }
@ -289,7 +291,7 @@ struct IndexView: View {
DateNavView(selectGroupId: self.$selectGroupId, showDateNavPopover: $showDateNavPopover) { selectedDate in DateNavView(selectGroupId: self.$selectGroupId, showDateNavPopover: $showDateNavPopover) { selectedDate in
print("new selected date: " + selectedDate) print("new selected date: " + selectedDate)
Task { Task {
await indexModel.loadDateUpdateDramas(userId: 1, date: selectedDate) await indexModel.loadDateUpdateDramas(userId: self.userId, date: selectedDate)
} }
} }
} }
@ -300,7 +302,7 @@ struct IndexView: View {
// //
self.isPrevLoading = true self.isPrevLoading = true
await self.indexModel.loadMoreUpdateDramas(userId: 1, mode: .prev) await self.indexModel.loadMoreUpdateDramas(userId: self.userId, mode: .prev)
self.isPrevLoading = false self.isPrevLoading = false
} }
@ -308,7 +310,7 @@ struct IndexView: View {
.frame(width: 370) .frame(width: 370)
.ignoresSafeArea(edges: .bottom) .ignoresSafeArea(edges: .bottom)
.task { .task {
await self.indexModel.loadData() await self.indexModel.loadData(userId: self.userId)
//print(userModel) //print(userModel)
} }
} }

View File

@ -46,7 +46,7 @@ final class ListModel {
var selectedEpisodes: [Episode] = [] var selectedEpisodes: [Episode] = []
@MainActor @MainActor
func loadData(userId: Int, id: Int) async { func loadData(userId: String, id: Int) async {
let response = await API.getDramaDetail(userId: userId, id: id, as: DramaDetailResponse.self) let response = await API.getDramaDetail(userId: userId, id: id, as: DramaDetailResponse.self)
switch response { switch response {
case .error(let code, let message): case .error(let code, let message):
@ -72,6 +72,8 @@ final class ListModel {
struct ListView: View { struct ListView: View {
@Environment(\.presentationMode) var presentationMode @Environment(\.presentationMode) var presentationMode
@AppStorage("userId") private var userId: String = Utils.defaultUserId()
@State var detailModel = ListModel() @State var detailModel = ListModel()
let id: Int let id: Int
@ -160,7 +162,7 @@ struct ListView: View {
} }
.frame(width: 370, alignment: .center) .frame(width: 370, alignment: .center)
.task { .task {
await detailModel.loadData(userId: 1, id: self.id) await detailModel.loadData(userId: self.userId, id: self.id)
} }
} }

View File

@ -12,7 +12,7 @@ import SwiftData
struct dimensionhubApp: App { struct dimensionhubApp: App {
var sharedModelContainer: ModelContainer = { var sharedModelContainer: ModelContainer = {
let schema = Schema([ let schema = Schema([
UserModel.self Item.self
]) ])
let modelConfiguration = ModelConfiguration( let modelConfiguration = ModelConfiguration(
schema: schema, schema: schema,
@ -21,22 +21,19 @@ struct dimensionhubApp: App {
) )
do { do {
let container = try ModelContainer(for: schema, configurations: [modelConfiguration]) return try ModelContainer(for: schema, configurations: [modelConfiguration])
//
var descriptor = FetchDescriptor<UserModel>(sortBy: [])
descriptor.fetchLimit = 1
let users = try container.mainContext.fetch(descriptor)
if users.isEmpty {
print("user is empty create user")
container.mainContext.insert(UserModel.defaultUser())
}
return container
} catch { } catch {
fatalError("Could not create ModelContainer: \(error)") fatalError("Could not create ModelContainer: \(error)")
} }
}() }()
init() {
if let userId = UserDefaults.standard.string(forKey: "userId") {
print("user_id is: \(userId)")
} else {
UserDefaults.standard.set(Utils.defaultUserId(), forKey: "userId")
}
}
var body: some Scene { var body: some Scene {
WindowGroup { WindowGroup {