
from flask import Flask, make_response, render_template, abort, send_file, request
import zipfile
import os
import mimetypes
import waitress

BASE_DIR = '/net/lepton/mnt/data_drive/proton2/GNSSResults'
webPort = 9999
app = Flask(__name__)

# Serve the favicon
@app.route('/favicon.ico')
def favicon():
  return send_file('static/favicon.ico', mimetype='image/vnd.microsoft.icon')


@app.route('/', defaults={'req_path': ''})
@app.route('/<path:req_path>')
def dir_listing(req_path):
  req_path = req_path.rstrip('/')
  request.path = request.path.rstrip('/')

  # Joining the base and the requested path
  abs_path = os.path.realpath(os.path.join(BASE_DIR, req_path))

  ######################################################################
  # Handle zip files
  zip_pos = abs_path.find('.zip')
  if zip_pos > 0:
    zip_path = abs_path[:zip_pos+4]
    file_path = abs_path[zip_pos+4:].strip('/')

    if file_path=='':
      # show zip file list
      with zipfile.ZipFile(zip_path) as z:
        files = sorted(z.namelist())
      return render_template('files.html', files=files)
    else:
      # extract zip content
      with zipfile.ZipFile(zip_path) as z:
        filebuffer = z.read(file_path)

      response = make_response(filebuffer)
      content_type,enc = mimetypes.guess_type(file_path)
      response.headers.set('Content-Type', content_type)
      return response

  ######################################################################
  # handle non-zip files

  # Return 404 if path doesn't exist
  if not os.path.exists(abs_path):
    return abort(404)

  if os.path.isfile(abs_path):
    return send_file(abs_path)

  # Show directory contents
  files = sorted(os.listdir(abs_path))
  return render_template('files.html', files=files, abs_path=abs_path)

if __name__ == "__main__":
  # waitress is more efficient than app.run()
  waitress.serve( app, host='0.0.0.0',port=webPort, threads=8 )

  # app.run() is good for debugging
  #app.run(host='0.0.0.0',port=webPort,threaded=True)
