84 lines
2.7 KiB
Swift
84 lines
2.7 KiB
Swift
//
|
|
// MatchesAPI.swift
|
|
// LiquipediaMenu
|
|
//
|
|
// Created by Felix Förtsch on 08.10.18.
|
|
// Copyright © 2018 Felix Förtsch. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
import SwiftSoup
|
|
|
|
protocol MatchesAPIDelegate {
|
|
|
|
}
|
|
|
|
class MatchesAPI {
|
|
|
|
func fetchMatches(for game: String) -> [Match]? {
|
|
let games = ["dota2", "starcraft", "starcraft2", "heroes", "counterstrike", "rocketleague", "rainbowsix", "overwatch"]
|
|
if !games.contains(game) { return nil }
|
|
if let data = fetchData(for: game) {
|
|
return extractMatches(from: data)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
private func fetchData(for game: String) -> String? {
|
|
let url = constructURL(for: game)
|
|
// DispatchQueue.global().async { [unowned self] in
|
|
if let url = URL(string: url) {
|
|
if let data = try? String(contentsOf: url) {
|
|
return data
|
|
}
|
|
}
|
|
// }
|
|
return nil
|
|
}
|
|
|
|
private func extractMatches(from data: String) -> [Match]? {
|
|
var tmp = data.replacingOccurrences(of: "\\n", with: "")
|
|
tmp = tmp.replacingOccurrences(of: "\\", with: "")
|
|
|
|
do {
|
|
let doc: Document = try SwiftSoup.parse(tmp)
|
|
let ongoing: Element = try doc.getElementById("infobox_matches")!
|
|
let matchString: Elements = try ongoing.getElementsByTag("table")
|
|
|
|
var matches = [Match]()
|
|
for match in matchString {
|
|
let score = try match.getElementsByClass("versus").text()
|
|
let split = score.split(separator: ":")
|
|
let leftscore = String(split[0])
|
|
let rightscore = String(split[1])
|
|
|
|
let newMatch = Match(
|
|
ongoing: true,
|
|
streamLink: "https://twitch.tv" + (match.getAttributes()?.get(key: "data-stream-twitch"))! ,
|
|
league: try match.select("tr > td > div > div > a").text(),
|
|
team1name: try match.getElementsByClass("team-left").text(),
|
|
team1score: leftscore,
|
|
team2name: try match.getElementsByClass("team-right").text(),
|
|
team2score: rightscore
|
|
)
|
|
matches.append(newMatch)
|
|
}
|
|
return matches
|
|
} catch Exception.Error(_, _) {
|
|
print("")
|
|
return nil
|
|
} catch {
|
|
print("")
|
|
return nil
|
|
}
|
|
}
|
|
|
|
private func constructURL(for game: String) -> String {
|
|
let baseURL = "https://liquipedia.net/"
|
|
let query = "/api.php?action=parse&page=Liquipedia:Upcoming_and_ongoing_matches&format=json&prop=text"
|
|
return baseURL + game + query
|
|
}
|
|
}
|
|
|
|
|