diff --git a/.ameba.yml b/.ameba.yml
index 36d7c48fa..3d0b25c0f 100644
--- a/.ameba.yml
+++ b/.ameba.yml
@@ -2,23 +2,15 @@
# Lint
#
+Lint/UnusedArgument:
+ Excluded:
+ - "**/*.ecr"
+
# Exclude assigns for ECR files
Lint/UselessAssign:
Excluded:
- - src/invidious.cr
- - src/invidious/helpers/errors.cr
- - src/invidious/routes/**/*.cr
-
-# Ignore false negative (if !db.query_one?...)
-Lint/UnreachableCode:
- Excluded:
- - src/invidious/database/base.cr
-
-# Ignore shadowed variable `key` (it works for now, and that's
-# a sensitive part of the code)
-Lint/ShadowingOuterLocalVar:
- Excluded:
- - src/invidious/helpers/tokens.cr
+ - "**/*.ecr"
+ - src/invidious/routes/**/*.cr
Lint/NotNil:
Enabled: false
@@ -27,41 +19,17 @@ Lint/SpecFilename:
Excluded:
- spec/parsers_helper.cr
-
#
# Style
#
-Style/RedundantBegin:
- Enabled: false
-
-Style/RedundantReturn:
- Enabled: false
-
-Style/RedundantNext:
- Enabled: false
-
-Style/ParenthesesAroundCondition:
- Enabled: false
-
# This requires a rewrite of most data structs (and their usage) in Invidious.
Naming/QueryBoolMethods:
Enabled: false
-Naming/AccessorMethodName:
- Enabled: false
-
Naming/BlockParameterName:
Enabled: false
-# Hides TODO comment warnings.
-#
-# Call `bin/ameba --only Documentation/DocumentationAdmonition` to
-# list them
-Documentation/DocumentationAdmonition:
- Enabled: false
-
-
#
# Metrics
#
diff --git a/.github/workflows/ameba.yml b/.github/workflows/ameba.yml
new file mode 100644
index 000000000..e321d6a96
--- /dev/null
+++ b/.github/workflows/ameba.yml
@@ -0,0 +1,19 @@
+name: Ameba
+
+on:
+ push:
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ lint:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Download source
+ uses: actions/checkout@v6
+
+ - name: Run Ameba Linter
+ uses: crystal-ameba/github-action@master
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 847342f77..21f9d0b44 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -26,7 +26,6 @@ on:
jobs:
build:
-
runs-on: ubuntu-latest
name: "build - crystal: ${{ matrix.crystal }}, stable: ${{ matrix.stable }}"
@@ -122,7 +121,6 @@ jobs:
run: docker compose logs
lint:
-
runs-on: ubuntu-latest
continue-on-error: true
@@ -159,6 +157,3 @@ jobs:
git diff
exit 1
fi
-
- - name: Run Ameba linter
- run: bin/ameba
diff --git a/shard.lock b/shard.lock
index 1265eda67..12f36d309 100644
--- a/shard.lock
+++ b/shard.lock
@@ -2,7 +2,7 @@ version: 2.0
shards:
ameba:
git: https://github.com/crystal-ameba/ameba.git
- version: 1.6.1
+ version: 1.7.0-dev+git.commit.9dbeb92f89d7a668940029bd7b935bef370f26c1
athena-negotiation:
git: https://github.com/athena-framework/negotiation.git
diff --git a/shard.yml b/shard.yml
index bc6c4bf48..494c64081 100644
--- a/shard.yml
+++ b/shard.yml
@@ -6,7 +6,7 @@ authors:
- Contributors!
description: |
- Invidious is an alternative front-end to YouTube
+ Invidious is an alternative front-end to YouTube
dependencies:
pg:
@@ -34,7 +34,7 @@ development_dependencies:
version: ~> 0.10.4
ameba:
github: crystal-ameba/ameba
- version: ~> 1.6.1
+ branch: master
crystal: ">= 1.10.0, < 2.0.0"
diff --git a/spec/http_server/handlers/static_assets_handler_spec.cr b/spec/http_server/handlers/static_assets_handler_spec.cr
index 76dc7be77..8619380eb 100644
--- a/spec/http_server/handlers/static_assets_handler_spec.cr
+++ b/spec/http_server/handlers/static_assets_handler_spec.cr
@@ -14,7 +14,7 @@ require "spectator"
require "../../../src/invidious/http_server/static_assets_handler.cr"
private def get_static_assets_handler
- return Invidious::HttpServer::StaticAssetsHandler.new "spec/http_server/handlers/static_assets_handler", directory_listing: false
+ Invidious::HttpServer::StaticAssetsHandler.new "spec/http_server/handlers/static_assets_handler", directory_listing: false
end
# Slightly modified version of `handle` function from
@@ -59,7 +59,7 @@ end
# Get relative file path to a file within the static_assets_handler folder
macro get_file_path(basename)
- "spec/http_server/handlers/static_assets_handler/#{ {{basename}} }"
+ "spec/http_server/handlers/static_assets_handler/#{ {{ basename }} }"
end
Spectator.describe StaticAssetsHandler do
@@ -125,7 +125,7 @@ Spectator.describe StaticAssetsHandler do
gzip.gets_to_end
end
- return expect(decompressed)
+ expect(decompressed)
end
it "For full file requests" do
diff --git a/spec/invidious/user/imports_spec.cr b/spec/invidious/user/imports_spec.cr
index 762ce0d89..2dffa1a9f 100644
--- a/spec/invidious/user/imports_spec.cr
+++ b/spec/invidious/user/imports_spec.cr
@@ -7,22 +7,22 @@ Spectator.configure do |config|
end
def csv_sample
- return <<-CSV
- Kanal-ID,Kanal-URL,Kanaltitel
- UC0hHW5Y08ggq-9kbrGgWj0A,http://www.youtube.com/channel/UC0hHW5Y08ggq-9kbrGgWj0A,Matias Marolla
- UC0vBXGSyV14uvJ4hECDOl0Q,http://www.youtube.com/channel/UC0vBXGSyV14uvJ4hECDOl0Q,Techquickie
- UC1sELGmy5jp5fQUugmuYlXQ,http://www.youtube.com/channel/UC1sELGmy5jp5fQUugmuYlXQ,Minecraft
- UC9kFnwdCRrX7oTjqKd6-tiQ,http://www.youtube.com/channel/UC9kFnwdCRrX7oTjqKd6-tiQ,LUMOX - Topic
- UCBa659QWEk1AI4Tg--mrJ2A,http://www.youtube.com/channel/UCBa659QWEk1AI4Tg--mrJ2A,Tom Scott
- UCGu6_XQ64rXPR6nuitMQE_A,http://www.youtube.com/channel/UCGu6_XQ64rXPR6nuitMQE_A,Callcenter Fun
- UCGwu0nbY2wSkW8N-cghnLpA,http://www.youtube.com/channel/UCGwu0nbY2wSkW8N-cghnLpA,Jaiden Animations
- UCQ0OvZ54pCFZwsKxbltg_tg,http://www.youtube.com/channel/UCQ0OvZ54pCFZwsKxbltg_tg,Methos
- UCRE6itj4Jte4manQEu3Y7OA,http://www.youtube.com/channel/UCRE6itj4Jte4manQEu3Y7OA,Chipflake
- UCRLc6zsv_d0OEBO8OOkz-DA,http://www.youtube.com/channel/UCRLc6zsv_d0OEBO8OOkz-DA,Kegy
- UCSl5Uxu2LyaoAoMMGp6oTJA,http://www.youtube.com/channel/UCSl5Uxu2LyaoAoMMGp6oTJA,Atomic Shrimp
- UCXuqSBlHAE6Xw-yeJA0Tunw,http://www.youtube.com/channel/UCXuqSBlHAE6Xw-yeJA0Tunw,Linus Tech Tips
- UCZ5XnGb-3t7jCkXdawN2tkA,http://www.youtube.com/channel/UCZ5XnGb-3t7jCkXdawN2tkA,Discord
- CSV
+ <<-CSV
+ Kanal-ID,Kanal-URL,Kanaltitel
+ UC0hHW5Y08ggq-9kbrGgWj0A,http://www.youtube.com/channel/UC0hHW5Y08ggq-9kbrGgWj0A,Matias Marolla
+ UC0vBXGSyV14uvJ4hECDOl0Q,http://www.youtube.com/channel/UC0vBXGSyV14uvJ4hECDOl0Q,Techquickie
+ UC1sELGmy5jp5fQUugmuYlXQ,http://www.youtube.com/channel/UC1sELGmy5jp5fQUugmuYlXQ,Minecraft
+ UC9kFnwdCRrX7oTjqKd6-tiQ,http://www.youtube.com/channel/UC9kFnwdCRrX7oTjqKd6-tiQ,LUMOX - Topic
+ UCBa659QWEk1AI4Tg--mrJ2A,http://www.youtube.com/channel/UCBa659QWEk1AI4Tg--mrJ2A,Tom Scott
+ UCGu6_XQ64rXPR6nuitMQE_A,http://www.youtube.com/channel/UCGu6_XQ64rXPR6nuitMQE_A,Callcenter Fun
+ UCGwu0nbY2wSkW8N-cghnLpA,http://www.youtube.com/channel/UCGwu0nbY2wSkW8N-cghnLpA,Jaiden Animations
+ UCQ0OvZ54pCFZwsKxbltg_tg,http://www.youtube.com/channel/UCQ0OvZ54pCFZwsKxbltg_tg,Methos
+ UCRE6itj4Jte4manQEu3Y7OA,http://www.youtube.com/channel/UCRE6itj4Jte4manQEu3Y7OA,Chipflake
+ UCRLc6zsv_d0OEBO8OOkz-DA,http://www.youtube.com/channel/UCRLc6zsv_d0OEBO8OOkz-DA,Kegy
+ UCSl5Uxu2LyaoAoMMGp6oTJA,http://www.youtube.com/channel/UCSl5Uxu2LyaoAoMMGp6oTJA,Atomic Shrimp
+ UCXuqSBlHAE6Xw-yeJA0Tunw,http://www.youtube.com/channel/UCXuqSBlHAE6Xw-yeJA0Tunw,Linus Tech Tips
+ UCZ5XnGb-3t7jCkXdawN2tkA,http://www.youtube.com/channel/UCZ5XnGb-3t7jCkXdawN2tkA,Discord
+ CSV
end
Spectator.describe Invidious::User::Import do
diff --git a/spec/parsers_helper.cr b/spec/parsers_helper.cr
index 6589acad8..79e256d2d 100644
--- a/spec/parsers_helper.cr
+++ b/spec/parsers_helper.cr
@@ -26,7 +26,7 @@ def load_mock(file) : Hash(String, JSON::Any)
file = File.join(__DIR__, "..", "mocks", file + ".json")
content = File.read(file)
- return JSON.parse(content).as_h
+ JSON.parse(content).as_h
end
Spectator.configure do |config|
diff --git a/src/invidious/channels/about.cr b/src/invidious/channels/about.cr
index 139095279..734749c4c 100644
--- a/src/invidious/channels/about.cr
+++ b/src/invidious/channels/about.cr
@@ -161,7 +161,7 @@ def get_about_info(ucid, locale) : AboutChannel
sub_count = 0
- if (metadata_rows = initdata.dig?("header", "pageHeaderRenderer", "content", "pageHeaderViewModel", "metadata", "contentMetadataViewModel", "metadataRows").try &.as_a)
+ if metadata_rows = initdata.dig?("header", "pageHeaderRenderer", "content", "pageHeaderViewModel", "metadata", "contentMetadataViewModel", "metadataRows").try &.as_a
metadata_rows.each do |row|
metadata_part = row.dig?("metadataParts").try &.as_a.find { |i| i.dig?("text", "content").try &.as_s.includes?("subscribers") }
if !metadata_part.nil?
diff --git a/src/invidious/channels/channels.cr b/src/invidious/channels/channels.cr
index 659823255..400483bac 100644
--- a/src/invidious/channels/channels.cr
+++ b/src/invidious/channels/channels.cr
@@ -26,21 +26,21 @@ struct ChannelVideo
json.object do
json.field "type", "shortVideo"
- json.field "title", self.title
- json.field "videoId", self.id
+ json.field "title", title
+ json.field "videoId", id
json.field "videoThumbnails" do
- Invidious::JSONify::APIv1.thumbnails(json, self.id)
+ Invidious::JSONify::APIv1.thumbnails(json, id)
end
- json.field "lengthSeconds", self.length_seconds
+ json.field "lengthSeconds", length_seconds
- json.field "author", self.author
- json.field "authorId", self.ucid
- json.field "authorUrl", "/channel/#{self.ucid}"
- json.field "published", self.published.to_unix
- json.field "publishedText", translate(locale, "`x` ago", recode_date(self.published, locale))
+ json.field "author", author
+ json.field "authorId", ucid
+ json.field "authorUrl", "/channel/#{ucid}"
+ json.field "published", published.to_unix
+ json.field "publishedText", translate(locale, "`x` ago", recode_date(published, locale))
- json.field "viewCount", self.views
+ json.field "viewCount", views
end
end
@@ -51,34 +51,34 @@ struct ChannelVideo
end
def to_xml(locale, query_params, xml : XML::Builder)
- query_params["v"] = self.id
+ query_params["v"] = id
xml.element("entry") do
- xml.element("id") { xml.text "yt:video:#{self.id}" }
- xml.element("yt:videoId") { xml.text self.id }
- xml.element("yt:channelId") { xml.text self.ucid }
- xml.element("title") { xml.text self.title }
+ xml.element("id") { xml.text "yt:video:#{id}" }
+ xml.element("yt:videoId") { xml.text id }
+ xml.element("yt:channelId") { xml.text ucid }
+ xml.element("title") { xml.text title }
xml.element("link", rel: "alternate", href: "#{HOST_URL}/watch?#{query_params}")
xml.element("author") do
- xml.element("name") { xml.text self.author }
- xml.element("uri") { xml.text "#{HOST_URL}/channel/#{self.ucid}" }
+ xml.element("name") { xml.text author }
+ xml.element("uri") { xml.text "#{HOST_URL}/channel/#{ucid}" }
end
xml.element("content", type: "xhtml") do
xml.element("div", xmlns: "http://www.w3.org/1999/xhtml") do
xml.element("a", href: "#{HOST_URL}/watch?#{query_params}") do
- xml.element("img", src: "#{HOST_URL}/vi/#{self.id}/mqdefault.jpg")
+ xml.element("img", src: "#{HOST_URL}/vi/#{id}/mqdefault.jpg")
end
end
end
- xml.element("published") { xml.text self.published.to_s("%Y-%m-%dT%H:%M:%S%:z") }
- xml.element("updated") { xml.text self.updated.to_s("%Y-%m-%dT%H:%M:%S%:z") }
+ xml.element("published") { xml.text published.to_s("%Y-%m-%dT%H:%M:%S%:z") }
+ xml.element("updated") { xml.text updated.to_s("%Y-%m-%dT%H:%M:%S%:z") }
xml.element("media:group") do
- xml.element("media:title") { xml.text self.title }
- xml.element("media:thumbnail", url: "#{HOST_URL}/vi/#{self.id}/mqdefault.jpg",
+ xml.element("media:title") { xml.text title }
+ xml.element("media:thumbnail", url: "#{HOST_URL}/vi/#{id}/mqdefault.jpg",
width: "320", height: "180")
end
end
@@ -93,7 +93,7 @@ struct ChannelVideo
def to_tuple
{% begin %}
{
- {{@type.instance_vars.map(&.name).splat}}
+ {{ @type.instance_vars.map(&.name).splat }}
}
{% end %}
end
@@ -107,7 +107,7 @@ class ChannelRedirect < Exception
end
def get_batch_channels(channels)
- finished_channel = Channel(String | Nil).new
+ finished_channel = Channel(String?).new
max_threads = 10
spawn do
@@ -141,7 +141,7 @@ def get_batch_channels(channels)
end
end
- return final
+ final
end
def get_channel(id) : InvidiousChannel
@@ -152,7 +152,7 @@ def get_channel(id) : InvidiousChannel
Invidious::Database::Channels.insert(channel, update_on_conflict: true)
end
- return channel
+ channel
end
def fetch_channel(ucid, pull_all_videos : Bool)
@@ -292,5 +292,5 @@ def fetch_channel(ucid, pull_all_videos : Bool)
end
channel.updated = Time.utc
- return channel
+ channel
end
diff --git a/src/invidious/channels/community.cr b/src/invidious/channels/community.cr
index 4256230cb..48d089690 100644
--- a/src/invidious/channels/community.cr
+++ b/src/invidious/channels/community.cr
@@ -21,7 +21,7 @@ def fetch_channel_community(ucid, cursor, locale, format, thin_mode)
items = container.as_a
end
- return extract_channel_community(items, ucid: ucid, locale: locale, format: format, thin_mode: thin_mode)
+ extract_channel_community(items, ucid: ucid, locale: locale, format: format, thin_mode: thin_mode)
end
def decode_ucid_from_post_protobuf(params)
@@ -30,7 +30,7 @@ def decode_ucid_from_post_protobuf(params)
.try { |i| IO::Memory.new(i) }
.try { |i| Protodec::Any.parse(i) }
- return decoded_protobuf.try(&.["56:0:embedded"]["2:0:string"].as_s)
+ decoded_protobuf.try(&.["56:0:embedded"]["2:0:string"].as_s)
end
def fetch_channel_community_post(ucid, post_id, locale, format, thin_mode)
@@ -53,7 +53,7 @@ def fetch_channel_community_post(ucid, post_id, locale, format, thin_mode)
items << item
end
- return extract_channel_community(items, ucid: ucid, locale: locale, format: format, thin_mode: thin_mode, is_single_post: true)
+ extract_channel_community(items, ucid: ucid, locale: locale, format: format, thin_mode: thin_mode, is_single_post: true)
end
def extract_channel_community(items, *, ucid, locale, format, thin_mode, is_single_post : Bool = false)
@@ -294,7 +294,7 @@ def extract_channel_community(items, *, ucid, locale, format, thin_mode, is_sing
end
end
- return response
+ response
end
def produce_channel_community_continuation(ucid, cursor)
@@ -310,7 +310,7 @@ def produce_channel_community_continuation(ucid, cursor)
.try { |i| Base64.urlsafe_encode(i) }
.try { |i| URI.encode_www_form(i) }
- return continuation
+ continuation
end
def extract_channel_community_cursor(continuation)
diff --git a/src/invidious/channels/playlists.cr b/src/invidious/channels/playlists.cr
index cba1abd9c..0f0089eab 100644
--- a/src/invidious/channels/playlists.cr
+++ b/src/invidious/channels/playlists.cr
@@ -24,7 +24,7 @@ def fetch_channel_playlists(ucid, author, continuation, sort_by)
initial_data = YoutubeAPI.browse(ucid, params: params || "")
end
- return extract_items(initial_data, author, ucid)
+ extract_items(initial_data, author, ucid)
end
def fetch_channel_podcasts(ucid, author, continuation)
@@ -33,7 +33,7 @@ def fetch_channel_podcasts(ucid, author, continuation)
else
initial_data = YoutubeAPI.browse(ucid, params: "Eghwb2RjYXN0c_IGBQoDugEA")
end
- return extract_items(initial_data, author, ucid)
+ extract_items(initial_data, author, ucid)
end
def fetch_channel_releases(ucid, author, continuation)
@@ -42,7 +42,7 @@ def fetch_channel_releases(ucid, author, continuation)
else
initial_data = YoutubeAPI.browse(ucid, params: "EghyZWxlYXNlc_IGBQoDsgEA")
end
- return extract_items(initial_data, author, ucid)
+ extract_items(initial_data, author, ucid)
end
def fetch_channel_courses(ucid, author, continuation)
@@ -51,5 +51,5 @@ def fetch_channel_courses(ucid, author, continuation)
else
initial_data = YoutubeAPI.browse(ucid, params: "Egdjb3Vyc2Vz8gYFCgPCAQA%3D")
end
- return extract_items(initial_data, author, ucid)
+ extract_items(initial_data, author, ucid)
end
diff --git a/src/invidious/channels/videos.cr b/src/invidious/channels/videos.cr
index 96400f471..c5c66a513 100644
--- a/src/invidious/channels/videos.cr
+++ b/src/invidious/channels/videos.cr
@@ -9,7 +9,7 @@ module Invidious::Channel::Tabs
# an author name and ucid directly (e.g in RSS feeds).
# TODO: figure out how to get rid of that
def get_videos(channel : AboutChannel, *, continuation : String? = nil, sort_by = "newest")
- return get_videos(
+ get_videos(
channel.author, channel.ucid,
continuation: continuation, sort_by: sort_by
)
@@ -19,7 +19,7 @@ module Invidious::Channel::Tabs
# an author name and ucid directly (e.g in RSS feeds).
# TODO: figure out how to get rid of that
def get_videos(channel : InvidiousChannel, *, continuation : String? = nil, sort_by = "newest")
- return get_videos(
+ get_videos(
channel.author, channel.id,
continuation: continuation, sort_by: sort_by
)
@@ -29,7 +29,7 @@ module Invidious::Channel::Tabs
continuation ||= make_initial_videos_ctoken(ucid, sort_by)
initial_data = YoutubeAPI.browse(continuation: continuation)
- return extract_items(initial_data, author, ucid)
+ extract_items(initial_data, author, ucid)
end
def get_60_videos(channel : AboutChannel, *, continuation : String? = nil, sort_by = "newest")
@@ -59,7 +59,7 @@ module Invidious::Channel::Tabs
continuation ||= make_initial_shorts_ctoken(channel.ucid, sort_by)
initial_data = YoutubeAPI.browse(continuation: continuation)
- return extract_items(initial_data, channel.author, channel.ucid)
+ extract_items(initial_data, channel.author, channel.ucid)
end
# -------------------
@@ -70,7 +70,7 @@ module Invidious::Channel::Tabs
continuation ||= make_initial_livestreams_ctoken(channel.ucid, sort_by)
initial_data = YoutubeAPI.browse(continuation: continuation)
- return extract_items(initial_data, channel.author, channel.ucid)
+ extract_items(initial_data, channel.author, channel.ucid)
end
def get_60_livestreams(channel : AboutChannel, *, continuation : String? = nil, sort_by = "newest")
@@ -98,10 +98,10 @@ module Invidious::Channel::Tabs
private def sort_options_videos_short(sort_by : String)
case sort_by
- when "newest" then return 4_i64
- when "popular" then return 2_i64
- when "oldest" then return 5_i64
- else return 4_i64 # Fallback to "newest"
+ when "newest" then 4_i64
+ when "popular" then 2_i64
+ when "oldest" then 5_i64
+ else 4_i64 # Fallback to "newest"
end
end
@@ -118,7 +118,7 @@ module Invidious::Channel::Tabs
},
}
- return channel_ctoken_wrap(ucid, object)
+ channel_ctoken_wrap(ucid, object)
end
# Generate the initial "continuation token" to get the first page of the
@@ -134,7 +134,7 @@ module Invidious::Channel::Tabs
},
}
- return channel_ctoken_wrap(ucid, object)
+ channel_ctoken_wrap(ucid, object)
end
# Generate the initial "continuation token" to get the first page of the
@@ -158,7 +158,7 @@ module Invidious::Channel::Tabs
},
}
- return channel_ctoken_wrap(ucid, object)
+ channel_ctoken_wrap(ucid, object)
end
# The protobuf structure common between videos/shorts/livestreams
@@ -187,6 +187,6 @@ module Invidious::Channel::Tabs
.try { |i| Base64.urlsafe_encode(i) }
.try { |i| URI.encode_www_form(i) }
- return continuation
+ continuation
end
end
diff --git a/src/invidious/comments/content.cr b/src/invidious/comments/content.cr
index 1f55bfe65..bd29b229a 100644
--- a/src/invidious/comments/content.cr
+++ b/src/invidious/comments/content.cr
@@ -37,7 +37,7 @@ def text_to_parsed_content(text : String) : JSON::Any
nodes << (node)
end
end
- return JSON.parse({"runs" => nodes}.to_json)
+ JSON.parse({"runs" => nodes}.to_json)
end
def parse_content(content : JSON::Any, video_id : String? = "") : String
@@ -85,5 +85,5 @@ def content_to_comment_html(content, video_id : String? = "")
text
end
- return html_array.join("").delete('\ufeff')
+ html_array.join("").delete('\ufeff')
end
diff --git a/src/invidious/comments/links_util.cr b/src/invidious/comments/links_util.cr
index f89b86d32..c82345191 100644
--- a/src/invidious/comments/links_util.cr
+++ b/src/invidious/comments/links_util.cr
@@ -45,7 +45,7 @@ module Invidious::Comments
html = node
end
- return html.to_xml(options: XML::SaveOptions::NO_DECL)
+ html.to_xml(options: XML::SaveOptions::NO_DECL)
end
def fill_links(html, scheme, host)
@@ -71,6 +71,6 @@ module Invidious::Comments
html = html.xpath_node(%q(//body/p)).not_nil!
end
- return html.to_xml(options: XML::SaveOptions::NO_DECL)
+ html.to_xml(options: XML::SaveOptions::NO_DECL)
end
end
diff --git a/src/invidious/comments/youtube.cr b/src/invidious/comments/youtube.cr
index e923b2f8d..c74342699 100644
--- a/src/invidious/comments/youtube.cr
+++ b/src/invidious/comments/youtube.cr
@@ -13,7 +13,7 @@ module Invidious::Comments
client_config = YoutubeAPI::ClientConfig.new(region: region)
response = YoutubeAPI.next(continuation: ctoken, client_config: client_config)
- return parse_youtube(id, response, format, locale, thin_mode, sort_by)
+ parse_youtube(id, response, format, locale, thin_mode, sort_by)
end
def fetch_community_post_comments(ucid, post_id, sort_by = "top")
@@ -58,7 +58,7 @@ module Invidious::Comments
.try { |i| URI.encode_www_form(i) }
initial_data = YoutubeAPI.browse(continuation: continuation)
- return initial_data
+ initial_data
end
def parse_youtube(id, response, format, locale, thin_mode, sort_by = "top", is_post = false)
@@ -320,7 +320,7 @@ module Invidious::Comments
end
end
- return response
+ response
end
def produce_continuation(video_id, cursor = "", sort_by = "top")
@@ -364,6 +364,6 @@ module Invidious::Comments
.try { |i| Base64.urlsafe_encode(i) }
.try { |i| URI.encode_www_form(i) }
- return continuation
+ continuation
end
end
diff --git a/src/invidious/config.cr b/src/invidious/config.cr
index 7853d9a3b..e439b0645 100644
--- a/src/invidious/config.cr
+++ b/src/invidious/config.cr
@@ -58,7 +58,7 @@ struct ConfigPreferences
def to_tuple
{% begin %}
{
- {{(@type.instance_vars.map { |var| "#{var.name}: #{var.name}".id }).splat}}
+ {{ (@type.instance_vars.map { |var| "#{var.name}: #{var.name}".id }).splat }}
}
{% end %}
end
@@ -183,15 +183,15 @@ class Config
def disabled?(option)
case disabled = CONFIG.disable_proxy
when Bool
- return disabled
+ disabled
when Array
if disabled.includes? option
- return true
+ true
else
- return false
+ false
end
else
- return false
+ false
end
end
@@ -212,14 +212,14 @@ class Config
{% for ivar in Config.instance_vars %}
{% env_id = "INVIDIOUS_#{ivar.id.upcase}" %}
- if ENV.has_key?({{env_id}})
- env_value = ENV.fetch({{env_id}})
+ if ENV.has_key?({{ env_id }})
+ env_value = ENV.fetch({{ env_id }})
success = false
# Use YAML converter if specified
{% ann = ivar.annotation(::YAML::Field) %}
{% if ann && ann[:converter] %}
- config.{{ivar.id}} = {{ann[:converter]}}.from_yaml(YAML::ParseContext.new, YAML::Nodes.parse(ENV.fetch({{env_id}})).nodes[0])
+ config.{{ ivar.id }} = {{ ann[:converter] }}.from_yaml(YAML::ParseContext.new, YAML::Nodes.parse(ENV.fetch({{ env_id }})).nodes[0])
success = true
# Use regular YAML parser otherwise
@@ -227,10 +227,10 @@ class Config
{% ivar_types = ivar.type.union? ? ivar.type.union_types : [ivar.type] %}
# Sort types to avoid parsing nulls and numbers as strings
{% ivar_types = ivar_types.sort_by { |ivar_type| ivar_type == Nil ? 0 : ivar_type == Int32 ? 1 : 2 } %}
- {{ivar_types}}.each do |ivar_type|
+ {{ ivar_types }}.each do |ivar_type|
if !success
begin
- config.{{ivar.id}} = ivar_type.from_yaml(env_value)
+ config.{{ ivar.id }} = ivar_type.from_yaml(env_value)
success = true
rescue
# nop
@@ -241,14 +241,14 @@ class Config
# Exit on fail
if !success
- puts %(Config.{{ivar.id}} failed to parse #{env_value} as {{ivar.type}})
+ puts %(Config.{{ ivar.id }} failed to parse #{env_value} as {{ ivar.type }})
exit(1)
end
end
# Warn when any config attribute is set to "CHANGE_ME!!"
- if config.{{ivar.id}} == "CHANGE_ME!!"
- puts "Config: The value of '#{ {{ivar.stringify}} }' needs to be changed!!"
+ if config.{{ ivar.id }} == "CHANGE_ME!!"
+ puts "Config: The value of '#{ {{ ivar.stringify }} }' needs to be changed!!"
exit(1)
end
{% end %}
@@ -318,6 +318,6 @@ class Config
end
end
- return config
+ config
end
end
diff --git a/src/invidious/database/annotations.cr b/src/invidious/database/annotations.cr
index 037494730..4bd3a2cf7 100644
--- a/src/invidious/database/annotations.cr
+++ b/src/invidious/database/annotations.cr
@@ -8,7 +8,7 @@ module Invidious::Database::Annotations
INSERT INTO annotations
VALUES ($1, $2)
ON CONFLICT DO NOTHING
- SQL
+ SQL
PG_DB.exec(request, id, annotations)
end
@@ -17,8 +17,8 @@ module Invidious::Database::Annotations
request = <<-SQL
SELECT * FROM annotations
WHERE id = $1
- SQL
+ SQL
- return PG_DB.query_one?(request, id, as: Annotation)
+ PG_DB.query_one?(request, id, as: Annotation)
end
end
diff --git a/src/invidious/database/base.cr b/src/invidious/database/base.cr
index 0fb1b6af0..a70516f2d 100644
--- a/src/invidious/database/base.cr
+++ b/src/invidious/database/base.cr
@@ -32,6 +32,7 @@ module Invidious::Database
def check_enum(enum_name, struct_type = nil)
return # TODO
+ # ameba:disable Lint/UnreachableCode
if !PG_DB.query_one?("SELECT true FROM pg_type WHERE typname = $1", enum_name, as: Bool)
LOGGER.info("check_enum: CREATE TYPE #{enum_name}")
@@ -131,6 +132,6 @@ module Invidious::Database
end
end
- return column_array
+ column_array
end
end
diff --git a/src/invidious/database/channels.cr b/src/invidious/database/channels.cr
index df44e485d..e967332c5 100644
--- a/src/invidious/database/channels.cr
+++ b/src/invidious/database/channels.cr
@@ -16,13 +16,13 @@ module Invidious::Database::Channels
request = <<-SQL
INSERT INTO channels
VALUES (#{arg_array(channel_array)})
- SQL
+ SQL
if update_on_conflict
request += <<-SQL
ON CONFLICT (id) DO UPDATE
SET author = $2, updated = $3
- SQL
+ SQL
end
PG_DB.exec(request, args: channel_array)
@@ -37,7 +37,7 @@ module Invidious::Database::Channels
UPDATE channels
SET updated = now(), author = $1, deleted = false
WHERE id = $2
- SQL
+ SQL
PG_DB.exec(request, author, id)
end
@@ -47,7 +47,7 @@ module Invidious::Database::Channels
UPDATE channels
SET subscribed = now()
WHERE id = $1
- SQL
+ SQL
PG_DB.exec(request, id)
end
@@ -57,7 +57,7 @@ module Invidious::Database::Channels
UPDATE channels
SET updated = now(), deleted = true
WHERE id = $1
- SQL
+ SQL
PG_DB.exec(request, id)
end
@@ -70,9 +70,9 @@ module Invidious::Database::Channels
request = <<-SQL
SELECT * FROM channels
WHERE id = $1
- SQL
+ SQL
- return PG_DB.query_one?(request, id, as: InvidiousChannel)
+ PG_DB.query_one?(request, id, as: InvidiousChannel)
end
def select(ids : Array(String)) : Array(InvidiousChannel)?
@@ -81,9 +81,9 @@ module Invidious::Database::Channels
request = <<-SQL
SELECT * FROM channels
WHERE id = ANY($1)
- SQL
+ SQL
- return PG_DB.query_all(request, ids, as: InvidiousChannel)
+ PG_DB.query_all(request, ids, as: InvidiousChannel)
end
end
@@ -112,9 +112,9 @@ module Invidious::Database::ChannelVideos
SET title = $2, published = $3, updated = $4, ucid = $5,
author = $6, length_seconds = $7, live_now = $8, #{last_items}
RETURNING (xmax=0) AS was_insert
- SQL
+ SQL
- return PG_DB.query_one(request, *video.to_tuple, as: Bool)
+ PG_DB.query_one(request, *video.to_tuple, as: Bool)
end
# -------------------
@@ -128,9 +128,9 @@ module Invidious::Database::ChannelVideos
SELECT * FROM channel_videos
WHERE id = ANY($1)
ORDER BY published DESC
- SQL
+ SQL
- return PG_DB.query_all(request, ids, as: ChannelVideo)
+ PG_DB.query_all(request, ids, as: ChannelVideo)
end
def select_notfications(ucid : String, since : Time) : Array(ChannelVideo)
@@ -139,9 +139,9 @@ module Invidious::Database::ChannelVideos
WHERE ucid = $1 AND published > $2
ORDER BY published DESC
LIMIT 15
- SQL
+ SQL
- return PG_DB.query_all(request, ucid, since, as: ChannelVideo)
+ PG_DB.query_all(request, ucid, since, as: ChannelVideo)
end
def select_popular_videos : Array(ChannelVideo)
@@ -151,7 +151,7 @@ module Invidious::Database::ChannelVideos
WHERE ucid IN (SELECT channel FROM (SELECT UNNEST(subscriptions) AS channel FROM users) AS d
GROUP BY channel ORDER BY COUNT(channel) DESC LIMIT 40)
ORDER BY ucid, published DESC
- SQL
+ SQL
PG_DB.query_all(request, as: ChannelVideo)
end
diff --git a/src/invidious/database/migrations/0001_create_channels_table.cr b/src/invidious/database/migrations/0001_create_channels_table.cr
index a1362bcf8..df7e31a12 100644
--- a/src/invidious/database/migrations/0001_create_channels_table.cr
+++ b/src/invidious/database/migrations/0001_create_channels_table.cr
@@ -4,27 +4,27 @@ module Invidious::Database::Migrations
def up(conn : DB::Connection)
conn.exec <<-SQL
- CREATE TABLE IF NOT EXISTS public.channels
- (
- id text NOT NULL,
- author text,
- updated timestamp with time zone,
- deleted boolean,
- subscribed timestamp with time zone,
- CONSTRAINT channels_id_key UNIQUE (id)
- );
- SQL
+ CREATE TABLE IF NOT EXISTS public.channels
+ (
+ id text NOT NULL,
+ author text,
+ updated timestamp with time zone,
+ deleted boolean,
+ subscribed timestamp with time zone,
+ CONSTRAINT channels_id_key UNIQUE (id)
+ );
+ SQL
conn.exec <<-SQL
- GRANT ALL ON TABLE public.channels TO current_user;
- SQL
+ GRANT ALL ON TABLE public.channels TO current_user;
+ SQL
conn.exec <<-SQL
- CREATE INDEX IF NOT EXISTS channels_id_idx
- ON public.channels
- USING btree
- (id COLLATE pg_catalog."default");
- SQL
+ CREATE INDEX IF NOT EXISTS channels_id_idx
+ ON public.channels
+ USING btree
+ (id COLLATE pg_catalog."default");
+ SQL
end
end
end
diff --git a/src/invidious/database/migrations/0002_create_videos_table.cr b/src/invidious/database/migrations/0002_create_videos_table.cr
index c2ac84f8f..1d0f5afb6 100644
--- a/src/invidious/database/migrations/0002_create_videos_table.cr
+++ b/src/invidious/database/migrations/0002_create_videos_table.cr
@@ -4,25 +4,25 @@ module Invidious::Database::Migrations
def up(conn : DB::Connection)
conn.exec <<-SQL
- CREATE UNLOGGED TABLE IF NOT EXISTS public.videos
- (
- id text NOT NULL,
- info text,
- updated timestamp with time zone,
- CONSTRAINT videos_pkey PRIMARY KEY (id)
- );
- SQL
+ CREATE UNLOGGED TABLE IF NOT EXISTS public.videos
+ (
+ id text NOT NULL,
+ info text,
+ updated timestamp with time zone,
+ CONSTRAINT videos_pkey PRIMARY KEY (id)
+ );
+ SQL
conn.exec <<-SQL
- GRANT ALL ON TABLE public.videos TO current_user;
- SQL
+ GRANT ALL ON TABLE public.videos TO current_user;
+ SQL
conn.exec <<-SQL
- CREATE UNIQUE INDEX IF NOT EXISTS id_idx
- ON public.videos
- USING btree
- (id COLLATE pg_catalog."default");
- SQL
+ CREATE UNIQUE INDEX IF NOT EXISTS id_idx
+ ON public.videos
+ USING btree
+ (id COLLATE pg_catalog."default");
+ SQL
end
end
end
diff --git a/src/invidious/database/migrations/0003_create_channel_videos_table.cr b/src/invidious/database/migrations/0003_create_channel_videos_table.cr
index c9b62e4c6..e4023fefe 100644
--- a/src/invidious/database/migrations/0003_create_channel_videos_table.cr
+++ b/src/invidious/database/migrations/0003_create_channel_videos_table.cr
@@ -4,32 +4,32 @@ module Invidious::Database::Migrations
def up(conn : DB::Connection)
conn.exec <<-SQL
- CREATE TABLE IF NOT EXISTS public.channel_videos
- (
- id text NOT NULL,
- title text,
- published timestamp with time zone,
- updated timestamp with time zone,
- ucid text,
- author text,
- length_seconds integer,
- live_now boolean,
- premiere_timestamp timestamp with time zone,
- views bigint,
- CONSTRAINT channel_videos_id_key UNIQUE (id)
- );
- SQL
+ CREATE TABLE IF NOT EXISTS public.channel_videos
+ (
+ id text NOT NULL,
+ title text,
+ published timestamp with time zone,
+ updated timestamp with time zone,
+ ucid text,
+ author text,
+ length_seconds integer,
+ live_now boolean,
+ premiere_timestamp timestamp with time zone,
+ views bigint,
+ CONSTRAINT channel_videos_id_key UNIQUE (id)
+ );
+ SQL
conn.exec <<-SQL
- GRANT ALL ON TABLE public.channel_videos TO current_user;
- SQL
+ GRANT ALL ON TABLE public.channel_videos TO current_user;
+ SQL
conn.exec <<-SQL
- CREATE INDEX IF NOT EXISTS channel_videos_ucid_idx
- ON public.channel_videos
- USING btree
- (ucid COLLATE pg_catalog."default");
- SQL
+ CREATE INDEX IF NOT EXISTS channel_videos_ucid_idx
+ ON public.channel_videos
+ USING btree
+ (ucid COLLATE pg_catalog."default");
+ SQL
end
end
end
diff --git a/src/invidious/database/migrations/0004_create_users_table.cr b/src/invidious/database/migrations/0004_create_users_table.cr
index a13ba15f0..3e561bc04 100644
--- a/src/invidious/database/migrations/0004_create_users_table.cr
+++ b/src/invidious/database/migrations/0004_create_users_table.cr
@@ -4,31 +4,31 @@ module Invidious::Database::Migrations
def up(conn : DB::Connection)
conn.exec <<-SQL
- CREATE TABLE IF NOT EXISTS public.users
- (
- updated timestamp with time zone,
- notifications text[],
- subscriptions text[],
- email text NOT NULL,
- preferences text,
- password text,
- token text,
- watched text[],
- feed_needs_update boolean,
- CONSTRAINT users_email_key UNIQUE (email)
- );
- SQL
+ CREATE TABLE IF NOT EXISTS public.users
+ (
+ updated timestamp with time zone,
+ notifications text[],
+ subscriptions text[],
+ email text NOT NULL,
+ preferences text,
+ password text,
+ token text,
+ watched text[],
+ feed_needs_update boolean,
+ CONSTRAINT users_email_key UNIQUE (email)
+ );
+ SQL
conn.exec <<-SQL
- GRANT ALL ON TABLE public.users TO current_user;
- SQL
+ GRANT ALL ON TABLE public.users TO current_user;
+ SQL
conn.exec <<-SQL
- CREATE UNIQUE INDEX IF NOT EXISTS email_unique_idx
- ON public.users
- USING btree
- (lower(email) COLLATE pg_catalog."default");
- SQL
+ CREATE UNIQUE INDEX IF NOT EXISTS email_unique_idx
+ ON public.users
+ USING btree
+ (lower(email) COLLATE pg_catalog."default");
+ SQL
end
end
end
diff --git a/src/invidious/database/migrations/0005_create_session_ids_table.cr b/src/invidious/database/migrations/0005_create_session_ids_table.cr
index 13c2228d1..e760ad166 100644
--- a/src/invidious/database/migrations/0005_create_session_ids_table.cr
+++ b/src/invidious/database/migrations/0005_create_session_ids_table.cr
@@ -4,25 +4,25 @@ module Invidious::Database::Migrations
def up(conn : DB::Connection)
conn.exec <<-SQL
- CREATE TABLE IF NOT EXISTS public.session_ids
- (
- id text NOT NULL,
- email text,
- issued timestamp with time zone,
- CONSTRAINT session_ids_pkey PRIMARY KEY (id)
- );
- SQL
+ CREATE TABLE IF NOT EXISTS public.session_ids
+ (
+ id text NOT NULL,
+ email text,
+ issued timestamp with time zone,
+ CONSTRAINT session_ids_pkey PRIMARY KEY (id)
+ );
+ SQL
conn.exec <<-SQL
- GRANT ALL ON TABLE public.session_ids TO current_user;
- SQL
+ GRANT ALL ON TABLE public.session_ids TO current_user;
+ SQL
conn.exec <<-SQL
- CREATE INDEX IF NOT EXISTS session_ids_id_idx
- ON public.session_ids
- USING btree
- (id COLLATE pg_catalog."default");
- SQL
+ CREATE INDEX IF NOT EXISTS session_ids_id_idx
+ ON public.session_ids
+ USING btree
+ (id COLLATE pg_catalog."default");
+ SQL
end
end
end
diff --git a/src/invidious/database/migrations/0006_create_nonces_table.cr b/src/invidious/database/migrations/0006_create_nonces_table.cr
index cf1229e16..c2ae7a873 100644
--- a/src/invidious/database/migrations/0006_create_nonces_table.cr
+++ b/src/invidious/database/migrations/0006_create_nonces_table.cr
@@ -4,24 +4,24 @@ module Invidious::Database::Migrations
def up(conn : DB::Connection)
conn.exec <<-SQL
- CREATE TABLE IF NOT EXISTS public.nonces
- (
- nonce text,
- expire timestamp with time zone,
- CONSTRAINT nonces_id_key UNIQUE (nonce)
- );
- SQL
+ CREATE TABLE IF NOT EXISTS public.nonces
+ (
+ nonce text,
+ expire timestamp with time zone,
+ CONSTRAINT nonces_id_key UNIQUE (nonce)
+ );
+ SQL
conn.exec <<-SQL
- GRANT ALL ON TABLE public.nonces TO current_user;
- SQL
+ GRANT ALL ON TABLE public.nonces TO current_user;
+ SQL
conn.exec <<-SQL
- CREATE INDEX IF NOT EXISTS nonces_nonce_idx
- ON public.nonces
- USING btree
- (nonce COLLATE pg_catalog."default");
- SQL
+ CREATE INDEX IF NOT EXISTS nonces_nonce_idx
+ ON public.nonces
+ USING btree
+ (nonce COLLATE pg_catalog."default");
+ SQL
end
end
end
diff --git a/src/invidious/database/migrations/0007_create_annotations_table.cr b/src/invidious/database/migrations/0007_create_annotations_table.cr
index dcecbc3b8..518e28860 100644
--- a/src/invidious/database/migrations/0007_create_annotations_table.cr
+++ b/src/invidious/database/migrations/0007_create_annotations_table.cr
@@ -4,17 +4,17 @@ module Invidious::Database::Migrations
def up(conn : DB::Connection)
conn.exec <<-SQL
- CREATE TABLE IF NOT EXISTS public.annotations
- (
- id text NOT NULL,
- annotations xml,
- CONSTRAINT annotations_id_key UNIQUE (id)
- );
- SQL
+ CREATE TABLE IF NOT EXISTS public.annotations
+ (
+ id text NOT NULL,
+ annotations xml,
+ CONSTRAINT annotations_id_key UNIQUE (id)
+ );
+ SQL
conn.exec <<-SQL
- GRANT ALL ON TABLE public.annotations TO current_user;
- SQL
+ GRANT ALL ON TABLE public.annotations TO current_user;
+ SQL
end
end
end
diff --git a/src/invidious/database/migrations/0008_create_playlists_table.cr b/src/invidious/database/migrations/0008_create_playlists_table.cr
index 6aa16e1a9..63901f61d 100644
--- a/src/invidious/database/migrations/0008_create_playlists_table.cr
+++ b/src/invidious/database/migrations/0008_create_playlists_table.cr
@@ -5,33 +5,33 @@ module Invidious::Database::Migrations
def up(conn : DB::Connection)
if !privacy_type_exists?(conn)
conn.exec <<-SQL
- CREATE TYPE public.privacy AS ENUM
- (
- 'Public',
- 'Unlisted',
- 'Private'
- );
- SQL
+ CREATE TYPE public.privacy AS ENUM
+ (
+ 'Public',
+ 'Unlisted',
+ 'Private'
+ );
+ SQL
end
conn.exec <<-SQL
- CREATE TABLE IF NOT EXISTS public.playlists
- (
- title text,
- id text primary key,
- author text,
- description text,
- video_count integer,
- created timestamptz,
- updated timestamptz,
- privacy privacy,
- index int8[]
- );
- SQL
+ CREATE TABLE IF NOT EXISTS public.playlists
+ (
+ title text,
+ id text primary key,
+ author text,
+ description text,
+ video_count integer,
+ created timestamptz,
+ updated timestamptz,
+ privacy privacy,
+ index int8[]
+ );
+ SQL
conn.exec <<-SQL
- GRANT ALL ON public.playlists TO current_user;
- SQL
+ GRANT ALL ON public.playlists TO current_user;
+ SQL
end
private def privacy_type_exists?(conn : DB::Connection) : Bool
@@ -42,7 +42,7 @@ module Invidious::Database::Migrations
WHERE pg_namespace.nspname = 'public'
AND pg_type.typname = 'privacy'
LIMIT 1;
- SQL
+ SQL
!conn.query_one?(request, as: Int32).nil?
end
diff --git a/src/invidious/database/migrations/0009_create_playlist_videos_table.cr b/src/invidious/database/migrations/0009_create_playlist_videos_table.cr
index 84938b9ba..82699b34b 100644
--- a/src/invidious/database/migrations/0009_create_playlist_videos_table.cr
+++ b/src/invidious/database/migrations/0009_create_playlist_videos_table.cr
@@ -4,24 +4,24 @@ module Invidious::Database::Migrations
def up(conn : DB::Connection)
conn.exec <<-SQL
- CREATE TABLE IF NOT EXISTS public.playlist_videos
- (
- title text,
- id text,
- author text,
- ucid text,
- length_seconds integer,
- published timestamptz,
- plid text references playlists(id),
- index int8,
- live_now boolean,
- PRIMARY KEY (index,plid)
- );
- SQL
+ CREATE TABLE IF NOT EXISTS public.playlist_videos
+ (
+ title text,
+ id text,
+ author text,
+ ucid text,
+ length_seconds integer,
+ published timestamptz,
+ plid text references playlists(id),
+ index int8,
+ live_now boolean,
+ PRIMARY KEY (index,plid)
+ );
+ SQL
conn.exec <<-SQL
- GRANT ALL ON TABLE public.playlist_videos TO current_user;
- SQL
+ GRANT ALL ON TABLE public.playlist_videos TO current_user;
+ SQL
end
end
end
diff --git a/src/invidious/database/migrations/0010_make_videos_unlogged.cr b/src/invidious/database/migrations/0010_make_videos_unlogged.cr
index f5d196834..37f1da234 100644
--- a/src/invidious/database/migrations/0010_make_videos_unlogged.cr
+++ b/src/invidious/database/migrations/0010_make_videos_unlogged.cr
@@ -4,8 +4,8 @@ module Invidious::Database::Migrations
def up(conn : DB::Connection)
conn.exec <<-SQL
- ALTER TABLE public.videos SET UNLOGGED;
- SQL
+ ALTER TABLE public.videos SET UNLOGGED;
+ SQL
end
end
end
diff --git a/src/invidious/database/migrator.cr b/src/invidious/database/migrator.cr
index 660c32034..200cf421b 100644
--- a/src/invidious/database/migrator.cr
+++ b/src/invidious/database/migrator.cr
@@ -44,6 +44,6 @@ class Invidious::Database::Migrator
id bigserial PRIMARY KEY,
version bigint NOT NULL
)
- SQL
+ SQL
end
end
diff --git a/src/invidious/database/nonces.cr b/src/invidious/database/nonces.cr
index b87c81ecb..38b8d44d1 100644
--- a/src/invidious/database/nonces.cr
+++ b/src/invidious/database/nonces.cr
@@ -12,7 +12,7 @@ module Invidious::Database::Nonces
INSERT INTO nonces
VALUES ($1, $2)
ON CONFLICT DO NOTHING
- SQL
+ SQL
PG_DB.exec(request, nonce, expire)
end
@@ -21,7 +21,7 @@ module Invidious::Database::Nonces
request = <<-SQL
DELETE FROM nonces *
WHERE expire < now()
- SQL
+ SQL
PG_DB.exec(request)
end
@@ -35,7 +35,7 @@ module Invidious::Database::Nonces
UPDATE nonces
SET expire = $1
WHERE nonce = $2
- SQL
+ SQL
PG_DB.exec(request, Time.utc(1990, 1, 1), nonce)
end
@@ -48,8 +48,8 @@ module Invidious::Database::Nonces
request = <<-SQL
SELECT * FROM nonces
WHERE nonce = $1
- SQL
+ SQL
- return PG_DB.query_one?(request, nonce, as: {String, Time})
+ PG_DB.query_one?(request, nonce, as: {String, Time})
end
end
diff --git a/src/invidious/database/playlists.cr b/src/invidious/database/playlists.cr
index 6dbcaa051..fe06c52cc 100644
--- a/src/invidious/database/playlists.cr
+++ b/src/invidious/database/playlists.cr
@@ -16,7 +16,7 @@ module Invidious::Database::Playlists
request = <<-SQL
INSERT INTO playlists
VALUES (#{arg_array(playlist_array)})
- SQL
+ SQL
PG_DB.exec(request, args: playlist_array)
end
@@ -27,7 +27,7 @@ module Invidious::Database::Playlists
request = <<-SQL
DELETE FROM playlists *
WHERE id = $1
- SQL
+ SQL
PG_DB.exec(request, id)
end
@@ -41,7 +41,7 @@ module Invidious::Database::Playlists
UPDATE playlists
SET title = $1, privacy = $2, description = $3, updated = $4
WHERE id = $5
- SQL
+ SQL
PG_DB.exec(request, title, privacy, description, updated, id)
end
@@ -51,7 +51,7 @@ module Invidious::Database::Playlists
UPDATE playlists
SET description = $1
WHERE id = $2
- SQL
+ SQL
PG_DB.exec(request, description, id)
end
@@ -61,7 +61,7 @@ module Invidious::Database::Playlists
UPDATE playlists
SET subscribed = now()
WHERE id = $1
- SQL
+ SQL
PG_DB.exec(request, id)
end
@@ -73,7 +73,7 @@ module Invidious::Database::Playlists
video_count = cardinality(index) + 1,
updated = now()
WHERE id = $2
- SQL
+ SQL
PG_DB.exec(request, index, id)
end
@@ -85,7 +85,7 @@ module Invidious::Database::Playlists
video_count = cardinality(index) - 1,
updated = now()
WHERE id = $2
- SQL
+ SQL
PG_DB.exec(request, index, id)
end
@@ -98,18 +98,18 @@ module Invidious::Database::Playlists
request = <<-SQL
SELECT * FROM playlists
WHERE id = $1
- SQL
+ SQL
- return PG_DB.query_one?(request, id, as: InvidiousPlaylist)
+ PG_DB.query_one?(request, id, as: InvidiousPlaylist)
end
def select_all(*, author : String) : Array(InvidiousPlaylist)
request = <<-SQL
SELECT * FROM playlists
WHERE author = $1
- SQL
+ SQL
- return PG_DB.query_all(request, author, as: InvidiousPlaylist)
+ PG_DB.query_all(request, author, as: InvidiousPlaylist)
end
# -------------------
@@ -121,7 +121,7 @@ module Invidious::Database::Playlists
SELECT * FROM playlists
WHERE author = $1 AND id LIKE 'IV%'
ORDER BY created
- SQL
+ SQL
PG_DB.query_all(request, email, as: InvidiousPlaylist)
end
@@ -131,7 +131,7 @@ module Invidious::Database::Playlists
SELECT * FROM playlists
WHERE author = $1 AND id NOT LIKE 'IV%'
ORDER BY created
- SQL
+ SQL
PG_DB.query_all(request, email, as: InvidiousPlaylist)
end
@@ -141,7 +141,7 @@ module Invidious::Database::Playlists
SELECT id,title FROM playlists
WHERE author = $1 AND id LIKE 'IV%'
ORDER BY title
- SQL
+ SQL
PG_DB.query_all(request, email, as: {String, String})
end
@@ -155,9 +155,9 @@ module Invidious::Database::Playlists
request = <<-SQL
SELECT id FROM playlists
WHERE id = $1
- SQL
+ SQL
- return PG_DB.query_one?(request, id, as: String).nil?
+ PG_DB.query_one?(request, id, as: String).nil?
end
# Count how many playlist a user has created.
@@ -165,9 +165,9 @@ module Invidious::Database::Playlists
request = <<-SQL
SELECT count(*) FROM playlists
WHERE author = $1
- SQL
+ SQL
- return PG_DB.query_one?(request, author, as: Int64) || 0_i64
+ PG_DB.query_one?(request, author, as: Int64) || 0_i64
end
end
@@ -189,7 +189,7 @@ module Invidious::Database::PlaylistVideos
request = <<-SQL
INSERT INTO playlist_videos
VALUES (#{arg_array(video_array)})
- SQL
+ SQL
PG_DB.exec(request, args: video_array)
end
@@ -198,7 +198,7 @@ module Invidious::Database::PlaylistVideos
request = <<-SQL
DELETE FROM playlist_videos *
WHERE index = $1
- SQL
+ SQL
PG_DB.exec(request, index)
end
@@ -207,7 +207,7 @@ module Invidious::Database::PlaylistVideos
request = <<-SQL
DELETE FROM playlist_videos *
WHERE plid = $1
- SQL
+ SQL
PG_DB.exec(request, plid)
end
@@ -223,9 +223,9 @@ module Invidious::Database::PlaylistVideos
ORDER BY array_position($2, index)
LIMIT $3
OFFSET $4
- SQL
+ SQL
- return PG_DB.query_all(request, plid, index, limit, offset, as: PlaylistVideo)
+ PG_DB.query_all(request, plid, index, limit, offset, as: PlaylistVideo)
end
def select_index(plid : String, vid : String) : Int64?
@@ -233,9 +233,9 @@ module Invidious::Database::PlaylistVideos
SELECT index FROM playlist_videos
WHERE plid = $1 AND id = $2
LIMIT 1
- SQL
+ SQL
- return PG_DB.query_one?(request, plid, vid, as: Int64)
+ PG_DB.query_one?(request, plid, vid, as: Int64)
end
def select_one_id(plid : String, index : VideoIndex) : String?
@@ -244,9 +244,9 @@ module Invidious::Database::PlaylistVideos
WHERE plid = $1
ORDER BY array_position($2, index)
LIMIT 1
- SQL
+ SQL
- return PG_DB.query_one?(request, plid, index, as: String)
+ PG_DB.query_one?(request, plid, index, as: String)
end
def select_ids(plid : String, index : VideoIndex, limit = 500) : Array(String)
@@ -255,8 +255,8 @@ module Invidious::Database::PlaylistVideos
WHERE plid = $1
ORDER BY array_position($2, index)
LIMIT $3
- SQL
+ SQL
- return PG_DB.query_all(request, plid, index, limit, as: String)
+ PG_DB.query_all(request, plid, index, limit, as: String)
end
end
diff --git a/src/invidious/database/sessions.cr b/src/invidious/database/sessions.cr
index 965870829..5537f087f 100644
--- a/src/invidious/database/sessions.cr
+++ b/src/invidious/database/sessions.cr
@@ -11,7 +11,7 @@ module Invidious::Database::SessionIDs
request = <<-SQL
INSERT INTO session_ids
VALUES ($1, $2, now())
- SQL
+ SQL
request += " ON CONFLICT (id) DO NOTHING" if handle_conflicts
@@ -26,7 +26,7 @@ module Invidious::Database::SessionIDs
request = <<-SQL
DELETE FROM session_ids *
WHERE id = $1
- SQL
+ SQL
PG_DB.exec(request, sid)
end
@@ -35,7 +35,7 @@ module Invidious::Database::SessionIDs
request = <<-SQL
DELETE FROM session_ids *
WHERE email = $1
- SQL
+ SQL
PG_DB.exec(request, email)
end
@@ -44,7 +44,7 @@ module Invidious::Database::SessionIDs
request = <<-SQL
DELETE FROM session_ids *
WHERE id = $1 AND email = $2
- SQL
+ SQL
PG_DB.exec(request, sid, email)
end
@@ -57,7 +57,7 @@ module Invidious::Database::SessionIDs
request = <<-SQL
SELECT email FROM session_ids
WHERE id = $1
- SQL
+ SQL
PG_DB.query_one?(request, sid, as: String)
end
@@ -67,7 +67,7 @@ module Invidious::Database::SessionIDs
SELECT id, issued FROM session_ids
WHERE email = $1
ORDER BY issued DESC
- SQL
+ SQL
PG_DB.query_all(request, email, as: {session: String, issued: Time})
end
diff --git a/src/invidious/database/statistics.cr b/src/invidious/database/statistics.cr
index 9e4963fde..cf2a138e6 100644
--- a/src/invidious/database/statistics.cr
+++ b/src/invidious/database/statistics.cr
@@ -10,7 +10,7 @@ module Invidious::Database::Statistics
def count_users_total : Int64
request = <<-SQL
SELECT count(*) FROM users
- SQL
+ SQL
PG_DB.query_one(request, as: Int64)
end
@@ -19,7 +19,7 @@ module Invidious::Database::Statistics
request = <<-SQL
SELECT count(*) FROM users
WHERE CURRENT_TIMESTAMP - updated < '6 months'
- SQL
+ SQL
PG_DB.query_one(request, as: Int64)
end
@@ -28,7 +28,7 @@ module Invidious::Database::Statistics
request = <<-SQL
SELECT count(*) FROM users
WHERE CURRENT_TIMESTAMP - updated < '1 month'
- SQL
+ SQL
PG_DB.query_one(request, as: Int64)
end
@@ -42,7 +42,7 @@ module Invidious::Database::Statistics
SELECT updated FROM channels
ORDER BY updated DESC
LIMIT 1
- SQL
+ SQL
PG_DB.query_one?(request, as: Time)
end
diff --git a/src/invidious/database/users.cr b/src/invidious/database/users.cr
index 4a3056ea5..15149cae3 100644
--- a/src/invidious/database/users.cr
+++ b/src/invidious/database/users.cr
@@ -14,13 +14,13 @@ module Invidious::Database::Users
request = <<-SQL
INSERT INTO users
VALUES (#{arg_array(user_array)})
- SQL
+ SQL
if update_on_conflict
request += <<-SQL
ON CONFLICT (email) DO UPDATE
SET updated = $1, subscriptions = $3
- SQL
+ SQL
end
PG_DB.exec(request, args: user_array)
@@ -30,7 +30,7 @@ module Invidious::Database::Users
request = <<-SQL
DELETE FROM users *
WHERE email = $1
- SQL
+ SQL
PG_DB.exec(request, user.email)
end
@@ -44,7 +44,7 @@ module Invidious::Database::Users
UPDATE users
SET watched = $1
WHERE email = $2
- SQL
+ SQL
PG_DB.exec(request, user.watched, user.email)
end
@@ -54,7 +54,7 @@ module Invidious::Database::Users
UPDATE users
SET watched = array_append(array_remove(watched, $1), $1)
WHERE email = $2
- SQL
+ SQL
PG_DB.exec(request, vid, user.email)
end
@@ -64,7 +64,7 @@ module Invidious::Database::Users
UPDATE users
SET watched = array_remove(watched, $1)
WHERE email = $2
- SQL
+ SQL
PG_DB.exec(request, vid, user.email)
end
@@ -74,7 +74,7 @@ module Invidious::Database::Users
UPDATE users
SET watched = '{}'
WHERE email = $1
- SQL
+ SQL
PG_DB.exec(request, user.email)
end
@@ -88,7 +88,7 @@ module Invidious::Database::Users
UPDATE users
SET feed_needs_update = true, subscriptions = $1
WHERE email = $2
- SQL
+ SQL
PG_DB.exec(request, user.subscriptions, user.email)
end
@@ -99,7 +99,7 @@ module Invidious::Database::Users
SET feed_needs_update = true,
subscriptions = array_append(subscriptions,$1)
WHERE email = $2
- SQL
+ SQL
PG_DB.exec(request, ucid, user.email)
end
@@ -110,7 +110,7 @@ module Invidious::Database::Users
SET feed_needs_update = true,
subscriptions = array_remove(subscriptions, $1)
WHERE email = $2
- SQL
+ SQL
PG_DB.exec(request, ucid, user.email)
end
@@ -125,7 +125,7 @@ module Invidious::Database::Users
SET notifications = array_cat(notifications, $1),
feed_needs_update = true
WHERE $2 = ANY(subscriptions)
- SQL
+ SQL
PG_DB.exec(request, video_ids, channel_id)
end
@@ -135,7 +135,7 @@ module Invidious::Database::Users
UPDATE users
SET notifications = array_remove(notifications, $1)
WHERE email = $2
- SQL
+ SQL
PG_DB.exec(request, vid, user.email)
end
@@ -145,7 +145,7 @@ module Invidious::Database::Users
UPDATE users
SET notifications = '{}', updated = now()
WHERE email = $1
- SQL
+ SQL
PG_DB.exec(request, user.email)
end
@@ -159,7 +159,7 @@ module Invidious::Database::Users
UPDATE users
SET feed_needs_update = true
WHERE $1 = ANY(subscriptions)
- SQL
+ SQL
PG_DB.exec(request, channel_id)
end
@@ -169,7 +169,7 @@ module Invidious::Database::Users
UPDATE users
SET preferences = $1
WHERE email = $2
- SQL
+ SQL
PG_DB.exec(request, user.preferences.to_json, user.email)
end
@@ -179,7 +179,7 @@ module Invidious::Database::Users
UPDATE users
SET password = $1
WHERE email = $2
- SQL
+ SQL
PG_DB.exec(request, pass, user.email)
end
@@ -192,9 +192,9 @@ module Invidious::Database::Users
request = <<-SQL
SELECT * FROM users
WHERE email = $1
- SQL
+ SQL
- return PG_DB.query_one?(request, email, as: User)
+ PG_DB.query_one?(request, email, as: User)
end
# Same as select, but can raise an exception
@@ -202,18 +202,18 @@ module Invidious::Database::Users
request = <<-SQL
SELECT * FROM users
WHERE email = $1
- SQL
+ SQL
- return PG_DB.query_one(request, email, as: User)
+ PG_DB.query_one(request, email, as: User)
end
def select(*, token : String) : User?
request = <<-SQL
SELECT * FROM users
WHERE token = $1
- SQL
+ SQL
- return PG_DB.query_one?(request, token, as: User)
+ PG_DB.query_one?(request, token, as: User)
end
def select_notifications(user : User) : Array(String)
@@ -221,8 +221,8 @@ module Invidious::Database::Users
SELECT notifications
FROM users
WHERE email = $1
- SQL
+ SQL
- return PG_DB.query_one(request, user.email, as: Array(String))
+ PG_DB.query_one(request, user.email, as: Array(String))
end
end
diff --git a/src/invidious/database/videos.cr b/src/invidious/database/videos.cr
index 695f5b335..28ac8850a 100644
--- a/src/invidious/database/videos.cr
+++ b/src/invidious/database/videos.cr
@@ -8,7 +8,7 @@ module Invidious::Database::Videos
INSERT INTO videos
VALUES ($1, $2, $3)
ON CONFLICT (id) DO NOTHING
- SQL
+ SQL
PG_DB.exec(request, video.id, video.info.to_json, video.updated)
end
@@ -17,7 +17,7 @@ module Invidious::Database::Videos
request = <<-SQL
DELETE FROM videos *
WHERE id = $1
- SQL
+ SQL
PG_DB.exec(request, id)
end
@@ -26,7 +26,7 @@ module Invidious::Database::Videos
request = <<-SQL
DELETE FROM videos *
WHERE updated < (now() - interval '6 hours')
- SQL
+ SQL
PG_DB.exec(request)
end
@@ -36,7 +36,7 @@ module Invidious::Database::Videos
UPDATE videos
SET (id, info, updated) = ($1, $2, $3)
WHERE id = $1
- SQL
+ SQL
PG_DB.exec(request, video.id, video.info.to_json, video.updated)
end
@@ -45,8 +45,8 @@ module Invidious::Database::Videos
request = <<-SQL
SELECT * FROM videos
WHERE id = $1
- SQL
+ SQL
- return PG_DB.query_one?(request, id, as: Video)
+ PG_DB.query_one?(request, id, as: Video)
end
end
diff --git a/src/invidious/exceptions.cr b/src/invidious/exceptions.cr
index 690db9077..b8416811a 100644
--- a/src/invidious/exceptions.cr
+++ b/src/invidious/exceptions.cr
@@ -23,7 +23,7 @@ class BrokenTubeException < Exception
end
def message
- return "Missing JSON element \"#{@element}\""
+ "Missing JSON element \"#{@element}\""
end
end
diff --git a/src/invidious/frontend/channel_page.cr b/src/invidious/frontend/channel_page.cr
index 4fe21b964..c612bd252 100644
--- a/src/invidious/frontend/channel_page.cr
+++ b/src/invidious/frontend/channel_page.cr
@@ -14,12 +14,12 @@ module Invidious::Frontend::ChannelPage
end
def generate_tabs_links(locale : String, channel : AboutChannel, selected_tab : TabsAvailable)
- return String.build(1500) do |str|
+ String.build(1500) do |str|
base_url = "/channel/#{channel.ucid}"
TabsAvailable.each do |tab|
# Ignore playlists, as it is not supported for auto-generated channels yet
- next if (tab.playlists? && channel.auto_generated)
+ next if tab.playlists? && channel.auto_generated
tab_name = tab.to_s.downcase
diff --git a/src/invidious/frontend/comments_reddit.cr b/src/invidious/frontend/comments_reddit.cr
index 4dda683ef..7ee357adc 100644
--- a/src/invidious/frontend/comments_reddit.cr
+++ b/src/invidious/frontend/comments_reddit.cr
@@ -11,38 +11,38 @@ module Invidious::Frontend::Comments
replies_html = ""
if child.replies.is_a?(RedditThing)
replies = child.replies.as(RedditThing)
- replies_html = self.template_reddit(replies.data.as(RedditListing).children, locale)
+ replies_html = template_reddit(replies.data.as(RedditListing).children, locale)
end
if child.depth > 0
- html << <<-END_HTML
-
-
-
-
- END_HTML
+ html << <<-HTML
+
+
+
+
+ HTML
else
- html << <<-END_HTML
-
-
- END_HTML
+ html << <<-HTML
+
+
+ HTML
end
- html << <<-END_HTML
-
- [ − ]
- #{child.author}
- #{translate_count(locale, "comments_points_count", child.score, NumberFormatting::Separator)}
- #{translate(locale, "`x` ago", recode_date(child.created_utc, locale))}
- #{translate(locale, "permalink")}
-
-
- #{body_html}
- #{replies_html}
-
-
-
- END_HTML
+ html << <<-HTML
+
+ [ − ]
+ #{child.author}
+ #{translate_count(locale, "comments_points_count", child.score, NumberFormatting::Separator)}
+ #{translate(locale, "`x` ago", recode_date(child.created_utc, locale))}
+ #{translate(locale, "permalink")}
+
+
+ #{body_html}
+ #{replies_html}
+
+
+
+ HTML
end
end
end
diff --git a/src/invidious/frontend/comments_youtube.cr b/src/invidious/frontend/comments_youtube.cr
index a0e1d783d..46012adf4 100644
--- a/src/invidious/frontend/comments_youtube.cr
+++ b/src/invidious/frontend/comments_youtube.cr
@@ -12,17 +12,17 @@ module Invidious::Frontend::Comments
NumberFormatting::Separator
)
- replies_html = <<-END_HTML
-
-
-
- END_HTML
+ HTML
elsif comments["authorId"]? && !comments["singlePost"]?
# for posts we should display a link to the post
replies_count_text = translate_count(locale,
@@ -31,16 +31,16 @@ module Invidious::Frontend::Comments
NumberFormatting::Separator
)
- replies_html = <<-END_HTML
-
-
-
- END_HTML
+ HTML
end
if !thin_mode
@@ -65,19 +65,19 @@ module Invidious::Frontend::Comments
str << %(width="16" height="16" />)
end
end
- html << <<-END_HTML
-
-
-
-
-
-
-
- #{author_name}
-
- #{sponsor_icon}
-
#{child["contentHtml"]}
- END_HTML
+ html << <<-HTML
+
+
+
+
+
+
+
+ #{author_name}
+
+ #{sponsor_icon}
+
#{child["contentHtml"]}
+ HTML
if child["attachment"]?
attachment = child["attachment"]
@@ -86,82 +86,81 @@ module Invidious::Frontend::Comments
when "image"
attachment = attachment["imageThumbnails"][1]
- html << <<-END_HTML
-
-
-
+ html << <<-HTML
+
+
+
+
-
- END_HTML
+ HTML
when "video"
if attachment["error"]?
- html << <<-END_HTML
-
-
#{attachment["error"]}
-
- END_HTML
+ html << <<-HTML
+
+
#{attachment["error"]}
+
+ HTML
else
- html << <<-END_HTML
-
-
-
- END_HTML
+ html << <<-HTML
+
+
+
+ HTML
end
when "multiImage"
- html << <<-END_HTML
+ html << <<-HTML
#{translate(locale, "carousel_skip")}
- END_HTML
+ HTML
image_array = attachment["images"].as_a
image_array.each_index do |i|
- html << <<-END_HTML
+ html << <<-HTML
(i + 1).to_s, "total" => image_array.size.to_s})}" tabindex="0">
- END_HTML
+ HTML
end
- html << <<-END_HTML
+ html << <<-HTML
- END_HTML
+ HTML
attachment["images"].as_a.each_index do |i|
- html << <<-END_HTML
+ html << <<-HTML
#{i + 1}
- END_HTML
+ HTML
end
- html << <<-END_HTML
-
-
-
- END_HTML
- else nil # Ignore
+ html << <<-HTML
+
+
+
+ HTML
end
end
- html << <<-END_HTML
-
- #{translate(locale, "`x` ago", recode_date(Time.unix(child["published"].as_i64), locale))} #{child["isEdited"] == true ? translate(locale, "(edited)") : ""}
- |
- END_HTML
+ html << <<-HTML
+
+ #{translate(locale, "`x` ago", recode_date(Time.unix(child["published"].as_i64), locale))} #{child["isEdited"] == true ? translate(locale, "(edited)") : ""}
+ |
+ HTML
if comments["videoId"]?
- html << <<-END_HTML
+ html << <<-HTML
[YT]
|
- END_HTML
+ HTML
elsif comments["authorId"]?
- html << <<-END_HTML
+ html << <<-HTML
[YT]
|
- END_HTML
+ HTML
end
- html << <<-END_HTML
+ html << <<-HTML
#{number_with_separator(child["likeCount"])}
- END_HTML
+ HTML
if child["creatorHeart"]?
if !thin_mode
@@ -170,7 +169,7 @@ module Invidious::Frontend::Comments
creator_thumbnail = ""
end
- html << <<-END_HTML
+ html << <<-HTML
@@ -180,28 +179,28 @@ module Invidious::Frontend::Comments
- END_HTML
+ HTML
end
- html << <<-END_HTML
-
- #{replies_html}
+ html << <<-HTML
+
+ #{replies_html}
+
-
- END_HTML
+ HTML
end
if comments["continuation"]?
- html << <<-END_HTML
-
-
- END_HTML
+ HTML
end
end
end
diff --git a/src/invidious/frontend/misc.cr b/src/invidious/frontend/misc.cr
index 9c30724a5..961ec2de4 100644
--- a/src/invidious/frontend/misc.cr
+++ b/src/invidious/frontend/misc.cr
@@ -6,9 +6,9 @@ module Invidious::Frontend::Misc
if preferences.automatic_instance_redirect
current_page = env.get?("current_page").as(String)
- return "/redirect?referer=#{current_page}"
+ "/redirect?referer=#{current_page}"
else
- return "https://redirect.invidious.io#{env.request.resource}"
+ "https://redirect.invidious.io#{env.request.resource}"
end
end
end
diff --git a/src/invidious/frontend/pagination.cr b/src/invidious/frontend/pagination.cr
index a29f59366..e3ab7b3ea 100644
--- a/src/invidious/frontend/pagination.cr
+++ b/src/invidious/frontend/pagination.cr
@@ -60,7 +60,7 @@ module Invidious::Frontend::Pagination
end
def nav_numeric(locale : String?, *, base_url : String | URI, current_page : Int, show_next : Bool = true)
- return String.build do |str|
+ String.build do |str|
str << %(
\n)
str << %(
\n)
@@ -70,7 +70,7 @@ module Invidious::Frontend::Pagination
params_prev = URI::Params{"page" => (current_page - 1).to_s}
url_prev = HttpServer::Utils.add_params_to_url(base_url, params_prev)
- self.previous_page(str, locale, url_prev.to_s)
+ previous_page(str, locale, url_prev.to_s)
end
str << %(
\n)
@@ -80,7 +80,7 @@ module Invidious::Frontend::Pagination
params_next = URI::Params{"page" => (current_page + 1).to_s}
url_next = HttpServer::Utils.add_params_to_url(base_url, params_next)
- self.next_page(str, locale, url_next.to_s)
+ next_page(str, locale, url_next.to_s)
end
str << %(
\n)
@@ -91,7 +91,7 @@ module Invidious::Frontend::Pagination
end
def nav_ctoken(locale : String?, *, base_url : String | URI, ctoken : String?, first_page : Bool, params : URI::Params)
- return String.build do |str|
+ String.build do |str|
str << %(
\n)
str << %(
\n)
@@ -109,7 +109,7 @@ module Invidious::Frontend::Pagination
params["continuation"] = ctoken
url_next = HttpServer::Utils.add_params_to_url(base_url, params)
- self.next_page(str, locale, url_next.to_s)
+ next_page(str, locale, url_next.to_s)
end
str << %(
\n)
diff --git a/src/invidious/frontend/search_filters.cr b/src/invidious/frontend/search_filters.cr
index 8ac0af2e9..1e27ae51d 100644
--- a/src/invidious/frontend/search_filters.cr
+++ b/src/invidious/frontend/search_filters.cr
@@ -3,7 +3,7 @@ module Invidious::Frontend::SearchFilters
# Generate the search filters collapsable widget.
def generate(filters : Search::Filters, query : String, page : Int, locale : String) : String
- return String.build(8000) do |str|
+ String.build(8000) do |str|
str << "
\n"
str << "\t
"
str << "\t\t" << translate(locale, "search_filters_title") << " \n"
@@ -41,11 +41,11 @@ module Invidious::Frontend::SearchFilters
str << "\t\t\t\t\n"
str << "\t\t\t\t\t"
- str << translate(locale, "search_filters_{{name}}_label")
+ str << translate(locale, "search_filters_{{ name }}_label")
str << "
\n"
str << "\t\t\t\t\t\n"
- make_{{name}}_filter_options(str, filters.{{name}}, locale)
+ make_{{ name }}_filter_options(str, filters.{{ name }}, locale)
str << "\t\t\t\t\t
"
str << "\t\t\t\t \n"
@@ -57,12 +57,12 @@ module Invidious::Frontend::SearchFilters
{% date = value.underscore %}
str << "\t\t\t\t\t\t"
- str << " '
- str << ""
- str << translate(locale, "search_filters_date_option_{{date}}")
+ str << ""
+ str << translate(locale, "search_filters_date_option_{{ date }}")
str << "
\n"
{% end %}
end
@@ -73,12 +73,12 @@ module Invidious::Frontend::SearchFilters
{% type = value.underscore %}
str << "\t\t\t\t\t\t"
- str << " '
- str << ""
- str << translate(locale, "search_filters_type_option_{{type}}")
+ str << ""
+ str << translate(locale, "search_filters_type_option_{{ type }}")
str << "
\n"
{% end %}
end
@@ -89,12 +89,12 @@ module Invidious::Frontend::SearchFilters
{% duration = value.underscore %}
str << "\t\t\t\t\t\t"
- str << " '
- str << ""
- str << translate(locale, "search_filters_duration_option_{{duration}}")
+ str << ""
+ str << translate(locale, "search_filters_duration_option_{{ duration }}")
str << "
\n"
{% end %}
end
@@ -106,12 +106,12 @@ module Invidious::Frontend::SearchFilters
{% feature = value.underscore %}
str << "\t\t\t\t\t\t"
- str << " '
- str << ""
- str << translate(locale, "search_filters_features_option_{{feature}}")
+ str << ""
+ str << translate(locale, "search_filters_features_option_{{ feature }}")
str << "
\n"
{% end %}
{% end %}
@@ -123,12 +123,12 @@ module Invidious::Frontend::SearchFilters
{% sort = value.underscore %}
str << "\t\t\t\t\t\t"
- str << " '
- str << ""
- str << translate(locale, "search_filters_sort_option_{{sort}}")
+ str << ""
+ str << translate(locale, "search_filters_sort_option_{{ sort }}")
str << "
\n"
{% end %}
end
diff --git a/src/invidious/frontend/watch_page.cr b/src/invidious/frontend/watch_page.cr
index 14e169e88..cdcca0a3d 100644
--- a/src/invidious/frontend/watch_page.cr
+++ b/src/invidious/frontend/watch_page.cr
@@ -28,12 +28,12 @@ module Invidious::Frontend::WatchPage
end
url = "/download"
- if (CONFIG.invidious_companion.present?)
+ if CONFIG.invidious_companion.present?
invidious_companion = CONFIG.invidious_companion.sample
url = "#{invidious_companion.public_url}/download?check=#{invidious_companion_encrypt(video.id)}"
end
- return String.build(4000) do |str|
+ String.build(4000) do |str|
str << " )
- return HTML.escape(details)
+ HTML.escape(details)
end
def get_issue_template(env : HTTP::Server::Context, exception : Exception) : Tuple(String, String)
issue_title = "#{exception.message} (#{exception.class})"
issue_template = <<-TEXT
- Title: `#{HTML.escape(issue_title)}`
- Date: `#{Time::Format::ISO_8601_DATE_TIME.format(Time.utc)}`
- Route: `#{HTML.escape(env.request.resource)}`
- Version: `#{SOFTWARE["version"]} @ #{SOFTWARE["branch"]}`
+ Title: `#{HTML.escape(issue_title)}`
+ Date: `#{Time::Format::ISO_8601_DATE_TIME.format(Time.utc)}`
+ Route: `#{HTML.escape(env.request.resource)}`
+ Version: `#{SOFTWARE["version"]} @ #{SOFTWARE["branch"]}`
- TEXT
+ TEXT
issue_template += github_details("Backtrace", exception.inspect_with_backtrace)
@@ -61,7 +61,8 @@ def error_template_helper(env : HTTP::Server::Context, status_code : Int32, exce
url_new_issue += "?labels=bug&template=bug_report.md&title="
url_new_issue += URI.encode_www_form("[Bug] " + issue_title)
- error_message = <<-END_HTML
+ # ameba:disable Lint/UselessAssign
+ error_message = <<-HTML
#{translate(locale, "crash_page_you_found_a_bug")}
@@ -80,13 +81,14 @@ def error_template_helper(env : HTTP::Server::Context, status_code : Int32, exce
#{issue_template}
- END_HTML
+ HTML
# Don't show the usual "next steps" widget. The same options are
# proposed above the error message, just worded differently.
+ # ameba:disable Lint/UselessAssign
next_steps = ""
- return templated "error"
+ templated "error"
end
def error_template_helper(env : HTTP::Server::Context, status_code : Int32, message : String)
@@ -95,10 +97,12 @@ def error_template_helper(env : HTTP::Server::Context, status_code : Int32, mess
locale = env.get("preferences").as(Preferences).locale
+ # ameba:disable Lint/UselessAssign
error_message = translate(locale, message)
+ # ameba:disable Lint/UselessAssign
next_steps = error_redirect_helper(env)
- return templated "error"
+ templated "error"
end
# -------------------
@@ -106,7 +110,7 @@ end
# -------------------
macro error_atom(*args)
- error_atom_helper(env, {{args.splat}})
+ error_atom_helper(env, {{ args.splat }})
end
def error_atom_helper(env : HTTP::Server::Context, status_code : Int32, exception : Exception)
@@ -117,14 +121,14 @@ def error_atom_helper(env : HTTP::Server::Context, status_code : Int32, exceptio
env.response.content_type = "application/atom+xml"
env.response.status_code = status_code
- return "
#{exception.inspect_with_backtrace} "
+ "
#{exception.inspect_with_backtrace} "
end
def error_atom_helper(env : HTTP::Server::Context, status_code : Int32, message : String)
env.response.content_type = "application/atom+xml"
env.response.status_code = status_code
- return "
#{message} "
+ "
#{message} "
end
# -------------------
@@ -132,14 +136,14 @@ end
# -------------------
macro error_json(*args)
- error_json_helper(env, {{args.splat}})
+ error_json_helper(env, {{ args.splat }})
end
def error_json_helper(
env : HTTP::Server::Context,
status_code : Int32,
exception : Exception,
- additional_fields : Hash(String, Object) | Nil = nil,
+ additional_fields : Hash(String, Object)? = nil,
)
if exception.is_a?(InfoException)
return error_json_helper(env, status_code, exception.message || "", additional_fields)
@@ -154,14 +158,14 @@ def error_json_helper(
error_message = error_message.merge(additional_fields)
end
- return error_message.to_json
+ error_message.to_json
end
def error_json_helper(
env : HTTP::Server::Context,
status_code : Int32,
message : String,
- additional_fields : Hash(String, Object) | Nil = nil,
+ additional_fields : Hash(String, Object)? = nil,
)
env.response.content_type = "application/json"
env.response.status_code = status_code
@@ -172,7 +176,7 @@ def error_json_helper(
error_message = error_message.merge(additional_fields)
end
- return error_message.to_json
+ error_message.to_json
end
# -------------------
@@ -191,7 +195,7 @@ def error_redirect_helper(env : HTTP::Server::Context)
go_to_youtube = translate(locale, "next_steps_error_message_go_to_youtube")
switch_instance = translate(locale, "Switch Invidious Instance")
- return <<-END_HTML
+ <<-HTML
#{next_steps_text}
@@ -204,8 +208,8 @@ def error_redirect_helper(env : HTTP::Server::Context)
#{go_to_youtube}
- END_HTML
+ HTML
else
- return ""
+ ""
end
end
diff --git a/src/invidious/helpers/handlers.cr b/src/invidious/helpers/handlers.cr
index 7c5ef1185..2d349993c 100644
--- a/src/invidious/helpers/handlers.cr
+++ b/src/invidious/helpers/handlers.cr
@@ -2,10 +2,10 @@ module HTTP::Handler
@@exclude_routes_tree = Radix::Tree(String).new
macro exclude(paths, method = "GET")
- class_name = {{@type.name}}
- method_downcase = {{method.downcase}}
+ class_name = {{ @type.name }}
+ method_downcase = {{ method.downcase }}
class_name_method = "#{class_name}/#{method_downcase}"
- ({{paths}}).each do |path|
+ ({{ paths }}).each do |path|
@@exclude_routes_tree.add class_name_method + path, '/' + method_downcase + path
end
end
@@ -20,8 +20,8 @@ module HTTP::Handler
end
class Kemal::RouteHandler
- {% for method in %w(GET POST PUT HEAD DELETE PATCH OPTIONS) %}
- exclude ["/api/v1/*"], {{method}}
+ {% for method in %w[GET POST PUT HEAD DELETE PATCH OPTIONS] %}
+ exclude ["/api/v1/*"], {{ method }}
{% end %}
# Processes the route if it's a match. Otherwise renders 404.
@@ -44,8 +44,8 @@ class Kemal::RouteHandler
end
class Kemal::ExceptionHandler
- {% for method in %w(GET POST PUT HEAD DELETE PATCH OPTIONS) %}
- exclude ["/api/v1/*"], {{method}}
+ {% for method in %w[GET POST PUT HEAD DELETE PATCH OPTIONS] %}
+ exclude ["/api/v1/*"], {{ method }}
{% end %}
private def call_exception_with_status_code(context : HTTP::Server::Context, exception : Exception, status_code : Int32)
@@ -72,8 +72,8 @@ class FilteredCompressHandler < HTTP::CompressHandler
end
class AuthHandler < Kemal::Handler
- {% for method in %w(GET POST PUT HEAD DELETE PATCH OPTIONS) %}
- only ["/api/v1/auth/*"], {{method}}
+ {% for method in %w[GET POST PUT HEAD DELETE PATCH OPTIONS] %}
+ only ["/api/v1/auth/*"], {{ method }}
{% end %}
def call(env)
@@ -121,8 +121,8 @@ class AuthHandler < Kemal::Handler
end
class APIHandler < Kemal::Handler
- {% for method in %w(GET POST PUT HEAD DELETE PATCH OPTIONS) %}
- only ["/api/v1/*"], {{method}}
+ {% for method in %w[GET POST PUT HEAD DELETE PATCH OPTIONS] %}
+ only ["/api/v1/*"], {{ method }}
{% end %}
exclude ["/api/v1/auth/notifications"], "GET"
exclude ["/api/v1/auth/notifications"], "POST"
diff --git a/src/invidious/helpers/helpers.cr b/src/invidious/helpers/helpers.cr
index 6add0237f..2a50ebd0d 100644
--- a/src/invidious/helpers/helpers.cr
+++ b/src/invidious/helpers/helpers.cr
@@ -32,7 +32,7 @@ def html_to_content(description_html : String)
description = XML.parse_html(description).content.strip("\n ")
end
- return description
+ description
end
def cache_annotation(id, annotations)
@@ -165,7 +165,7 @@ def create_notification_stream(env, topics, connection_channel)
end
def extract_initial_data(body) : Hash(String, JSON::Any)
- return JSON.parse(body.match(/(window\["ytInitialData"\]|var\s*ytInitialData)\s*=\s*(?
{.*?});<\/script>/mx).try &.["info"] || "{}").as_h
+ JSON.parse(body.match(/(window\["ytInitialData"\]|var\s*ytInitialData)\s*=\s*(?{.*?});<\/script>/mx).try &.["info"] || "{}").as_h
end
def proxy_file(response, env)
@@ -196,5 +196,5 @@ def get_playback_statistic
Invidious::Jobs::StatisticsRefreshJob::STATISTICS["playback"] = tracker
end
- return tracker.as(Hash(String, Int64 | Float64))
+ tracker.as(Hash(String, Int64 | Float64))
end
diff --git a/src/invidious/helpers/i18n.cr b/src/invidious/helpers/i18n.cr
index bca2edda9..e638f5cde 100644
--- a/src/invidious/helpers/i18n.cr
+++ b/src/invidious/helpers/i18n.cr
@@ -91,10 +91,10 @@ def load_all_locales
locales[name] = JSON.parse(File.read("locales/#{name}.json")).as_h
end
- return locales
+ locales
end
-def translate(locale : String?, key : String, text : String | Hash(String, String) | Nil = nil) : String
+def translate(locale : String?, key : String, text : String | Hash(String, String)? = nil) : String
# Log a warning if "key" doesn't exist in en-US locale and return
# that key as the text, so this is more or less transparent to the user.
if !LOCALES["en-US"].has_key?(key)
@@ -141,7 +141,7 @@ def translate(locale : String?, key : String, text : String | Hash(String, Strin
end
end
- return translation
+ translation
end
def translate_count(locale : String, key : String, count : Int, format = NumberFormatting::None) : String
@@ -177,15 +177,15 @@ def translate_count(locale : String, key : String, count : Int, format = NumberF
else count_txt = count.to_s
end
- return translation.gsub("{{count}}", count_txt)
+ translation.gsub("{{count}}", count_txt)
end
def translate_bool(locale : String?, translation : Bool)
case translation
when true
- return translate(locale, "Yes")
+ translate(locale, "Yes")
when false
- return translate(locale, "No")
+ translate(locale, "No")
end
end
@@ -195,5 +195,5 @@ def locale_is_rtl?(locale : String?)
# Arabic, Persian, Hebrew
# See https://en.wikipedia.org/wiki/Right-to-left_script#List_of_RTL_scripts
- return {"ar", "fa", "he"}.includes? locale
+ {"ar", "fa", "he"}.includes? locale
end
diff --git a/src/invidious/helpers/i18next.cr b/src/invidious/helpers/i18next.cr
index 684e6d145..ad5d07e09 100644
--- a/src/invidious/helpers/i18next.cr
+++ b/src/invidious/helpers/i18next.cr
@@ -151,17 +151,17 @@ module I18next::Plurals
@version = version.to_u8
end
- self.init_rules
+ init_rules
end
def init_rules
# Look into sets
PLURAL_SETS.each do |form, langs|
- langs.each { |lang| self.forms[lang] = form }
+ langs.each { |lang| forms[lang] = form }
end
# Add plurals from the "singles" set
- self.forms.merge!(PLURAL_SINGLES)
+ forms.merge!(PLURAL_SINGLES)
end
def get_plural_form(locale : String) : PluralForms
@@ -170,12 +170,12 @@ module I18next::Plurals
locale = locale.split('-')[0]
end
- return self.forms[locale] if self.forms[locale]?
+ return forms[locale] if forms[locale]?
# If nothing was found, then use the most common form, i.e
# one singular and one plural, as in english. Not perfect,
# but better than yielding an exception at the user.
- return PluralForms::Single_not_one
+ PluralForms::Single_not_one
end
def get_suffix(locale : String, count : Int) : String
@@ -183,19 +183,19 @@ module I18next::Plurals
# determine if comparison should be done on a signed or unsigned integer,
# but this variable is never set, resulting in the comparison always
# being done on absolute numbers.
- return get_suffix_retrocompat(locale, count.abs)
+ get_suffix_retrocompat(locale, count.abs)
end
# Emulate the `rule.numbers.size == 2 && rule.numbers[0] == 1` check
# from original i18next code
private def simple_plural?(form : PluralForms) : Bool
case form
- when .single_gt_one? then return true
- when .single_not_one? then return true
- when .special_icelandic? then return true
- when .special_macedonian? then return true
+ when .single_gt_one? then true
+ when .single_not_one? then true
+ when .special_icelandic? then true
+ when .special_macedonian? then true
else
- return false
+ false
end
end
@@ -226,7 +226,7 @@ module I18next::Plurals
# when 2
# return "_#{suffix}"
# else # v3
- return "_#{idx}"
+ "_#{idx}"
# end
end
end
@@ -238,35 +238,35 @@ module I18next::Plurals
module SuffixIndex
def self.get_index(plural_form : PluralForms, count : Int) : UInt8
case plural_form
- when .single_gt_one? then return (count > 1) ? 1_u8 : 0_u8
- when .single_not_one? then return (count != 1) ? 1_u8 : 0_u8
- when .none? then return 0_u8
- when .dual_slavic? then return dual_slavic(count)
- when .special_arabic? then return special_arabic(count)
- when .special_czech_slovak? then return special_czech_slovak(count)
- when .special_polish_kashubian? then return special_polish_kashubian(count)
- when .special_welsh? then return special_welsh(count)
- when .special_irish? then return special_irish(count)
- when .special_scottish_gaelic? then return special_scottish_gaelic(count)
- when .special_icelandic? then return special_icelandic(count)
- when .special_javanese? then return special_javanese(count)
- when .special_cornish? then return special_cornish(count)
- when .special_lithuanian? then return special_lithuanian(count)
- when .special_latvian? then return special_latvian(count)
- when .special_macedonian? then return special_macedonian(count)
- when .special_mandinka? then return special_mandinka(count)
- when .special_maltese? then return special_maltese(count)
- when .special_romanian? then return special_romanian(count)
- when .special_slovenian? then return special_slovenian(count)
- when .special_hebrew? then return special_hebrew(count)
- when .special_odia? then return special_odia(count)
+ when .single_gt_one? then (count > 1) ? 1_u8 : 0_u8
+ when .single_not_one? then (count != 1) ? 1_u8 : 0_u8
+ when .none? then 0_u8
+ when .dual_slavic? then dual_slavic(count)
+ when .special_arabic? then special_arabic(count)
+ when .special_czech_slovak? then special_czech_slovak(count)
+ when .special_polish_kashubian? then special_polish_kashubian(count)
+ when .special_welsh? then special_welsh(count)
+ when .special_irish? then special_irish(count)
+ when .special_scottish_gaelic? then special_scottish_gaelic(count)
+ when .special_icelandic? then special_icelandic(count)
+ when .special_javanese? then special_javanese(count)
+ when .special_cornish? then special_cornish(count)
+ when .special_lithuanian? then special_lithuanian(count)
+ when .special_latvian? then special_latvian(count)
+ when .special_macedonian? then special_macedonian(count)
+ when .special_mandinka? then special_mandinka(count)
+ when .special_maltese? then special_maltese(count)
+ when .special_romanian? then special_romanian(count)
+ when .special_slovenian? then special_slovenian(count)
+ when .special_hebrew? then special_hebrew(count)
+ when .special_odia? then special_odia(count)
# Mixed v3/v4 forms
- when .special_spanish_italian? then return special_cldr_spanish_italian(count)
- when .special_french_portuguese? then return special_cldr_french_portuguese(count)
- when .special_hungarian_serbian? then return special_cldr_hungarian_serbian(count)
+ when .special_spanish_italian? then special_cldr_spanish_italian(count)
+ when .special_french_portuguese? then special_cldr_french_portuguese(count)
+ when .special_hungarian_serbian? then special_cldr_hungarian_serbian(count)
else
# default, if nothing matched above
- return 0_u8
+ 0_u8
end
end
@@ -280,11 +280,11 @@ module I18next::Plurals
n_mod_100 = count % 100
if n_mod_10 == 1 && n_mod_100 != 11
- return 0_u8
+ 0_u8
elsif n_mod_10 >= 2 && n_mod_10 <= 4 && (n_mod_100 < 10 || n_mod_100 >= 20)
- return 1_u8
+ 1_u8
else
- return 2_u8
+ 2_u8
end
end
@@ -294,13 +294,13 @@ module I18next::Plurals
# Rule: (n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5)
#
def self.special_arabic(count : Int) : UInt8
- return count.to_u8 if (count == 0 || count == 1 || count == 2)
+ return count.to_u8 if count == 0 || count == 1 || count == 2
n_mod_100 = count % 100
- return 3_u8 if (n_mod_100 >= 3 && n_mod_100 <= 10)
- return 4_u8 if (n_mod_100 >= 11)
- return 5_u8
+ return 3_u8 if n_mod_100 >= 3 && n_mod_100 <= 10
+ return 4_u8 if n_mod_100 >= 11
+ 5_u8
end
# Plural form for Czech and Slovak languages
@@ -309,9 +309,9 @@ module I18next::Plurals
# Rule: ((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2)
#
def self.special_czech_slovak(count : Int) : UInt8
- return 0_u8 if (count == 1)
- return 1_u8 if (count >= 2 && count <= 4)
- return 2_u8
+ return 0_u8 if count == 1
+ return 1_u8 if count >= 2 && count <= 4
+ 2_u8
end
# Plural form for Polish and Kashubian languages
@@ -320,15 +320,15 @@ module I18next::Plurals
# Rule: (n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)
#
def self.special_polish_kashubian(count : Int) : UInt8
- return 0_u8 if (count == 1)
+ return 0_u8 if count == 1
n_mod_10 = count % 10
n_mod_100 = count % 100
if n_mod_10 >= 2 && n_mod_10 <= 4 && (n_mod_100 < 10 || n_mod_100 >= 20)
- return 1_u8
+ 1_u8
else
- return 2_u8
+ 2_u8
end
end
@@ -338,10 +338,10 @@ module I18next::Plurals
# Rule: ((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3)
#
def self.special_welsh(count : Int) : UInt8
- return 0_u8 if (count == 1)
- return 1_u8 if (count == 2)
- return 2_u8 if (count != 8 && count != 11)
- return 3_u8
+ return 0_u8 if count == 1
+ return 1_u8 if count == 2
+ return 2_u8 if count != 8 && count != 11
+ 3_u8
end
# Plural form for Irish language
@@ -350,11 +350,11 @@ module I18next::Plurals
# Rule: (n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4)
#
def self.special_irish(count : Int) : UInt8
- return 0_u8 if (count == 1)
- return 1_u8 if (count == 2)
- return 2_u8 if (count < 7)
- return 3_u8 if (count < 11)
- return 4_u8
+ return 0_u8 if count == 1
+ return 1_u8 if count == 2
+ return 2_u8 if count < 7
+ return 3_u8 if count < 11
+ 4_u8
end
# Plural form for Gaelic language
@@ -363,10 +363,10 @@ module I18next::Plurals
# Rule: ((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3)
#
def self.special_scottish_gaelic(count : Int) : UInt8
- return 0_u8 if (count == 1 || count == 11)
- return 1_u8 if (count == 2 || count == 12)
- return 2_u8 if (count > 2 && count < 20)
- return 3_u8
+ return 0_u8 if count == 1 || count == 11
+ return 1_u8 if count == 2 || count == 12
+ return 2_u8 if count > 2 && count < 20
+ 3_u8
end
# Plural form for Icelandic language
@@ -376,9 +376,9 @@ module I18next::Plurals
#
def self.special_icelandic(count : Int) : UInt8
if (count % 10) != 1 || (count % 100) == 11
- return 1_u8
+ 1_u8
else
- return 0_u8
+ 0_u8
end
end
@@ -388,7 +388,7 @@ module I18next::Plurals
# Rule: (n !== 0)
#
def self.special_javanese(count : Int) : UInt8
- return (count != 0) ? 1_u8 : 0_u8
+ (count != 0) ? 1_u8 : 0_u8
end
# Plural form for Cornish language
@@ -400,7 +400,7 @@ module I18next::Plurals
return 0_u8 if count == 1
return 1_u8 if count == 2
return 2_u8 if count == 3
- return 3_u8
+ 3_u8
end
# Plural form for Lithuanian language
@@ -413,11 +413,11 @@ module I18next::Plurals
n_mod_100 = count % 100
if n_mod_10 == 1 && n_mod_100 != 11
- return 0_u8
+ 0_u8
elsif n_mod_10 >= 2 && (n_mod_100 < 10 || n_mod_100 >= 20)
- return 1_u8
+ 1_u8
else
- return 2_u8
+ 2_u8
end
end
@@ -428,11 +428,11 @@ module I18next::Plurals
#
def self.special_latvian(count : Int) : UInt8
if (count % 10) == 1 && (count % 100) != 11
- return 0_u8
+ 0_u8
elsif count != 0
- return 1_u8
+ 1_u8
else
- return 2_u8
+ 2_u8
end
end
@@ -443,9 +443,9 @@ module I18next::Plurals
#
def self.special_macedonian(count : Int) : UInt8
if count == 1 || ((count % 10) == 1 && (count % 100) != 11)
- return 0_u8
+ 0_u8
else
- return 1_u8
+ 1_u8
end
end
@@ -455,7 +455,7 @@ module I18next::Plurals
# Rule: (n==0 ? 0 : n==1 ? 1 : 2)
#
def self.special_mandinka(count : Int) : UInt8
- return (count == 0 || count == 1) ? count.to_u8 : 2_u8
+ (count == 0 || count == 1) ? count.to_u8 : 2_u8
end
# Plural form for Maltese language
@@ -468,9 +468,9 @@ module I18next::Plurals
return 1_u8 if count == 0
n_mod_100 = count % 100
- return 1_u8 if (n_mod_100 > 1 && n_mod_100 < 11)
- return 2_u8 if (n_mod_100 > 10 && n_mod_100 < 20)
- return 3_u8
+ return 1_u8 if n_mod_100 > 1 && n_mod_100 < 11
+ return 2_u8 if n_mod_100 > 10 && n_mod_100 < 20
+ 3_u8
end
# Plural form for Romanian language
@@ -483,8 +483,8 @@ module I18next::Plurals
return 1_u8 if count == 0
n_mod_100 = count % 100
- return 1_u8 if (n_mod_100 > 0 && n_mod_100 < 20)
- return 2_u8
+ return 1_u8 if n_mod_100 > 0 && n_mod_100 < 20
+ 2_u8
end
# Plural form for Slovenian language
@@ -494,10 +494,10 @@ module I18next::Plurals
#
def self.special_slovenian(count : Int) : UInt8
n_mod_100 = count % 100
- return 1_u8 if (n_mod_100 == 1)
- return 2_u8 if (n_mod_100 == 2)
- return 3_u8 if (n_mod_100 == 3 || n_mod_100 == 4)
- return 0_u8
+ return 1_u8 if n_mod_100 == 1
+ return 2_u8 if n_mod_100 == 2
+ return 3_u8 if n_mod_100 == 3 || n_mod_100 == 4
+ 0_u8
end
# Plural form for Hebrew language
@@ -506,13 +506,13 @@ module I18next::Plurals
# Rule: (n==1 ? 0 : n==2 ? 1 : (n<0 || n>10) && n%10==0 ? 2 : 3)
#
def self.special_hebrew(count : Int) : UInt8
- return 0_u8 if (count == 1)
- return 1_u8 if (count == 2)
+ return 0_u8 if count == 1
+ return 1_u8 if count == 2
if (count < 0 || count > 10) && (count % 10) == 0
- return 2_u8
+ 2_u8
else
- return 3_u8
+ 3_u8
end
end
@@ -523,7 +523,7 @@ module I18next::Plurals
# special rule for it.
#
def self.special_odia(count : Int) : UInt8
- return (count == 1) ? 0_u8 : 1_u8
+ (count == 1) ? 0_u8 : 1_u8
end
# -------------------
@@ -535,9 +535,9 @@ module I18next::Plurals
# This rule is mostly compliant to CLDR v42
#
def self.special_cldr_spanish_italian(count : Int) : UInt8
- return 0_u8 if (count == 1) # one
- return 1_u8 if (count != 0 && count % 1_000_000 == 0) # many
- return 2_u8 # other
+ return 0_u8 if count == 1 # one
+ return 1_u8 if count != 0 && count % 1_000_000 == 0 # many
+ 2_u8 # other
end
# Plural form for French and Portuguese
@@ -545,9 +545,9 @@ module I18next::Plurals
# This rule is mostly compliant to CLDR v42
#
def self.special_cldr_french_portuguese(count : Int) : UInt8
- return 0_u8 if (count == 0 || count == 1) # one
- return 1_u8 if (count % 1_000_000 == 0) # many
- return 2_u8 # other
+ return 0_u8 if count == 0 || count == 1 # one
+ return 1_u8 if count % 1_000_000 == 0 # many
+ 2_u8 # other
end
# Plural form for Hungarian and Serbian
@@ -558,9 +558,9 @@ module I18next::Plurals
n_mod_10 = count % 10
n_mod_100 = count % 100
- return 0_u8 if (n_mod_10 == 1 && n_mod_100 != 11) # one
- return 1_u8 if (2 <= n_mod_10 <= 4 && (n_mod_100 < 12 || 14 < n_mod_100)) # few
- return 2_u8 # other
+ return 0_u8 if n_mod_10 == 1 && n_mod_100 != 11 # one
+ return 1_u8 if 2 <= n_mod_10 <= 4 && (n_mod_100 < 12 || 14 < n_mod_100) # few
+ 2_u8 # other
end
end
end
diff --git a/src/invidious/helpers/logger.cr b/src/invidious/helpers/logger.cr
index 033495955..5b06612ea 100644
--- a/src/invidious/helpers/logger.cr
+++ b/src/invidious/helpers/logger.cr
@@ -55,10 +55,10 @@ class Invidious::LogHandler < Kemal::BaseLogHandler
end
end
- {% for level in %w(trace debug info warn error fatal) %}
- def {{level.id}}(message : String)
- if LogLevel::{{level.id.capitalize}} >= @level
- puts("#{Time.utc} [{{level.id}}] #{message}".colorize(color(LogLevel::{{level.id.capitalize}})))
+ {% for level in %w[trace debug info warn error fatal] %}
+ def {{ level.id }}(message : String)
+ if LogLevel::{{ level.id.capitalize }} >= @level
+ puts("#{Time.utc} [{{ level.id }}] #{message}".colorize(color(LogLevel::{{ level.id.capitalize }})))
end
end
{% end %}
diff --git a/src/invidious/helpers/macros.cr b/src/invidious/helpers/macros.cr
index 848473218..4e2f4bb24 100644
--- a/src/invidious/helpers/macros.cr
+++ b/src/invidious/helpers/macros.cr
@@ -49,24 +49,24 @@ module JSON::Serializable
end
macro templated(_filename, template = "template", navbar_search = true)
- navbar_search = {{navbar_search}}
+ navbar_search = {{ navbar_search }}
{{ filename = "src/invidious/views/" + _filename + ".ecr" }}
{{ layout = "src/invidious/views/" + template + ".ecr" }}
- __content_filename__ = {{filename}}
- render {{filename}}, {{layout}}
+ __content_filename__ = {{ filename }}
+ render {{ filename }}, {{ layout }}
end
macro rendered(filename)
- render("src/invidious/views/#{{{filename}}}.ecr")
+ render("src/invidious/views/#{{{ filename }}}.ecr")
end
# Similar to Kemals halt method but works in a
# method.
macro haltf(env, status_code = 200, response = "")
- {{env}}.response.status_code = {{status_code}}
- {{env}}.response.print {{response}}
- {{env}}.response.close
+ {{ env }}.response.status_code = {{ status_code }}
+ {{ env }}.response.print {{ response }}
+ {{ env }}.response.close
return
end
diff --git a/src/invidious/helpers/serialized_yt_data.cr b/src/invidious/helpers/serialized_yt_data.cr
index 2796a8dc6..c7054d896 100644
--- a/src/invidious/helpers/serialized_yt_data.cr
+++ b/src/invidious/helpers/serialized_yt_data.cr
@@ -28,19 +28,19 @@ struct SearchVideo
property badges : VideoBadges
def to_xml(auto_generated, query_params, xml : XML::Builder)
- query_params["v"] = self.id
+ query_params["v"] = id
xml.element("entry") do
- xml.element("id") { xml.text "yt:video:#{self.id}" }
- xml.element("yt:videoId") { xml.text self.id }
- xml.element("yt:channelId") { xml.text self.ucid }
- xml.element("title") { xml.text self.title }
+ xml.element("id") { xml.text "yt:video:#{id}" }
+ xml.element("yt:videoId") { xml.text id }
+ xml.element("yt:channelId") { xml.text ucid }
+ xml.element("title") { xml.text title }
xml.element("link", rel: "alternate", href: "#{HOST_URL}/watch?#{query_params}")
xml.element("author") do
if auto_generated
- xml.element("name") { xml.text self.author }
- xml.element("uri") { xml.text "#{HOST_URL}/channel/#{self.ucid}" }
+ xml.element("name") { xml.text author }
+ xml.element("uri") { xml.text "#{HOST_URL}/channel/#{ucid}" }
else
xml.element("name") { xml.text author }
xml.element("uri") { xml.text "#{HOST_URL}/channel/#{ucid}" }
@@ -50,24 +50,24 @@ struct SearchVideo
xml.element("content", type: "xhtml") do
xml.element("div", xmlns: "http://www.w3.org/1999/xhtml") do
xml.element("a", href: "#{HOST_URL}/watch?#{query_params}") do
- xml.element("img", src: "#{HOST_URL}/vi/#{self.id}/mqdefault.jpg")
+ xml.element("img", src: "#{HOST_URL}/vi/#{id}/mqdefault.jpg")
end
- xml.element("p", style: "word-break:break-word;white-space:pre-wrap") { xml.text html_to_content(self.description_html) }
+ xml.element("p", style: "word-break:break-word;white-space:pre-wrap") { xml.text html_to_content(description_html) }
end
end
- xml.element("published") { xml.text self.published.to_s("%Y-%m-%dT%H:%M:%S%:z") }
+ xml.element("published") { xml.text published.to_s("%Y-%m-%dT%H:%M:%S%:z") }
xml.element("media:group") do
- xml.element("media:title") { xml.text self.title }
- xml.element("media:thumbnail", url: "#{HOST_URL}/vi/#{self.id}/mqdefault.jpg",
+ xml.element("media:title") { xml.text title }
+ xml.element("media:thumbnail", url: "#{HOST_URL}/vi/#{id}/mqdefault.jpg",
width: "320", height: "180")
- xml.element("media:description") { xml.text html_to_content(self.description_html) }
+ xml.element("media:description") { xml.text html_to_content(description_html) }
end
xml.element("media:community") do
- xml.element("media:statistics", views: self.views)
+ xml.element("media:statistics", views: views)
end
end
end
@@ -81,13 +81,13 @@ struct SearchVideo
def to_json(locale : String?, json : JSON::Builder)
json.object do
json.field "type", "video"
- json.field "title", self.title
- json.field "videoId", self.id
+ json.field "title", title
+ json.field "videoId", id
- json.field "author", self.author
- json.field "authorId", self.ucid
- json.field "authorUrl", "/channel/#{self.ucid}"
- json.field "authorVerified", self.author_verified
+ json.field "author", author
+ json.field "authorId", ucid
+ json.field "authorUrl", "/channel/#{ucid}"
+ json.field "authorVerified", author_verified
author_thumbnail = self.author_thumbnail
@@ -108,31 +108,31 @@ struct SearchVideo
end
json.field "videoThumbnails" do
- Invidious::JSONify::APIv1.thumbnails(json, self.id)
+ Invidious::JSONify::APIv1.thumbnails(json, id)
end
- json.field "description", html_to_content(self.description_html)
- json.field "descriptionHtml", self.description_html
+ json.field "description", html_to_content(description_html)
+ json.field "descriptionHtml", description_html
- json.field "viewCount", self.views
- json.field "viewCountText", translate_count(locale, "generic_views_count", self.views, NumberFormatting::Short)
- json.field "published", self.published.to_unix
- json.field "publishedText", translate(locale, "`x` ago", recode_date(self.published, locale))
- json.field "lengthSeconds", self.length_seconds
- json.field "liveNow", self.badges.live_now?
- json.field "premium", self.badges.premium?
- json.field "isUpcoming", self.upcoming?
+ json.field "viewCount", views
+ json.field "viewCountText", translate_count(locale, "generic_views_count", views, NumberFormatting::Short)
+ json.field "published", published.to_unix
+ json.field "publishedText", translate(locale, "`x` ago", recode_date(published, locale))
+ json.field "lengthSeconds", length_seconds
+ json.field "liveNow", badges.live_now?
+ json.field "premium", badges.premium?
+ json.field "isUpcoming", upcoming?
- if self.premiere_timestamp
- json.field "premiereTimestamp", self.premiere_timestamp.try &.to_unix
+ if premiere_timestamp
+ json.field "premiereTimestamp", premiere_timestamp.try &.to_unix
end
- json.field "isNew", self.badges.new?
- json.field "is4k", self.badges.four_k?
- json.field "is8k", self.badges.eight_k?
- json.field "isVr180", self.badges.vr180?
- json.field "isVr360", self.badges.vr360?
- json.field "is3d", self.badges.three_d?
- json.field "hasCaptions", self.badges.closed_captions?
+ json.field "isNew", badges.new?
+ json.field "is4k", badges.four_k?
+ json.field "is8k", badges.eight_k?
+ json.field "isVr180", badges.vr180?
+ json.field "isVr360", badges.vr360?
+ json.field "is3d", badges.three_d?
+ json.field "hasCaptions", badges.closed_captions?
end
end
@@ -175,20 +175,20 @@ struct SearchPlaylist
def to_json(locale : String?, json : JSON::Builder)
json.object do
json.field "type", "playlist"
- json.field "title", self.title
- json.field "playlistId", self.id
- json.field "playlistThumbnail", self.thumbnail
+ json.field "title", title
+ json.field "playlistId", id
+ json.field "playlistThumbnail", thumbnail
- json.field "author", self.author
- json.field "authorId", self.ucid
- json.field "authorUrl", "/channel/#{self.ucid}"
+ json.field "author", author
+ json.field "authorId", ucid
+ json.field "authorUrl", "/channel/#{ucid}"
- json.field "authorVerified", self.author_verified
+ json.field "authorVerified", author_verified
- json.field "videoCount", self.video_count
+ json.field "videoCount", video_count
json.field "videos" do
json.array do
- self.videos.each do |video|
+ videos.each do |video|
json.object do
json.field "title", video.title
json.field "videoId", video.id
@@ -232,17 +232,17 @@ struct SearchChannel
def to_json(locale : String?, json : JSON::Builder)
json.object do
json.field "type", "channel"
- json.field "author", self.author
- json.field "authorId", self.ucid
- json.field "authorUrl", "/channel/#{self.ucid}"
- json.field "authorVerified", self.author_verified
+ json.field "author", author
+ json.field "authorId", ucid
+ json.field "authorUrl", "/channel/#{ucid}"
+ json.field "authorVerified", author_verified
json.field "authorThumbnails" do
json.array do
qualities = {32, 48, 76, 100, 176, 512}
qualities.each do |quality|
json.object do
- json.field "url", self.author_thumbnail.gsub(/=s\d+/, "=s#{quality}")
+ json.field "url", author_thumbnail.gsub(/=s\d+/, "=s#{quality}")
json.field "width", quality
json.field "height", quality
end
@@ -250,13 +250,13 @@ struct SearchChannel
end
end
- json.field "autoGenerated", self.auto_generated
- json.field "subCount", self.subscriber_count
- json.field "videoCount", self.video_count
- json.field "channelHandle", self.channel_handle
+ json.field "autoGenerated", auto_generated
+ json.field "subCount", subscriber_count
+ json.field "videoCount", video_count
+ json.field "channelHandle", channel_handle
- json.field "description", html_to_content(self.description_html)
- json.field "descriptionHtml", self.description_html
+ json.field "description", html_to_content(description_html)
+ json.field "descriptionHtml", description_html
end
end
@@ -283,10 +283,10 @@ struct SearchHashtag
def to_json(locale : String?, json : JSON::Builder)
json.object do
json.field "type", "hashtag"
- json.field "title", self.title
- json.field "url", self.url
- json.field "videoCount", self.video_count
- json.field "channelCount", self.channel_count
+ json.field "title", title
+ json.field "url", url
+ json.field "videoCount", video_count
+ json.field "channelCount", channel_count
end
end
end
@@ -315,7 +315,7 @@ struct ProblematicTimelineItem
# Provides compatibility with PlaylistVideo
def to_json(json : JSON::Builder, *args, **kwargs)
- return to_json("", json)
+ to_json("", json)
end
def to_xml(env, locale, xml : XML::Builder)
@@ -352,10 +352,10 @@ class Category
def to_json(locale : String?, json : JSON::Builder)
json.object do
json.field "type", "category"
- json.field "title", self.title
+ json.field "title", title
json.field "contents" do
json.array do
- self.contents.each do |item|
+ contents.each do |item|
item.to_json(locale, json)
end
end
diff --git a/src/invidious/helpers/tokens.cr b/src/invidious/helpers/tokens.cr
index a44988cd3..4675dedef 100644
--- a/src/invidious/helpers/tokens.cr
+++ b/src/invidious/helpers/tokens.cr
@@ -16,7 +16,7 @@ def generate_token(email, scopes, expire, key)
token["signature"] = sign_token(key, token)
- return token.to_json
+ token.to_json
end
def generate_response(session, scopes, key, expire = 6.hours, use_nonce = false)
@@ -36,7 +36,7 @@ def generate_response(session, scopes, key, expire = 6.hours, use_nonce = false)
token["signature"] = sign_token(key, token)
- return token.to_json
+ token.to_json
end
def sign_token(key, hash)
@@ -45,6 +45,7 @@ def sign_token(key, hash)
# TODO: figure out which "key" variable is used
# Ameba reports a warning for "Lint/ShadowingOuterLocalVar" on this
# variable, but it's preferable to not touch that (works fine atm).
+ # ameba:disable Lint/ShadowingOuterLocalVar
hash.each do |key, value|
next if key == "signature"
@@ -63,7 +64,7 @@ def sign_token(key, hash)
end
string_to_sign = string_to_sign.sort.join("\n")
- return Base64.urlsafe_encode(OpenSSL::HMAC.digest(:sha256, key, string_to_sign)).strip
+ Base64.urlsafe_encode(OpenSSL::HMAC.digest(:sha256, key, string_to_sign)).strip
end
def validate_request(token, session, request, key, locale = nil)
@@ -116,7 +117,7 @@ def scope_includes_scope(scope, subset)
subset_endpoint = subset_endpoint.downcase
if methods.empty?
- methods = %w(GET POST PUT HEAD DELETE PATCH OPTIONS)
+ methods = %w[GET POST PUT HEAD DELETE PATCH OPTIONS]
end
if methods & subset_methods != subset_methods
@@ -131,7 +132,7 @@ def scope_includes_scope(scope, subset)
return false
end
- return true
+ true
end
def scopes_include_scope(scopes, subset)
@@ -141,5 +142,5 @@ def scopes_include_scope(scopes, subset)
end
end
- return false
+ false
end
diff --git a/src/invidious/helpers/utils.cr b/src/invidious/helpers/utils.cr
index 5637e5338..abaf3a7eb 100644
--- a/src/invidious/helpers/utils.cr
+++ b/src/invidious/helpers/utils.cr
@@ -8,7 +8,7 @@ def ci_lower_bound(pos, n)
z = 1.96
phat = 1.0*pos/n
- return (phat + z*z/(2*n) - z * Math.sqrt((phat*(1 - phat) + z*z/(4*n))/n))/(1 + z*z/n)
+ (phat + z*z/(2*n) - z * Math.sqrt((phat*(1 - phat) + z*z/(4*n))/n))/(1 + z*z/n)
end
def elapsed_text(elapsed)
@@ -31,12 +31,12 @@ def decode_length_seconds(string)
seconds: length_seconds[2]
).total_seconds.to_i32
- return length_seconds
+ length_seconds
end
def recode_length_seconds(time)
if time <= 0
- return ""
+ ""
else
time = time.seconds
text = "#{time.minutes.to_s.rjust(2, '0')}:#{time.seconds.to_s.rjust(2, '0')}"
@@ -47,7 +47,7 @@ def recode_length_seconds(time)
text = text.lchop('0')
- return text
+ text
end
end
@@ -66,7 +66,7 @@ def decode_interval(string : String) : Time::Span
time = Time::Span.new(minutes: raw_minutes)
end
- return time
+ time
end
def decode_time(string)
@@ -88,7 +88,7 @@ def decode_time(string)
time = hours * 3600 + minutes * 60 + seconds + millis // 1000
end
- return time
+ time
end
def decode_date(string : String)
@@ -108,7 +108,6 @@ def decode_date(string : String)
return Time.utc
when "yesterday"
return Time.utc - 1.day
- else nil # Continue
end
# String matches format "20 hours ago", "4 months ago", "20s ago", "15min ago"...
@@ -137,26 +136,26 @@ def decode_date(string : String)
raise "Could not parse #{string}"
end
- return Time.utc - delta
+ Time.utc - delta
end
def recode_date(time : Time, locale)
span = Time.utc - time
if span.total_days > 365.0
- return translate_count(locale, "generic_count_years", span.total_days.to_i // 365)
+ translate_count(locale, "generic_count_years", span.total_days.to_i // 365)
elsif span.total_days > 30.0
- return translate_count(locale, "generic_count_months", span.total_days.to_i // 30)
+ translate_count(locale, "generic_count_months", span.total_days.to_i // 30)
elsif span.total_days > 7.0
- return translate_count(locale, "generic_count_weeks", span.total_days.to_i // 7)
+ translate_count(locale, "generic_count_weeks", span.total_days.to_i // 7)
elsif span.total_hours > 24.0
- return translate_count(locale, "generic_count_days", span.total_days.to_i)
+ translate_count(locale, "generic_count_days", span.total_days.to_i)
elsif span.total_minutes > 60.0
- return translate_count(locale, "generic_count_hours", span.total_hours.to_i)
+ translate_count(locale, "generic_count_hours", span.total_hours.to_i)
elsif span.total_seconds > 60.0
- return translate_count(locale, "generic_count_minutes", span.total_minutes.to_i)
+ translate_count(locale, "generic_count_minutes", span.total_minutes.to_i)
else
- return translate_count(locale, "generic_count_seconds", span.total_seconds.to_i)
+ translate_count(locale, "generic_count_seconds", span.total_seconds.to_i)
end
end
@@ -174,9 +173,9 @@ def short_text_to_number(short_text : String) : Int64
when "b" then number *= 1_000_000_000
end
- return number.to_i64
+ number.to_i64
rescue ex
- return 0_i64
+ 0_i64
end
def number_to_short_text(number)
@@ -209,7 +208,7 @@ def arg_array(array, start = 1)
args = args.join(",")
end
- return args
+ args
end
def make_host_url(kemal_config)
@@ -235,7 +234,7 @@ def make_host_url(kemal_config)
host = CONFIG.domain.not_nil!.lchop(".")
- return "#{scheme}#{host}#{port}"
+ "#{scheme}#{host}#{port}"
end
def get_referer(env, fallback = "/", unroll = true)
@@ -268,13 +267,13 @@ def get_referer(env, fallback = "/", unroll = true)
referer = fallback
end
- return referer
+ referer
end
def sha256(text)
digest = OpenSSL::Digest.new("SHA256")
digest << text
- return digest.final.hexstring
+ digest.final.hexstring
end
def subscribe_pubsub(topic, key)
@@ -302,7 +301,7 @@ def subscribe_pubsub(topic, key)
"hub.secret" => key.to_s,
}
- return make_client(PUBSUB_URL, &.post("/subscribe", form: body))
+ make_client(PUBSUB_URL, &.post("/subscribe", form: body))
end
def parse_range(range)
@@ -328,7 +327,7 @@ def reduce_uri(uri : URI | String, max_length : Int32 = 50, suffix : String = "
if str.size > max_length
str = "#{str[0, max_length]}#{suffix}"
end
- return str
+ str
end
# Get the html link from a NavigationEndpoint or an innertubeCommand
@@ -381,7 +380,7 @@ def parse_link_endpoint(endpoint : JSON::Any, text : String, video_id : String)
text = %(#{reduce_uri(text)} )
end
end
- return text
+ text
end
def encrypt_ecb_without_salt(data, key)
@@ -394,11 +393,11 @@ def encrypt_ecb_without_salt(data, key)
io.write(cipher.final)
io.rewind
- return io
+ io
end
def invidious_companion_encrypt(data)
timestamp = Time.utc.to_unix
encrypted_data = encrypt_ecb_without_salt("#{timestamp}|#{data}", CONFIG.invidious_companion_key)
- return Base64.urlsafe_encode(encrypted_data)
+ Base64.urlsafe_encode(encrypted_data)
end
diff --git a/src/invidious/helpers/webvtt.cr b/src/invidious/helpers/webvtt.cr
index 260d250fa..212ab2e4c 100644
--- a/src/invidious/helpers/webvtt.cr
+++ b/src/invidious/helpers/webvtt.cr
@@ -20,7 +20,7 @@ module WebVTT
# Writes an vtt cue with the specified time stamp and contents
def cue(start_time : Time::Span, end_time : Time::Span, text : String)
timestamp(start_time, end_time)
- @io << self.escape(text)
+ @io << escape(text)
@io << "\n\n"
end
@@ -40,7 +40,7 @@ module WebVTT
end
private def escape(text : String) : String
- return text.gsub(ESCAPE_SUBSTITUTIONS)
+ text.gsub(ESCAPE_SUBSTITUTIONS)
end
def document(setting_fields : Hash(String, String)? = nil, &)
diff --git a/src/invidious/http_server/static_assets_handler.cr b/src/invidious/http_server/static_assets_handler.cr
index 7902c95bf..8b8a6732b 100644
--- a/src/invidious/http_server/static_assets_handler.cr
+++ b/src/invidious/http_server/static_assets_handler.cr
@@ -68,7 +68,7 @@ module Invidious::HttpServer
end
end
- return flush_io_to_cache(retrieve_bytes_from, file_path, file_info)
+ flush_io_to_cache(retrieve_bytes_from, file_path, file_info)
end
# Writes file data to the cache
@@ -106,7 +106,7 @@ module Invidious::HttpServer
# Can be removed once https://github.com/crystal-lang/crystal/issues/15817 is fixed.
private def serve_file_range(context : HTTP::Server::Context, file : IO, range_header : String, file_info)
# Paste in the body of inherited serve_file_range
- {{@type.superclass.methods.select(&.name.==("serve_file_range"))[0].body}}
+ {{ @type.superclass.methods.select(&.name.==("serve_file_range"))[0].body }}
end
# Clear cached files.
@@ -114,7 +114,7 @@ module Invidious::HttpServer
# This is only used in the specs to clear the cache before each handler test
def self.clear_cache
@@current_cache_size = 0
- return @@cached_files.clear
+ @@cached_files.clear
end
end
end
diff --git a/src/invidious/http_server/utils.cr b/src/invidious/http_server/utils.cr
index 623a91771..fd8cda4c0 100644
--- a/src/invidious/http_server/utils.cr
+++ b/src/invidious/http_server/utils.cr
@@ -14,9 +14,9 @@ module Invidious::HttpServer
url.query_params = params
if absolute
- return "#{HOST_URL}#{url.request_target}"
+ "#{HOST_URL}#{url.request_target}"
else
- return url.request_target
+ url.request_target
end
end
@@ -35,7 +35,7 @@ module Invidious::HttpServer
str << params
end
- return url
+ url
end
end
end
diff --git a/src/invidious/jobs/instance_refresh_job.cr b/src/invidious/jobs/instance_refresh_job.cr
index cb4280b96..bcf9fff6d 100644
--- a/src/invidious/jobs/instance_refresh_job.cr
+++ b/src/invidious/jobs/instance_refresh_job.cr
@@ -25,7 +25,7 @@ class Invidious::Jobs::InstanceListRefreshJob < Invidious::Jobs::BaseJob
# - Is it an instance with a good uptime?
# - Is it an updated instance?
private def refresh_instances
- raw_instance_list = self.fetch_instances
+ raw_instance_list = fetch_instances
filtered_instance_list = [] of Tuple(String, String)
raw_instance_list.each do |instance_data|
@@ -73,7 +73,7 @@ class Invidious::Jobs::InstanceListRefreshJob < Invidious::Jobs::BaseJob
raw_instance_list = [] of JSON::Any
end
- return raw_instance_list
+ raw_instance_list
end
# Checks if the given target instance is outdated
@@ -84,7 +84,7 @@ class Invidious::Jobs::InstanceListRefreshJob < Invidious::Jobs::BaseJob
remote_commit_date = Time.parse(remote_commit_date[0], "%Y.%m.%d", Time::Location::UTC)
local_commit_date = Time.parse(CURRENT_VERSION, "%Y.%m.%d", Time::Location::UTC)
- return (remote_commit_date - local_commit_date).abs.days > 30
+ (remote_commit_date - local_commit_date).abs.days > 30
end
# Checks if the uptime of the target instance is greater than 90% over a 30 day period
@@ -92,6 +92,6 @@ class Invidious::Jobs::InstanceListRefreshJob < Invidious::Jobs::BaseJob
return true if !target_instance_health_monitor["down"].as_bool == false
return true if target_instance_health_monitor["uptime"].as_f < 90
- return false
+ false
end
end
diff --git a/src/invidious/jsonify/api_v1/video_json.cr b/src/invidious/jsonify/api_v1/video_json.cr
index ff9ea70ac..569c4a827 100644
--- a/src/invidious/jsonify/api_v1/video_json.cr
+++ b/src/invidious/jsonify/api_v1/video_json.cr
@@ -13,10 +13,10 @@ module Invidious::JSONify::APIv1
json.field "error", video.info["reason"] if video.info["reason"]?
json.field "videoThumbnails" do
- self.thumbnails(json, video.id)
+ thumbnails(json, video.id)
end
json.field "storyboards" do
- self.storyboards(json, video.id, video.storyboards)
+ storyboards(json, video.id, video.storyboards)
end
json.field "description", video.description
@@ -138,7 +138,7 @@ module Invidious::JSONify::APIv1
if fmt_info = Invidious::Videos::Formats.itag_to_metadata?(fmt["itag"])
json.field "container", fmt_info["ext"]
- json.field "encoding", fmt_info["vcodec"]? || fmt_info["acodec"]
+ json.field "encoding", (fmt_info["vcodec"]? || fmt_info["acodec"])
end
# Livestream chunk infos
@@ -199,7 +199,7 @@ module Invidious::JSONify::APIv1
if fmt_info = Invidious::Videos::Formats.itag_to_metadata?(fmt["itag"])
json.field "container", fmt_info["ext"]
- json.field "encoding", fmt_info["vcodec"]? || fmt_info["acodec"]
+ json.field "encoding", (fmt_info["vcodec"]? || fmt_info["acodec"])
end
end
end
@@ -241,7 +241,7 @@ module Invidious::JSONify::APIv1
json.field "videoId", rv["id"]
json.field "title", rv["title"]
json.field "videoThumbnails" do
- self.thumbnails(json, rv["id"])
+ thumbnails(json, rv["id"])
end
json.field "author", rv["author"]
diff --git a/src/invidious/mixes.cr b/src/invidious/mixes.cr
index 28ff0ff6e..66bb7fc8b 100644
--- a/src/invidious/mixes.cr
+++ b/src/invidious/mixes.cr
@@ -74,7 +74,7 @@ def fetch_mix(rdid, video_id, cookies = nil, locale = nil)
videos.uniq!(&.id)
videos = videos.first(50)
- return Mix.new({
+ Mix.new({
title: mix_title,
id: rdid,
videos: videos,
@@ -82,18 +82,18 @@ def fetch_mix(rdid, video_id, cookies = nil, locale = nil)
end
def template_mix(mix, listen)
- html = <<-END_HTML
-
-
\ No newline at end of file
+
diff --git a/src/invidious/views/post.ecr b/src/invidious/views/post.ecr
index f644d634c..a27f44611 100644
--- a/src/invidious/views/post.ecr
+++ b/src/invidious/views/post.ecr
@@ -45,4 +45,4 @@
%>
-
\ No newline at end of file
+
diff --git a/src/invidious/views/template.ecr b/src/invidious/views/template.ecr
index 0e0f2e16f..40f5544fe 100644
--- a/src/invidious/views/template.ecr
+++ b/src/invidious/views/template.ecr
@@ -159,7 +159,7 @@
<% end %>
@ <%= CURRENT_BRANCH %>
<% if CURRENT_TAG != "" %>
- (
+ (
<% if CONFIG.modified_source_code_url %>
<%= CURRENT_TAG %>
<% else %>
diff --git a/src/invidious/views/user/login.ecr b/src/invidious/views/user/login.ecr
index 7ac96bc6f..3e0b192c1 100644
--- a/src/invidious/views/user/login.ecr
+++ b/src/invidious/views/user/login.ecr
@@ -25,7 +25,6 @@
<% end %>
<% if captcha %>
- <% captcha = captcha.not_nil! %>
<% captcha[:tokens].each_with_index do |token, i| %>
diff --git a/src/invidious/yt_backend/connection_pool.cr b/src/invidious/yt_backend/connection_pool.cr
index 42241d159..0cdd715ee 100644
--- a/src/invidious/yt_backend/connection_pool.cr
+++ b/src/invidious/yt_backend/connection_pool.cr
@@ -41,7 +41,7 @@ struct YoutubeConnectionPool
)
DB::Pool(HTTP::Client).new(options) do
- next make_client(url, force_resolve: true)
+ make_client(url, force_resolve: true)
end
end
end
@@ -133,7 +133,7 @@ def make_client(url : URI, region = nil, force_resolve : Bool = false, force_you
client.read_timeout = 10.seconds
client.connect_timeout = 10.seconds
- return client
+ client
end
def make_client(url : URI, region = nil, force_resolve : Bool = false, use_http_proxy : Bool = true, &)
@@ -149,7 +149,7 @@ def make_configured_http_proxy_client
# This method is only called when configuration for an HTTP proxy are set
config_proxy = CONFIG.http_proxy.not_nil!
- return HTTP::Proxy::Client.new(
+ HTTP::Proxy::Client.new(
config_proxy.host,
config_proxy.port,
@@ -163,12 +163,12 @@ end
# Creates a new one when the specified pool for the subdomain does not exist
def get_ytimg_pool(subdomain)
if pool = YTIMG_POOLS[subdomain]?
- return pool
+ pool
else
LOGGER.info("ytimg_pool: Creating a new HTTP pool for \"https://#{subdomain}.ytimg.com\"")
pool = YoutubeConnectionPool.new(URI.parse("https://#{subdomain}.ytimg.com"), capacity: CONFIG.pool_size)
YTIMG_POOLS[subdomain] = pool
- return pool
+ pool
end
end
diff --git a/src/invidious/yt_backend/extractors.cr b/src/invidious/yt_backend/extractors.cr
index 04e00f202..44342b3bf 100644
--- a/src/invidious/yt_backend/extractors.cr
+++ b/src/invidious/yt_backend/extractors.cr
@@ -37,15 +37,13 @@ record AuthorFallback, name : String, id : String
private module Parsers
module BaseParser
def parse(*args)
- begin
- return parse_internal(*args)
- rescue ex
- LOGGER.debug("#{{{@type.name}}}: Failed to render item.")
- LOGGER.debug("#{{{@type.name}}}: Got exception: #{ex.message}")
- ProblematicTimelineItem.new(
- parse_exception: ex
- )
- end
+ parse_internal(*args)
+ rescue ex
+ LOGGER.debug("#{{{ @type.name }}}: Failed to render item.")
+ LOGGER.debug("#{{{ @type.name }}}: Got exception: #{ex.message}")
+ ProblematicTimelineItem.new(
+ parse_exception: ex
+ )
end
end
@@ -64,7 +62,7 @@ private module Parsers
def process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = (item["videoRenderer"]? || item["gridVideoRenderer"]?)
- return self.parse(item_contents, author_fallback)
+ return parse(item_contents, author_fallback)
end
end
@@ -152,7 +150,6 @@ private module Parsers
when "Premium"
# TODO: Potentially available as item_contents["topStandaloneBadge"]["metadataBadgeRenderer"]
badges |= VideoBadges::Premium
- else nil # Ignore
end
end
@@ -173,7 +170,7 @@ private module Parsers
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -192,7 +189,7 @@ private module Parsers
def process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = (item["channelRenderer"]? || item["gridChannelRenderer"]?)
- return self.parse(item_contents, author_fallback)
+ return parse(item_contents, author_fallback)
end
end
@@ -207,7 +204,7 @@ private module Parsers
# TODO change default value to nil
subscriber_count = item_contents.dig?("subscriberCountText", "simpleText").try &.as_s
- channel_handle = subscriber_count if (subscriber_count.try &.starts_with? "@")
+ channel_handle = subscriber_count if subscriber_count.try &.starts_with? "@"
# Since youtube added channel handles, `VideoCountText` holds the number of
# subscribers and `subscriberCountText` holds the handle, except when the
@@ -240,7 +237,7 @@ private module Parsers
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -255,7 +252,7 @@ private module Parsers
def process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = item["hashtagTileRenderer"]?
- return self.parse(item_contents)
+ return parse(item_contents)
end
end
@@ -280,7 +277,7 @@ private module Parsers
end
end
- return SearchHashtag.new({
+ SearchHashtag.new({
title: title,
url: url,
video_count: short_text_to_number(video_count_txt || ""),
@@ -289,7 +286,7 @@ private module Parsers
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -308,7 +305,7 @@ private module Parsers
def process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = item["gridPlaylistRenderer"]?
- return self.parse(item_contents, author_fallback)
+ return parse(item_contents, author_fallback)
end
end
@@ -334,7 +331,7 @@ private module Parsers
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -352,7 +349,7 @@ private module Parsers
def process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = item["playlistRenderer"]?
- return self.parse(item_contents, author_fallback)
+ return parse(item_contents, author_fallback)
end
end
@@ -395,7 +392,7 @@ private module Parsers
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -415,7 +412,7 @@ private module Parsers
def process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = item["shelfRenderer"]?
- return self.parse(item_contents, author_fallback)
+ return parse(item_contents, author_fallback)
end
end
@@ -467,7 +464,7 @@ private module Parsers
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -484,7 +481,7 @@ private module Parsers
def process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = item.dig?("itemSectionRenderer", "contents", 0)
- return self.parse(item_contents, author_fallback)
+ return parse(item_contents, author_fallback)
end
end
@@ -492,11 +489,11 @@ private module Parsers
child = VideoRendererParser.process(item_contents, author_fallback)
child ||= PlaylistRendererParser.process(item_contents, author_fallback)
- return child
+ child
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -513,7 +510,7 @@ private module Parsers
def process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = item.dig?("richItemRenderer", "content")
- return self.parse(item_contents, author_fallback)
+ return parse(item_contents, author_fallback)
end
end
@@ -523,11 +520,11 @@ private module Parsers
child ||= PlaylistRendererParser.process(item_contents, author_fallback)
child ||= LockupViewModelParser.process(item_contents, author_fallback)
child ||= ShortsLockupViewModelParser.process(item_contents, author_fallback)
- return child
+ child
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -546,7 +543,7 @@ private module Parsers
def process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = item["reelItemRenderer"]?
- return self.parse(item_contents, author_fallback)
+ return parse(item_contents, author_fallback)
end
end
@@ -626,7 +623,7 @@ private module Parsers
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -643,7 +640,7 @@ private module Parsers
def process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = item["lockupViewModel"]?
- return self.parse(item_contents, author_fallback)
+ return parse(item_contents, author_fallback)
end
end
@@ -674,9 +671,9 @@ private module Parsers
video_count = thumbnail_view_model.dig("overlays").as_a
.compact_map(&.dig?("thumbnailOverlayBadgeViewModel", "thumbnailBadges").try &.as_a)
.flatten
- .find(nil, &.dig?("thumbnailBadgeViewModel", "text").try { |node|
+ .find(nil, &.dig?("thumbnailBadgeViewModel", "text").try do |node|
{"episodes", "videos"}.any? { |str| node.as_s.ends_with?(str) }
- })
+ end)
.try &.dig("thumbnailBadgeViewModel", "text").as_s.to_i(strict: false)
metadata = item_contents.dig("metadata", "lockupMetadataViewModel")
@@ -691,7 +688,7 @@ private module Parsers
# item_contents.dig("rendererContext", "commandContext", "onTap", "innertubeCommand", "watchEndpoint")
# Available fields: "videoId", "playlistId", "params"
- return SearchPlaylist.new({
+ SearchPlaylist.new({
title: title,
id: playlist_id,
author: author_fallback.name,
@@ -704,7 +701,7 @@ private module Parsers
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -721,7 +718,7 @@ private module Parsers
def process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = item["shortsLockupViewModel"]?
- return self.parse(item_contents, author_fallback)
+ return parse(item_contents, author_fallback)
end
end
@@ -762,7 +759,7 @@ private module Parsers
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -778,7 +775,7 @@ private module Parsers
module ContinuationItemRendererParser
def self.process(item : JSON::Any, author_fallback : AuthorFallback)
if item_contents = item["continuationItemRenderer"]?
- return self.parse(item_contents)
+ return parse(item_contents)
end
end
@@ -791,7 +788,7 @@ private module Parsers
end
def self.parser_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
end
@@ -831,7 +828,7 @@ private module Extractors
module YouTubeTabs
def self.process(initial_data : InitialData)
if target = initial_data["twoColumnBrowseResultsRenderer"]?
- self.extract(target)
+ extract(target)
end
end
@@ -845,7 +842,7 @@ private module Extractors
raw_items = rich_grid_contents.as_a
end
- return raw_items
+ raw_items
end
private def self.unpack_section_list(contents)
@@ -853,13 +850,13 @@ private module Extractors
contents.as_a.each do |item|
if item_section_content = item.dig?("itemSectionRenderer", "contents")
- raw_items += self.unpack_item_section(item_section_content)
+ raw_items += unpack_item_section(item_section_content)
else
raw_items << item
end
end
- return raw_items
+ raw_items
end
private def self.unpack_item_section(contents)
@@ -874,11 +871,11 @@ private module Extractors
end
end
- return raw_items
+ raw_items
end
def self.extractor_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -902,7 +899,7 @@ private module Extractors
module SearchResults
def self.process(initial_data : InitialData)
if target = initial_data["twoColumnSearchResultsRenderer"]?
- self.extract(target)
+ extract(target)
end
end
@@ -915,11 +912,11 @@ private module Extractors
end
end
- return raw_items.flatten
+ raw_items.flatten
end
def self.extractor_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
@@ -936,11 +933,11 @@ private module Extractors
module ContinuationContent
def self.process(initial_data : InitialData)
if target = initial_data["continuationContents"]?
- self.extract(target)
+ extract(target)
elsif target = initial_data["appendContinuationItemsAction"]?
- self.extract(target)
+ extract(target)
elsif target = initial_data["reloadContinuationItemsCommand"]?
- self.extract(target)
+ extract(target)
end
end
@@ -949,11 +946,11 @@ private module Extractors
content ||= target.dig?("gridContinuation", "items")
content ||= target.dig?("richGridContinuation", "contents")
- return content.nil? ? [] of JSON::Any : content.as_a
+ content.nil? ? [] of JSON::Any : content.as_a
end
def self.extractor_name
- return {{@type.name}}
+ {{ @type.name }}
end
end
end
@@ -969,14 +966,14 @@ module HelperExtractors
def self.get_video_count(container : JSON::Any) : Int32
if box = container["videoCountText"]?
if (extracted_text = extract_text(box)) && !extracted_text.includes? " subscriber"
- return extracted_text.gsub(/\D/, "").to_i
+ extracted_text.gsub(/\D/, "").to_i
else
- return 0
+ 0
end
elsif box = container["videoCount"]?
- return box.as_s.to_i
+ box.as_s.to_i
else
- return 0
+ 0
end
end
@@ -990,7 +987,7 @@ module HelperExtractors
# Simpletext: "4M views"
# runs: {"text": "1.1K"},{"text":" watching"}
- return box["simpleText"]?.try &.as_s.sub(" views", "") ||
+ box["simpleText"]?.try &.as_s.sub(" views", "") ||
box.dig?("runs", 0, "text").try &.as_s || "0"
end
@@ -1000,7 +997,7 @@ module HelperExtractors
#
# Raises when it's unable to parse from the given JSON data.
def self.get_thumbnails(container : JSON::Any) : String
- return container.dig("thumbnail", "thumbnails", 0, "url").as_s
+ container.dig("thumbnail", "thumbnails", 0, "url").as_s
end
# ditto
@@ -1008,13 +1005,13 @@ module HelperExtractors
# YouTube sometimes sends the thumbnail as:
# {"thumbnails": [{"thumbnails": [{"url": "example.com"}, ...]}]}
def self.get_thumbnails_plural(container : JSON::Any) : String
- return container.dig("thumbnails", 0, "thumbnails", 0, "url").as_s
+ container.dig("thumbnails", 0, "thumbnails", 0, "url").as_s
end
# Retrieves the ID required for querying the InnerTube browse endpoint.
# Returns an empty string when it's unable to do so
def self.get_browse_id(container)
- return container.dig?("navigationEndpoint", "browseEndpoint", "browseId").try &.as_s || ""
+ container.dig?("navigationEndpoint", "browseEndpoint", "browseId").try &.as_s || ""
end
end
diff --git a/src/invidious/yt_backend/extractors_utils.cr b/src/invidious/yt_backend/extractors_utils.cr
index c83a2de5a..caf6b1ec6 100644
--- a/src/invidious/yt_backend/extractors_utils.cr
+++ b/src/invidious/yt_backend/extractors_utils.cr
@@ -17,15 +17,13 @@
# another nil will be returned.
def extract_text(item : JSON::Any?) : String?
if item.nil?
- return nil
+ return
end
if text_container = item["simpleText"]?
- return text_container.as_s
+ text_container.as_s
elsif text_container = item["runs"]?
return text_container.as_a.map(&.["text"].as_s).join("")
- else
- nil
end
end
@@ -60,18 +58,18 @@ def has_verified_badge?(badges : JSON::Any?)
return true if style == "BADGE_STYLE_TYPE_VERIFIED_ARTIST"
end
- return false
+ false
rescue ex
LOGGER.debug("Unable to parse owner badges. Got exception: #{ex.message}")
LOGGER.trace("Owner badges data: #{badges.to_json}")
- return false
+ false
end
# This function extracts SearchVideo items from a Category.
# Categories are commonly returned in search results and trending pages.
def extract_category(category : Category) : Array(SearchVideo)
- return category.contents.select(SearchVideo)
+ category.contents.select(SearchVideo)
end
# :ditto:
@@ -83,5 +81,5 @@ end
def extract_selected_tab(tabs)
# Extract the selected tab from the array of tabs Youtube returns
- return tabs.as_a.select(&.["tabRenderer"]?.try &.["selected"]?.try &.as_bool)[0]["tabRenderer"]
+ tabs.as_a.select(&.["tabRenderer"]?.try &.["selected"]?.try &.as_bool)[0]["tabRenderer"]
end
diff --git a/src/invidious/yt_backend/url_sanitizer.cr b/src/invidious/yt_backend/url_sanitizer.cr
index d539dadbb..d42985615 100644
--- a/src/invidious/yt_backend/url_sanitizer.cr
+++ b/src/invidious/yt_backend/url_sanitizer.cr
@@ -30,7 +30,7 @@ module UrlSanitizer
return false
end
- return true
+ true
end
# Return which kind of parameters are allowed based on the
@@ -38,15 +38,15 @@ module UrlSanitizer
private def determine_allowed(path_root : String)
case path_root
when "watch", "w", "v", "embed", "e", "shorts", "clip"
- return :watch
+ :watch
when .starts_with?("@"), "c", "channel", "user", "profile", "attribution_link"
- return :channel
+ :channel
when "playlist", "mix"
- return :playlist
+ :playlist
when "results", "search"
- return :search
+ :search
else # hashtag, post, trending, brand URLs, etc..
- return nil
+ return
end
end
@@ -61,7 +61,7 @@ module UrlSanitizer
end
end
- return new_params
+ new_params
end
# Transform any user-supplied youtube URL into something we can trust
@@ -78,7 +78,7 @@ module UrlSanitizer
new_uri = URI.new(path: "/")
# Redirect to homepage for bogus URLs
- return new_uri if (unsafe_host.nil? || unsafe_path.nil?)
+ return new_uri if unsafe_host.nil? || unsafe_path.nil?
breadcrumbs = unsafe_path
.split('/', remove_empty: true)
@@ -116,6 +116,6 @@ module UrlSanitizer
new_uri.query_params = new_params
end
- return new_uri
+ new_uri
end
end
diff --git a/src/invidious/yt_backend/youtube_api.cr b/src/invidious/yt_backend/youtube_api.cr
index dd709920a..01d77c07d 100644
--- a/src/invidious/yt_backend/youtube_api.cr
+++ b/src/invidious/yt_backend/youtube_api.cr
@@ -207,7 +207,7 @@ module YoutubeAPI
# Region to provide to youtube, e.g to alter search results
# (this is passed as the `gl` parameter).
- property region : String | Nil
+ property region : String?
# Initialization function
def initialize(
@@ -267,8 +267,8 @@ module YoutubeAPI
# Convert to string, for logging purposes
def to_s
- return {
- client_type: self.name,
+ {
+ client_type: name,
region: @region,
}.to_s
end
@@ -283,7 +283,7 @@ module YoutubeAPI
# Return, as a Hash, the "context" data required to request the
# youtube API endpoints.
#
- private def make_context(client_config : ClientConfig | Nil, video_id = "dQw4w9WgXcQ") : Hash
+ private def make_context(client_config : ClientConfig?, video_id = "dQw4w9WgXcQ") : Hash
# Use the default client config if nil is passed
client_config ||= DEFAULT_CLIENT_CONFIG
@@ -331,7 +331,7 @@ module YoutubeAPI
client_context["client"]["platform"] = platform
end
- return client_context
+ client_context
end
####################################################################
@@ -353,14 +353,14 @@ module YoutubeAPI
#
# - A playlist ID (parameters MUST be an empty string)
#
- def browse(continuation : String, client_config : ClientConfig | Nil = nil)
+ def browse(continuation : String, client_config : ClientConfig? = nil)
# JSON Request data, required by the API
data = {
- "context" => self.make_context(client_config),
+ "context" => make_context(client_config),
"continuation" => continuation,
}
- return self._post_json("/youtubei/v1/browse", data, client_config)
+ _post_json("/youtubei/v1/browse", data, client_config)
end
# :ditto:
@@ -368,12 +368,12 @@ module YoutubeAPI
browse_id : String,
*, # Force the following parameters to be passed by name
params : String,
- client_config : ClientConfig | Nil = nil,
+ client_config : ClientConfig? = nil,
)
# JSON Request data, required by the API
data = {
"browseId" => browse_id,
- "context" => self.make_context(client_config),
+ "context" => make_context(client_config),
}
# Append the additional parameters if those were provided
@@ -382,7 +382,7 @@ module YoutubeAPI
data["params"] = params
end
- return self._post_json("/youtubei/v1/browse", data, client_config)
+ _post_json("/youtubei/v1/browse", data, client_config)
end
####################################################################
@@ -421,29 +421,29 @@ module YoutubeAPI
# })
# ```
#
- def next(continuation : String, *, client_config : ClientConfig | Nil = nil)
+ def next(continuation : String, *, client_config : ClientConfig? = nil)
# JSON Request data, required by the API
data = {
- "context" => self.make_context(client_config),
+ "context" => make_context(client_config),
"continuation" => continuation,
}
- return self._post_json("/youtubei/v1/next", data, client_config)
+ _post_json("/youtubei/v1/next", data, client_config)
end
# :ditto:
- def next(data : Hash, *, client_config : ClientConfig | Nil = nil)
+ def next(data : Hash, *, client_config : ClientConfig? = nil)
# JSON Request data, required by the API
data2 = data.merge({
- "context" => self.make_context(client_config),
+ "context" => make_context(client_config),
})
- return self._post_json("/youtubei/v1/next", data2, client_config)
+ _post_json("/youtubei/v1/next", data2, client_config)
end
# Allow a NamedTuple to be passed, too.
- def next(data : NamedTuple, *, client_config : ClientConfig | Nil = nil)
- return self.next(data.to_h, client_config: client_config)
+ def next(data : NamedTuple, *, client_config : ClientConfig? = nil)
+ self.next(data.to_h, client_config: client_config)
end
####################################################################
@@ -461,9 +461,9 @@ module YoutubeAPI
}
if CONFIG.invidious_companion.present?
- return self._post_invidious_companion("/youtubei/v1/player", data)
+ _post_invidious_companion("/youtubei/v1/player", data)
else
- return nil
+ return
end
end
@@ -495,13 +495,13 @@ module YoutubeAPI
# channel_b = YoutubeAPI.resolve_url("https://youtube.com/c/invalid")
# ```
#
- def resolve_url(url : String, client_config : ClientConfig | Nil = nil)
+ def resolve_url(url : String, client_config : ClientConfig? = nil)
data = {
- "context" => self.make_context(nil),
+ "context" => make_context(nil),
"url" => url,
}
- return self._post_json("/youtubei/v1/navigation/resolve_url", data, client_config)
+ _post_json("/youtubei/v1/navigation/resolve_url", data, client_config)
end
####################################################################
@@ -521,16 +521,16 @@ module YoutubeAPI
def search(
search_query : String,
params : String,
- client_config : ClientConfig | Nil = nil,
+ client_config : ClientConfig? = nil,
)
# JSON Request data, required by the API
data = {
"query" => search_query,
- "context" => self.make_context(client_config),
+ "context" => make_context(client_config),
"params" => params,
}
- return self._post_json("/youtubei/v1/search", data, client_config)
+ _post_json("/youtubei/v1/search", data, client_config)
end
####################################################################
@@ -547,14 +547,14 @@ module YoutubeAPI
def get_transcript(
params : String,
- client_config : ClientConfig | Nil = nil,
+ client_config : ClientConfig? = nil,
) : Hash(String, JSON::Any)
data = {
- "context" => self.make_context(client_config),
+ "context" => make_context(client_config),
"params" => params,
}
- return self._post_json("/youtubei/v1/get_transcript", data, client_config)
+ _post_json("/youtubei/v1/get_transcript", data, client_config)
end
####################################################################
@@ -569,7 +569,7 @@ module YoutubeAPI
def _post_json(
endpoint : String,
data : Hash,
- client_config : ClientConfig | Nil,
+ client_config : ClientConfig?,
) : Hash(String, JSON::Any)
# Use the default client config if nil is passed
client_config ||= DEFAULT_CLIENT_CONFIG
@@ -602,7 +602,7 @@ module YoutubeAPI
status code #{response.status_code}. See
\
https://docs.invidious.io/youtube-errors-explained/ for troubleshooting.")
end
- self._decompress(response.body_io, response.headers["Content-Encoding"]?)
+ _decompress(response.body_io, response.headers["Content-Encoding"]?)
end
end
@@ -623,7 +623,7 @@ module YoutubeAPI
error #{code} with message:
\"#{message}\"")
end
- return initial_data
+ initial_data
end
####################################################################
@@ -661,7 +661,7 @@ module YoutubeAPI
end
end
- return response_body
+ response_body
rescue ex
raise InfoException.new("Error while communicating with Invidious companion: " + (ex.message || "no extra info found"))
end
@@ -685,7 +685,7 @@ module YoutubeAPI
# Multiple encodings can be combined, and are listed in the order
# in which they were applied. E.g: "deflate, gzip" means that the
# content must be first "gunzipped", then "defated".
- encodings.split(',').reverse.each do |enc|
+ encodings.split(',').reverse!.each do |enc|
case enc.strip(' ')
when "gzip"
body_io = Compress::Gzip::Reader.new(body_io, sync_close: true)
@@ -695,6 +695,6 @@ module YoutubeAPI
end
end
- return body_io.gets_to_end
+ body_io.gets_to_end
end
end # End of module