forked from stefansundin/rssbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
1311 lines (1135 loc) · 52.4 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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
# export RUBYOPT=--enable-frozen-string-literal
require "sinatra"
require "./config/application"
require "active_support/core_ext/string"
require "open-uri"
before do
content_type :text
end
after do
if env["HTTP_ACCEPT"] == "application/json" && @response.redirect?
content_type :json
status 200
location = @response.headers["Location"]
@response.headers.delete("Location")
if location.start_with?(@request.root_url)
location = location[@request.root_url.length..]
end
body location.to_json
end
end
get "/" do
SecureHeaders.use_secure_headers_override(request, :index)
erb :index
end
get "/live" do
content_type :html
SecureHeaders.use_secure_headers_override(request, :live)
send_file File.join(settings.public_folder, "live.html")
end
get "/countdown" do
content_type :html
SecureHeaders.use_secure_headers_override(request, :countdown)
send_file File.join(settings.public_folder, "countdown.html")
end
get "/go" do
return [400, "Insufficient parameters"] if params[:q].empty?
if /^https?:\/\/(?:mobile\.)?twitter\.com\// =~ params[:q]
redirect Addressable::URI.new(path: "/twitter", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:www\.|gaming\.)?youtu(?:\.be|be\.com)/ =~ params[:q]
redirect Addressable::URI.new(path: "/youtube", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:www\.)?facebook\.com/ =~ params[:q]
redirect Addressable::URI.new(path: "/facebook", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:www\.)?instagram\.com/ =~ params[:q]
redirect Addressable::URI.new(path: "/instagram", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:www\.)?(?:periscope|pscp)\.tv/ =~ params[:q]
redirect Addressable::URI.new(path: "/periscope", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:www\.)?soundcloud\.com/ =~ params[:q]
redirect Addressable::URI.new(path: "/soundcloud", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:www\.)?mixcloud\.com/ =~ params[:q]
redirect Addressable::URI.new(path: "/mixcloud", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:www\.|go\.)?twitch\.tv/ =~ params[:q]
redirect Addressable::URI.new(path: "/twitch", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:www\.)?speedrun\.com/ =~ params[:q]
redirect Addressable::URI.new(path: "/speedrun", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:www\.)?ustream\.tv/ =~ params[:q]
redirect Addressable::URI.new(path: "/ustream", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:www\.)?dailymotion\.com/ =~ params[:q]
redirect Addressable::URI.new(path: "/dailymotion", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:www\.)?vimeo\.com/ =~ params[:q]
redirect Addressable::URI.new(path: "/vimeo", query_values: params).normalize.to_s
elsif /^https?:\/\/(?:[a-z0-9]+\.)?imgur\.com/ =~ params[:q]
redirect Addressable::URI.new(path: "/imgur", query_values: params).normalize.to_s
elsif /^https?:\/\/medium\.com\/(?<user>@?[^\/?&#]+)/ =~ params[:q]
redirect Addressable::URI.parse("https://medium.com/feed/#{user}").normalize.to_s
elsif /^https?:\/\/(?<name>[a-z0-9\-]+)\.blogspot\./ =~ params[:q]
redirect Addressable::URI.parse("https://#{name}.blogspot.com/feeds/posts/default").normalize.to_s
elsif /^https?:\/\/groups\.google\.com\/forum\/#!(?:[a-z]+)\/(?<name>[^\/?&#]+)/ =~ params[:q]
redirect Addressable::URI.parse("https://groups.google.com/forum/feed/#{name}/msgs/atom.xml?num=50").normalize.to_s
elsif /^https?:\/\/www\.deviantart\.com\/(?<user>[^\/]+)/ =~ params[:q]
redirect "https://backend.deviantart.com/rss.xml" + Addressable::URI.new(query: "type=deviation&q=by:#{user} sort:time").normalize.to_s
elsif /^(?<baseurl>https?:\/\/[a-zA-Z0-9\-]+\.tumblr\.com)/ =~ params[:q]
redirect "#{baseurl}/rss"
elsif /^https?:\/\/itunes\.apple\.com\/.+\/id(?<id>\d+)/ =~ params[:q]
# https://itunes.apple.com/us/podcast/the-bernie-sanders-show/id1223800705
response = HTTP.get("https://itunes.apple.com/lookup?id=#{id}")
raise(HTTPError, response) if !response.success?
redirect response.json["results"][0]["feedUrl"]
elsif /^https?:\/\/(?:www\.)?svtplay\.se/ =~ params[:q]
redirect Addressable::URI.new(path: "/svtplay", query_values: params).normalize.to_s
else
return [404, "Unknown service"]
end
end
get "/twitter" do
return [400, "Insufficient parameters"] if params[:q].empty?
if params[:q].include?("twitter.com/i/") || params[:q].include?("twitter.com/who_to_follow/")
return [404, "Unsupported url. Sorry."]
elsif params[:q].include?("twitter.com/hashtag/") || params[:q].start_with?("#")
return [404, "This app does not support hashtags. Sorry."]
elsif /twitter\.com\/intent\/.+[?&]user_id=(?<user_id>\d+)/ =~ params[:q]
# https://twitter.com/intent/user?user_id=34313404
# https://twitter.com/intent/user?user_id=71996998
elsif /twitter\.com\/(?:#!\/|@)?(?<user>[^\/?#]+)/ =~ params[:q] || /@(?<user>[^\/?#]+)/ =~ params[:q]
# https://twitter.com/#!/infected
# https://twitter.com/infected
# @username
else
# it's probably a username
user = params[:q]
end
if user
query = { screen_name: user }
elsif user_id
query = { user_id: user_id }
end
response = Twitter.get("/users/show.json", query: query)
return [response.code, response.json["errors"][0]["message"]] if response.json.has_key?("errors")
raise(TwitterError, response) if !response.success?
user_id = response.json["id_str"]
screen_name = response.json["screen_name"].or(response.json["name"])
redirect Addressable::URI.new(path: "/twitter/#{user_id}/#{screen_name}", query: params[:type]).normalize.to_s
end
get %r{/twitter/(?<id>\d+)/(?<username>.+)} do |id, username|
@user_id = id
response = Twitter.get("/statuses/user_timeline.json", query: {
user_id: id,
count: 100,
tweet_mode: "extended",
include_rts: %w[0 1].pick(params[:include_rts]) || "1",
exclude_replies: %w[0 1].pick(params[:exclude_replies]) || "0",
})
return [response.code, response.body] if response.code == 401
return [response.code, "This user id no longer exists. The user was likely deleted or recreated. Try resubscribing."] if response.code == 404
raise(TwitterError, response) if !response.success?
@data = response.json
if @data[0] && !@data[0]["user"]["screen_name"].empty?
@username = @data[0]["user"]["screen_name"]
else
@username = CGI.unescape(username)
end
if params[:with_media] == "video"
@data.select! { |t| t["extended_entities"] && t["extended_entities"]["media"].any? { |m| m.has_key?("video_info") } }
elsif params[:with_media] == "picture"
@data.select! { |t| t["extended_entities"] && !t["extended_entities"]["media"].any? { |m| m.has_key?("video_info") } }
elsif params[:with_media]
@data.select! { |t| t["extended_entities"] }
end
@data.map do |t|
t = t["retweeted_status"] if t.has_key?("retweeted_status")
t["entities"]["urls"].each do |entity|
t["full_text"].gsub!(entity["url"], entity["expanded_url"])
end
t["full_text"].grep_urls
end.flatten.tap { |urls| URL.resolve(urls) }
erb :twitter_feed
end
get "/youtube" do
return [400, "Insufficient parameters"] if params[:q].empty?
if /youtube\.com\/channel\/(?<channel_id>(UC|S)[^\/?#]+)(?:\/search\?query=(?<query>[^&#]+))?/ =~ params[:q]
# https://www.youtube.com/channel/UC4a-Gbdw7vOaccHmFo40b9g/videos
# https://www.youtube.com/channel/SWu5RTwuNMv6U
# https://www.youtube.com/channel/UCd6MoB9NC6uYN2grvUNT-Zg/search?query=aurora
elsif /youtube\.com\/(?<type>user|c|show)\/(?<slug>[^\/?#]+)(?:\/search\?query=(?<query>[^&#]+))?/ =~ params[:q]
# https://www.youtube.com/user/khanacademy/videos
# https://www.youtube.com/c/khanacademy
# https://www.youtube.com/show/redvsblue
# https://www.youtube.com/user/AmazonWebServices/search?query=aurora
# https://www.youtube.com/c/khanacademy/search?query=Frequency+stability
# there is no way to resolve these accurately through the API, the best way is to look for the channelId meta tag in the website HTML
# note that slug != username, e.g. https://www.youtube.com/c/kawaiiguy and https://www.youtube.com/user/kawaiiguy are two different channels
user = "#{type}/#{slug}"
elsif /youtube\.com\/.*[?&]v=(?<video_id>[^&#]+)/ =~ params[:q]
# https://www.youtube.com/watch?v=vVXbgbMp0oY&t=5s
elsif /youtube\.com\/.*[?&]list=(?<playlist_id>[^&#]+)/ =~ params[:q]
# https://www.youtube.com/playlist?list=PL0QrZvg7QIgpoLdNFnEePRrU-YJfr9Be7
elsif /youtube\.com\/(?<user>[^\/?#]+)/ =~ params[:q]
# https://www.youtube.com/khanacademy
elsif /youtu\.be\/(?<video_id>[^?#]+)/ =~ params[:q]
# https://youtu.be/vVXbgbMp0oY?t=1s
elsif /\b(?<channel_id>(?:UC[^\/?#]{22,}|S[^\/?#]{12,}))/ =~ params[:q]
# it's a channel id
else
# it's probably a channel name
user = params[:q]
end
if user
response = HTTP.get("https://www.youtube.com/#{user}")
if response.redirect?
# https://www.youtube.com/tyt -> https://www.youtube.com/user/theyoungturks (different from https://www.youtube.com/user/tyt)
response = HTTP.get(response.redirect_url)
end
return [response.code, "Could not find the user. Please try with a video url instead."] if response.code == 404
raise(GoogleError, response) if !response.success?
doc = Nokogiri::HTML(response.body)
channel_id = doc.at("meta[itemprop='channelId']")["content"]
end
if video_id
response = Google.get("/youtube/v3/videos", query: { part: "snippet", id: video_id })
raise(GoogleError, response) if !response.success?
if response.json["items"].length > 0
channel_id = response.json["items"][0]["snippet"]["channelId"]
end
end
if query || params[:type]
# it's no longer possible to get usernames using the API
# note that the values include " - YouTube" at the end if the User-Agent is a browser
og = OpenGraph.new("https://www.youtube.com/channel/#{channel_id}")
username = og.url.split("/")[-1]
username = og.title if username == channel_id
end
if query
query = CGI.unescape(query) # youtube uses + here instead of %20
redirect Addressable::URI.new(path: "/youtube/#{channel_id}/#{username}", query_values: { q: query }).normalize.to_s
elsif params[:type] == "live"
redirect Addressable::URI.new(path: "/youtube/#{channel_id}/#{username}", query_values: { eventType: "live,upcoming" }.merge(params.slice(:tz))).normalize.to_s
elsif channel_id
redirect "https://www.youtube.com/feeds/videos.xml" + Addressable::URI.new(query: "channel_id=#{channel_id}").normalize.to_s
elsif playlist_id
redirect "https://www.youtube.com/feeds/videos.xml" + Addressable::URI.new(query: "playlist_id=#{playlist_id}").normalize.to_s
else
return [404, "Could not find the channel. Sorry."]
end
end
get "/youtube/:channel_id/:username" do
@channel_id = params[:channel_id]
@username = params[:username]
@tz = params[:tz]
query = { part: "id", type: "video", order: "date", channelId: @channel_id, maxResults: 50 }
if params.has_key?(:q)
@query = query[:q] = params[:q]
@title = "\"#{params[:q]}\" from #{@username}"
else
@title = "#{@username} on YouTube"
end
ids = if params.has_key?(:eventType)
eventTypes = params[:eventType].split(",")
if eventTypes.any? { |type| !%w[completed live upcoming].include?(type) }
return [400, "Invalid eventType. Valid types: completed live upcoming."]
end
eventTypes.map do |eventType|
query[:eventType] = eventType
response = Google.get("/youtube/v3/search", query: query)
raise(GoogleError, response) if !response.success?
response.json["items"]
end.flatten.uniq { |v| v["id"]["videoId"] }.sort_by { |v| v["snippet"]["publishedAt"] }.reverse
else
response = Google.get("/youtube/v3/search", query: query)
raise(GoogleError, response) if !response.success?
response.json["items"]
end.map { |v| v["id"]["videoId"] }
response = Google.get("/youtube/v3/videos", query: { part: "snippet,liveStreamingDetails,contentDetails", id: ids.join(",") })
raise(GoogleError, response) if !response.success?
@data = response.json["items"]
# filter out all live streams that are not completed if we don't specifically want specific event types
if !params[:eventType]
@data.select! { |v| !v["liveStreamingDetails"] || v["liveStreamingDetails"]["actualEndTime"] }
end
# The YouTube API can bug out and return videos from other channels even though "channelId" is used, so make doubly sure
@data.select! { |v| v["snippet"]["channelId"] == @channel_id }
if params.has_key?(:q)
q = params[:q].downcase
@data.select! { |v| v["snippet"]["title"].downcase.include?(q) }
end
@data.map do |video|
video["snippet"]["description"].grep_urls
end.flatten.tap { |urls| URL.resolve(urls) }
erb :youtube_feed
end
get %r{/googleplus/(?<id>\d+)/(?<username>.+)} do |id, username|
return [404, "RIP Google+ 2011-2019"]
end
get "/vimeo" do
return [400, "Insufficient parameters"] if params[:q].empty?
if /vimeo\.com\/user(?<user_id>\d+)/ =~ params[:q]
# https://vimeo.com/user7103699
elsif /vimeo\.com\/ondemand\/(?<user>[^\/?&#]+)/ =~ params[:q]
# https://vimeo.com/ondemand/thealphaquadrant/
response = Vimeo.get("/ondemand/pages/#{user}")
raise(VimeoError, response) if !response.success?
user_id = response.json["user"]["uri"][/\d+/]
elsif /vimeo\.com\/(?<video_id>\d+)/ =~ params[:q]
# https://vimeo.com/155672086
response = Vimeo.get("/videos/#{video_id}")
raise(VimeoError, response) if !response.success?
user_id = response.json["user"]["uri"][/\d+/]
elsif /vimeo\.com\/(?:channels\/)?(?<user>[^\/?&#]+)/ =~ params[:q] || user = params[:q]
# it's probably a channel name
response = Vimeo.get("/users", query: { query: user })
raise(VimeoError, response) if !response.success?
if response.json["data"].length > 0
user_id = response.json["data"][0]["uri"].gsub("/users/","").to_i
end
end
if user_id
redirect "https://vimeo.com/user#{user_id}/videos/rss"
else
return [404, "Could not find the channel. Sorry."]
end
end
get "/facebook" do
return [404, "Facebook credentials not configured"] if ENV["FACEBOOK_APP_ID"].empty? || ENV["FACEBOOK_APP_SECRET"].empty?
return [400, "Insufficient parameters"] if params[:q].empty?
params[:q].gsub!("facebookcorewwwi.onion", "facebook.com") if params[:q].include?("facebookcorewwwi.onion")
if /https:\/\/www\.facebook\.com\/plugins\/.+[?&]href=(?<href>.+)$/ =~ params[:q]
# https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Finfectedmushroom%2Fvideos%2F10154638763917261%2F&show_text=0&width=400
params[:q] = CGI.unescape(href)
end
if /facebook\.com\/pages\/[^\/]+\/(?<id>\d+)/ =~ params[:q]
# https://www.facebook.com/pages/Lule%C3%A5-Sweden/106412259396611?fref=ts
elsif /facebook\.com\/groups\/(?<id>\d+)/ =~ params[:q]
# https://www.facebook.com/groups/223764997793315
elsif /facebook\.com\/video\/[^\d]+(?<id>\d+)/ =~ params[:q]
# https://www.facebook.com/video/embed?video_id=1192228974143110
elsif /facebook\.com\/[^\/]+-(?<id>[\d]+)/ =~ params[:q]
# https://www.facebook.com/TNG-Recuts-867357396651373/
elsif /facebook\.com\/(?:pg\/)?(?<id>[^\/?#]+)/ =~ params[:q]
# https://www.facebook.com/celldweller/info?tab=overview
else
id = params[:q]
end
response = Facebook.get("/", query: { id: id, metadata: "1" })
return [response.code, "Can't find a page with that name. Sorry."] if response.code == 404
return [response.code, "#{Facebook::BASE_URL}/#{id} returned code #{response.code}."] if response.code == 400
raise(FacebookError, response) if !response.success?
data = response.json
if data["metadata"]["fields"].any? { |field| field["name"] == "from" }
# this is needed if the url is for e.g. a photo and not the main page
response = Facebook.get("/", query: { id: id, fields: "from", metadata: "1" })
raise(FacebookError, response) if !response.success?
id = response.json["from"]["id"]
response = Facebook.get("/", query: { id: id, metadata: "1" })
raise(FacebookError, response) if !response.success?
data = response.json
end
if data["metadata"]["fields"].any? { |field| field["name"] == "username" }
response = Facebook.get("/", query: { id: id, fields: "username,name" })
raise(FacebookError, response) if !response.success?
data = response.json
end
return [404, "Please use a link directly to the Facebook page."] if !data["id"].numeric?
redirect Addressable::URI.new(path: "/facebook/#{data["id"]}/#{data["username"] || data["name"]}", query_values: params.slice(:type)).normalize.to_s
end
get "/facebook/download" do
if /\/(?<id>\d+)/ =~ params[:url]
# https://www.facebook.com/infectedmushroom/videos/10153430677732261/
# https://www.facebook.com/infectedmushroom/videos/vb.8811047260/10153371214897261/?type=2&theater
elsif /\d+_(?<id>\d+)/ =~ params[:url]
elsif /v=(?<id>\d+)/ =~ params[:url]
elsif /(?<id>\d+)/ =~ params[:url]
else
id = params[:url]
end
response = HTTP.get("https://www.facebook.com/#{id}")
response = HTTP.get(response.redirect_url) if response.redirect_same_origin?
if response.success?
if /hd_src(?:_no_ratelimit)?:"(?<url>[^"]+)"/ =~ response.body
elsif /https:\/\/[^"]+_#{id}_[^"]+\.jpg[^"]+/o =~ response.body
# This is not the best quality of the picture, but it will have to do
url = CGI.unescapeHTML($&)
end
if !url
return [404, "Video/photo not found."]
end
if env["HTTP_ACCEPT"] == "application/json"
content_type :json
fn = nil
if /<title[^>]*>(?<title>[^<]+)<\/title>/ =~ response.body && /data-utime="(?<utime>\d+)"/ =~ response.body
title = title.force_encoding("UTF-8").gsub(" | Facebook", "")
created_time = Time.at(utime.to_i)
fn = "#{created_time.to_date} - #{title}.#{url.url_ext}".to_filename
end
return {
url: url,
filename: fn,
}.to_json
end
redirect url
end
end
get %r{/facebook/(?<id>\d+)/(?<username>.+)} do |id, username|
return [404, "Facebook credentials not configured"] if ENV["FACEBOOK_APP_ID"].empty? || ENV["FACEBOOK_APP_SECRET"].empty?
@id = id
@type = @edge = %w[videos photos live].pick(params[:type]) || "posts"
@edge = "videos" if @type == "live"
fields = {
"posts" => "updated_time,from,parent_id,type,story,name,message,description,link,source,picture,full_picture,properties",
"videos" => "updated_time,from,title,description,embed_html,length,live_status",
"photos" => "updated_time,from,message,description,name,link,source",
}[@edge]
query = { fields: fields, since: Time.now.to_i-365*24*60*60 } # date -v -1w +%s
if params.has_key?(:locale)
query[:locale] = params[:locale]
end
response = Facebook.get("/#{id}/#{@edge}", query: query)
return [response.code, "#{Facebook::BASE_URL}/#{id}/#{@edge} returned code #{response.code}."] if response.code == 400
raise(FacebookError, response) if !response.success?
@data = response.json["data"]
if @edge == "posts"
# Copy down video length from properties array
@data.each do |post|
if post.has_key?("properties")
post["properties"].each do |prop|
if prop["name"] == "Length" && /^(?<m>\d+):(?<s>\d+)$/ =~ prop["text"]
post["length"] = 60*m.to_i + s.to_i
end
end
end
end
elsif @type == "live"
@data.select! { |post| post["live_status"] }
end
# Remove live videos from most feeds
if @type != "live"
@data.select! { |post| post["live_status"] != "LIVE" }
end
@user = @data[0]["from"]["name"] rescue CGI.unescape(username)
@title = @user
if @type == "live"
@title += "'s live videos"
elsif @type != "posts"
@title += "'s #{@type}"
end
@title += " on Facebook"
@data.map do |post|
post.slice("message", "description", "link").values.map(&:grep_urls)
end.flatten.tap { |urls| URL.resolve(urls) }
erb :facebook_feed
end
get "/instagram" do
return [400, "Insufficient parameters"] if params[:q].empty?
if /instagram\.com\/p\/(?<post_id>[^\/?#]+)/ =~ params[:q]
# https://www.instagram.com/p/4KaPsKSjni/
response = Instagram.get("/p/#{post_id}/")
return [response.code, "This post does not exist or is a private post."] if response.code == 404
raise(InstagramError, response) if !response.success?
user = response.json["graphql"]["shortcode_media"]["owner"]
elsif params[:q].include?("instagram.com/explore/") || params[:q].start_with?("#")
return [404, "This app does not support hashtags. Sorry."]
elsif /instagram\.com\/(?<name>[^\/?#]+)/ =~ params[:q]
# https://www.instagram.com/infectedmushroom/
else
name = params[:q][/[^\/?#]+/]
end
if name
response = Instagram.get("/#{name}/")
if response.success?
user = response.json["graphql"]["user"]
else
# https://www.instagram.com/web/search/topsearch/?query=infected
response = Instagram.get("/web/search/topsearch/", query: { query: name })
raise(InstagramError, response) if !response.success?
user = response.json["users"][0]["user"]
end
end
if user
redirect Addressable::URI.new(path: "/instagram/#{user["id"] || user["pk"]}/#{user["username"]}", query_values: params.slice(:type)).normalize.to_s
else
return [404, "Can't find a user with that name. Sorry."]
end
end
get "/instagram/download" do
if /instagram\.com\/p\/(?<post_id>[^\/?#]+)/ =~ params[:url]
# https://www.instagram.com/p/4KaPsKSjni/
else
post_id = params[:url]
end
response = Instagram.get("/p/#{post_id}/")
return [404, "Please use a URL directly to a post."] if !response.success?
data = response.json["graphql"]["shortcode_media"]
if env["HTTP_ACCEPT"] == "application/json"
content_type :json
created_at = Time.at(data["taken_at_timestamp"])
caption = data["edge_media_to_caption"]["edges"][0]["node"]["text"] rescue post_id
if data.has_key?("edge_sidecar_to_children")
return data["edge_sidecar_to_children"]["edges"].map { |edge| edge["node"] }.map.with_index do |node, i|
url = node["video_url"] || node["display_url"]
{
url: url,
filename: "#{created_at.to_date} - #{data["owner"]["username"]} - #{caption} - #{i+1}#{url.url_ext}".to_filename
}
end.to_json
else
url = data["video_url"] || data["display_url"]
return [{
url: url,
filename: "#{created_at.to_date} - #{data["owner"]["username"]} - #{caption}#{url.url_ext}".to_filename,
}].to_json
end
end
if data.has_key?("edge_sidecar_to_children")
node = data["edge_sidecar_to_children"]["edges"][0]["node"]
url = node["video_url"] || node["display_url"]
else
url = data["video_url"] || data["display_url"]
end
redirect url
end
get %r{/instagram/(?<user_id>\d+)/(?<username>.+)} do |user_id, username|
@user_id = user_id
options = nil
tokens = nil
if params[:csrftoken] && params[:rhx_gis] && params[:sessionid]
# To subscribe to private feeds, follow these steps in bash:
# u=your_username
# p=your_password
# your_friends_username=your_friends_username
# your_friends_userid=$(curl -s "https://www.instagram.com/$your_friends_username/" | grep -oE '"id":"([0-9]+)"' | cut -d'"' -f4)
# ua="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:59.0) Gecko/20100101 Firefox/59.0"
# csrftoken=$(curl -sI https://www.instagram.com/ -A "$ua" | grep -i 'set-cookie: csrftoken=' | cut -d';' -f1 | cut -d= -f2)
# rhx_gis=$(curl -s https://www.instagram.com/ -A "$ua" -b "csrftoken=$csrftoken" | grep -oE '"rhx_gis":"([A-Za-z0-9]+)"' | cut -d'"' -f4)
# sessionid=$(curl -sv https://www.instagram.com/accounts/login/ajax/ -A "$ua" -H 'referer: https://www.instagram.com/accounts/login/' -b "csrftoken=$csrftoken" -H "x-csrftoken: $csrftoken" --data "username=$u&password=$p" 2>&1 | grep -i 'set-cookie: sessionid=' | cut -d';' -f1 | cut -d= -f2)
# echo "https://rssbox.herokuapp.com/instagram/$your_friends_userid/$your_friends_username?csrftoken=$csrftoken&rhx_gis=$rhx_gis&sessionid=$sessionid"
# Please host the app yourself if you decide to do this, otherwise you will leak the tokens to me and the privacy of your friends posts.
options = {
headers: {"Cookie" => "sessionid=#{CGI.escape(params[:sessionid])}"}
}
tokens = {
csrftoken: params[:csrftoken],
rhx_gis: params[:rhx_gis],
}
end
response = Instagram.get("/#{username}/", options, tokens)
return [response.code, "Instagram username does not exist. If the user changed their username, go here to find the new username: https://www.instagram.com/graphql/query/?query_id=17880160963012870&id=#{@user_id}&first=1"] if response.code == 404
return [401, "The sessionid expired!"] if params.has_key?(:sessionid) && response.code == 302
raise(InstagramError, response) if !response.success? || !response.json
@data = response.json["graphql"]["user"]
@user = @data["username"] rescue CGI.unescape(username)
type = %w[videos photos].pick(params[:type]) || "posts"
@data["edge_owner_to_timeline_media"]["edges"].map! do |post|
if post["node"]["__typename"] == "GraphSidecar"
post["nodes"] = Instagram.get_post(post["node"]["shortcode"], options, tokens)
else
post["nodes"] = [post["node"]]
end
post
end
if type == "videos"
@data["edge_owner_to_timeline_media"]["edges"].select! { |post| post["nodes"].any? { |node| node["is_video"] } }
elsif type == "photos"
@data["edge_owner_to_timeline_media"]["edges"].select! { |post| !post["nodes"].any? { |node| node["is_video"] } }
end
@title = @user
@title += "'s #{type}" if type != "posts"
@title += " on Instagram"
@data["edge_owner_to_timeline_media"]["edges"].select do |post|
post["node"]["edge_media_to_caption"]["edges"][0]
end.map do |post|
post["node"]["edge_media_to_caption"]["edges"][0]["node"]["text"].grep_urls
end.flatten.tap { |urls| URL.resolve(urls) }
erb :instagram_feed
end
get "/periscope" do
return [400, "Insufficient parameters"] if params[:q].empty?
if /(?:periscope|pscp)\.tv\/w\/(?<broadcast_id>[^\/?#]+)/ =~ params[:q]
# https://www.periscope.tv/w/1gqxvBmMZdexB
# https://www.pscp.tv/w/1gqxvBmMZdexB
elsif /(?:periscope|pscp)\.tv\/(?<username>[^\/?#]+)/ =~ params[:q]
# https://www.periscope.tv/jimmy_dore
# https://www.pscp.tv/jimmy_dore
else
username = params[:q]
end
url = if broadcast_id
"https://www.periscope.tv/w/#{broadcast_id}"
else
"https://www.periscope.tv/#{username}"
end
response = Periscope.get(url)
return [response.code, "That username does not exist."] if response.code == 404
return [response.code, "That broadcast has expired."] if response.code == 410
return [response.code, "Please enter a username."] if response.code/100 == 4
raise(PeriscopeError, response) if !response.success?
doc = Nokogiri::HTML(response.body)
data = doc.at("div#page-container")["data-store"]
json = JSON.parse(data)
username, user_id = json["UserCache"]["usernames"].to_a[0]
redirect Addressable::URI.new(path: "/periscope/#{user_id}/#{username}").normalize.to_s
end
get %r{/periscope/(?<id>[^/]+)/(?<username>.+)} do |id, username|
@id = id
@username = CGI.unescape(username)
response = Periscope.get_broadcasts(id)
raise(PeriscopeError, response) if !response.success?
@data = response.json["broadcasts"]
@user = if @data.length > 0
@data[0]["user_display_name"]
else
@username
end
erb :periscope_feed
end
get %r{/periscope_img/(?<broadcast_id>[^/]+)} do |id|
# The image url expires after 24 hours, so to avoid it being cached by the RSS client and then expire, we just proxy it on demand
# Interestingly enough, if a request is made before the token expires, it will be cached by their CDN and continue to work even after the token expires
# Can't just redirect either since it looks at the referer header, and most web based RSS clients will send that
# For whatever reason, the accessVideoPublic endpoint doesn't require a session_id
response = Periscope.get("/accessVideoPublic", query: { broadcast_id: id })
cache_control :public, :max_age => 31556926 # cache a long time
return [response.code, "Image not found."] if response.code == 404
raise(PeriscopeError, response) if !response.success?
if response.json["broadcast"]["image_url"].empty?
return [404, "Image not found."]
end
response = HTTP.get(response.json["broadcast"]["image_url"])
content_type response.headers["content-type"][0]
response.body
end
get "/soundcloud" do
return [400, "Insufficient parameters"] if params[:q].empty?
if /soundcloud\.com\/(?<username>[^\/?#]+)/ =~ params[:q]
# https://soundcloud.com/infectedmushroom/01-she-zorement?in=infectedmushroom/sets/converting-vegetarians-ii
else
username = params[:q]
end
response = Soundcloud.get("/resolve", query: { url: "https://soundcloud.com/#{username}" })
if response.code == 302
uri = Addressable::URI.parse(response.json["location"])
return [404, "URL does not resolve to a user."] if !uri.path.start_with?("/users/")
id = uri.path[/\d+/]
elsif response.code == 404 && username.numeric?
response = Soundcloud.get("/users/#{username}")
return [response.code, "Can't find a user with that id. Sorry."] if response.code == 404
raise(SoundcloudError, response) if !response.success?
id = response.json["id"]
elsif response.code == 404
return [response.code, "Can't find a user with that name. Sorry."]
else
raise(SoundcloudError, response)
end
response = Soundcloud.get("/users/#{id}")
raise(SoundcloudError, response) if !response.success?
data = response.json
redirect Addressable::URI.new(path: "/soundcloud/#{data["id"]}/#{data["permalink"]}").normalize.to_s
end
get "/soundcloud/download" do
url = params[:url]
url = "https://#{url}" if !url.start_with?("http:", "https:")
response = Soundcloud.get("/resolve", query: { url: url })
return [response.code, "URL does not resolve."] if response.code == 404
raise(SoundcloudError, response) if response.code != 302
uri = Addressable::URI.parse(response.json["location"])
return [404, "URL does not resolve to a track."] if !uri.path.start_with?("/tracks/")
response = Soundcloud.get("#{uri.path}/stream")
raise(SoundcloudError, response) if response.code != 302
media_url = response.json["location"]
if env["HTTP_ACCEPT"] == "application/json"
response = Soundcloud.get("#{uri.path}")
content_type :json
data = response.json
created_at = Time.parse(data["created_at"])
return {
url: media_url,
filename: "#{created_at.to_date} - #{data["title"]}.mp3".to_filename,
}.to_json
end
redirect media_url
end
get %r{/soundcloud/(?<id>\d+)/(?<username>.+)} do |id, username|
@id = id
response = Soundcloud.get("/users/#{id}/tracks")
return [404, "That user no longer exist."] if response.code == 500 && response.body == '{"error":"Match failed"}'
raise(SoundcloudError, response) if !response.success?
@data = response.json
@username = @data[0]["user"]["permalink"] rescue CGI.unescape(username)
@user = @data[0]["user"]["username"] rescue CGI.unescape(username)
@data.map do |track|
track["description"]
end.compact.map(&:grep_urls).flatten.tap { |urls| URL.resolve(urls) }
erb :soundcloud_feed
end
get "/mixcloud" do
return [400, "Insufficient parameters"] if params[:q].empty?
if /mixcloud\.com\/(?<username>[^\/?#]+)/ =~ params[:q]
# https://www.mixcloud.com/infected-live/infected-mushroom-liveedc-las-vegas-21-5-2014/
else
username = params[:q]
end
response = Mixcloud.get("/#{username}/")
return [response.code, "Can't find a user with that name. Sorry."] if response.code == 404
raise(MixcloudError, response) if !response.success?
data = response.json
redirect Addressable::URI.new(path: "/mixcloud/#{data["username"]}/#{data["name"]}").normalize.to_s
end
get %r{/mixcloud/(?<username>[^/]+)/(?<user>.+)} do |username, user|
response = Mixcloud.get("/#{username}/cloudcasts/")
return [response.code, "That username no longer exist."] if response.code == 404
raise(MixcloudError, response) if !response.success?
@data = response.json["data"]
@username = @data[0]["user"]["username"] rescue CGI.unescape(username)
@user = @data[0]["user"]["name"] rescue CGI.unescape(user)
erb :mixcloud_feed
end
get "/twitch" do
return [400, "Insufficient parameters"] if params[:q].empty?
if /twitch\.tv\/directory\/game\/(?<game_name>[^\/?#]+)/ =~ params[:q]
# https://www.twitch.tv/directory/game/Perfect%20Dark
game_name = Addressable::URI.unescape(game_name)
elsif /twitch\.tv\/directory/ =~ params[:q]
# https://www.twitch.tv/directory/all/tags/7cefbf30-4c3e-4aa7-99cd-70aabb662f27
return [404, "Unsupported url. Sorry."]
elsif /twitch\.tv\/videos\/(?<vod_id>\d+)/ =~ params[:q]
# https://www.twitch.tv/videos/25133028
elsif /twitch\.tv\/(?<username>[^\/?#]+)/ =~ params[:q]
# https://www.twitch.tv/majinphil
# https://www.twitch.tv/gsl/video/25133028 (legacy url)
else
username = params[:q]
end
if game_name
response = Twitch.get("/games", query: { name: game_name })
raise(TwitchError, response) if !response.success?
data = response.json["data"][0]
return [404, "Can't find a game with that name."] if data.nil?
redirect Addressable::URI.new(path: "/twitch/directory/game/#{data["id"]}/#{game_name}", query_values: params.slice(:type)).normalize.to_s
elsif vod_id
response = Twitch.get("/videos", query: { id: vod_id })
return [response.code, "Video does not exist."] if response.code == 404
raise(TwitchError, response) if !response.success?
data = response.json["data"][0]
redirect Addressable::URI.new(path: "/twitch/#{data["user_id"]}/#{data["user_name"]}", query_values: params.slice(:type)).normalize.to_s
else
response = Twitch.get("/users", query: { login: username })
return [response.code, "The username contains invalid characters."] if response.code == 400
raise(TwitchError, response) if !response.success?
data = response.json["data"][0]
return [404, "Can't find a user with that name. Sorry."] if data.nil?
redirect Addressable::URI.new(path: "/twitch/#{data["id"]}/#{data["display_name"]}", query_values: params.slice(:type)).normalize.to_s
end
end
get "/twitch/download" do
return [400, "Insufficient parameters"] if params[:url].empty?
if /twitch\.tv\/[^\/]+\/clip\/(?<clip_slug>[^?&#]+)/ =~ params[:url] || /clips\.twitch\.tv\/(?:embed\?clip=)?(?<clip_slug>[^?&#]+)/ =~ params[:url]
# https://www.twitch.tv/majinphil/clip/TenaciousCreativePieNotATK
# https://clips.twitch.tv/DignifiedThirstyDogYee
# https://clips.twitch.tv/majinphil/UnusualClamRaccAttack (legacy url, redirects to the one above)
# https://clips.twitch.tv/embed?clip=DignifiedThirstyDogYee&autoplay=false
elsif /twitch\.tv\/(?:[^\/]+\/)?(?:v|videos?)\/(?<vod_id>\d+)/ =~ params[:url] || /(?:^|v)(?<vod_id>\d+)/ =~ params[:url]
# https://www.twitch.tv/videos/25133028
# https://www.twitch.tv/gsl/video/25133028 (legacy url)
# https://www.twitch.tv/gamesdonequick/video/34377308?t=53m40s
# https://www.twitch.tv/gamesdonequick/v/34377308?t=53m40s (legacy url)
# https://player.twitch.tv/?video=v103620362 ("v" is optional)
elsif /twitch\.tv\/(?<channel_name>[^\/?#]+)/ =~ params[:url]
# https://www.twitch.tv/trevperson
else
channel_name = params[:url]
end
if clip_slug
response = HTTP.get("https://clips.twitch.tv/api/v2/clips/#{clip_slug}/status")
return [response.code, "Clip does not seem to exist."] if response.code == 404
raise(TwitchError, response) if !response.success?
url = response.json["quality_options"][0]["source"]
return [404, "Can't find clip."] if url.nil?
redirect url
return
elsif vod_id
response = Twitch.get("/videos", query: { id: vod_id })
return [response.code, "Video does not exist."] if response.code == 404
raise(TwitchError, response) if !response.success?
data = response.json["data"][0]
response = TwitchToken.get("/vods/#{vod_id}/access_token")
raise(TwitchError, response) if !response.success?
vod_data = response.json
url = "http://usher.twitch.tv" + Addressable::URI.new(path: "/vod/#{vod_id}", query: "nauthsig=#{vod_data["sig"]}&nauth=#{vod_data["token"]}").normalize.to_s
fn = "#{data["created_at"].to_date} - #{data["user_name"]} - #{data["title"]}.mp4".to_filename
elsif channel_name
response = TwitchToken.get("/channels/#{channel_name}/access_token")
return [response.code, "Channel does not seem to exist."] if response.code == 404
raise(TwitchError, response) if !response.success?
data = response.json
token_data = JSON.parse(data["token"])
url = "http://usher.ttvnw.net" + Addressable::URI.new(path: "/api/channel/hls/#{token_data["channel"]}.m3u8", query: "token=#{data["token"]}&sig=#{data["sig"]}&allow_source=true&allow_spectre=true").normalize.to_s
fn = "#{Time.now.to_date} - #{token_data["channel"]} live.mp4".to_filename
end
"ffmpeg -i '#{url}' -acodec copy -vcodec copy -absf aac_adtstoasc '#{fn}'"
end
get "/twitch/watch" do
return [400, "Insufficient parameters"] if params[:url].empty?
if /twitch\.tv\/[^\/]+\/clip\/(?<clip_slug>[^?&#]+)/ =~ params[:url] || /clips\.twitch\.tv\/(?:embed\?clip=)?(?<clip_slug>[^?&#]+)/ =~ params[:url]
# https://www.twitch.tv/majinphil/clip/TenaciousCreativePieNotATK
# https://clips.twitch.tv/DignifiedThirstyDogYee
# https://clips.twitch.tv/majinphil/UnusualClamRaccAttack (legacy url, redirects to the one above)
# https://clips.twitch.tv/embed?clip=DignifiedThirstyDogYee&autoplay=false
elsif /twitch\.tv\/(?:[^\/]+\/)?(?:v|videos?)\/(?<vod_id>\d+)/ =~ params[:url] || /(?:^|v)(?<vod_id>\d+)/ =~ params[:url]
# https://www.twitch.tv/gsl/video/25133028
# https://www.twitch.tv/gamesdonequick/video/34377308?t=53m40s
# https://www.twitch.tv/videos/25133028 (legacy url)
# https://www.twitch.tv/gamesdonequick/v/34377308?t=53m40s (legacy url)
# https://player.twitch.tv/?video=v103620362
elsif /twitch\.tv\/(?<channel_name>[^\/?#]+)/ =~ params[:url]
# https://www.twitch.tv/trevperson
else
channel_name = params[:url]
end
if clip_slug
response = HTTP.get("https://clips.twitch.tv/api/v2/clips/#{clip_slug}/status")
return [response.code, "Clip does not seem to exist."] if response.code == 404
raise(TwitchError, response) if !response.success?
streams = response.json["quality_options"].map { |s| s["source"] }
return [404, "Can't find clip."] if streams.empty?
elsif vod_id
response = TwitchToken.get("/vods/#{vod_id}/access_token")
return [response.code, "Video does not exist."] if response.code == 404
raise(TwitchError, response) if !response.success?
data = response.json
playlist_url = "http://usher.twitch.tv" + Addressable::URI.new(path: "/vod/#{vod_id}", query: "nauthsig=#{data["sig"]}&nauth=#{data["token"]}").normalize.to_s
response = HTTP.get(playlist_url)
streams = response.body.split("\n").reject { |line| line[0] == "#" } + [playlist_url]
elsif channel_name
response = TwitchToken.get("/channels/#{channel_name}/access_token")
return [response.code, "Channel does not seem to exist."] if response.code == 404
raise(TwitchError, response) if !response.success?
data = response.json
token_data = JSON.parse(data["token"])
playlist_url = "http://usher.ttvnw.net" + Addressable::URI.new(path: "/api/channel/hls/#{token_data["channel"]}.m3u8", query: "token=#{data["token"]}&sig=#{data["sig"]}&allow_source=true&allow_spectre=true").normalize.to_s
response = HTTP.get(playlist_url)
return [response.code, "Channel does not seem to be online."] if response.code == 404
raise(TwitchError, response) if !response.success?
streams = response.body.split("\n").reject { |line| line.start_with?("#") } + [playlist_url]
end
if request.user_agent["Mozilla/"]
redirect "vlc://#{streams[0]}" if params.has_key?("open")
"Open this url in VLC and it will automatically open the top stream.\nTo open vlc:// links, see: https://github.com/stefansundin/vlc-protocol\n\n#{streams.join("\n")}"
else
redirect streams[0]
end
end
get %r{/twitch/directory/game/(?<id>\d+)/(?<game_name>.+)} do |id, game_name|
@id = id
@type = "game"
type = %w[all upload archive highlight].pick(params[:type]) || "all"
response = Twitch.get("/videos", query: { game_id: id, type: type })
raise(TwitchError, response) if !response.success?
@data = response.json["data"]
@alternate_url = Addressable::URI.parse("https://www.twitch.tv/directory/game/#{game_name}").normalize.to_s
# live broadcasts show up here too, and the simplest way of filtering them out seems to be to see if thumbnail_url is populated or not
@data.reject! { |v| v["thumbnail_url"].empty? }
@title = game_name
@title += " highlights" if type == "highlight"
@title += " on Twitch"
@data.map do |video|
video["description"]
end.compact.map(&:grep_urls).flatten.tap { |urls| URL.resolve(urls) }
erb :twitch_feed
end
get %r{/twitch/(?<id>\d+)/(?<user>.+)} do |id, user|
@id = id
@type = "user"
type = %w[all upload archive highlight].pick(params[:type]) || "all"
response = Twitch.get("/videos", query: { user_id: id, type: type })
raise(TwitchError, response) if !response.success?
@data = response.json["data"]
user = @data[0]["user_name"] || CGI.unescape(user)
@alternate_url = Addressable::URI.parse("https://www.twitch.tv/#{user.downcase}").normalize.to_s
# live broadcasts show up here too, and the simplest way of filtering them out seems to be to see if thumbnail_url is populated or not
@data.reject! { |v| v["thumbnail_url"].empty? }
@title = user
@title += "'s highlights" if type == "highlight"
@title += " on Twitch"
@data.map do |video|
video["description"]
end.compact.map(&:grep_urls).flatten.tap { |urls| URL.resolve(urls) }
erb :twitch_feed
end
get "/speedrun" do
return [400, "Insufficient parameters"] if params[:q].empty?
if /speedrun\.com\/run\/(?<run_id>[^\/?#]+)/ =~ params[:q]
# https://www.speedrun.com/run/1zx0qkez
response = Speedrun.get("/runs/#{run_id}")
raise(SpeedrunError, response) if !response.success?
game = response.json["data"]["game"]
elsif /speedrun\.com\/(?<game>[^\/?#]+)/ =~ params[:q]
# https://www.speedrun.com/alttp#No_Major_Glitches
else
game = params[:q]
end