test thumbnails

This commit is contained in:
Francesco 2024-12-19 17:41:14 +01:00
parent 3a68ded645
commit 14858d5d70
3 changed files with 136 additions and 8 deletions

View file

@ -21,6 +21,7 @@ struct AnimeInfoView: View {
@State var episodes: [String] = []
@State var isLoading: Bool = true
@State var showFullSynopsis: Bool = false
@State var animeID: Int?
@AppStorage("externalPlayer") private var externalPlayer: String = "Default"
@ -135,7 +136,7 @@ struct AnimeInfoView: View {
let totalTime = UserDefaults.standard.double(forKey: "totalTime_\(episodeURL)")
let progress = totalTime > 0 ? lastPlayedTime / totalTime : 0
EpisodeCell(episode: episodes[index], episodeID: index, imageUrl: anime.imageUrl, progress: progress)
EpisodeCell(episode: episodes[index], episodeID: index, imageUrl: anime.imageUrl, progress: progress, animeID: animeID ?? 0)
.onTapGesture {
fetchEpisodeStream(urlString: episodeURL)
}
@ -149,6 +150,16 @@ struct AnimeInfoView: View {
}
.onAppear {
fetchAnimeDetails()
fetchAnimeID(byTitle: anime.name) { result in
switch result {
case .success(let id):
animeID = id
Logger.shared.log("Fetched Anime ID: \(id)")
case .failure(let error):
print("Failed to fetch Anime ID: \(error)")
Logger.shared.log("Failed to fetch Anime ID: \(error)")
}
}
}
}
@ -208,4 +219,52 @@ struct AnimeInfoView: View {
UIApplication.shared.open(streamUrl, options: [:], completionHandler: nil)
Logger.shared.log("Unable to open the stream: 'streamUrl'")
}
private func fetchAnimeID(byTitle title: String, completion: @escaping (Result<Int, Error>) -> Void) {
let query = """
query {
Media(search: "\(title)", type: ANIME) {
id
}
}
"""
guard let url = URL(string: "https://graphql.anilist.co") else {
completion(.failure(NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])))
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let parameters: [String: Any] = ["query": query]
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "No data received"])))
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let data = json["data"] as? [String: Any],
let media = data["Media"] as? [String: Any],
let id = media["id"] as? Int {
completion(.success(id))
} else {
let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid response"])
completion(.failure(error))
}
} catch {
completion(.failure(error))
}
}.resume()
}
}

View file

@ -13,18 +13,35 @@ struct EpisodeCell: View {
let episodeID: Int
let imageUrl: String
let progress: Double
let animeID: Int
@State private var episodeTitle: String = ""
@State private var episodeImageUrl: String = ""
@State private var isLoading: Bool = true
var body: some View {
HStack {
KFImage(URL(string: "https://cdn.discordapp.com/attachments/1218851049625092138/1318941731349332029/IMG_5081.png?ex=676427b5&is=6762d635&hm=923252d3448fda337f52c964f1428538095cbd018e36a6cfb21d01918e071c9d&"))
.resizable()
.aspectRatio(16/9, contentMode: .fill)
.frame(width: 100, height: 56)
.cornerRadius(8)
ZStack {
KFImage(URL(string: episodeImageUrl.isEmpty ? imageUrl : episodeImageUrl))
.resizable()
.aspectRatio(16/9, contentMode: .fill)
.frame(width: 100, height: 56)
.cornerRadius(8)
if isLoading {
ProgressView()
.progressViewStyle(CircularProgressViewStyle())
}
}
VStack(alignment: .leading) {
Text("Episode \(episodeID + 1)")
.font(.headline)
.font(.system(size: 15))
if !episodeTitle.isEmpty {
Text(episodeTitle)
.font(.system(size: 13))
.foregroundColor(.secondary)
}
}
Spacer()
@ -32,5 +49,57 @@ struct EpisodeCell: View {
CircularProgressBar(progress: progress)
.frame(width: 40, height: 40)
}
.onAppear {
fetchEpisodeDetails()
}
}
}
func fetchEpisodeDetails() {
guard let url = URL(string: "https://api.ani.zip/mappings?anilist_id=\(animeID)") else {
isLoading = false
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Failed to fetch episode details: \(error)")
DispatchQueue.main.async {
self.isLoading = false
}
return
}
guard let data = data else {
print("No data received")
DispatchQueue.main.async {
self.isLoading = false
}
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let episodes = json["episodes"] as? [String: Any],
let episodeDetails = episodes["\(episodeID + 1)"] as? [String: Any],
let title = episodeDetails["title"] as? [String: String],
let image = episodeDetails["image"] as? String {
DispatchQueue.main.async {
self.episodeTitle = title["en"] ?? ""
self.episodeImageUrl = image
self.isLoading = false
}
} else {
print("Invalid response")
DispatchQueue.main.async {
self.isLoading = false
}
}
} catch {
print("Failed to parse JSON: \(error)")
DispatchQueue.main.async {
self.isLoading = false
}
}
}.resume()
}
}