#!/usr/bin/env python

# This script polls an image every second and updates it on the screen
# It also reads the thttpd log and if a new record exists prints a message
# saying the web server is being accessed.
# The webcam image gets updated using the webcam program

# Author: Pat Carr (c) 2005
# Released under the GNU Public License 2.0

import pygtk
pygtk.require('2.0')
import gtk
import gobject

class ImagesExample:
    image = gtk.Image()
    text = gtk.Label()
    prev_line = ""
    webcam = "/var/www/thttpd/html/webcam.jpeg"
    log = "/var/log/thttpd.log"

    # when invoked (via signal delete_event), terminates the application.
    def close_application(self, widget, event, data=None):
        gtk.main_quit()
        return False

    # is invoked when the button is clicked.  It just prints a message.
    def button_clicked(self, widget, data=None):
        self.image.set_from_file(self.webcam)

    def refresh(self):
        self.image.set_from_file(self.webcam)
        f = open(self.log, "rb")
        f.seek(-512, 2)                 # position at (end - 512 bytes)
        data = f.read(512)              # read a 512 bytes chunk
        line = data.split('\n')[-2]	    # last line in log
        if self.prev_line == line or self.prev_line == "": 
            self.text.set_markup("<span size=\"x-large\" foreground=\"black\">No Visitors</span>")
        else:
            self.text.set_markup("<span size=\"x-large\" foreground=\"red\">Broadcasting!</span>")
        self.prev_line = line
        timer = gobject.timeout_add(1000, self.refresh)
		

    def __init__(self):
        # create the main window, and attach delete_event signal to terminating
        # the application
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.connect("delete_event", self.close_application)
        window.set_border_width(10)
        window.show()

        # a horizontal box to hold the buttons
        hbox = gtk.VBox()
        hbox.show()
        window.add(hbox)

        self.image.set_from_file(self.webcam)
        self.image.show()
        # a button to contain the image widget
        button = gtk.Button()
        button.add(self.image)
        button.show()
        hbox.pack_start(button)
        button.connect("clicked", self.button_clicked, "1")

        self.text.set_markup("<span size=\"x-large\" foreground=\"black\">No Visitors</span>")
        self.text.show()
        hbox.pack_start(self.text)

        timer = gobject.timeout_add(1000, self.refresh)

def main():
    gtk.main()
    return 0

if __name__ == "__main__":
    ImagesExample()
    main()

