85 lines
3.1 KiB
Swift
85 lines
3.1 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
|
|
|
|
class LiquipediaMatchesAPI {
|
|
|
|
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)
|
|
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()
|
|
newMatch.ongoing = true
|
|
|
|
// Tries to extract the stream link. If there is none, the string streamLink will be empty.
|
|
// TODO: data-stream-twitch doesn't always contain the twitch user, so it can't always be used to go to the twitch site.
|
|
print(try match.getAllElements().toString())
|
|
print(try match.getElementsByClass("timer-object-countdown"))
|
|
newMatch.streamLink = try match.getElementsByClass("timer-object-countdown").select("span").attr("href")
|
|
|
|
newMatch.league = try match.select("tr > td > div > div > a").text()
|
|
newMatch.team1name = try match.getElementsByClass("team-left").text()
|
|
newMatch.team1score = leftscore
|
|
newMatch.team2name = try match.getElementsByClass("team-right").text()
|
|
newMatch.team2score = rightscore
|
|
matches.append(newMatch)
|
|
}
|
|
if matches.count == 0 {
|
|
return nil
|
|
}
|
|
return matches
|
|
} catch Exception.Error(_, _) {
|
|
print("")
|
|
return nil
|
|
} catch {
|
|
print("")
|
|
return nil
|
|
}
|
|
}
|
|
|
|
private func constructURL(for game: String) -> URL {
|
|
let baseURL = "https://liquipedia.net/"
|
|
let query = "/api.php?action=parse&page=Liquipedia:Upcoming_and_ongoing_matches&format=json&prop=text"
|
|
return URL(string: baseURL + game + query)!
|
|
}
|
|
}
|
|
|
|
|