public-health-ch/feedler/models/admin.py

76 lines
2.6 KiB
Python
Raw Normal View History

2017-07-03 11:36:01 +00:00
# -*- coding: utf-8 -*-
import requests, json, codecs
from django.contrib import admin
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.core.mail import send_mail
from wagtail.contrib.settings.models import BaseSetting, register_setting
2017-10-12 22:08:15 +00:00
from wagtail.wagtailadmin import messages
2017-07-03 11:36:01 +00:00
2017-07-03 14:01:44 +00:00
from .models import Entry, Stream
2017-07-04 09:05:58 +00:00
import feedler.feedparser as feedparser
2017-07-03 14:01:44 +00:00
import logging
logger = logging.getLogger('feedler')
2017-07-03 11:36:01 +00:00
# Feedly integration module
@register_setting
class FeedlySettings(BaseSetting):
feedly_auth = models.TextField(
help_text='Your developer authorization key', blank=True)
feedly_pages = models.IntegerField(
choices=(
(1, '2'),
(2, '5'),
(3, '10'),
(4, '50'),
2017-09-20 10:18:12 +00:00
), blank=True, null=True, editable=False,
2017-07-03 11:36:01 +00:00
help_text='How many pages to fetch?'
)
2017-09-20 10:18:12 +00:00
feedly_stream = models.ManyToManyField(Stream,
help_text='Which streams to update')
2017-07-03 11:36:01 +00:00
class Meta:
verbose_name = 'Feedly'
2017-07-03 14:01:44 +00:00
API_BASEURL = 'https://cloud.feedly.com/v3/streams/contents?streamId='
2017-07-03 11:36:01 +00:00
@receiver(pre_save, sender=FeedlySettings)
def handle_save_settings(sender, instance, *args, **kwargs):
2017-07-03 14:01:44 +00:00
if instance.feedly_auth:
streams = instance.feedly_stream.all()
for stream in streams:
# Start a request to download the feed
logger.info("Processing stream %s" % stream.title)
url = API_BASEURL + stream.ident
headers = {
'Authorization': 'OAuth ' + instance.feedly_auth
}
contents = requests.get(url, headers=headers).json()
if 'errorMessage' in contents:
2017-10-12 22:08:15 +00:00
# Usually this is a token expired
if 'token expired' in contents['errorMessage']:
# TODO: request new token
pass
logger.error(contents['errorMessage'])
messages.error(sender, "Failed to fetch items: %s" % contents['errorMessage'])
return
2017-07-03 14:01:44 +00:00
for raw_entry in contents['items']:
eid = raw_entry['id']
# Create or update data
try:
entry = Entry.objects.get(entry_id=eid)
logger.info("Updating entry '%s'" % eid)
except Entry.DoesNotExist:
logger.info("Adding entry '%s'" % eid)
entry = Entry()
2017-09-04 21:03:01 +00:00
# Parse the Feedly object
2017-07-04 09:05:58 +00:00
entry = feedparser.parse(entry, raw_entry, stream)
2017-09-04 21:03:01 +00:00
# Persist resulting object
2017-07-03 14:01:44 +00:00
entry.save()