2018-07-02 19:19:50 -04:00
|
|
|
from urllib.parse import urlparse
|
|
|
|
|
|
|
|
from django.contrib.sites.models import Site
|
|
|
|
from django.http import HttpResponse
|
|
|
|
from django.urls import resolve, Resolver404
|
|
|
|
from micropub.views import error
|
2018-07-02 19:41:00 -04:00
|
|
|
from lemoncurry.middleware import ResponseException
|
2018-07-02 19:19:50 -04:00
|
|
|
|
|
|
|
from .models import Entry
|
|
|
|
|
|
|
|
|
2018-07-02 19:41:00 -04:00
|
|
|
def from_url(url: str) -> Entry:
|
2018-07-02 19:19:50 -04:00
|
|
|
domain = Site.objects.get_current().domain
|
|
|
|
if not url:
|
2018-07-02 19:41:00 -04:00
|
|
|
raise ResponseException(error.bad_req('url parameter required'))
|
2018-07-02 19:19:50 -04:00
|
|
|
if '//' not in url:
|
|
|
|
url = '//' + url
|
|
|
|
parts = urlparse(url, scheme='https')
|
|
|
|
if parts.scheme not in ('http', 'https') or parts.netloc != domain:
|
2018-07-02 19:41:00 -04:00
|
|
|
raise ResponseException(error.bad_req('url does not point to this site'))
|
2018-07-02 19:19:50 -04:00
|
|
|
|
|
|
|
try:
|
|
|
|
match = resolve(parts.path)
|
|
|
|
except Resolver404:
|
2018-07-02 19:41:00 -04:00
|
|
|
raise ResponseException(error.bad_req('url does not point to a valid page on this site'))
|
2018-07-02 19:19:50 -04:00
|
|
|
|
|
|
|
if match.view_name != 'entries:entry':
|
2018-07-02 19:41:00 -04:00
|
|
|
raise ResponseException(error.bad_req('url does not point to an entry on this site'))
|
2018-07-02 19:19:50 -04:00
|
|
|
|
|
|
|
try:
|
|
|
|
entry = Entry.objects.get(pk=match.kwargs['id'])
|
|
|
|
except Entry.DoesNotExist:
|
2018-07-02 19:41:00 -04:00
|
|
|
raise ResponseException(error.bad_req('url does not point to an existing entry'))
|
2018-07-02 19:19:50 -04:00
|
|
|
|
|
|
|
return entry
|