+
+class Place(WikidataModel):
+ name = models.CharField(_('name'), max_length=255, blank=True)
+ locative = models.CharField(_('locative'), max_length=255, blank=True, help_text=_('in…'))
+
+ class Meta:
+ verbose_name = _('place')
+ verbose_name_plural = _('places')
+
+ class Wikidata:
+ name = 'label'
+
+ def __str__(self):
+ return self.name
+
+
+class BookMonthlyStats(models.Model):
+ book = models.ForeignKey('catalogue.Book', models.CASCADE)
+ date = models.DateField()
+ views_reader = models.IntegerField(default=0)
+ views_page = models.IntegerField(default=0)
+
+ @classmethod
+ def build_for_month(cls, date):
+ date = date.replace(day=1)
+ period = 'month'
+
+ date = date.isoformat()
+ url = f'{settings.PIWIK_URL}?date={date}&filter_limit=-1&format=CSV&idSite={settings.PIWIK_WL_SITE_ID}&language=pl&method=Actions.getPageUrls&module=API&period={period}&segment=&token_auth={settings.PIWIK_TOKEN}&flat=1'
+ data = urlopen(url).read().decode('utf-16')
+ lines = data.split('\n')[1:]
+ for line in lines:
+ m = re.match('^/katalog/lektura/([^,./]+)\.html,', line)
+ if m is not None:
+ which = 'views_reader'
+ else:
+ m = re.match('^/katalog/lektura/([^,./]+)/,', line)
+ if m is not None:
+ which = 'views_page'
+ if m is not None:
+ slug = m.group(1)
+ _url, _uviews, views, _rest = line.split(',', 3)
+ views = int(views)
+ try:
+ book = Book.objects.get(slug=slug)
+ except Book.DoesNotExist:
+ continue
+ else:
+ cls.objects.update_or_create(
+ book=book, date=date,
+ defaults={which: views}
+ )
+ book.update_monthly_stats()