#! /usr/bin/env python
#-*- coding: iso-8859-1 -*-

"""
photoserver - simplest of all possible server type, taking JSON encoded
              and named content and puts them somewhere to be seen

author   : Werner Thie, wth
last edit: wth, 20.03.2009
modhistory:
  18.03.2009 - wth, created
"""

import os, sys, json

from twisted.protocols import basic

from twisted.internet import protocol

from twisted.web import http

gRSRC = None

if sys.platform == 'win32':
  basepath = 'b:\\'
else:
  basepath = '/var/www/tmp'

class JSONProtocol(basic.LineReceiver):
  MAX_LENGTH = 512000

  def connectionMade(self):
    print "Connection from", self.transport.getPeer().host

  def lineReceived(self, line):
    if line == 'quit':
      self.sendLine("Goodbye.")
      self.transport.loseConnection()
    else:
      msg = json.read(line)
      print 'Picture received: ', msg['name']

      f = open(os.path.join(basepath, msg['name']), 'wb')
      f.write(msg['jpeg'])
      f.close()

class JSONFactory(protocol.ServerFactory):
  protocol  = JSONProtocol
