linkding/bookmarks/services/bookmarks.py

62 lines
1.9 KiB
Python
Raw Normal View History

2019-06-29 00:01:26 +00:00
import requests
from bs4 import BeautifulSoup
2019-06-28 17:37:41 +00:00
from django.contrib.auth.models import User
from django.utils import timezone
2019-07-01 20:05:38 +00:00
from bookmarks.models import Bookmark, BookmarkForm, parse_tag_string
from services.tags import get_or_create_tags
2019-06-28 17:37:41 +00:00
2019-07-01 20:05:38 +00:00
def create_bookmark(form: BookmarkForm, current_user: User):
bookmark = form.save(commit=False)
2019-06-28 17:37:41 +00:00
# Update website info
_update_website_metadata(bookmark)
# Set currently logged in user as owner
bookmark.owner = current_user
# Set dates
bookmark.date_added = timezone.now()
2019-06-28 22:27:20 +00:00
bookmark.date_modified = timezone.now()
bookmark.save()
2019-07-01 20:05:38 +00:00
# Update tag list
_update_bookmark_tags(bookmark, form.data['tag_string'], current_user)
bookmark.save()
2019-06-28 22:27:20 +00:00
2019-07-01 20:05:38 +00:00
def update_bookmark(form: BookmarkForm, current_user: User):
bookmark = form.save(commit=False)
2019-06-28 22:27:20 +00:00
# Update website info
_update_website_metadata(bookmark)
2019-07-01 20:05:38 +00:00
# Update tag list
_update_bookmark_tags(bookmark, form.data['tag_string'], current_user)
2019-06-28 22:27:20 +00:00
# Update dates
bookmark.date_modified = timezone.now()
2019-06-28 17:37:41 +00:00
bookmark.save()
def _update_website_metadata(bookmark: Bookmark):
2019-06-29 00:01:26 +00:00
# noinspection PyBroadException
try:
page_text = load_page(bookmark.url)
soup = BeautifulSoup(page_text, 'html.parser')
title = soup.title.string if soup.title is not None else None
description_tag = soup.find('meta', attrs={'name': 'description'})
description = description_tag['content'] if description_tag is not None else None
bookmark.website_title = title
bookmark.website_description = description
except Exception:
bookmark.website_title = None
bookmark.website_description = None
2019-07-01 20:05:38 +00:00
def _update_bookmark_tags(bookmark: Bookmark, tag_string: str, user: User):
tag_names = parse_tag_string(tag_string, ' ')
tags = get_or_create_tags(tag_names, user)
bookmark.tags.set(tags)
2019-06-29 00:01:26 +00:00
def load_page(url: str):
r = requests.get(url)
return r.text