linkding/bookmarks/services/importer.py

71 lines
2.0 KiB
Python
Raw Normal View History

import logging
from dataclasses import dataclass
2019-06-29 06:42:54 +00:00
from datetime import datetime
from django.contrib.auth.models import User
2019-07-01 20:05:38 +00:00
from bookmarks.models import Bookmark, parse_tag_string
from bookmarks.services.parser import parse, NetscapeBookmark
2019-07-03 15:18:29 +00:00
from bookmarks.services.tags import get_or_create_tags
2019-06-29 06:42:54 +00:00
logger = logging.getLogger(__name__)
@dataclass
class ImportResult:
total: int = 0
success: int = 0
failed: int = 0
2019-06-29 06:42:54 +00:00
def import_netscape_html(html: str, user: User):
result = ImportResult()
try:
netscape_bookmarks = parse(html)
except:
logging.exception('Could not read bookmarks file.')
raise
2019-06-29 06:42:54 +00:00
for netscape_bookmark in netscape_bookmarks:
result.total = result.total + 1
try:
_import_bookmark_tag(netscape_bookmark, user)
result.success = result.success + 1
except:
shortened_bookmark_tag_str = str(netscape_bookmark)[:100] + '...'
logging.exception('Error importing bookmark: ' + shortened_bookmark_tag_str)
result.failed = result.failed + 1
return result
2019-06-29 06:42:54 +00:00
def _import_bookmark_tag(netscape_bookmark: NetscapeBookmark, user: User):
2019-06-29 06:42:54 +00:00
# Either modify existing bookmark for the URL or create new one
bookmark = _get_or_create_bookmark(netscape_bookmark.href, user)
2019-06-29 06:42:54 +00:00
bookmark.url = netscape_bookmark.href
bookmark.date_added = datetime.utcfromtimestamp(int(netscape_bookmark.date_added)).astimezone()
2019-06-29 06:42:54 +00:00
bookmark.date_modified = bookmark.date_added
bookmark.unread = False
bookmark.title = netscape_bookmark.title
if netscape_bookmark.description:
bookmark.description = netscape_bookmark.description
2019-06-29 06:42:54 +00:00
bookmark.owner = user
bookmark.save()
2019-06-30 05:15:46 +00:00
# Set tags
tag_names = parse_tag_string(netscape_bookmark.tag_string)
2019-07-01 20:05:38 +00:00
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()