/* Copyright © 2024 filifa This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package statsapi import ( "encoding/json" "io" "net/http" "net/url" "github.com/evanphx/json-patch/v5" ) var DefaultClient = NewClient(http.DefaultClient) func RequestSchedule(sportId, teamId string) ([]byte, error) { return DefaultClient.RequestSchedule(sportId, teamId) } func RequestFeed(gamePk string) ([]byte, error) { return DefaultClient.RequestFeed(gamePk) } func RequestDiffPatch(gamePk, startTimecode, pushUpdateId string) (DiffPatchResponse, error) { return DefaultClient.RequestDiffPatch(gamePk, startTimecode, pushUpdateId) } type DiffPatchResponse []byte type Client struct { baseURL url.URL httpClient *http.Client } func NewClient(c *http.Client) *Client { return &Client{ baseURL: url.URL{ Scheme: "https", Host: "statsapi.mlb.com", }, httpClient: c, } } func (resp *DiffPatchResponse) ExtractPatches() ([]jsonpatch.Patch, error) { var patches []jsonpatch.Patch var objs []map[string]any err := json.Unmarshal([]byte(*resp), &objs) if err != nil { return patches, err } for _, obj := range objs { diff := obj["diff"] patch, err := json.Marshal(diff) if err != nil { break } p, err := jsonpatch.DecodePatch(patch) if err != nil { break } patches = append(patches, p) } return patches, err } func (c *Client) RequestSchedule(sportId, teamId string) ([]byte, error) { endpoint := url.URL{Path: "api/v1/schedule"} query := endpoint.Query() query.Add("sportId", sportId) query.Add("teamId", teamId) endpoint.RawQuery = query.Encode() return c.get(&endpoint) } func (c *Client) RequestFeed(gamePk string) ([]byte, error) { endpoint := url.URL{Path: "api/v1.1/game/" + gamePk + "/feed/live"} return c.get(&endpoint) } func (c *Client) RequestDiffPatch(gamePk, startTimecode, pushUpdateId string) (DiffPatchResponse, error) { endpoint := url.URL{Path: "api/v1.1/game/" + gamePk + "/feed/live/diffPatch"} query := endpoint.Query() query.Add("language", "en") query.Add("startTimecode", startTimecode) query.Add("pushUpdateId", pushUpdateId) endpoint.RawQuery = query.Encode() return c.get(&endpoint) } func (c *Client) get(endpoint *url.URL) ([]byte, error) { url := c.baseURL.ResolveReference(endpoint) req, err := http.NewRequest("GET", url.String(), nil) if err != nil { return nil, err } resp, err := c.httpClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) return body, err }