Files
meterios/common/types/User.swift
T

47 lines
1.8 KiB
Swift

//
// User.swift
// meterios
//
// (c) 2025 Martin "maride" Dessauer
//
import SwiftUI
import CryptoKit
struct User: Decodable, Identifiable, Hashable {
var id: UUID = UUID() // Careful: meterios-internal ID, not Mete/Backend user accoint ID!
var meteID: Int
var displayName: String
var displayImageURL: String
var balance: Float
private enum KeyMap : String, CodingKey { case id, name, email, balance }
// Init function to be used with JSONDecoder, converting from SpaceMarket API's strange types to proper types
init(from decoder : Decoder) throws {
let container = try decoder.container(keyedBy: KeyMap.self)
self.meteID = try container.decode(Int.self, forKey: .id)
self.displayName = try container.decode(String.self, forKey: .name)
self.displayImageURL = String(
format: "https://secure.gravatar.com/avatar/%@?s=300",
Insecure.MD5.hash(
// e-mails may be empty as they are not required during the registration process in Mete
// however, Gravatar requires them for the profile picture functionality.
// Default to the profile picture of md5("0"), which is simply the Gravatar logo on blue background
data: (((try? container.decode(String.self, forKey: .email)) ?? "0").data(using: .utf8)!)
).compactMap {
String(format: "%02x", $0)
}.joined()
)
self.balance = Float(try container.decode(String.self, forKey: .balance)) ?? -9999.99
}
// Init function, as straight-forward as it gets
init(meteID: Int, displayName: String, displayImageURL: String, balance: Float) {
self.meteID = meteID
self.displayName = displayName
self.displayImageURL = displayImageURL
self.balance = balance
}
}