# Path: src/config.py
# UPLOAD_CHUNK_LENGTH = 8 * _1MB
# 
# UPLOAD_UNSAVORY_EXTS = ['bat', 'cmd', 'exe', 'iso', 'php', 'vbs']
# 
# UPLOADED_FILES_DEST = '/tmp'
# 
# Path: src/forms.py
# class UserForm(ModelForm):
#     class Meta:
#         model = Users
#         exclude = common_exclusions
#         #~ only = tuple('''
#             #~ name email timezone desc
#         #~ '''.split())
#         only = tuple('name email timezone desc'.split())
# 
# Path: src/logcfg.py
# DEBUG_TEMPL = '  %(levelname)-7.7s %(funcName)s: %(message)s'
# PROD_TEMPL  = '%(asctime)s %(levelname)-7.7s %(funcName)s: %(message)s'
# DEBUG = logging.DEBUG
# class ColorFmtr(Formatter):
#     def __init__(self, *args, **kwargs):
#     def format(self, record):
# def makefunc(level):
#         def tb_func(msg, *args, **kwargs):
#     def thefunc(msg, *args, **kwargs):
# 
# Path: src/main.py
# def on_shutdown():


from os.path import join, splitext
from http_status import name as http_status_text
from http_status import description as http_status_description
from flask import (
    #~ abort,
    flash,      # flash categories: success, (blank) info, warning, error
    #~ g,
    jsonify,
    redirect,
    render_template as render,
    request,
    url_for,
)
from flask_login import current_user
from sqlalchemy.exc import SQLAlchemyError
from werkzeug.utils import secure_filename
from .config import (UPLOAD_CHUNK_LENGTH, UPLOAD_UNSAVORY_EXTS,
                     UPLOADED_FILES_DEST)
from .forms import UserForm
from .logcfg import log
from .main import app, db
from . import utils
        # if this was an ajax request, return json instead of html
        if request.accept_mimetypes.best == 'application/json':
            log.debug('client prefers json, skipping page render.')
            return jsonify(status='success',
                           files=[ f.filename for f in files ])

        flash('File(s) uploaded.', 'success')

    return render('upload.html', title='Uploads', debug=int(app_debug))


# this doesn't seem to respect max size, like post does
@app.route('/upload', methods=('PUT',))
def upload_file_put():

    filename = secure_filename(request.headers.get('X-File-Name', 'upload.dat'))
    con_len = request.headers.get('Content-Length', 0)

    if splitext(filename)[1][1:] in UPLOAD_UNSAVORY_EXTS:
        msg = ('An unsupported file type %r was uploaded, '
               'canceling submission.' % filename)
        log.error(msg)
        # might be a good idea to record these to user account
        return jsonify(status='failure', reason='Unsupported file type.',
                       file=dict(name=filename)), 415  # media

    path = join(UPLOADED_FILES_DEST, filename)
    log.info('saving file as: %r', path)
    with open(path, 'wb') as f:
        while True:     # may be duplicating stream chunking?

# Path: src/config.py
# UPLOAD_CHUNK_LENGTH = 8 * _1MB
# 
# UPLOAD_UNSAVORY_EXTS = ['bat', 'cmd', 'exe', 'iso', 'php', 'vbs']
# 
# UPLOADED_FILES_DEST = '/tmp'
# 
# Path: src/forms.py
# class UserForm(ModelForm):
#     class Meta:
#         model = Users
#         exclude = common_exclusions
#         #~ only = tuple('''
#             #~ name email timezone desc
#         #~ '''.split())
#         only = tuple('name email timezone desc'.split())
# 
# Path: src/logcfg.py
# DEBUG_TEMPL = '  %(levelname)-7.7s %(funcName)s: %(message)s'
# PROD_TEMPL  = '%(asctime)s %(levelname)-7.7s %(funcName)s: %(message)s'
# DEBUG = logging.DEBUG
# class ColorFmtr(Formatter):
#     def __init__(self, *args, **kwargs):
#     def format(self, record):
# def makefunc(level):
#         def tb_func(msg, *args, **kwargs):
#     def thefunc(msg, *args, **kwargs):
# 
# Path: src/main.py
# def on_shutdown():


# Path: src/views.py
from os.path import join, splitext
from http_status import name as http_status_text
from http_status import description as http_status_description
from flask import (
    #~ abort,
    flash,      # flash categories: success, (blank) info, warning, error
    #~ g,
    jsonify,
    redirect,
    render_template as render,
    request,
    url_for,
)
from flask_login import current_user
from sqlalchemy.exc import SQLAlchemyError
from werkzeug.utils import secure_filename
from .config import (UPLOAD_CHUNK_LENGTH, UPLOAD_UNSAVORY_EXTS,
                     UPLOADED_FILES_DEST)
from .forms import UserForm
from .logcfg import log
from .main import app, db
from . import utils

        # if this was an ajax request, return json instead of html
        if request.accept_mimetypes.best == 'application/json':
            log.debug('client prefers json, skipping page render.')
            return jsonify(status='success',
                           files=[ f.filename for f in files ])

        flash('File(s) uploaded.', 'success')

    return render('upload.html', title='Uploads', debug=int(app_debug))


# this doesn't seem to respect max size, like post does
@app.route('/upload', methods=('PUT',))
def upload_file_put():

    filename = secure_filename(request.headers.get('X-File-Name', 'upload.dat'))
    con_len = request.headers.get('Content-Length', 0)

    if splitext(filename)[1][1:] in UPLOAD_UNSAVORY_EXTS:
        msg = ('An unsupported file type %r was uploaded, '
               'canceling submission.' % filename)
        log.error(msg)
        # might be a good idea to record these to user account
        return jsonify(status='failure', reason='Unsupported file type.',
                       file=dict(name=filename)), 415  # media

    path = join(UPLOADED_FILES_DEST, filename)
    log.info('saving file as: %r', path)
    with open(path, 'wb') as f:
        while True:     # may be duplicating stream chunking?

            chunk = request.stream.read(UPLOAD_CHUNK_LENGTH)