# Path: core/config.py

# 
# Path: core/api/crud.py
# def get(collection, criteria_projection_order):
# def remove(collection, criterias = []):
# def add(collection, documents_list):
# def update(collection, document):
# 
# Path: core/validation/validation.py
# class TSValidationError(Exception):
# def recursive_merge(container, container_override):
# def recursive_replace(container, replace_function):
# def _replace_function_sanitize_objectify_json(container):
# def sanitize_objectify_json(json_in):
# def _replace_function_stringify_objectid_json(container):
# def stringify_objectid_cursor(cursor_in):
# def _replace_function_stringify_objectid_list(container):
# def stringify_objectid_list(list_in):
# def validate_json_list(collection, list_in):
# def validate_request(collection, json_in):
# def update_password_salt_user_list(collection, list_in):
# def update_password_salt_user_json(json_in):
# def get_password_salt(password_in):
# 
# Path: core/validation/permissions.py
# def check_datamine_permissions(action, document):
#     # Get datamine permissions
#     
#     try:
#         restrictions = cherrypy.session['_ts_user']['restrictions'][action]
#     except (KeyError, TypeError):
#         restrictions = None
#         
#     if not restrictions:
#         raise TSValidationError("Access to '%s' is restricted for current user" % (action))
#     elif restrictions != True:
#         validator(restrictions, format_checker=jsonschema.FormatChecker()).validate(document)


import tempfile, os, shutil, cherrypy, time
import logging
from core.config import conf_uploads
from core.api.crud import db
from core.validation.validation import TSValidationError, validate_request, cgi, ObjectId, sanitize_objectify_json
from core.validation.permissions import check_datamine_permissions

db_log_severity = logging.INFO

def upload():
    
    # Check permissions  
    check_datamine_permissions('file_upload', cherrypy.request.params)
    
    file_uploading = cherrypy.request.params['data']
    
    uploaded_temp = tempfile.NamedTemporaryFile(mode='w+b', dir=conf_uploads['folder'], delete=False)

    try:
        while True:
            data = file_uploading.file.read(8192)
            if not data:
                break
            else:
                uploaded_temp.write(data)
    
        uploaded_temp.close()
        upload_id = str(db.upload.insert({ 'name' : str(file_uploading.filename), 'content_type' : cgi.escape(str(file_uploading.content_type)), 'owner' : cherrypy.session['_ts_user']['username'], 'date' :  time.strftime("%Y-%m-%d%H:%M:%S", time.gmtime()) }))

        cherrypy.log('%s %s' % (str(file_uploading.filename), str(file_uploading.content_type)) , context = 'TS.FILE.UPLOAD', severity = db_log_severity)
        

# Path: core/config.py

# 
# Path: core/api/crud.py
# def get(collection, criteria_projection_order):
# def remove(collection, criterias = []):
# def add(collection, documents_list):
# def update(collection, document):
# 
# Path: core/validation/validation.py
# class TSValidationError(Exception):
# def recursive_merge(container, container_override):
# def recursive_replace(container, replace_function):
# def _replace_function_sanitize_objectify_json(container):
# def sanitize_objectify_json(json_in):
# def _replace_function_stringify_objectid_json(container):
# def stringify_objectid_cursor(cursor_in):
# def _replace_function_stringify_objectid_list(container):
# def stringify_objectid_list(list_in):
# def validate_json_list(collection, list_in):
# def validate_request(collection, json_in):
# def update_password_salt_user_list(collection, list_in):
# def update_password_salt_user_json(json_in):
# def get_password_salt(password_in):
# 
# Path: core/validation/permissions.py
# def check_datamine_permissions(action, document):
#     # Get datamine permissions
#     
#     try:
#         restrictions = cherrypy.session['_ts_user']['restrictions'][action]
#     except (KeyError, TypeError):
#         restrictions = None
#         
#     if not restrictions:
#         raise TSValidationError("Access to '%s' is restricted for current user" % (action))
#     elif restrictions != True:
#         validator(restrictions, format_checker=jsonschema.FormatChecker()).validate(document)


# Path: core/api/uploads.py
import tempfile, os, shutil, cherrypy, time
import logging
from core.config import conf_uploads
from core.api.crud import db
from core.validation.validation import TSValidationError, validate_request, cgi, ObjectId, sanitize_objectify_json
from core.validation.permissions import check_datamine_permissions


db_log_severity = logging.INFO

def upload():
    
    # Check permissions  
    check_datamine_permissions('file_upload', cherrypy.request.params)
    
    file_uploading = cherrypy.request.params['data']
    
    uploaded_temp = tempfile.NamedTemporaryFile(mode='w+b', dir=conf_uploads['folder'], delete=False)

    try:
        while True:
            data = file_uploading.file.read(8192)
            if not data:
                break
            else:
                uploaded_temp.write(data)
    
        uploaded_temp.close()
        upload_id = str(db.upload.insert({ 'name' : str(file_uploading.filename), 'content_type' : cgi.escape(str(file_uploading.content_type)), 'owner' : cherrypy.session['_ts_user']['username'], 'date' :  time.strftime("%Y-%m-%d%H:%M:%S", time.gmtime()) }))

        cherrypy.log('%s %s' % (str(file_uploading.filename), str(file_uploading.content_type)) , context = 'TS.FILE.UPLOAD', severity = db_log_severity)
        

        uploaded_temp_path = os.path.join(conf_uploads['folder'], uploaded_temp.name)