Esempio n. 1
0
def download(download_hash):

    if not download_hash:
        return response(request, 'No download hash specified', 400)

    if re.search('[^A-Za-z0-9_]', download_hash):
        return response(request, 'invalid download hash', 400)

    fb = FbQuery()
    # fetch file
    f = fb.file_get(download_hash)

    if not f:
        return response(request, 'Could not find file', 404)

    if f.expire != '0':
        # Expire date exists
        if fb.file_expired(f.expire):
            # Remove expired file from storage and database
            fb.file_remove(download_hash, f.filename)
            return response(request, 'This download has expired', 410)

    if f.download_password:
        # This file is password protected.
        if request.method == 'POST':
            # Validate download_password from database with user input
            pw = Password(config.get('settings', 'secret_key'))
            if not pw.validate(f.download_password, request.form['password']):
                return render_template('download.html',
                                       error='Invalid Password')

        else:
            return render_template('download.html', error=None)

    if f.one_time_download:
        # Set expire date to current time, download will be invalid in a minute
        fb.file_set_expiry(download_hash,
                           datetime.now().strftime('%Y%m%d%H%M%S'))

    # Serve images in browser
    type = guess_type(
        os.path.join(app.config['UPLOAD_FOLDER'], download_hash,
                     f.filename))[0]
    attachment = True
    if type and 'image' in type:
        attachment = False

    # Serve file, everything is ok
    return send_from_directory(os.path.join(app.config['UPLOAD_FOLDER'],
                                            download_hash),
                               f.filename,
                               as_attachment=attachment,
                               cache_timeout=0)