81 lines
2.9 KiB
Swift
81 lines
2.9 KiB
Swift
//
|
|
// LiquipediaMatchesAPI.swift
|
|
// LiquipediaMenu
|
|
//
|
|
//This class scrapes the Liquipedia upcoming matches page. It extracts them and puts them into a [Match]? by, using the Match class as a data storage objet.
|
|
// 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
|
|
// TODO: Handle what happens when there is no twitch page. Currently it just opens Twicht main page.
|
|
newMatch.streamLink = try "https://twitch.tv/" + match.getElementsByClass("timer-object").attr("data-stream-twitch")
|
|
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)!
|
|
}
|
|
}
|
|
|
|
|