yattee/Model/Video.swift

87 lines
2.5 KiB
Swift
Raw Normal View History

2021-06-10 22:50:10 +00:00
import Alamofire
import Foundation
import SwiftyJSON
2021-06-11 00:05:59 +00:00
final class Video: Identifiable, ObservableObject {
2021-06-10 22:50:10 +00:00
let id: String
var title: String
var thumbnailURL: URL
var author: String
2021-06-11 00:05:59 +00:00
var length: TimeInterval
var published: String
var views: Int
2021-06-10 22:50:10 +00:00
@Published var url: URL?
@Published var error: Bool = false
2021-06-11 00:05:59 +00:00
init(id: String, title: String, thumbnailURL: URL, author: String, length: TimeInterval, published: String, views: Int = 0) {
2021-06-10 22:50:10 +00:00
self.id = id
self.title = title
self.thumbnailURL = thumbnailURL
self.author = author
2021-06-11 00:05:59 +00:00
self.length = length
self.published = published
self.views = views
2021-06-10 22:50:10 +00:00
}
init(_ json: JSON) {
2021-06-11 12:36:26 +00:00
func extractThumbnailURL(from details: JSON) -> URL {
if details["videoThumbnails"].arrayValue.isEmpty {
return URL(string: "https://invidious.home.arekf.net/vi/LuKwJyBNBsE/maxres.jpg")!
}
return details["videoThumbnails"][0]["url"].url!
}
func extractFormatStreamURL(from streams: [JSON]) -> URL? {
if streams.isEmpty {
error = true
return nil
}
let stream = streams.last!
return stream["url"].url
}
2021-06-10 22:50:10 +00:00
id = json["videoId"].stringValue
title = json["title"].stringValue
2021-06-11 12:36:26 +00:00
thumbnailURL = extractThumbnailURL(from: json)
2021-06-10 22:50:10 +00:00
author = json["author"].stringValue
2021-06-11 00:05:59 +00:00
length = json["lengthSeconds"].doubleValue
published = json["publishedText"].stringValue
views = json["viewCount"].intValue
2021-06-11 12:36:26 +00:00
url = extractFormatStreamURL(from: json["formatStreams"].arrayValue)
2021-06-10 22:50:10 +00:00
}
2021-06-11 00:05:59 +00:00
var playTime: String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = length >= (60 * 60) ? [.hour, .minute, .second] : [.minute, .second]
formatter.zeroFormattingBehavior = [.pad]
return formatter.string(from: length)
}
var viewsCount: String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 1
var number: NSNumber
var unit: String
if views < 1_000_000 {
number = NSNumber(value: Double(views) / 1000.0)
unit = "K"
} else {
number = NSNumber(value: Double(views) / 1_000_000.0)
unit = "M"
}
return "\(formatter.string(from: number)!)\(unit)"
}
2021-06-10 22:50:10 +00:00
}