greenbeanyum / sc-wikihoops

// ==UserScript==
// @name         sc-wikihoops
// @version      1.0.2
// @description  Add wikihoops scores to sportscult.org
// @author       greenbeanyum
// @updateURL    https://openuserjs.org/meta/greenbeanyum/sc-wikihoops.meta.js
// @downloadURL  https://openuserjs.org/install/greenbeanyum/sc-wikihoops.user.js
// @license      GPL-3.0-or-later
// @match        https://sportscult.org/index.php?page=torrent-details&id=*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=sportscult.org
// @grant        none
// ==/UserScript==

// ==OpenUserJS==
// @author greenbeanyum
// ==/OpenUserJS==

const wikiHoopsHTML = document.createElement('tr')
wikiHoopsHTML.innerHTML = `
  <td align="right" class="header" valign="top">Wikihoops</td>
  <td class="red lista wikihoops" align="center" style="text-align:left;" valign="top">loading</td>
`
function injectFrame() {
  const contentSelector = document.querySelector(".b-content>div>table>tbody")
  contentSelector.prepend(wikiHoopsHTML)
}


let torrentName = ""

const regexDate = /\s(\d{2}\s\d{2})|\s(\d{2}\/\d{2})/g // This will match the 2 digits followed by a space or a slash. 23 03 or 23/03
const regexTeam = /(\d{4}\s)(\w.*)\svs/ // This will match the 4 digits followed by a space and the team name. 2024 Memphis Grizzlies vs -> Memphis Grizzlies
const regexValidGame = /NBA.*202/ // This will match titles that start with NBA (anything, e.g. playin, playoffs) 202(0,1,2,3,4)

let gameInfo = {
  "date": "",
  "team": "",
  "city": "",
}

const parseName = (name) => {
  const cities = ["los", "san", "new", "city"]

  // Extract date from name
  const date = name.match(regexDate)[0].trim()

  // Extract team name and city from name
  let team = name.match(regexTeam)[2].trim()
  let city = ""
  for (const c of cities) {
    if (team.toLowerCase().includes(c)) {
      const splitTeam = team.split(" ")
      city = splitTeam.slice(0, 2).join(" ")
      team = splitTeam[2]
      break;
    }
  }
  if (!city) {
    const splitTeam = team.split(" ")
    city = splitTeam[0]
    team = splitTeam[1]
  }

  // Update gameInfo object
  gameInfo.date = date
  gameInfo.team = team
  gameInfo.city = city

  // Fetch data
  fetchWikiHoops()
}


// parse fetched html
const getGame = (doc, team, city, wikiUrl) => {
  const games = doc.querySelectorAll("section article")
  for (const game of games) {
    let homeTeam = game.querySelector(".home-team .team-name").innerText
    let awayTeam = game.querySelector(".away-team .team-name").innerText
    let homeCity = game.querySelector(".home-team .team-city").innerText
    let awayCity = game.querySelector(".away-team .team-city").innerText
    let teams = [homeTeam.toLowerCase(), awayTeam.toLowerCase(), homeCity.toLowerCase(), awayCity.toLowerCase()]
    let userScore = game.querySelector(".rating-value").innerText
    let userPct = game.querySelector(".upvotes-pct").innerText
    let userVotes = game.querySelector(".upvotes-total").innerText
    let downVotes = game.querySelector(".downvotes-total").innerText
    if (teams.includes(team.toLowerCase()) || teams.includes(city.toLowerCase())) {
      let wikihoops = document.querySelector(".lista.wikihoops")
      if (parseInt(userScore) >= 8 && parseInt(userScore) < 15) {
        wikihoops.classList.remove("red")
        wikihoops.classList.add("yellow")
      } else if (parseInt(userScore) >= 15) {
        wikihoops.classList.remove("red")
        wikihoops.classList.add("green")
      }
      wikihoops.innerText = ``
      wikihoops.innerHTML += ` <a href="${wikiUrl}" target="_blank">Score: ${userScore} Percentage: ${userPct} Total Upvotes: ${userVotes} Total Downvotes: ${downVotes}</a>`
      break;
    }
  }
}

// fetch date on wikihoops
function fetchWikiHoops() {
  let day = gameInfo.date.split(" ")[0]
  let month = gameInfo.date.split(" ")[1]
  let team = gameInfo.team
  let city = gameInfo.city
  const wikiUrl = `https://wikihoops.com/games/2024-${month}-${day}/`
  const url = 'https://corsproxy.io/?' + encodeURIComponent(wikiUrl);
  fetch(url)
    .then(function (response) {
      return response.text()
    })
    .then(function (html) {
      var parser = new DOMParser();
      var doc = parser.parseFromString(html, "text/html");
      let games = doc.querySelector("article.scoreboard")
      getGame(games, team, city, wikiUrl)
    })
    .catch(function (err) {
      console.log('Failed to fetch page: ', err);
    });
}


var c = document.querySelectorAll('.b-content tbody tr');
if (c) {
  for (const row of c) {
    let text = row.innerText
    if (text.includes("NBA G")) {
      break;
    }
    if (regexValidGame.test(text)) {
      injectFrame()
      torrentName = text
      parseName(torrentName)
      break;
    }
  }
}