added page configuration module randomphoto-piwigo
authorSabine Engelhardt (Becker) <frosch@atari-frosch.de>
Fri, 12 Jul 2019 19:34:55 +0000 (21:34 +0200)
committerSabine Engelhardt (Becker) <frosch@atari-frosch.de>
Fri, 12 Jul 2019 19:34:55 +0000 (21:34 +0200)
CHANGELOG
ToDo
defaults.py
makesite.py
modules/randomphoto-piwigo.py [new file with mode: 0755]
piwigo-db.txt
randomphoto-piwigo.py [deleted file]

index 9219940..6aa00f5 100644 (file)
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,22 @@
+2019-07-11 frosch@atari-frosch.de
+
+    * makesite.py: After adding a new variable of type dict named
+      addpagecontent that can be set in a single page.py file it is now
+      possible to add variable page content with each recreation of a page.
+      The content can be created by a function within the page.py file
+      and gets passed on by addpagecontent to makesite.
+
+    * Version number set to 0.2, as this is an important step forward in
+      order to create semi-dynamic static web pages.
+
+    * New folder modules for Python modules that can be added to page.py
+      files in order to create additional page content.
+
+    * First module is randomphoto-piwigo.py, which retrieves a random photo
+      from a Piwigo installation's database (of course only if you have
+      legal access to that database) to be shown on a static web page and
+      renewed every time the site gets recreated.
+
 2019-07-09 frosch@atari-frosch.de
 
     * makesite.py: It is now possible to set a different target path in the
diff --git a/ToDo b/ToDo
index bb711b9..a173cbe 100644 (file)
--- a/ToDo
+++ b/ToDo
@@ -45,11 +45,4 @@ makesite.py:
 
 * FEAT: create sitemap.xml
 
-* FEAT: Use addtobody{} and prepare functions that include content from
-        other sources and sites, Twitter, GNUsocial, Mastodon, Diaspora, a
-        git, an rss feed, …
-
-* FEAT: Add random photo from a Piwigo instance using the now stand-alone
-  script randomphoto-piwigo.py
-
 * FEAT: create redirect for apache2 and nginx when moving a file?
index 0342cbe..88b4498 100755 (executable)
@@ -1,5 +1,5 @@
 #!/usr/bin/env python3
 # -*- coding: utf8 -*-
 
-myversion = "0.1"
+myversion = "0.2"
 generator = "htmlglue v" + myversion
index 2265c7a..e7505c7 100755 (executable)
@@ -313,6 +313,7 @@ def createpage(filename, sitepath, targetdir, snippets):
         purefilename = os.path.basename(filename)
         filepath = filename.replace(purefilename, "")
         targetfile = targetdir + purefilename + "l"
+
         pagepy = filename.replace(".htm", ".py")
         pageconfig = run_path(pagepy)
         contenttime = os.path.getmtime(filename)
@@ -401,7 +402,7 @@ def createpage(filename, sitepath, targetdir, snippets):
                     menupos = "below"
 
             if settings.headcontent == True:
-                # this possibility is not tested yet!
+                # this option is not tested yet!
                 contentstartfile = snippets["contentstart"]
                 f = open(contentstartfile, "r")
                 contentstarthtml = f.read()
@@ -416,23 +417,23 @@ def createpage(filename, sitepath, targetdir, snippets):
             try:
                 settings.addtobody
             except AttributeError:
-                addtobody = {}
+                pass
             else:
                 addtobody = settings.addtobody
 
+            # addtobody content from the settings is not yet added to the
+            # content, but actually not needed; removal is in consideration
+
             try:
-                pageconfig["addtobody"]
+                pageconfig["addpagecontent"]
             except KeyError:
-                pass
+                logging.debug('No additional content found.')
             else:
-                addtobody += pageconfig["addtobody"]
-                for addto in addtobody:
+                addpagecontent = pageconfig["addpagecontent"]
+                for addto in addpagecontent:
                     if addto in content:
-                        addfile = sitepath + "/SNIPPETS/" + addtobody[addto]
-                        f = open(addfile, "r")
-                        addpart = f.read()
-                        f.close()
-                        content = content.replace(addto, addpart)
+                        content = content.replace(addto, addpagecontent[addto])
+                        logging.debug('Content %s added to page.', addto)
 
             htmlpage += content
 
diff --git a/modules/randomphoto-piwigo.py b/modules/randomphoto-piwigo.py
new file mode 100755 (executable)
index 0000000..4acf4f5
--- /dev/null
@@ -0,0 +1,163 @@
+#!/usr/bin/env python3
+# -*- coding: utf8 -*-
+
+from sys import argv
+
+def randomphoto(piwigoconfig, basewidth, baseheight, randompiclog, piwigosite, randomsnippet):
+    import pymysql
+    import random
+    from PIL import Image
+    from datetime import datetime
+    from time import strftime
+
+    picdata = {}
+    f = open(piwigoconfig, "r")
+    pwgconfig = f.read()
+    f.close()
+    pwgconfiglines = pwgconfig.split("\n")
+    for line in pwgconfiglines:
+        if line.startswith("$conf['db_base']"):
+            lineparts = line.split(" ")
+            dbname = lineparts[2].replace("'", "")
+            dbname = dbname.replace(";", "")
+        elif line.startswith("$conf['db_user']"):
+            lineparts = line.split(" ")
+            dbuser = lineparts[2].replace("'", "")
+            dbuser = dbuser.replace(";", "")
+        elif line.startswith("$conf['db_password']"):
+            lineparts = line.split(" ")
+            dbpass = lineparts[2].replace("'", "")
+            dbpass = dbpass.replace(";", "")
+        elif line.startswith("$conf['db_host']"):
+            lineparts = line.split(" ")
+            dbhost = lineparts[2].replace("'", "")
+            dbhost = dbhost.replace(";", "")
+
+    # create the MySQL statement to retrieve the list of publicly available photos
+    if dbname != "" and dbuser != "" and dbpass != "" and dbhost != "":
+        getpubphotos = "SELECT id FROM pwg_images WHERE level = '0' and file LIKE '%.jpg'"
+        # level = 0 means publicly available
+        # there might be other files than .jpg if the plugin for videos is installed
+        db = pymysql.connect(dbhost, dbuser, dbpass, dbname)
+        cursor = db.cursor()
+        cursor.execute(getpubphotos)
+        pubphotolist = cursor.fetchall()
+        db.close()
+
+        # select a photo by random
+        photocount = len(pubphotolist)
+        picdata['number'] = str(photocount)
+        photodict = {}
+        for i in range(len(pubphotolist)):
+            photoid = int(pubphotolist[i][0])
+            photodict[i] = photoid
+
+        random.seed()
+        photolistnumber = random.randint(1, photocount)
+        photo = photodict[photolistnumber]
+        picdata['photoid'] = str(photo) 
+
+        # request the chosen photo with additional information
+        getinfo = "SELECT path, date_creation, name, comment, author FROM pwg_images where id = " + str(photo)
+        db = pymysql.connect(dbhost, dbuser, dbpass, dbname)
+        cursor = db.cursor()
+        cursor.execute(getinfo)
+        picinfo = cursor.fetchone()
+        # list example picinfo:
+        # ('./upload/2017/12/26/20171226004242-fc764b7e.jpg',
+        # datetime.datetime(2009, 4, 28, 20, 45, 17),
+        # '20090428-204517', None, 'Atari-Frosch')
+
+        # 0 = path; example: ./upload/2018/08/12/20180812185450-b8b65c68.jpg
+        filepath = picinfo[0][1:]
+        basepath = piwigoconfig.split("/local/")[0]
+        fullpath = basepath + filepath
+        img = Image.open(fullpath)
+        # rescale and save to target file
+        if img.size[0] > img.size[1]:
+            wpercent = (basewidth / float(img.size[0]))
+            hsize = int((float(img.size[1]) * float(wpercent)))
+            img = img.resize((basewidth, hsize), Image.ANTIALIAS)
+            img.save(pictargetfile)
+        else:
+            wpercent = (baseheight / float(img.size[1]))
+            wsize = int((float(img.size[0]) * float(wpercent)))
+            img = img.resize((wsize, baseheight), Image. ANTIALIAS)
+            img.save(pictargetfile)
+
+        pictime = picinfo[1]
+        # 1 = date_creation; this field has the format datetime
+        if pictime != None:
+            pictimestamp = pictime.strftime("%d.%m.%Y, %H:%M")
+        else:
+            pictimestamp = "(n/a)"
+        picdata['phototime'] = pictimestamp
+
+        # 2 = name; title of photo
+        picdata['title'] = picinfo[2]
+
+        # 3 = comment; photo description
+        if picinfo[3] == None:
+            picdata['descr'] = "&nbsp;"
+        else:
+            picdata['descr'] = picinfo[3]
+
+        # 4 = author name
+        picdata['author'] = picinfo[4]
+
+        getcat = "SELECT category_id FROM pwg_image_category where image_id = " + str(photo)
+        db = pymysql.connect(dbhost, dbuser, dbpass, dbname)
+        cursor = db.cursor()
+        cursor.execute(getcat)
+        category = cursor.fetchone()
+
+        if not piwigosite.endswith("/"):
+             piwigosite += "/"
+
+        picsource = piwigosite + "picture.php?/" + str(photo) + "/category/" + str(category[0])
+        picdata['piclink'] = picsource
+
+        curtime = datetime.now()
+        logtime = curtime.strftime("%b %d %H:%M:%S")
+        log = open(randompiclog, "a")
+        out = logtime + " " + str(photo) + " out of " + str(photocount) + ", " + filepath + "\n"
+        log.write(out)
+        log.close()
+
+
+        f = open(randomsnippet, "r")
+        snipcontent = f.read()
+        f.close()
+
+        snipcontent = snipcontent.replace("[PICSOURCE]", picdata['piclink'])
+        snipcontent = snipcontent.replace("[TITLE]", picdata['title'])
+        snipcontent = snipcontent.replace("[PICTIME]", picdata['phototime'])
+        snipcontent = snipcontent.replace("[AUTHOR]", picdata['author'])
+        snipcontent = snipcontent.replace("[DESCR]", picdata['descr'])
+        snipcontent = snipcontent.replace("[PHOTOID]", picdata['photoid'])
+        snipcontent = snipcontent.replace("[NUM]", picdata['number'])
+
+        from subprocess import call
+        contentfile = myfilename.replace(".py", ".htm")
+        call(["touch", contentfile])
+
+    return snipcontent
+
+###
+
+# replace $names with your configuration.
+
+piwigoconfig = "$piwigopath/local/config/database.inc.php"
+# target width of photos in landscape format
+basewidth = 600
+# target height of photos in portrait format
+baseheight = 600
+pictargetfile = "$targetpath/randompic.jpg"
+randompiclog = "$logpath/random.log"
+piwigosite = "https://$yourpiwigosite"
+
+myfilename = argv[0]
+randomsnippet = myfilename.rsplit("/", 1)[0] + "/SNIPPETS/randomphoto.htm"
+addphoto = randomphoto(piwigoconfig, basewidth, baseheight, randompiclog, piwigosite, randomsnippet)
+addpagecontent = {}
+addpagecontent['[RANDOMPHOTO]'] = addphoto
index 3305cca..08e5828 100644 (file)
@@ -31,3 +31,21 @@ MariaDB [piwigodb]> show columns from pwg_images;
 file = original file name
 name = title
 level = level of privacy (0: for everyone)
+
+
+MariaDB [piwigodb]> show columns from pwg_image_category;
++-------------+-----------------------+------+-----+---------+-------+
+| Field       | Type                  | Null | Key | Default | Extra |
++-------------+-----------------------+------+-----+---------+-------+
+| image_id    | mediumint(8) unsigned | NO   | PRI | 0       |       |
+| category_id | smallint(5) unsigned  | NO   | PRI | 0       |       |
+| rank        | mediumint(8) unsigned | YES  |     | NULL    |       |
++-------------+-----------------------+------+-----+---------+-------+
+
+MariaDB [piwigodb]> show columns from pwg_copyrights_media;
++----------+---------+------+-----+---------+-------+
+| Field    | Type    | Null | Key | Default | Extra |
++----------+---------+------+-----+---------+-------+
+| media_id | int(11) | NO   | PRI | NULL    |       |
+| cr_id    | int(11) | NO   |     | NULL    |       |
++----------+---------+------+-----+---------+-------+
diff --git a/randomphoto-piwigo.py b/randomphoto-piwigo.py
deleted file mode 100755 (executable)
index ef05c6c..0000000
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/env python3
-
-import pymysql
-import random
-from PIL import Image
-from datetime import datetime
-from time import strftime
-
-'''
-randomphoto-piwigo.py Version 0.1 by Atari-Frosch
-started: 2019-04-28
-'''
-
-pwgconfigfile = "/srv/atarifrosch-media/local/config/database.inc.php"
-pwgphpconfig = open(pwgconfigfile, "r")
-pwgconfig = pwgphpconfig.read()
-pwgphpconfig.close()
-pwgconfiglines = pwgconfig.split("\n")
-for line in pwgconfiglines:
-    if line.startswith("$conf['db_base']"):
-        lineparts = line.split(" ")
-        dbname = lineparts[2].replace("'", "")
-        dbname = dbname.replace(";", "")
-    elif line.startswith("$conf['db_user']"):
-        lineparts = line.split(" ")
-        dbuser = lineparts[2].replace("'", "")
-        dbuser = dbuser.replace(";", "")
-    elif line.startswith("$conf['db_password']"):
-        lineparts = line.split(" ")
-        dbpass = lineparts[2].replace("'", "")
-        dbpass = dbpass.replace(";", "")
-    elif line.startswith("$conf['db_host']"):
-        lineparts = line.split(" ")
-        dbhost = lineparts[2].replace("'", "")
-        dbhost = dbhost.replace(";", "")
-
-# build the MySQL statement to retrieve the list of publicly available photos
-if dbname != "" and dbuser != "" and dbpass != "" and dbhost != "":
-    getpubphotos = "SELECT id FROM pwg_images WHERE level = '0' and file LIKE '%.jpg'"
-    # level = 0 means publicly available
-    # if the plugin for videos is installed, there might be other files than .jpg
-    db = pymysql.connect(dbhost, dbuser, dbpass, dbname)
-    cursor = db.cursor()
-    cursor.execute(getpubphotos)
-    pubphotolist = cursor.fetchall()
-    db.close()
-
-    # select a photo by random
-    photocount = len(pubphotolist)
-    photodict = {}
-    for i in range(len(pubphotolist)):
-        photoid = int(pubphotolist[i][0])
-        photodict[i] = photoid
-
-    random.seed()
-    photolistnumber = random.randint(1, photocount)
-    photo = photodict[photolistnumber]
-
-    # request the chosen photo
-    # first we need the path to the actual image file
-    getpath = "SELECT path FROM pwg_images where id = " + str(photo)
-    db = pymysql.connect(dbhost, dbuser, dbpass, dbname)
-    cursor = db.cursor()
-    cursor.execute(getpath)
-    path = cursor.fetchone()
-    # path looks like ./upload/2018/08/12/20180812185450-b8b65c68.jpg
-    filepath = path[0][1:]
-    basepath = pwgconfigfile.split("/local/")[0]
-    fullpath = basepath + filepath
-    img = Image.open(fullpath)
-    # rescale and save to target file
-    if img.size[0] > img.size[1]:
-        basewidth = 600
-        wpercent = (basewidth / float(img.size[0]))
-        hsize = int((float(img.size[1]) * float(wpercent)))
-        img = img.resize((basewidth, hsize), Image.ANTIALIAS)
-        img.save("/srv/atarifrosch/bilder/randompic.jpg")
-    else:
-        baseheight = 500
-        wpercent = (baseheight / float(img.size[1]))
-        wsize = int((float(img.size[0]) * float(wpercent)))
-        img = img.resize((wsize, baseheight), Image. ANTIALIAS)
-        img.save("/srv/atarifrosch/bilder/randompic.jpg")
-
-    curtime = datetime.now()
-    logtime = curtime.strftime("%b %d %H:%M:%S")
-    log = open("/home/frosch/scripts/random.log", "a")
-    out = logtime + " " + fullpath + "\n"
-    log.write(out)
-    log.close()
-