mirror of
https://git.sr.ht/~edwardloveall/scribe
synced 2025-12-10 12:41:23 +00:00
Better article ID parsing
A new ArticleIdParser class takes in an HTTP::Request object and parses the article ID from it. It intentinoally fails on tag, user, and search pages and attempts to only catch articles.
This commit is contained in:
@@ -2,7 +2,7 @@ require "json"
|
||||
|
||||
class Articles::Show < BrowserAction
|
||||
fallback do
|
||||
post_id = maybe_post_id(context.request)
|
||||
post_id = ArticleIdParser.parse(context.request)
|
||||
case post_id
|
||||
in Monads::Just
|
||||
response = client_class.post_data(post_id.value!)
|
||||
@@ -18,27 +18,6 @@ class Articles::Show < BrowserAction
|
||||
end
|
||||
end
|
||||
|
||||
def maybe_post_id(request : HTTP::Request)
|
||||
from_params = post_id_from_params(request.query_params)
|
||||
from_path = post_id_from_path(request.path)
|
||||
from_path.or(from_params)
|
||||
end
|
||||
|
||||
def post_id_from_path(request_path : String)
|
||||
Monads::Try(Regex::MatchData)
|
||||
.new(->{ request_path.match(/([0-9a-f]+)$/i) })
|
||||
.to_maybe
|
||||
.fmap(->(matches : Regex::MatchData) { matches[1] })
|
||||
end
|
||||
|
||||
def post_id_from_params(params : URI::Params)
|
||||
maybe_uri = Monads::Try(String)
|
||||
.new(->{ params["redirectUrl"] })
|
||||
.to_maybe
|
||||
.fmap(->(url : String) { URI.parse(url) })
|
||||
.bind(->(uri : URI) { post_id_from_path(uri.path) })
|
||||
end
|
||||
|
||||
def client_class
|
||||
if use_local?
|
||||
LocalClient
|
||||
|
||||
31
src/classes/article_id_parser.cr
Normal file
31
src/classes/article_id_parser.cr
Normal file
@@ -0,0 +1,31 @@
|
||||
class ArticleIdParser
|
||||
include Monads
|
||||
|
||||
ID_REGEX = /[\/\-]([0-9a-f]+)/i
|
||||
|
||||
def self.parse(request : HTTP::Request)
|
||||
new.parse(request)
|
||||
end
|
||||
|
||||
def parse(request : HTTP::Request) : Maybe
|
||||
from_params = post_id_from_params(request.query_params)
|
||||
from_path = post_id_from_path(request.path)
|
||||
from_path.or(from_params)
|
||||
end
|
||||
|
||||
private def post_id_from_path(request_path : String)
|
||||
return Nothing(String).new if request_path.starts_with?("/tag/")
|
||||
Try(Regex::MatchData)
|
||||
.new(->{ request_path.match(ID_REGEX) })
|
||||
.to_maybe
|
||||
.fmap(->(matches : Regex::MatchData) { matches[1] })
|
||||
end
|
||||
|
||||
private def post_id_from_params(params : URI::Params)
|
||||
maybe_uri = Try(String)
|
||||
.new(->{ params["redirectUrl"] })
|
||||
.to_maybe
|
||||
.fmap(->(url : String) { URI.parse(url) })
|
||||
.bind(->(uri : URI) { post_id_from_path(uri.path) })
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user