linkding/bookmarks/services/importer.py

53 lines
1.3 KiB
Python
Raw Normal View History

2019-06-29 06:42:54 +00:00
from datetime import datetime
2019-06-30 05:15:46 +00:00
import bs4
from bs4 import BeautifulSoup
2019-06-29 06:42:54 +00:00
from django.contrib.auth.models import User
2019-07-01 20:05:38 +00:00
from bookmarks.models import Bookmark, parse_tag_string
from services.tags import get_or_create_tags
2019-06-29 06:42:54 +00:00
def import_netscape_html(html: str, user: User):
soup = BeautifulSoup(html, 'html.parser')
bookmark_tags = soup.find_all('dt')
for bookmark_tag in bookmark_tags:
_import_bookmark_tag(bookmark_tag, user)
2019-06-30 05:15:46 +00:00
def _import_bookmark_tag(bookmark_tag: bs4.Tag, user: User):
2019-06-29 06:42:54 +00:00
link_tag = bookmark_tag.a
if link_tag is None:
return
# Either modify existing bookmark for the URL or create new one
url = link_tag['href']
bookmark = _get_or_create_bookmark(url, user)
bookmark.url = url
bookmark.date_added = datetime.utcfromtimestamp(int(link_tag['add_date']))
bookmark.date_modified = bookmark.date_added
bookmark.unread = link_tag['toread'] == '1'
bookmark.title = link_tag.string
bookmark.owner = user
bookmark.save()
2019-06-30 05:15:46 +00:00
# Set tags
tag_string = link_tag['tags']
2019-07-01 20:05:38 +00:00
tag_names = parse_tag_string(tag_string)
tags = get_or_create_tags(tag_names, user)
2019-06-30 05:15:46 +00:00
bookmark.tags.set(tags)
bookmark.save()
2019-06-29 06:42:54 +00:00
def _get_or_create_bookmark(url: str, user: User):
try:
return Bookmark.objects.get(url=url, owner=user)
except Bookmark.DoesNotExist:
return Bookmark()