#!/usr/bin/env python # Sync # # Douglas Thrift # # $Id$ from __init__ import lock import base64 from ccscslab.laptops.jsons import SyncJSONEncoder, sync_object_hook from ccscslab.laptops.models import Entry, Sync from django.db import transaction from django.db.models import Q import getpass from M2Crypto import m2urllib2, SSL import optparse import urllib, urllib2 try: import simplejson as json except ImportError: import json @transaction.commit_on_success def main(): parser = optparse.OptionParser() parser.add_option('-D', '--debug', action = 'store_true', dest = 'debug') parser.add_option('-s', '--secret', action = 'store_true', dest = 'secret') options = parser.parse_args()[0] lock(options.debug) sync, inserted = Sync.sync(True) if options.debug: print 'sync:\n %s\n %s' % (sync, 'inserted' if inserted else 'updated') entries = sync.entry_set.all() if sync.last_uuid: if options.debug: print ' %s' % sync.last_uuid entries = entries.filter(when__gt = Entry.objects.get(uuid = sync.last_uuid).when) data = {'s': unicode(sync)} if entries: if options.debug: for entry in entries: print '%s %s:\n %s' % (entry.person, entry.mac_address, entry.when) if entry.deleted: print ' deleted' elif entry.name: print ' %s' % entry.name data['e'] = json.dumps(entries, cls = SyncJSONEncoder) sync.last_uuid = list(entries)[-1].uuid sync.save() context = SSL.Context() context.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 2) context.load_verify_locations(cafile = 'ssl/cacert.pem') realm = 'Laptops Sync' url = 'https://cscl.creativestudies.org/laptops/sync' handler = urllib2.HTTPBasicAuthHandler() if options.secret: with open('/ccs/etc/web.secret', 'rb') as file: handler.add_password(realm, url, *base64.b64decode(file.readline().rstrip().decode('rot13')).split(':', 1)) else: handler.add_password(realm, url, raw_input('User: '), getpass.getpass()) opener = m2urllib2.build_opener(context, handler) data = urllib.urlencode(data) data = json.load(opener.open(url, data) if not inserted else opener.open(url + '?' + data), object_hook = sync_object_hook) if 'e' in data: for entry in data['e']: entry.save() if options.debug: print '%s %s:\n %s' % (entry.person, entry.mac_address, entry.when) if not entry.deleted: if options.debug and entry.name: print ' %s' % entry.name inserted = entry()[1] if options.debug: print ' %s' % ('inserted' if inserted else 'updated') else: if options.debug: print ' deleted' entry() if __name__ == '__main__': main()