Skip to content

Commit 575b039

Browse files
authored
Merge pull request #2922 from SamantazFox/download-widget-fix
Download widget fix
2 parents 7a32269 + 004e371 commit 575b039

File tree

6 files changed

+191
-57
lines changed

6 files changed

+191
-57
lines changed

src/invidious.cr

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ require "protodec/utils"
2929
require "./invidious/database/*"
3030
require "./invidious/helpers/*"
3131
require "./invidious/yt_backend/*"
32+
require "./invidious/frontend/*"
33+
3234
require "./invidious/*"
3335
require "./invidious/channels/*"
3436
require "./invidious/user/*"
@@ -234,6 +236,7 @@ before_all do |env|
234236
"/api/manifest/",
235237
"/videoplayback",
236238
"/latest_version",
239+
"/download",
237240
}.any? { |r| env.request.resource.starts_with? r }
238241

239242
if env.request.cookies.has_key? "SID"
@@ -349,6 +352,8 @@ end
349352
Invidious::Routing.get "/e/:id", Invidious::Routes::Watch, :redirect
350353
Invidious::Routing.get "/redirect", Invidious::Routes::Misc, :cross_instance_redirect
351354

355+
Invidious::Routing.post "/download", Invidious::Routes::Watch, :download
356+
352357
Invidious::Routing.get "/embed/", Invidious::Routes::Embed, :redirect
353358
Invidious::Routing.get "/embed/:id", Invidious::Routes::Embed, :show
354359

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
module Invidious::Frontend::WatchPage
2+
extend self
3+
4+
# A handy structure to pass many elements at
5+
# once to the download widget function
6+
struct VideoAssets
7+
getter full_videos : Array(Hash(String, JSON::Any))
8+
getter video_streams : Array(Hash(String, JSON::Any))
9+
getter audio_streams : Array(Hash(String, JSON::Any))
10+
getter captions : Array(Caption)
11+
12+
def initialize(
13+
@full_videos,
14+
@video_streams,
15+
@audio_streams,
16+
@captions
17+
)
18+
end
19+
end
20+
21+
def download_widget(locale : String, video : Video, video_assets : VideoAssets) : String
22+
if CONFIG.disabled?("downloads")
23+
return "<p id=\"download\">#{translate(locale, "Download is disabled.")}</p>"
24+
end
25+
26+
return String.build(4000) do |str|
27+
str << "<form"
28+
str << " class=\"pure-form pure-form-stacked\""
29+
str << " action='/download'"
30+
str << " method='post'"
31+
str << " rel='noopener'"
32+
str << " target='_blank'>"
33+
str << '\n'
34+
35+
# Hidden inputs for video id and title
36+
str << "<input type='hidden' name='id' value='" << video.id << "'/>\n"
37+
str << "<input type='hidden' name='title' value='" << HTML.escape(video.title) << "'/>\n"
38+
39+
str << "\t<div class=\"pure-control-group\">\n"
40+
41+
str << "\t\t<label for='download_widget'>"
42+
str << translate(locale, "Download as: ")
43+
str << "</label>\n"
44+
45+
# TODO: remove inline style
46+
str << "\t\t<select style=\"width:100%\" name='download_widget' id='download_widget'>\n"
47+
48+
# Non-DASH videos (audio+video)
49+
50+
video_assets.full_videos.each do |option|
51+
mimetype = option["mimeType"].as_s.split(";")[0]
52+
53+
height = itag_to_metadata?(option["itag"]).try &.["height"]?
54+
55+
value = {"itag": option["itag"], "ext": mimetype.split("/")[1]}.to_json
56+
57+
str << "\t\t\t<option value='" << value << "'>"
58+
str << (height || "~240") << "p - " << mimetype
59+
str << "</option>\n"
60+
end
61+
62+
# DASH video streams
63+
64+
video_assets.video_streams.each do |option|
65+
mimetype = option["mimeType"].as_s.split(";")[0]
66+
67+
value = {"itag": option["itag"], "ext": mimetype.split("/")[1]}.to_json
68+
69+
str << "\t\t\t<option value='" << value << "'>"
70+
str << option["qualityLabel"] << " - " << mimetype << " @ " << option["fps"] << "fps - video only"
71+
str << "</option>\n"
72+
end
73+
74+
# DASH audio streams
75+
76+
video_assets.audio_streams.each do |option|
77+
mimetype = option["mimeType"].as_s.split(";")[0]
78+
79+
value = {"itag": option["itag"], "ext": mimetype.split("/")[1]}.to_json
80+
81+
str << "\t\t\t<option value='" << value << "'>"
82+
str << mimetype << " @ " << (option["bitrate"]?.try &.as_i./ 1000) << "k - audio only"
83+
str << "</option>\n"
84+
end
85+
86+
# Subtitles (a.k.a "closed captions")
87+
88+
video_assets.captions.each do |caption|
89+
value = {"label": caption.name, "ext": "#{caption.language_code}.vtt"}.to_json
90+
91+
str << "\t\t\t<option value='" << value << "'>"
92+
str << translate(locale, "download_subtitles", translate(locale, caption.name))
93+
str << "</option>\n"
94+
end
95+
96+
# End of form
97+
98+
str << "\t\t</select>\n"
99+
str << "\t</div>\n"
100+
101+
str << "\t<button type=\"submit\" class=\"pure-button pure-button-primary\">\n"
102+
str << "\t\t<b>" << translate(locale, "Download") << "</b>\n"
103+
str << "\t</button>\n"
104+
105+
str << "</form>\n"
106+
end
107+
end
108+
end

src/invidious/routes/api/v1/videos.cr

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,11 @@ module Invidious::Routes::API::V1::Videos
2323
env.response.content_type = "application/json"
2424

2525
id = env.params.url["id"]
26-
region = env.params.query["region"]?
26+
region = env.params.query["region"]? || env.params.body["region"]?
27+
28+
if id.nil? || id.size != 11 || !id.matches?(/^[\w-]+$/)
29+
return error_json(400, "Invalid video ID")
30+
end
2731

2832
# See https://github.com/ytdl-org/youtube-dl/blob/6ab30ff50bf6bd0585927cb73c7421bef184f87a/youtube_dl/extractor/youtube.py#L1354
2933
# It is possible to use `/api/timedtext?type=list&v=#{id}` and

src/invidious/routes/video_playback.cr

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,9 @@ module Invidious::Routes::VideoPlayback
164164

165165
if title = query_params["title"]?
166166
# https://blog.fastmail.com/2011/06/24/download-non-english-filenames/
167-
env.response.headers["Content-Disposition"] = "attachment; filename=\"#{URI.encode_www_form(title)}\"; filename*=UTF-8''#{URI.encode_www_form(title)}"
167+
filename = URI.encode_www_form(title, space_to_plus: false)
168+
header = "attachment; filename=\"#{filename}\"; filename*=UTF-8''#{filename}"
169+
env.response.headers["Content-Disposition"] = header
168170
end
169171

170172
if !resp.headers.includes_word?("Transfer-Encoding", "chunked")
@@ -242,31 +244,25 @@ module Invidious::Routes::VideoPlayback
242244
# YouTube /videoplayback links expire after 6 hours,
243245
# so we have a mechanism here to redirect to the latest version
244246
def self.latest_version(env)
245-
if env.params.query["download_widget"]?
246-
download_widget = JSON.parse(env.params.query["download_widget"])
247+
id = env.params.query["id"]?
248+
itag = env.params.query["itag"]?.try &.to_i?
247249

248-
id = download_widget["id"].as_s
249-
title = URI.decode_www_form(download_widget["title"].as_s)
250-
251-
if label = download_widget["label"]?
252-
return env.redirect "/api/v1/captions/#{id}?label=#{label}&title=#{title}"
253-
else
254-
itag = download_widget["itag"].as_s.to_i
255-
local = "true"
256-
end
250+
# Sanity checks
251+
if id.nil? || id.size != 11 || !id.matches?(/^[\w-]+$/)
252+
return error_template(400, "Invalid video ID")
257253
end
258254

259-
id ||= env.params.query["id"]?
260-
itag ||= env.params.query["itag"]?.try &.to_i
255+
if itag.nil? || itag <= 0 || itag >= 1000
256+
return error_template(400, "Invalid itag")
257+
end
261258

262259
region = env.params.query["region"]?
260+
local = (env.params.query["local"]? == "true")
263261

264-
local ||= env.params.query["local"]?
265-
local ||= "false"
266-
local = local == "true"
262+
title = env.params.query["title"]?
267263

268-
if !id || !itag
269-
haltf env, status_code: 400, response: "TESTING"
264+
if title && CONFIG.disabled?("downloads")
265+
return error_template(403, "Administrator has disabled this endpoint.")
270266
end
271267

272268
video = get_video(id, region: region)
@@ -278,8 +274,10 @@ module Invidious::Routes::VideoPlayback
278274
haltf env, status_code: 404
279275
end
280276

281-
url = URI.parse(url).request_target.not_nil! if local
282-
url = "#{url}&title=#{title}" if title
277+
if local
278+
url = URI.parse(url).request_target.not_nil!
279+
url += "&title=#{URI.encode_www_form(title, space_to_plus: false)}" if title
280+
end
283281

284282
return env.redirect url
285283
end

src/invidious/routes/watch.cr

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,14 @@ module Invidious::Routes::Watch
189189
return env.redirect url
190190
end
191191

192+
# Structure used for the download widget
193+
video_assets = Invidious::Frontend::WatchPage::VideoAssets.new(
194+
full_videos: fmt_stream,
195+
video_streams: video_streams,
196+
audio_streams: audio_streams,
197+
captions: video.captions
198+
)
199+
192200
templated "watch"
193201
end
194202

@@ -281,4 +289,49 @@ module Invidious::Routes::Watch
281289
return error_template(404, "The requested clip doesn't exist")
282290
end
283291
end
292+
293+
def self.download(env)
294+
if CONFIG.disabled?("downloads")
295+
return error_template(403, "Administrator has disabled this endpoint.")
296+
end
297+
298+
title = env.params.body["title"]? || ""
299+
video_id = env.params.body["id"]? || ""
300+
selection = env.params.body["download_widget"]?
301+
302+
if title.empty? || video_id.empty? || selection.nil?
303+
return error_template(400, "Missing form data")
304+
end
305+
306+
download_widget = JSON.parse(selection)
307+
308+
extension = download_widget["ext"].as_s
309+
filename = "#{video_id}-#{title}.#{extension}"
310+
311+
# Pass form parameters as URL parameters for the handlers of both
312+
# /latest_version and /api/v1/captions. This avoids an un-necessary
313+
# redirect and duplicated (and hazardous) sanity checks.
314+
env.params.query["id"] = video_id
315+
env.params.query["title"] = filename
316+
317+
# Delete the useless ones
318+
env.params.body.delete("id")
319+
env.params.body.delete("title")
320+
env.params.body.delete("download_widget")
321+
322+
if label = download_widget["label"]?
323+
# URL params specific to /api/v1/captions/:id
324+
env.params.query["label"] = URI.encode_www_form(label.as_s, space_to_plus: false)
325+
326+
return Invidious::Routes::API::V1::Videos.captions(env)
327+
elsif itag = download_widget["itag"]?.try &.as_i
328+
# URL params specific to /latest_version
329+
env.params.query["itag"] = itag.to_s
330+
env.params.query["local"] = "true"
331+
332+
return Invidious::Routes::VideoPlayback.latest_version(env)
333+
else
334+
return error_template(400, "Invalid label or itag")
335+
end
336+
end
284337
end

src/invidious/views/watch.ecr

Lines changed: 1 addition & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -168,41 +168,7 @@ we're going to need to do it here in order to allow for translations.
168168
<% end %>
169169
<% end %>
170170
171-
<% if CONFIG.dmca_content.includes?(video.id) || CONFIG.disabled?("downloads") %>
172-
<p id="download"><%= translate(locale, "Download is disabled.") %></p>
173-
<% else %>
174-
<form class="pure-form pure-form-stacked" action="/latest_version" method="get" rel="noopener" target="_blank">
175-
<div class="pure-control-group">
176-
<label for="download_widget"><%= translate(locale, "Download as: ") %></label>
177-
<select style="width:100%" name="download_widget" id="download_widget">
178-
<% fmt_stream.each do |option| %>
179-
<option value='{"id":"<%= video.id %>","itag":"<%= option["itag"] %>","title":"<%= URI.encode_www_form(video.title) %>-<%= video.id %>.<%= option["mimeType"].as_s.split(";")[0].split("/")[1] %>"}'>
180-
<%= itag_to_metadata?(option["itag"]).try &.["height"]? || "~240" %>p - <%= option["mimeType"].as_s.split(";")[0] %>
181-
</option>
182-
<% end %>
183-
<% video_streams.each do |option| %>
184-
<option value='{"id":"<%= video.id %>","itag":"<%= option["itag"] %>","title":"<%= URI.encode_www_form(video.title) %>-<%= video.id %>.<%= option["mimeType"].as_s.split(";")[0].split("/")[1] %>"}'>
185-
<%= option["qualityLabel"] %> - <%= option["mimeType"].as_s.split(";")[0] %> @ <%= option["fps"] %>fps - video only
186-
</option>
187-
<% end %>
188-
<% audio_streams.each do |option| %>
189-
<option value='{"id":"<%= video.id %>","itag":"<%= option["itag"] %>","title":"<%= URI.encode_www_form(video.title) %>-<%= video.id %>.<%= option["mimeType"].as_s.split(";")[0].split("/")[1] %>"}'>
190-
<%= option["mimeType"].as_s.split(";")[0] %> @ <%= option["bitrate"]?.try &.as_i./ 1000 %>k - audio only
191-
</option>
192-
<% end %>
193-
<% captions.each do |caption| %>
194-
<option value='{"id":"<%= video.id %>","label":"<%= caption.name %>","title":"<%= URI.encode_www_form(video.title) %>-<%= video.id %>.<%= caption.language_code %>.vtt"}'>
195-
<%= translate(locale, "download_subtitles", translate(locale, caption.name)) %>
196-
</option>
197-
<% end %>
198-
</select>
199-
</div>
200-
201-
<button type="submit" class="pure-button pure-button-primary">
202-
<b><%= translate(locale, "Download") %></b>
203-
</button>
204-
</form>
205-
<% end %>
171+
<%= Invidious::Frontend::WatchPage.download_widget(locale, video, video_assets) %>
206172
207173
<p id="views"><i class="icon ion-ios-eye"></i> <%= number_with_separator(video.views) %></p>
208174
<p id="likes"><i class="icon ion-ios-thumbs-up"></i> <%= number_with_separator(video.likes) %></p>

0 commit comments

Comments
 (0)