This repository was archived by the owner on Dec 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.rb
671 lines (491 loc) · 20 KB
/
app.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
152
153
154
155
156
157
158
159
160
161
162
163
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
require 'sinatra'
require 'sinatra/namespace'
require 'rollbar/middleware/sinatra'
require 'redis'
require 'fileutils'
require_relative 'lib/redis_cache'
require_relative 'services/mal_network_service'
require_relative 'utilities/request_helper'
require_relative 'railgun'
class App < Sinatra::Base
register Sinatra::Namespace
use Rollbar::Middleware::Sinatra
redis = Redis.new
error_logger = File.new(File.join(FileUtils.mkdir_p("#{File.dirname(File.expand_path(__FILE__))}/log"),'error.log'), 'a+')
error_logger.sync = true
configure :production, :development do
enable :logging
end
configure :development do
# disable :show_exceptions
register Sinatra::Reloader
end
before do
content_type 'application/json;charset=utf-8'
env['rack.errors'] = error_logger
end
configure do
# enable :sessions, :static, :methodoverride
# disable :raise_errors
set :public_folder, Proc.new { File.join(File.dirname(__FILE__), 'public') }
# JSON CSRF protection interferes with CORS requests. Seeing as we're only acting
# as a proxy and not dealing with sensitive information, we'll disable this to
# prevent all manner of headaches.
# set :protection, :except => :json_csrf
end
error Railgun::NotFoundError do
status 404
logger.warn "Resource not found: #{request.env['sinatra.error'].message}"
body = { :error => 'not-found', :details => request.env['sinatra.error'].message }.to_json
params[:callback].nil? ? body : "#{params[:callback]}(#{body})"
end
error Railgun::NetworkError do
logger.warn "An error occurred: #{request.env['sinatra.error'].message}"
body = { :error => 'network-error', :details => request.env['sinatra.error'].message }.to_json
params[:callback].nil? ? body : "#{params[:callback]}(#{body})"
end
error do
logger.warn "An error occurred: #{request.env['sinatra.error'].message}"
body = { :error => 'unknown-error', :details => request.env['sinatra.error'].message }.to_json
params[:callback].nil? ? body : "#{params[:callback]}(#{body})"
end
namespace '/1.0' do
#
# Anime Endpoints
#
# GET /anime/#{anime_id}
# Get an anime's details.
# Parameters:
# - id: The anime's ID.
# - options (optional): A comma-separated list of strings that define additional stats.
# Available options include 'stats' and 'characters_and_staff'.
get '/anime/:id' do
pass unless params[:id] =~ /^\d+$/
options = []
if params.include? 'options'
options = params[:options].split(',')
end
logger.info "Fetching anime with ID #{params[:id]}..."
logger.info "Options: #{options}" unless options.count == 0
# FIXME: Removing caching on search for now. Figure out how to better cache this
# expires 3600, :public, :must_revalidate
# last_modified Time.now
# etag "anime/#{params[:id]}/#{options}"
anime = Railgun::Anime.scrape(params[:id], options)
anime.to_json
end
# GET /anime?q=#{query}
# Searches for an anime based on a given query.
# Parameters:
# - q: A search query.
get '/anime?' do
pass unless !params[:q].nil? && params[:q].strip.length > 0
query = CGI.escape(params[:q].strip)
# FIXME: Removing caching on search for now. Figure out how to better cache this
#expires 3600, :public, :must_revalidate
#last_modified Time.now
#etag "anime?#{query}"
results = Railgun::Anime.search(query)
results.to_json
end
# GET /anime/top
# Gets a page of a ranked list of anime. A page consists of 50 anime.
# Parameters:
# - type (optional): The type of list to fetch. Available options:
# 'all', 'airing', 'upcoming', 'tv', 'movie', 'ova', 'special', 'popular', 'favorite'.
# If no type is provided, this defaults to 'all'.
# - page (optional): The page of anime to fetch. If no value is provided, this defaults to 0.
# Each page consists of 50 anime; fetching page 1 returns anime
# ranked 51-100, page 2 returns 101-150, etc.
get '/anime/top' do
options = {
type: 'all',
page: 0
}
if params.include? 'type' and Railgun::MALNetworkService.rank_type_is_acceptable_for_anime_request(params[:type])
options[:type] = params[:type]
end
if params.include? 'page' and params[:page].is_a? Integer
options[:page] = params[:page]
end
logger.info "Fetching anime list with options #{options}..."
expires 3600, :public, :must_revalidate
last_modified Time.now
etag "anime/top/#{options[:type]}/#{options[:page]}"
anime = Railgun::Anime.top(options)
anime.to_json
end
# GET /anime/season
# Gets a page of a seaonal list of anime.
# Parameters:
# - year (optional): The year, expressed in four digits (i.e. 2006).
# If no value is provided, this defaults to the current year.
# You _must_ provide a seasonif you provide a year.
# - season (optional): The season, expressed as a string (i.e. 'summer').
# Available options: 'spring', 'summer', 'fall', 'winter'.
# If no value is provided, this defaults to whatever
# MyAnimeList deems as the current season.
# You _must_ provide a year if you provide a season.
get '/anime/season' do
options = {}
# options = {
# year: Time.now.year.to_s
# }
# if params.include? 'type' and Railgun::MALNetworkService.rank_type_is_acceptable_for_anime_request(params[:type])
# options[:year] = params[:type]
# end
#
# if params.include? 'page' and params[:page].is_a? Integer
# options[:page] = params[:page]
# end
logger.info "Fetching seasonal anime list with options #{options}..."
expires 3600, :public, :must_revalidate
last_modified Time.now
etag "anime/season/#{options[:year]}/#{options[:season]}"
anime = Railgun::Anime.season(options)
anime.to_json
end
#
# Manga Endpoints
#
# GET /manga/#{manga_id}
# Get a manga's details.
# Parameters:
# - id: The manga's ID.
# - options (optional): A comma-separated list of strings that define additional stats.
# Available options include 'stats' and 'characters_and_staff'.
get '/manga/:id' do
pass unless params[:id] =~ /^\d+$/
options = []
if params.include? 'options'
options = params[:options].split(',')
end
logger.info "Fetching manga with ID #{params[:id]}..."
logger.info "Options: #{options}" unless options.count == 0
# FIXME: Removing caching on search for now. Figure out how to better cache this
# expires 3600, :public, :must_revalidate
# last_modified Time.now
# etag "manga/#{params[:id]}/#{options}"
manga = Railgun::Manga.scrape(params[:id], options)
manga.to_json
end
# GET /manga?q=#{query}
# Searches for a manga based on a given query.
# Parameters:
# - q: A search query.
get '/manga?' do
pass unless !params[:q].nil? && params[:q].strip.length > 0
query = CGI.escape(params[:q].strip)
# FIXME: Removing caching on search for now. Figure out how to better cache this
#expires 3600, :public, :must_revalidate
#last_modified Time.now
#etag "manga?#{query}"
results = Railgun::Manga.search(query)
results.to_json
end
# GET /manga/top
# Gets a page of a ranked list of manga. A page consists of 50 manga.
# Parameters:
# - type (optional): The type of list to fetch. Available options:
# 'all', 'manga', 'novels', 'oneshots', 'doujinshi', 'manhwa', 'manhua', 'popular', 'favorite'.
# If no type is provided, this defaults to 'all'.
# - page (optional): The page of manga to fetch. If no value is provided, this defaults to 0.
# Each page consists of 50 manga; fetching page 1 returns manga
# ranked 51-100, page 2 returns 101-150, etc.
get '/manga/top' do
options = {
type: 'all',
page: 0
}
if params.include? 'type' and Railgun::MALNetworkService.rank_type_is_acceptable_for_manga_request(params[:type])
options[:type] = params[:type]
end
if params.include? 'page' and params[:page].is_a? Integer
options[:page] = params[:page]
end
logger.info "Fetching manga list with options #{options}..."
expires 3600, :public, :must_revalidate
last_modified Time.now
etag "manga/top/#{options[:type]}/#{options[:page]}"
manga = Railgun::Manga.top(options)
manga.to_json
end
#
# Character Endpoints
#
# GET /character/#{character_id}
# Get details for a character.
# Parameters:
# - id: The character's ID.
get '/character/:id' do
pass unless params[:id] =~ /^\d+$/
logger.info "Fetching character with ID #{params[:id]}..."
expires 3600, :public, :must_revalidate
last_modified Time.now
etag "character/#{params[:id]}"
character = Railgun::Character.scrape(params[:id])
character.to_json
end
#
# Person Endpoints
#
# GET /person/#{person_id}
# Get details for a person.
# Parameters:
# - id: The person's ID.
get '/person/:id' do
pass unless params[:id] =~ /^\d+$/
logger.info "Fetching person with ID #{params[:id]}..."
expires 3600, :public, :must_revalidate
last_modified Time.now
etag "person/#{params[:id]}"
person = Railgun::Person.scrape(params[:id])
person.to_json
end
end
namespace '/1.1' do
#
# Anime Endpoints
#
# GET /anime/#{anime_id}
# Get an anime's details.
# Parameters:
# - id: The anime's ID.
# - options (optional): A comma-separated list of strings that define additional stats.
# Available options include 'stats' and 'characters_and_staff'.
get '/anime/:id' do
pass unless params[:id] =~ /^\d+$/
options = []
if params.include? 'options'
options = params[:options].split(',')
end
id = params[:id]
logger.info "Fetching anime with ID #{id}..."
logger.info "Options: #{options}" unless options.count == 0
cache_control :public, :must_revalidate, :max_age => 259200
last_modified Date.today
etag Railgun::RequestHelper.generate_etag('anime', params[:id], Date.today)
# cached_json = redis.get "anime:#{id}"
# if cached_json.nil?
# NOTE: Disabling redis for now.
# logger.info 'Anime was not found in redis, making a request...'
nokogiri = Railgun::MALNetworkService.nokogiri_from_request(Railgun::MALNetworkService.anime_request_for_id(id))
anime = Railgun::Anime.scrape(nokogiri, id)
# Cache the contents if we can.
# begin
# logger.info '[REDIS] Storing in redis...'
# redis.setnx "anime:#{id}", anime.to_json
# redis.cache(id, 21600) { anime.to_json }
# rescue Exception => e
# logger.warn "[REDIS] Could not store in redis! An exception occurred: #{e}"
# end
# Are there additional options? We'll need to make additional requests if so.
if options.count > 0
if options.include? 'characters_and_staff'
logger.info 'Scraping characters and staff...'
nokogiri = Railgun::MALNetworkService.nokogiri_from_request(anime.additional_info_urls[:characters_and_staff])
anime.summary_stats = Railgun::Anime.scrape_characters_and_staff(nokogiri, anime)
end
if options.include? 'stats'
logger.info 'Scraping stats...'
nokogiri = Railgun::MALNetworkService.nokogiri_from_request(anime.additional_info_urls[:stats])
anime.score_stats = Railgun::Anime.scrape_stats(nokogiri, anime)
end
end
anime.to_json
# else
# logger.info "[REDIS] Cached version of #{params[:id]} found, returning..."
# cached_json
# end
end
# GET /anime?q=#{query}
# Searches for an anime based on a given query.
# Parameters:
# - q: A search query.
get '/anime?' do
pass unless !params[:q].nil? && params[:q].strip.length > 0
query = CGI.escape(params[:q].strip)
# FIXME: Removing caching on search for now. Figure out how to better cache this
#expires 3600, :public, :must_revalidate
#last_modified Time.now
#etag "anime?#{query}"
results = Railgun::Anime.search(query)
results.to_json
end
# GET /anime/top
# Gets a page of a ranked list of anime. A page consists of 50 anime.
# Parameters:
# - type (optional): The type of list to fetch. Available options:
# 'all', 'airing', 'upcoming', 'tv', 'movie', 'ova', 'special', 'popular', 'favorite'.
# If no type is provided, this defaults to 'all'.
# - page (optional): The page of anime to fetch. If no value is provided, this defaults to 0.
# Each page consists of 50 anime; fetching page 1 returns anime
# ranked 51-100, page 2 returns 101-150, etc.
get '/anime/top' do
options = {
type: 'all',
page: 0
}
if params.include? 'type' and Railgun::MALNetworkService.rank_type_is_acceptable_for_anime_request(params[:type])
options[:type] = params[:type]
end
if params.include? 'page' and params[:page].is_a? Integer
options[:page] = params[:page]
end
logger.info "Fetching anime list with options #{options}..."
cache_control :public, :must_revalidate, :max_age => 259200
last_modified Date.today
etag Railgun::RequestHelper.generate_etag('animetop', params[:type], Date.today)
anime = Railgun::Anime.top(options)
anime.to_json
end
# GET /anime/season
# Gets a page of a seaonal list of anime.
# Parameters:
# - year (optional): The year, expressed in four digits (i.e. 2006).
# If no value is provided, this defaults to the current year.
# You _must_ provide a seasonif you provide a year.
# - season (optional): The season, expressed as a string (i.e. 'summer').
# Available options: 'spring', 'summer', 'fall', 'winter'.
# If no value is provided, this defaults to whatever
# MyAnimeList deems as the current season.
# You _must_ provide a year if you provide a season.
get '/anime/season' do
options = {}
# options = {
# year: Time.now.year.to_s
# }
# if params.include? 'type' and Railgun::MALNetworkService.rank_type_is_acceptable_for_anime_request(params[:type])
# options[:year] = params[:type]
# end
#
# if params.include? 'page' and params[:page].is_a? Integer
# options[:page] = params[:page]
# end
logger.info "Fetching seasonal anime list with options #{options}..."
cache_control :public, :must_revalidate, :max_age => 259200
last_modified Date.today
etag "anime/season/#{options[:year]}/#{options[:season]}"
anime = Railgun::Anime.season(options)
anime.to_json
end
#
# Manga Endpoints
#
# GET /manga/#{manga_id}
# Get a manga's details.
# Parameters:
# - id: The manga's ID.
# - options (optional): A comma-separated list of strings that define additional stats.
# Available options include 'stats' and 'characters_and_staff'.
get '/manga/:id' do
pass unless params[:id] =~ /^\d+$/
options = []
if params.include? 'options'
options = params[:options].split(',')
end
logger.info "Fetching manga with ID #{params[:id]}..."
logger.info "Options: #{options}" unless options.count == 0
cache_control :public, :must_revalidate, :max_age => 259200
last_modified Date.today
etag Railgun::RequestHelper.generate_etag('manga', params[:id], Date.today)
manga = Railgun::Manga.scrape(params[:id], options)
manga.to_json
end
# GET /manga?q=#{query}
# Searches for a manga based on a given query.
# Parameters:
# - q: A search query.
get '/manga?' do
pass unless !params[:q].nil? && params[:q].strip.length > 0
query = CGI.escape(params[:q].strip)
# FIXME: Removing caching on search for now. Figure out how to better cache this
#expires 3600, :public, :must_revalidate
#last_modified Time.now
#etag "manga?#{query}"
results = Railgun::Manga.search(query)
results.to_json
end
# GET /manga/top
# Gets a page of a ranked list of manga. A page consists of 50 manga.
# Parameters:
# - type (optional): The type of list to fetch. Available options:
# 'all', 'manga', 'novels', 'oneshots', 'doujinshi', 'manhwa', 'manhua', 'popular', 'favorite'.
# If no type is provided, this defaults to 'all'.
# - page (optional): The page of manga to fetch. If no value is provided, this defaults to 0.
# Each page consists of 50 manga; fetching page 1 returns manga
# ranked 51-100, page 2 returns 101-150, etc.
get '/manga/top' do
options = {
type: 'all',
page: 0
}
if params.include? 'type' and Railgun::MALNetworkService.rank_type_is_acceptable_for_manga_request(params[:type])
options[:type] = params[:type]
end
if params.include? 'page' and params[:page].is_a? Integer
options[:page] = params[:page]
end
logger.info "Fetching manga list with options #{options}..."
cache_control :public, :must_revalidate, :max_age => 259200
last_modified Date.today
etag Railgun::RequestHelper.generate_etag('mangatop', params[:type], Date.today)
manga = Railgun::Manga.top(options)
manga.to_json
end
#
# Character Endpoints
#
# GET /character/#{character_id}
# Get details for a character.
# Parameters:
# - id: The character's ID.
get '/character/:id' do
pass unless params[:id] =~ /^\d+$/
logger.info "Fetching character with ID #{params[:id]}..."
cache_control :public, :must_revalidate, :max_age => 259200
last_modified Date.today
etag Railgun::RequestHelper.generate_etag('character', params[:id], Date.today)
character = Railgun::Character.scrape(params[:id])
character.to_json
end
#
# Person Endpoints
#
# GET /person/#{person_id}
# Get details for a person.
# Parameters:
# - id: The person's ID.
get '/person/:id' do
pass unless params[:id] =~ /^\d+$/
logger.info "Fetching person with ID #{params[:id]}..."
cache_control :public, :must_revalidate, :max_age => 259200
last_modified Date.today
etag Railgun::RequestHelper.generate_etag('person', params[:id], Date.today)
person = Railgun::Person.scrape(params[:id])
person.to_json
end
#
# User Endpoints
#
# GET /user/#{user_id}/friends
# Get a list of friends for a user.
# Parameters:
# - id: The user's username.
get '/user/:id/:option' do
pass unless params[:id] =~ /^\d+$/ || params[:option] =~ /^\w+$/
if params[:option] == 'friends'
logger.info "Fetching friends for user with ID #{params[:id]}..."
cache_control :public, :must_revalidate, :max_age => 259200
last_modified Date.today
etag Railgun::RequestHelper.generate_etag('user', params[:id], Date.today)
users = Railgun::User.scrape_friends(params[:id])
users.to_json
end
end
end
get '/' do
content_type 'text/html;charset=utf-8'
send_file File.expand_path('index.html', settings.public_folder)
end
end