# CCS Computer Science # Webcam Daemon # # Douglas Thrift # # $Id$ import getpass import keyring import os import pycurl import servicemanager import tempfile import threading import time import VideoCapture import win32service, win32serviceutil class WebcamService(win32serviceutil.ServiceFramework): _svc_name_ = 'CCSCSLabWebcam' _svc_display_name_ = 'CCS CS Lab Webcam' _svc_description_ = 'Captures images from the webcam and uploads them.' _svc_deps_ = ('Dnscache',) def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self._stop = threading.Event() def SvcDoRun(self): cam = VideoCapture.Device() cam.setResolution(320, 240) with tempfile.NamedTemporaryFile(prefix = 'webcam_', suffix = '.jpg', delete = False) as file: image = file.name with open(os.path.join(os.path.expanduser('~'), 'webcam.dat')) as file: number = file.readline().rstrip() user = getpass.getuser() curl = pycurl.Curl() curl.setopt(pycurl.CAINFO, os.path.join(os.path.abspath(os.path.dirname(__file__)), 'cacert.crt')) curl.setopt(pycurl.URL, 'https://cscl.creativestudies.org/webcam/upload') curl.setopt(pycurl.USERPWD, '%s:%s' % (user, str(keyring.get_password(self._svc_name_, user)))) curl.setopt(pycurl.VERBOSE, 1) while not self._stop.isSet(): start = time.time() cam.getImage().save(image, options = 'optimize') curl.setopt(pycurl.HTTPPOST, [('n', number), ('i', (pycurl.FORM_FILE, image, pycurl.FORM_CONTENTTYPE, 'image/jpeg', pycurl.FORM_FILENAME, 'webcam.jpg'))]) try: curl.perform() except pycurl.error, error: servicemanager.LogErrorMsg('%s: %s' % (str(error.__class__), str(error))) while not self._stop.isSet() and time.time() - start < 5: try: time.sleep(0.5) except IOError: pass os.unlink(image) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self._stop.set() if __name__ == '__main__': import sys try: index = sys.argv.index('--prompt') except ValueError: pass else: import win32console win32console.SetConsoleTitle(WebcamService._svc_display_name_) while True: try: username = raw_input('Account: ') if not username: print 'Empty account name.' continue password = getpass.getpass('Password: ') if not password: print 'Empty password.' continue if password != getpass.getpass('Confirm Password: '): print 'Password and confirm password mismatched.' continue except KeyboardInterrupt: print else: keyring.set_password(WebcamService._svc_name_, username, password) sys.argv[index:index + 1] = ['--username', '.\\' + username, '--password', password] break path = os.path.join(os.path.expanduser('~'), 'webcam.dat') if not os.path.exists(path): while True: try: webcam = int(raw_input('Webcam: ')) except KeyboardInterrupt: print except ValueError: pass else: with open(path, 'w') as file: file.write('%u\n' % webcam) break win32serviceutil.HandleCommandLine(WebcamService)