Download visit stats.
authorRadek Czajka <rczajka@rczajka.pl>
Mon, 31 May 2021 13:37:27 +0000 (15:37 +0200)
committerRadek Czajka <rczajka@rczajka.pl>
Mon, 31 May 2021 13:37:27 +0000 (15:37 +0200)
src/stats/admin.py [new file with mode: 0644]
src/stats/models.py

diff --git a/src/stats/admin.py b/src/stats/admin.py
new file mode 100644 (file)
index 0000000..979f180
--- /dev/null
@@ -0,0 +1,5 @@
+from django.contrib import admin
+from . import models
+
+
+admin.site.register(models.Visits)
index e69de29..ea1a790 100644 (file)
@@ -0,0 +1,36 @@
+import re
+from django.conf import settings
+from django.db import models
+
+
+class Visits(models.Model):
+    book = models.ForeignKey('catalogue.Book', models.CASCADE)
+    year = models.PositiveSmallIntegerField()
+    month = models.PositiveSmallIntegerField()
+    views = models.IntegerField()
+    unique_views = models.IntegerField()
+
+    @classmethod
+    def build_month(cls, year, month):
+        ### TODO: Delete existing?
+
+        date = f'{year}-{month:02d}'
+        url = f'{settings.PIWIK_URL}?date={date}&filter_limit=-1&format=CSV&idSite={settings.PIWIK_SITE_ID}&language=pl&method=Actions.getPageUrls&module=API&period=month&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:
+                slug = m.group(1)
+                _url, uviews, views = line.split(',', 3)
+                uviews = int(uviews)
+                views = int(views)
+                try:
+                    book = Book.objects.get(slug=slug)
+                except Book.DoesNotExists:
+                    continue
+                else:
+                    cls.objects.create(
+                        book=book, year=year, month=month,
+                        views=views, uviews=uviews
+                    )