bookwyrm/fedireads/openlibrary.py

55 lines
1.7 KiB
Python
Raw Normal View History

2020-01-25 21:46:30 +00:00
''' activitystream api and books '''
from django.core.exceptions import ObjectDoesNotExist
2020-01-25 23:25:19 +00:00
from fedireads.models import Author, Book, Work
2020-01-27 01:55:02 +00:00
from fedireads.settings import OL_URL
2020-01-25 21:46:30 +00:00
import requests
2020-01-27 01:55:02 +00:00
def get_or_create_book(olkey, user=None, update=True):
''' add a book '''
2020-01-25 21:46:30 +00:00
# check if this is a valid open library key, and a book
2020-01-27 03:50:22 +00:00
olkey = olkey
2020-01-27 01:55:02 +00:00
response = requests.get(OL_URL + olkey + '.json')
2020-01-25 21:46:30 +00:00
# get the existing entry from our db, if it exists
try:
2020-01-28 02:47:54 +00:00
book = Book.objects.get(openlibrary_key=olkey)
2020-01-27 01:55:02 +00:00
if not update:
return book
2020-01-25 21:46:30 +00:00
except ObjectDoesNotExist:
2020-01-28 02:47:54 +00:00
book = Book(openlibrary_key=olkey)
2020-01-25 21:46:30 +00:00
data = response.json()
book.data = data
2020-01-27 01:55:02 +00:00
if user and user.is_authenticated:
book.added_by = user
2020-01-25 21:46:30 +00:00
book.save()
for work_id in data['works']:
work_id = work_id['key']
book.works.add(get_or_create_work(work_id))
2020-01-25 23:25:19 +00:00
for author_id in data['authors']:
author_id = author_id['key']
book.authors.add(get_or_create_author(author_id))
2020-01-27 01:55:02 +00:00
return book
2020-01-25 21:46:30 +00:00
def get_or_create_work(olkey):
2020-01-27 01:55:02 +00:00
''' load em up '''
2020-01-25 21:46:30 +00:00
try:
2020-01-28 02:47:54 +00:00
work = Work.objects.get(openlibrary_key=olkey)
2020-01-25 21:46:30 +00:00
except ObjectDoesNotExist:
2020-01-27 01:55:02 +00:00
response = requests.get(OL_URL + olkey + '.json')
2020-01-25 21:46:30 +00:00
data = response.json()
2020-01-28 02:47:54 +00:00
work = Work(openlibrary_key=olkey, data=data)
2020-01-25 21:46:30 +00:00
work.save()
return work
2020-01-25 23:25:19 +00:00
def get_or_create_author(olkey):
2020-01-27 01:55:02 +00:00
''' load that author '''
2020-01-25 23:25:19 +00:00
try:
2020-01-28 02:47:54 +00:00
author = Author.objects.get(openlibrary_key=olkey)
2020-01-25 23:25:19 +00:00
except ObjectDoesNotExist:
2020-01-27 01:55:02 +00:00
response = requests.get(OL_URL + olkey + '.json')
2020-01-25 23:25:19 +00:00
data = response.json()
2020-01-28 02:47:54 +00:00
author = Author(openlibrary_key=olkey, data=data)
2020-01-25 23:25:19 +00:00
author.save()
return author