#!/usr/bin/python

#-------------------------------------------------------------------------------
import web
from web.wsgiserver import CherryPyWSGIServer
import os.path
import sys
import json
import database
import data
import pipeline

#-------------------------------------------------------------------------------
CherryPyWSGIServer.ssl_certificate = "cert/server.crt"
CherryPyWSGIServer.ssl_private_key = "cert/server.key"

web.config.debug = False

#-------------------------------------------------------------------------------
urls = (
    '/favicon.ico', 'Favicon',
    '/', 'Home',
    '/howto','Howto',
    '/run_job',"RunJob",
    '/about', 'About',
    '/login', 'Login',
    '/login_error', 'LoginError',
    '/logout', 'Logout',
    '/ajax/me', 'AjaxMe',
    '/ajax/file', 'AjaxFiles',
    '/ajax/filepart', 'AjaxFileParts',
    '/ajax/job', 'AjaxJobs',
    '/job/(.*)', 'Job',
    '/file/(.*)/.*', 'File',
    '/manager', 'Manager',
)

#-------------------------------------------------------------------------------
app = web.application( urls, globals() )
store = web.session.DiskStore( 'sessions' )
session = web.session.Session( app, store, initializer={'login': 0, 'user': None} )

#-------------------------------------------------------------------------------
def logged():
    return (session.login == 1)

#-------------------------------------------------------------------------------
def get_render():
    if logged():
        return web.template.render( 'templates/logged', base="layout" )
    else:
        return web.template.render( 'templates/anom', base="layout" )

#-------------------------------------------------------------------------------
def clearSession():
    session.login = 0
    session.user = None

#-------------------------------------------------------------------------------
class Favicon:
    def GET( self ):
        raise web.seeother('/static/favicon.ico')

#-------------------------------------------------------------------------------
class Home:
    def GET( self ):
        return get_render().main()

#-------------------------------------------------------------------------------
class Howto:
    def GET( self ):
        return get_render().howto()

#-------------------------------------------------------------------------------
class RunJob:
    def GET( self ):
        return get_render().run_job()

#-------------------------------------------------------------------------------
class About:
    def GET( self ):
        return get_render().about()

#-------------------------------------------------------------------------------
class Manager:
    def GET( self ):
        return get_render().manager()

#-------------------------------------------------------------------------------
class Login:
    def GET( self ):
        raise web.seeother('/')

    def POST(self):
        try:
            name = web.input().user
            passwd = web.input().passwd
            if database.checkUser( name, passwd ):
                session.login = 1
                session.user = name
            else:
                clearSession()
        except:
            clearSession()

        if logged():
            raise web.seeother('/')
        else:
            raise web.seeother('/login_error')

#-------------------------------------------------------------------------------
class LoginError:
    def GET( self ):
        return get_render().login_error()

#-------------------------------------------------------------------------------
class Logout:
    def GET( self ):
        session.login = 0
        session.kill()
        raise web.seeother('/')

#-------------------------------------------------------------------------------
class AjaxMe:
    def GET( self ):
        if logged():
            return json.dumps( {'username': session.user} )
        else:
            raise web.seeother('/')

#-------------------------------------------------------------------------------
class AjaxFiles:
    def GET( self ):
        if logged():
            web.header('Content-Type', 'application/json')
            x = web.input()
            try:
                files = []
                if x.has_key( 'filetype' ):
                    filetype = x['filetype']
                    files = database.getUserFilesWithType( session.user, int(filetype) )
                else:
                    files = database.getUserFiles( session.user )

                return json.dumps( {'files': files} )
            except:
                print sys.exc_info()
                web.debug( "can't get filelist" )

        else:
            raise web.seeother('/')

    def PUT( self ):
        if logged():
            try:
                x = web.input(myfile={})
                filename = data.getUserFilename( session.user, x['myfile'].filename )
                filetype = data.getFileType( x['myfile'].filename, x['myfiletype'] )
                data.saveFile( filename, x['myfile'].file )
                database.insertFileWithType( session.user, x['myfile'].filename, filetype )
            except:
                print sys.exc_info()
                web.debug( "can't save file" )

            return "OK"

        else:
            raise web.seeother('/')

#-------------------------------------------------------------------------------
class AjaxFileParts:
    def PUT( self ):
        if logged():
            try:
                x = web.input(myfile={})
                if x['status'] == "start":
                    filename = data.getUserFilename( session.user, x['myfilename'] )
                    data.clearFilePart( filename )
                elif x['status'] == "end":
                    filename = data.getUserFilename( session.user, x['myfilename'] )
                    filetype = data.getFileType( x['myfilename'], x['myfiletype'] )
                    data.endFilePart( filename )
                    database.insertFileWithType( session.user, x['myfilename'], filetype )
                elif x['status'] == "part":
                    filename = data.getUserFilename( session.user, x['myfilename'] )
                    data.saveFilePart( filename, x['myfile'].file )

            except:
                print sys.exc_info()
                web.debug( "can't save file" )

            return "OK"

        else:
            raise web.seeother('/')

#-------------------------------------------------------------------------------
class AjaxJobs:
    def GET( self ):
        if logged():
            web.header('Content-Type', 'application/json')
            jobs = database.getUserJobs( session.user )
            return json.dumps( {'jobs': jobs} )
        else:
            raise web.seeother('/')

    def POST( self ):
        if logged():
            x = web.input()

            try:
                pipeline.startJob( session.user, x )

            except:
                print sys.exc_info()
                web.debug( "can't start new job" )

            return "OK"
        else:
            raise web.seeother('/')

#-------------------------------------------------------------------------------
class File:
    def GET( self, fileid ):
        if logged():
            if database.isFileAllowedFromUser( fileid, session.user ):
                filename = database.getFileFullName( fileid )
                with open( filename, "r" ) as f:
                    return f.read()
            else:
                return get_render().notallowed()
        else:
            raise web.seeother('/')

#-------------------------------------------------------------------------------
class Job:
    def GET( self, jobid ):
        if logged():
            if database.isJobFromUser( jobid, session.user ):
                jobinfo = database.getJobInfo( jobid )
                return get_render().job( jobinfo )
            else:
                return get_render().notallowed()
        else:
            raise web.seeother('/')

#-------------------------------------------------------------------------------
if __name__ == "__main__":
    database.init()
    p = pipeline.run()
    app.run()
    p.terminate()

#-------------------------------------------------------------------------------

@@ -678,24 +678,47 @@
 ', 'Login',%0A
+    '/setup', 'Setup',%0A
     '/login_
@@ -2654,32 +2654,57 @@
 ef GET( self ):%0A
+        if logged():%0A    
         return g
@@ -2724,16 +2724,293 @@
 anager()
+%0A        else:%0A            raise web.seeother('/')%0A%0A#-------------------------------------------------------------------------------%0Aclass Setup:%0A    def GET( self ):%0A        if logged():%0A            return get_render().setup()%0A        else:%0A            raise web.seeother('/')
 %0A%0A#-----

add setup response in server