# Path: core/api/uploads.py
# def upload():
# def download(upload_id):
# def remove(upload_ids):
# 
# Path: core/validation/validation.py
# class TSValidationError(Exception):
#     pass
# 
# Path: core/auth/auth.py
# class AuthController(object):
#     
#     def reload_users_projects(self):
# 
#         # Save ids of managed_projects
#         cherrypy.session['_ts_user']['managed_projects'] = []
#         cursor = db.project.find({ 'responsibles._id' : cherrypy.session['_ts_user']['_id'] }, { '_id' : 1 })
#         for document in cursor:
#             cherrypy.session['_ts_user']['managed_projects'].append(str(document['_id']))
# 
#         # Save ids of taken projects
#         cherrypy.session['_ts_user']['employed_projects'] = []
#         cursor = db.project.find({ 'employees._id' : cherrypy.session['_ts_user']['_id'] }, { '_id' : 1 })
#         for document in cursor:
#             cherrypy.session['_ts_user']['employed_projects'].append(str(document['_id']))
# 
#         # Uniq and ordered ids of all projects
#         cherrypy.session['_ts_user']['projects'] = _unique_keeping_order(cherrypy.session['_ts_user']['employed_projects'] +
#                                                                         cherrypy.session['_ts_user']['managed_projects'])
# 
#         # Save formatted permissions schemas to speedup following accesses
#         cherrypy.session['_ts_user']['restrictions'] = get_user_restrictions()
# 
#         cherrypy.log('%s' % (pprint.pformat(cherrypy.session['_ts_user'])), context = 'TS.AUTH.session_permission', severity = logging.INFO)
# 
#     def on_login(self, username):
#         """Called on successful login"""
#         
#         # Save user data
#         cherrypy.session['_ts_user'] = db.user.find_one({ 'username' : username }, { 'username' : 1, 'group' : 1, 'name' : 1, 'surname' : 1, 'email' : 1 })
#         
#         self.reload_users_projects()
# 
#         cherrypy.request.login = username
#         
#     def on_logout(self, username):
#         """Called on logout"""
#         cherrypy.lib.sessions.expire()
#     
#     def get_loginform(self, username, msg="", from_page="/"):
#         return templates.get_template('auth.tpl').render(message=msg)
#         
#     @cherrypy.expose
#     def login(self, username=None, password=None, from_page="/"):
#         if username is None or password is None:
#             return self.get_loginform("", from_page=from_page)
#         
#         error_msg = check_credentials(username, password)
#         if not error_msg:
#             error_msg = check_active_status(username)
#         
#         if error_msg:
#             return self.get_loginform(username, error_msg, from_page)
#         else:
#             self.on_login(username)
#             raise cherrypy.HTTPRedirect(from_page or "/")
#     
#     @cherrypy.expose
#     def logout(self, from_page="/"):
#         sess = cherrypy.session
#         userdata = sess.get('_ts_user', None)
#         username = userdata.get('username', None)
#         sess['_ts_user'] = None
#         if username:
#             cherrypy.request.login = None
#             self.on_logout(username)
#         raise cherrypy.HTTPRedirect(from_page or "/")
# 
# def require(*conditions):
#     """A decorator that appends conditions to the auth.require config
#     variable."""
#     def decorate(f):
#         if not hasattr(f, '_cp_config'):
#             f._cp_config = dict()
#         if 'auth.require' not in f._cp_config:
#             f._cp_config['auth.require'] = []
#         f._cp_config['auth.require'].extend(conditions)
#         return f
#     return decorate
# 
# def is_logged():
#     return lambda: bool(cherrypy.request.login)


from cherrypy.lib.static import serve_file
from core.api import uploads
from jsonschema.exceptions import ValidationError
from core.validation.validation import TSValidationError
from core.auth.auth import AuthController, require, is_logged
import cherrypy, traceback, logging, cgi
        
        Returns file content.
        """
        
        try:
            file_path, content_type = uploads.download(upload_id)
        except Exception as e:      
            error_msg = '%s %s\n%s %s\n' % (str(''), type(e).__name__, str(e), traceback.format_exc())
        else:
            error_msg = None
        
        if error_msg:
            cherrypy.log('%s %s' % (cherrypy.request.path_info, error_msg), context = 'TS', severity = logging.ERROR)
        else:
            return serve_file(file_path, content_type=content_type)
    
    @cherrypy.expose
    @require(is_logged())
    @cherrypy.tools.allow(methods=['POST'])
    @cherrypy.tools.json_out(on = True)
    def upload(self, **postdata):
        """
        Upload stored files.
        
        POST /file/upload
        
        Returns { 'error' : string, 'upload_id' : string }
        """
        
        try:

# Path: core/api/uploads.py
# def upload():
# def download(upload_id):
# def remove(upload_ids):
# 
# Path: core/validation/validation.py
# class TSValidationError(Exception):
#     pass
# 
# Path: core/auth/auth.py
# class AuthController(object):
#     
#     def reload_users_projects(self):
# 
#         # Save ids of managed_projects
#         cherrypy.session['_ts_user']['managed_projects'] = []
#         cursor = db.project.find({ 'responsibles._id' : cherrypy.session['_ts_user']['_id'] }, { '_id' : 1 })
#         for document in cursor:
#             cherrypy.session['_ts_user']['managed_projects'].append(str(document['_id']))
# 
#         # Save ids of taken projects
#         cherrypy.session['_ts_user']['employed_projects'] = []
#         cursor = db.project.find({ 'employees._id' : cherrypy.session['_ts_user']['_id'] }, { '_id' : 1 })
#         for document in cursor:
#             cherrypy.session['_ts_user']['employed_projects'].append(str(document['_id']))
# 
#         # Uniq and ordered ids of all projects
#         cherrypy.session['_ts_user']['projects'] = _unique_keeping_order(cherrypy.session['_ts_user']['employed_projects'] +
#                                                                         cherrypy.session['_ts_user']['managed_projects'])
# 
#         # Save formatted permissions schemas to speedup following accesses
#         cherrypy.session['_ts_user']['restrictions'] = get_user_restrictions()
# 
#         cherrypy.log('%s' % (pprint.pformat(cherrypy.session['_ts_user'])), context = 'TS.AUTH.session_permission', severity = logging.INFO)
# 
#     def on_login(self, username):
#         """Called on successful login"""
#         
#         # Save user data
#         cherrypy.session['_ts_user'] = db.user.find_one({ 'username' : username }, { 'username' : 1, 'group' : 1, 'name' : 1, 'surname' : 1, 'email' : 1 })
#         
#         self.reload_users_projects()
# 
#         cherrypy.request.login = username
#         
#     def on_logout(self, username):
#         """Called on logout"""
#         cherrypy.lib.sessions.expire()
#     
#     def get_loginform(self, username, msg="", from_page="/"):
#         return templates.get_template('auth.tpl').render(message=msg)
#         
#     @cherrypy.expose
#     def login(self, username=None, password=None, from_page="/"):
#         if username is None or password is None:
#             return self.get_loginform("", from_page=from_page)
#         
#         error_msg = check_credentials(username, password)
#         if not error_msg:
#             error_msg = check_active_status(username)
#         
#         if error_msg:
#             return self.get_loginform(username, error_msg, from_page)
#         else:
#             self.on_login(username)
#             raise cherrypy.HTTPRedirect(from_page or "/")
#     
#     @cherrypy.expose
#     def logout(self, from_page="/"):
#         sess = cherrypy.session
#         userdata = sess.get('_ts_user', None)
#         username = userdata.get('username', None)
#         sess['_ts_user'] = None
#         if username:
#             cherrypy.request.login = None
#             self.on_logout(username)
#         raise cherrypy.HTTPRedirect(from_page or "/")
# 
# def require(*conditions):
#     """A decorator that appends conditions to the auth.require config
#     variable."""
#     def decorate(f):
#         if not hasattr(f, '_cp_config'):
#             f._cp_config = dict()
#         if 'auth.require' not in f._cp_config:
#             f._cp_config['auth.require'] = []
#         f._cp_config['auth.require'].extend(conditions)
#         return f
#     return decorate
# 
# def is_logged():
#     return lambda: bool(cherrypy.request.login)


# Path: core/routes/uploads.py
from cherrypy.lib.static import serve_file
from core.api import uploads
from jsonschema.exceptions import ValidationError
from core.validation.validation import TSValidationError
from core.auth.auth import AuthController, require, is_logged
import cherrypy, traceback, logging, cgi

        
        Returns file content.
        """
        
        try:
            file_path, content_type = uploads.download(upload_id)
        except Exception as e:      
            error_msg = '%s %s\n%s %s\n' % (str(''), type(e).__name__, str(e), traceback.format_exc())
        else:
            error_msg = None
        
        if error_msg:
            cherrypy.log('%s %s' % (cherrypy.request.path_info, error_msg), context = 'TS', severity = logging.ERROR)
        else:
            return serve_file(file_path, content_type=content_type)
    
    @cherrypy.expose
    @require(is_logged())
    @cherrypy.tools.allow(methods=['POST'])
    @cherrypy.tools.json_out(on = True)
    def upload(self, **postdata):
        """
        Upload stored files.
        
        POST /file/upload
        
        Returns { 'error' : string, 'upload_id' : string }
        """
        
        try:

            upload_id = uploads.upload()