#!/usr/bin/python
# Download images from webcam as soon as it gets changed
# example webcams:
# http://lheppc17.unibe.ch/~einstein/images/Jungfrau/img630x504.jpg
# http://www.gurtenpark.ch/webcam/hscam002.jpg
# http://lheppc17.unibe.ch/~einstein/images/Bern/img630x504.jpg
# http://www.bern-altstadt.ch/livecam/bern_00001.jpg
# http://www.bern-altstadt.ch/livecam/bern_01001.jpg
# http://www.bern-altstadt.ch/livecam/bern_02001.jpg
import urllib,os,time,sys
url=sys.argv[1]
fSize=lambda x : os.stat(x)[6]
tdir='/root/j/'
bdir=url.split('/')[-1].split('.')[0]

tdir=bdir+'/'
lfn=bdir+'.log'
def log(x):
 x=time.strftime('%c - ')+x+'\n'
 if os.path.isfile(lfn): open(lfn,'a').write(x)
 else: open(lfn,'w').write(x)
 print x,
    
if not os.path.isdir(tdir): os.mkdir(tdir)
maxWait=200 # dont wait longer than that
nsec=10
isec=5
msec=5
lastSave=time.time()-nsec
while True:
 tryTime=time.time()
 try: bild=urllib.urlopen(url).read()
 except: log('Failed to fetch image!')
 last=filter(lambda x:x.find('.jpg')>-1,os.listdir(tdir))
 if last:
  last.sort()
  lastSize=fSize(tdir+last[-1])
  if len(bild)==lastSize or len(bild)<999: 
   log('Filesize identical, sleeping %ds...' % (isec))
   time.sleep(isec)
   continue
 ofn='%sbild%d.jpg' % (tdir,time.time())
 open(ofn,'w').write(bild)
 nsec=tryTime-lastSave-1
 if nsec<msec: nsec=msec
 if nsec>maxWait: nsec=maxWait
 lastSave=time.time()
 log('%d bytes written to %s\nSleeping %ds...' % (len(bild),ofn,nsec))
 time.sleep(nsec)