Class: Mysportsfeeds::Api::API_v1_0

Inherits:
Object
  • Object
show all
Defined in:
lib/mysportsfeeds/api/API_v1_0.rb

Overview

API class for dealing with v1.0 of the API

Instance Method Summary collapse

Constructor Details

#initialize(verbose, store_type = nil, store_location = nil) ⇒ API_v1_0

Constructor



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/mysportsfeeds/api/API_v1_0.rb', line 15

def initialize(verbose, store_type=nil, store_location=nil)
    @base_uri = URI("https://www.mysportsfeeds.com/api/feed/pull")
    @headers = {
        "Accept-Encoding" => "gzip",
        "User-Agent" => "MySportsFeeds Ruby/#{Mysportsfeeds::Ruby::VERSION} (#{RUBY_PLATFORM})"
    }

    @verbose = verbose
    @store_type = store_type
    @store_location = store_location

    @valid_feeds = [
        'current_season',
        'cumulative_player_stats',
        'full_game_schedule',
        'daily_game_schedule',
        'daily_player_stats',
        'game_playbyplay',
        'game_boxscore',
        'scoreboard',
        'player_gamelogs',
        'team_gamelogs',
        'roster_players',
        'game_startinglineup',
        'active_players',
        'player_injuries',
        'latest_updates',
        'daily_dfs',
        'overall_team_standings',
        'conference_team_standings',
        'division_team_standings',
        'playoff_team_standings'
    ]
end

Instance Method Details

#__league_and_season_url(league, season, feed, output_format, params) ⇒ Object

Feed URL (with league + season specified)



89
90
91
92
93
94
95
96
97
98
99
# File 'lib/mysportsfeeds/api/API_v1_0.rb', line 89

def __league_and_season_url(league, season, feed, output_format, params)
    url = "#{@base_uri.to_s}/#{league}/#{season}/#{feed}.#{output_format}"

    delim = "?"
    params.each do |key, value|
        url << delim << key << "=" << value
        delim = "&"
    end

    return url
end

#__league_only_url(league, feed, output_format, params) ⇒ Object

Feed URL (with only a league specified)



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/mysportsfeeds/api/API_v1_0.rb', line 76

def __league_only_url(league, feed, output_format, params)
    url "#{@base_uri.to_s}/#{league}/#{feed}.#{output_format}"

    delim = "?"
    params.each do |key, value|
        url << delim << key << "=" << value
        delim = "&"
    end

    return url
end

#__make_output_filename(league, season, feed, output_format, params) ⇒ Object

Generate the appropriate filename for a feed request



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/mysportsfeeds/api/API_v1_0.rb', line 102

def __make_output_filename(league, season, feed, output_format, params)
    filename = "#{feed}-#{league.downcase}-#{season}"

    if params.key?("gameid")
        filename << "-" << params["gameid"]
    end

    if params.key?("fordate")
        filename << "-" << params["fordate"]
    end

    filename << "." << output_format

    return filename
end

#__save_feed(response, league, season, feed, output_format, params) ⇒ Object

Save a feed response based on the store_type



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/mysportsfeeds/api/API_v1_0.rb', line 119

def __save_feed(response, league, season, feed, output_format, params)
    # Save to memory regardless of selected method

    if output_format == "json"
        store_output = JSON.parse(response)
    elsif output_format == "xml"
        store_output = response
    elsif output_format == "csv"
        store_output = response
    end

    if @store_type == "file"
        if !File.exist?(@store_location)
            FileUtils::mkdir_p(@store_location)
        end

        filename = __make_output_filename(league, season, feed, output_format, params)

        outfile = File.open(@store_location + filename, "w")
        if output_format == "json"  # This is JSON

            json_out = response.to_json.gsub('\\', '').strip
            outfile.write(json_out[1..json_out.size-2])

        elsif output_format == "xml"  # This is xml

            outfile.write(store_output)

        elsif output_format == "csv"  # This is csv

            outfile.write(store_output)

        else
            raise Exception.new("Could not interpret feed output format")
        end
    end
end

#__verify_feed_name(feed) ⇒ Object

Verify a feed



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/mysportsfeeds/api/API_v1_0.rb', line 51

def __verify_feed_name(feed)
    is_valid = false

    for value in @valid_feeds
        if value == feed
            is_valid = true
            break
        end
    end

    return is_valid
end

#__verify_format(format) ⇒ Object

Verify output format



65
66
67
68
69
70
71
72
73
# File 'lib/mysportsfeeds/api/API_v1_0.rb', line 65

def __verify_format(format)
    is_valid = true

    if format != 'json' and format != 'xml' and format != 'csv'
        is_valid = false
    end

    return is_valid
end

#get_data(league, season, feed, output_format, kwargs) ⇒ Object

Request data (and store it if applicable)



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/mysportsfeeds/api/API_v1_0.rb', line 164

def get_data(league, season, feed, output_format, kwargs)
    if !@auth
        raise Exception.new("You must authenticate() before making requests.")
    end

    # establish defaults for all variables

    params = {}

    # add force=false parameter (helps prevent unnecessary bandwidth use)

    kwargs.each do |kwarg|
        kwarg.each do |key, value|
            params[key] = value
        end
    end

    if !params.key?("force")
        params['force'] = 'false'
    end

    if __verify_feed_name(feed) == false
        raise Exception.new("Unknown feed '" + feed + "'.")
    end

    if __verify_format(output_format) == false
        raise Exception.new("Unsupported format '" + output_format + "'.")
    end

    if feed == 'current_season'
        url = __league_only_url(league, feed, output_format, params)
    else
        url = __league_and_season_url(league, season, feed, output_format, params)
    end

    if @verbose
        puts "Making API request to '#{url}'."
        puts "  with headers:"
        puts @headers
    end

    http = Net::HTTP.new(@base_uri.host, @base_uri.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    request = Net::HTTP::Get.new(url)
    request.basic_auth(@auth["username"], @auth["password"])

    r = http.request(request)
    if @verbose
        puts "response = #{r}"
    end

    if r.code == "200"
        if @store_type != nil
            __save_feed(r.body, league, season, feed, output_format, params)
        end

        if output_format == "json"
            data = JSON.parse(r.body)
        elsif output_format == "xml"
            data = r.body
        else
            data = r.body
        end

    elsif r.code == "304"
        if @verbose
            puts "Data hasn't changed since last call"
        end

        filename = __make_output_filename(league, season, feed, output_format, params)

        f = File.read(@store_location + filename)
        if output_format == "json"
            data = JSON.parse(f)
        elsif output_format == "xml"
            data = f
        else
            data = f
        end

    else
        puts "API call failed with error: #{r.code}"
    end

    return data
end

#set_auth_credentials(username, password) ⇒ Object

Establish BASIC auth credentials



159
160
161
# File 'lib/mysportsfeeds/api/API_v1_0.rb', line 159

def set_auth_credentials(username, password)
    @auth = {"username" => username, "password" => password}
end

#supports_basic_authObject

Indicate this version does support BASIC auth



154
155
156
# File 'lib/mysportsfeeds/api/API_v1_0.rb', line 154

def supports_basic_auth()
    return true
end