#### Source code for /var/www/kryogenix.org/html/code/conposter/daemon/posterd.py ####


#!/usr/bin/python

"""
The background daemon for the Conservative poster system.

1. Look in QUEUE_DIR for the oldest N.txt file
2. Open that file, and read the lines:
  line 1: "thinking" slogan
  line 2: name of ttf font
  all other lines: main slogan
3. close the file
4. open images/poster.png, write the slogans on it
   in the font, save it as queue/N.png
5. delete N.txt
repeat until false.

"""

import os, stat, time, Image, ImageFont, ImageDraw

# Some constants; paths relative to the daemon's location
QUEUE_DIR = '../queue'
FONTS_DIR = 'fonts'
BASE_IMAGE_NAME = '../images/poster.png'
FONT_SIZES = {
  'tahomabd': 20, 
  'another': 80, 
  'martin': 80, 
  'morgan': 72, 
  'phillip': 80, 
  'rabin': 64, 
  'rai': 64, 
  'reid': 80, 
  'sandra': 64
}

FONTS = {}; 
BASE_IMAGE = None; 

def getNextFile(): 
  """find the next file that needs processing. Do this by creating a dictionary
     keyed on file creation time with file as the value, and then get the first
     one from the sorted dictionary."""
  d = dict(
        [(os.stat(os.path.join(QUEUE_DIR, f))[stat.ST_CTIME], f)
          for f in os.listdir(QUEUE_DIR)
          if os.path.splitext(f)[1] == '.txt']
      )
  k = d.keys()
  if not k:  return None
  k.sort()
  return d[k[0]]

def processFile(f): 
  global QUEUE_DIR
  thinking, main, font = getFileData(f)
  image = createImage(thinking, main, font)
  outfn = os.path.join(QUEUE_DIR, 
                       os.path.splitext(f)[0])+'.png'
  image.save(outfn, "PNG")
  os.remove(os.path.join(QUEUE_DIR, f))

def getFileData(f): 
  fp = open(os.path.join(QUEUE_DIR, f))
  t = fp.readline().strip()
  f = fp.readline().strip()
  m = ''.join(fp.readlines())
  return t, m, f

def createImage(t, m, f): 
  global FONTS, BASE_IMAGE
  i = BASE_IMAGE.copy()
  draw = ImageDraw.Draw(i)
  offsetHeight = 50
  for l in m.split('\r\n'):  # php writes crlf line endings
    l2 = ' '+l.strip()+' '
    if FONTS.has_key(f): 
      fnt = FONTS[f]
    else: 
      fnt = FONTS[FONTS.keys()[0]]
    w, h = draw.textsize(l2, font = fnt)
    left = 400-(w/2)
    draw.text((left, offsetHeight), l2, font = fnt, fill = 0)
    
    offsetHeight += h
    
  draw.text((10, 467), t, font = FONTS['tahomabd'], fill = 0)
  return i

def loadFonts(): 
  global FONTS_LIST, FONT_SIZES
  for f in os.listdir(FONTS_DIR): 
    fontname = os.path.splitext(f)[0].lower()
    if FONT_SIZES.has_key(fontname): 
      fsize = FONT_SIZES[fontname]
    else: 
      fsize = 36
    i = ImageFont.truetype(os.path.join(FONTS_DIR, f), fsize)
    FONTS[fontname] = i

def loadImage(): 
  global BASE_IMAGE
  BASE_IMAGE = Image.open(BASE_IMAGE_NAME)

def main(): 
  loadFonts()
  loadImage()
  while 1: 
    nextFile = getNextFile()
    if nextFile: 
      processFile(nextFile)
    time.sleep(5)

if __name__ == "__main__": 
  main()

[Created with py2html Ver:0.62]

Valid HTML 4.01!