from flask import Flask, redirect, request
from flask import render_template
from flask import  send_file
import sys, os
from functools import wraps
from flask import Response, jsonify
import random, json
import subprocess

sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'lib')))

import ec_config

app = Flask(__name__, static_url_path='/static')
# static dir is  ~iottalk/iottalk_server_1.0/da/static
# because this thile is  ~iottalk/iottalk_server_1.0/da/web.py
# this web.py is listening port 80   (See the very LAST line in this file)

'''
@app.route('/')
def index():
    return redirect('http://{}:9999/da/Remote_control'.format(request.host))
'''
@app.route('/iot')
@app.route('/iottalk')
@app.route('/IOT')
@app.route('/IOTTALK')
@app.route('/i0t')
@app.route('/I0T')
@app.route('/aiot')
@app.route('/iot0')
@app.route('/IOT0')
@app.route('/AIOT')
def aiotAsiaCMU():
    return render_template('aiot.html', name='Tsaiwn')


@app.route('/iotcmu')
@app.route('/iotcmu/')
def iotcmuAs2024CMU():
    return render_template('iotcmu.html', name='Tsaiwn')


@app.route('/cmuaiot')
@app.route('/cmuaiot/')
@app.route('/CMUAIOT')
@app.route('/CMUAIOT/')
def cmuaiotAsiaCMU():
    return render_template('cmuaiot.html', name='Tsaiwn')

@app.route('/cmuaiot1')
@app.route('/cmuaiot1/')
def cmuaiot1AsiaCMU():
    return render_template('cmuaiot1.html', name='Tsaiwn')

@app.route('/cmuaiot2')
@app.route('/cmuaiot2/')
def cmuaiot2AsiaCMU():
    return render_template('cmuaiot2.html', name='Tsaiwn')

@app.route('/cmuaiot3')
@app.route('/cmuaiot3/')
def cmuaiot3AsiaCMU():
    return render_template('cmuaiot3.html', name='Tsaiwn')

@app.route('/cmuaiot4')
@app.route('/cmuaiot4/')
def cmuaiot4AsiaCMU():
    return render_template('cmuaiot4.html', name='Tsaiwn')

@app.route('/cmuaiot5')
@app.route('/cmuaiot5/')
def cmuaiot5AsiaCMU():
    return render_template('cmuaiot5.html', name='Tsaiwn')

@app.route('/cmuaiot6')
@app.route('/cmuaiot6/')
def cmuaiot6AsiaCMU():
    return render_template('cmuaiot6.html', name='Tsaiwn')

@app.route('/ai')
@app.route('/ai/')
@app.route('/AI')
@app.route('/AI/')
def go_static_AI():
    return redirect('/static/ai/a/index.html')

@app.route('/bao')
@app.route('/pao')
@app.route('/bao/')
@app.route('/pao/')
def go_static_Bao():
    return redirect('/static/bao/index.html')

@app.route('/td/')
@app.route('/td')
@app.route('/taidon')
@app.route('/taidong')
@app.route('/TaiDong')
@app.route('/TaiDon')
def go_static_TD_():
    return redirect('/static/tr/td/index.ht')

@app.route('/sf')
@app.route('/sf/')
def go_static_Sf_():
    return redirect('/static/tr/sf/wine/index.html')

@app.route('/os')
@app.route('/osinfo')
def give_osinfo():
    osinfo =  subprocess.check_output("cat /etc/*relea*", shell=True).decode("utf-8")
    return "<PRE><b><font color=blue size=5>" + osinfo + '</pre><hr style="borde-top:2px solid red">'

@app.route('/ggyy')
def ggyy_haha():
    return "Hello ggyy"

@app.route('/ggyy2')
def ggyy_haha2():
   name = subprocess.check_output("whoami", shell=True).decode("utf-8")
   fqdn = subprocess.check_output("domainname", shell=True).decode("utf-8")
   name = name.rstrip()    #chop( )
   fqdn = fqdn.rstrip()
   return  jsonify({'User name':name, 'Domain name':fqdn}) # key=value形式的参数

@app.route('/yyy')
def Remote_con_redirect():
    return redirect('http://{}:9999/da/Remote_control'.format(request.host))

@app.route('/600')
@app.route('/600/')
def go_static_600():
    return redirect('/static/600/index.html')

@app.route('/601')
@app.route('/601/')
def go_static_601():
    return redirect('/static/601/index.html')

@app.route('/602')
@app.route('/602/')
def go_static_602():
    return redirect('/static/602/index.html')

@app.route('/603')
@app.route('/603/')
def go_static_603():
    return redirect('/static/603/index.html')

@app.route('/604')
@app.route('/604/')
def go_static_604():
    return redirect('/static/604/index.html')

@app.route('/605')
@app.route('/605/')
def go_static_605():
    return redirect('/static/605/index.html')

@app.route('/606')
@app.route('/606/')
def go_static_606():
    return redirect('/static/606/index.html')

@app.route('/607')
@app.route('/607/')
def go_static_607():
    return redirect('/static/607/index.html')

@app.route('/608')
@app.route('/608/')
def go_static_608():
    return redirect('/static/608/index.html')


@app.route('/8')
@app.route('/8/')
@app.route('/88')
@app.route('/88/')
def go_static_88():
    return redirect('/static/88/index.html')


@app.route('/map')
def map_Map_redirect():
    return redirect('/static/map/index.html')

@app.route('/echotest')
@app.route('/testecho')
def echotest():
    return render_template('echotest.html', name='Tsaiwn')

@app.route('/echoans', methods = ['POST', 'GET'])
def processEcho():
    if request.method == 'GET':           # 如果從網址打 /echoans 就會是 GET
        return redirect('/echotest')      # .. 那就轉址到 /echotest
        #return redirect('http://{}/echotest'.format(request.host))
    # read json "data" that "POST" to me, then pass "data" into  echoans.html, along with OS Information
    data = request.get_json(force=True)
    #print("Got ",data)
    osinfo = subprocess.check_output("cat /etc/*release", shell=True).decode("utf-8")
    nginxinfo =  subprocess.check_output("cat /etc/nginx/sites-enabled/*", shell=True).decode("utf-8")
    return render_template('echoans.html', data=data, name='蔡文能', osinfo=osinfo, nginx=nginxinfo)


@app.route('/echotest22.txt')
def echotest22_txt():
    return send_file('templates/echotest22.html', attachment_filename='echotest22.txt')
@app.route('/echotest22')
def echotest22():
    return render_template('echotest22.html', name='Tsaiwn')

@app.route('/echoans22', methods = ['POST'])
def processEcho22():
    data = request.get_json(force=True)
    result = ''
    for item in data:
        # loop over every row
        make = str(item['make'])
        if(make == 'Porsche'):
            result += make + ' -- 好車 That is a good manufacturer\n<br>'
        elif (make == 'Benz') :
            result += make + ' -- <font color=red>哇哇 That is a car for  有錢人</font>\n<br>'
        else:
            result += make + ' -- 普普 That is only an average manufacturer\n<br>'
    #print("result=\n", result)
    return result
    #return Response(result, mimetype='application/text', status=200)
    #return jsonify(result)
    #return Response(result, mimetype='application/text')
    #return Response(result, mimetype='text/html', status=200) 



@app.route('/echotest.txt')
@app.route('/testecho.txt')
def echotest_txt():
    return send_file('templates/echotest.html', attachment_filename='echotest.txt')
@app.route('/echoans.txt')
def giveEchoText():
    return send_file('templates/echoans.html', attachment_filename='echoans.txt')


@app.route('/rc')
def Remote_control_redirect():
    return redirect('http://{}:9999/da/Remote_control'.format(request.host))

@app.route('/m')
@app.route('/mtc')
@app.route('/openmtc')
def openmtc_redirect():
    return redirect('https://www.openmtc.org')

@app.route('/')
def home_redirect():
    #from urlparse import urlparse
    from urllib.parse import urlparse
    result = urlparse( request.url_root )
    hostname = result.hostname
    print('hostname===' + hostname)
    print ('format with hostname = http://{}:9999/'.format(hostname))
    print ('format with/and full_path = http://{}:9999/{}'.format(hostname, request.full_path))
    #return redirect('http://{}:9999/'.format(hostname))
    return redirect('http://{}:9999{}'.format(hostname, request.full_path))

@app.route('/msg/')
def msg_redirect():
    return redirect('http://{}:9999/msg'.format(request.host))


# templates dir is  ~iottalk/iottalk_server_1.0/da/templates
# because this thile is in ~iottalk/iottalk_server_1.0/da
@app.route('/0')
@app.route('/0/')
def iotArchitectureInfo():
    return render_template('iottalk00.html')

@app.route('/50')
@app.route('/50/')
def iotHigh50School():
    return render_template('50.html')

@app.route('/404')
@app.route('/404/')
def give404page():
    return render_template('404.html')

@app.route('/007')
@app.route('/007/')
def iotHighSchool():
    return render_template('777.html')

@app.route('/777/')
@app.route('/777')
def testggiot777HighSchool():
    return render_template('777new.html')

@app.route('/777x')
@app.route('/777x/')
def testggiotHighSchool():
    return render_template('testgg.html')

@app.route('/Nim')
@app.route('/Nim/')
@app.route('/nim')
@app.route('/nim/')
@app.route('/NIM')
@app.route('/NIM/')
def iotNim():
    return render_template('nim.html')

@app.route('/idcheck')
@app.route('/idcheck/')
@app.route('/Idcheck')
@app.route('/Idcheck/')
def iotIdcheck():
    return render_template('idcheck.html')

@app.route('/b1/')
@app.route('/b1')
def iotBall1school():
    return render_template('b1.html')

@app.route('/b2')
@app.route('/b2/')
def iotBall2school():
    return render_template('b2.html')

@app.route('/b3')
@app.route('/b3/')
def iotBall3333():
    return render_template('b3.html')

@app.route('/b38')
@app.route('/b38/')
def iotBall3838pendulum():
    return render_template('b38.html')

@app.route('/b38tt/')
def iotBall3838testpendulum():
    return render_template('b38test.html')


@app.route('/b49')
@app.route('/b49/')
def iotBall4949pendulum():
    return render_template('b49.html')

@app.route('/edutalk')
@app.route('/edutalk/')
@app.route('/edu')
@app.route('/edu/')
def iot2edutalk():
    return render_template('edutalk.html')

@app.route('/tcu/')
@app.route('/tcu')
def iotTCUschool():
    return render_template('tcu.html')

@app.route('/chu/')
@app.route('/chu')
def iotCHUschool():
    return render_template('chu.html')

@app.route('/ydu/')
@app.route('/ydu')
def iotYDUschool():
    return render_template('ydu.html')

import os
from flask import send_from_directory
@app.route('/favicon.ico')
def iotIconFav():
    return send_from_directory(os.path.join(app.root_path, 'static/img2'),
             'iot.png', mimetype='image/vnd.microsoft.icon')


@app.route('/pwd')
@app.route('/pwd/')
@app.route('/PWD')
@app.route('/PWD/')
@app.route('/unix')
@app.route('/unix/')
@app.route('/linux')
@app.route('/linux/')
@app.route('/Linux/')
@app.route('/LINUX/')
def pwdManual_redirect():
    return redirect('/static/iottalk/08/index.html')

@app.route('/abc/')
@app.route('/abc')
@app.route('/ABC/')
@app.route('/ABC')
def iotRControl():
    return render_template('abc.html')


@app.route('/000')
@app.route('/000/')
@app.route('/ooo')
@app.route('/ooo/')
def iotManual_redirect():
    return redirect('/static/iottalk/01/indexNew.html')

@app.route('/dht11')
@app.route('/dht11/')
@app.route('/dht')
@app.route('/dht/')
def iotDHTdht_redirect():
    return redirect('/static/iottalk/dht11/index.html')

@app.route('/bus')
@app.route('/bus/')
@app.route('/Bus/')
@app.route('/Bus')
@app.route('/bus182')
@app.route('/bus182/')
@app.route('/182')
@app.route('/182/')
@app.route('/BUS/')
@app.route('/BUS')
def iotBus182_redirect():
    return redirect('/static/bus182/index.html')


@app.route('/2023')
@app.route('/2023/')
def iotManCAL2023_redirect():
    return redirect('/static/CAL/www.i-write.idv.tw/life/info/CFcalendar/CFcalendar2023.html')


@app.route('/00/')
@app.route('/00')
@app.route('/o/')
@app.route('/o')
@app.route('/oo')
@app.route('/oo/')
@app.route('/O')
@app.route('/O/')
@app.route('/developer')
@app.route('/archi')
@app.route('/architecture')
def iotDevelop_redirect():
    return redirect('http://{}/0'.format(request.host))


@app.route('/2/')
@app.route('/2')
@app.route('/h')
@app.route('/H')
@app.route('/HOW')
@app.route('/HOw')
@app.route('/HoW')
@app.route('/How')
@app.route('/hOW')
@app.route('/hOw')
@app.route('/hoW')
@app.route('/how')
def iotGuide():
    return render_template('myIotHow.html')

@app.route('/3/')
@app.route('/3')
@app.route('/build')
@app.route('/cancel')
@app.route('/suit')
@app.route('/suite')
def readSuite():
    return render_template('readSuite.html')

@app.route('/getHow')
@app.route('/gethow')
@app.route('/GetHow')
@app.route('/Gethow')
def saveHowFile():
   try:
      return send_file('templates/myIotHow.html', attachment_filename='myIotHow.html')
   except Exception as e:
      return str(e)
# ######
@app.route('/howCen')
@app.route('/howcen')
@app.route('/howcent')
@app.route('/howcentos')
@app.route('/howCentos')
@app.route('/howCentOs')
@app.route('/1')
@app.route('/1/')
@app.route('/l')
@app.route('/L')
def iotGuideCen():
    return render_template('myIotHowCen.html')

# ######
@app.route('/4')
@app.route('/4/')
def iotShowOSinfo():
    return render_template('showOSInfo.htm')


# ######
@app.route('/5/')
@app.route('/5')
@app.route('/aws')
@app.route('/AWS')
def iotAWS():
    return render_template('useFreeVPS.htm')
@app.route('/555/')
def iotAWS555():
    return render_template('555.htm')

@app.route('/6/')
@app.route('/6')
def usingFlaskctureInfo():
    return render_template('ioflask6.html')

@app.route('/board')
@app.route('/board/')
@app.route('/dashboard')
@app.route('/dashboard/')
def boardManual_redirect():
    return redirect('/static/iottalk/02/index.html')

@app.route('/dashb2')
@app.route('/dashb2/')
def board2oldManual_redirect():
    return redirect('/static/iottalk/dashb2/index.html')

@app.route('/7')
@app.route('/7/')
@app.route('/17')
@app.route('/17/')
@app.route('/qr')
@app.route('/qr/')
@app.route('/qrcode')
@app.route('/qrcode/')
def iotQR1234567Info():
    return render_template('iottalk7.html')


# ##################################################################
@app.route('/getHowCen')
def saveHowFileCen():
   try:
      return send_file('templates/myIotHowCen.html', attachment_filename='myIotHowCen.html')
   except Exception as e:
      return str(e)
# ######


@app.route('/wsgi_csm')
def giveRAWcsmWSGIfile():
   try:
      return send_file('wsgi_csm.ini', attachment_filename='wsgi_csm.ini.txt') 
   except Exception as e:
      return str(e)


@app.route('/wsgi_csm.ini')
def givecsmWSGIfile():
   try:
      return send_file('wsgi_csm.ini', attachment_filename='wsgi_csm.ini') 
   except Exception as e:
      return str(e)


@app.route('/wsgi_ccm')
def giveRawCCMWSGIfile():
   try:
      return send_file('wsgi_ccm.ini', attachment_filename='wsgi_ccm.ini.txt') 
   except Exception as e:
      return str(e)

@app.route('/wsgi_ccm.ini')
def giveCCMWSGIfile():
   try:
      return send_file('wsgi_ccm.ini', attachment_filename='wsgi_ccm.ini') 
   except Exception as e:
      return str(e)


@app.route('/eicar.com.txt')
@app.route('/eicar.com')
@app.route('/eicar')
def giveEICARstringText():
   return str("X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*")

@app.route('/eicar2')
@app.route('/eicar2.com.txt')
@app.route('/eicar2.com')
def giveEICARfile():
   try:
      return send_file('eicar.com.txt', attachment_filename='eicar.com') 
   except Exception as e:
      return str(e)


@app.route('/ngi')
@app.route('/Nginx')
@app.route('/nginx')
@app.route('/nginxConfig')
@app.route('/nginxconfig')
def giveTheNginxConfigFile():
   try:
      return send_file('wsgi_nginx_conf', attachment_filename='wsgi_nginx_conf.txt') 
   except Exception as e:
      return str(e)


@app.route('/wsgi_nginx_conf/')
def givetheWsgiNginxConfigfile():
   try:
      return send_file('wsgi_nginx_conf', attachment_filename='wsgi_nginx_conf.sh') 
   except Exception as e:
      return str(e)




@app.route('/ngivip')
@app.route('/nginVIP')
@app.route('/nginxVip')
def giveTheNginxIottalk_VIP():
   try:
      return send_file('/etc/nginx/sites-enabled/redir8080', attachment_filename='ngiconfig.txt') 
   except Exception as e:
      return str(e)


@app.route('/ngiin')
@app.route('/ngiIN')
@app.route('/ngiind')
@app.route('/ngiInd')
@app.route('/ngiIND')
@app.route('/nginxin')
@app.route('/nginxIN')
@app.route('/nginxIndo')
def giveTheNginxIottalk_IN():
   try:
      return send_file('rawfiles/csmsock', attachment_filename='csmsock.txt') 
   except Exception as e:
      return str(e)

# file startup.sh
@app.route('/startup.sh')
def giveTheStartFile():
   try:
      return send_file('../setup/startup.sh', attachment_filename='startup.sh') 
   except Exception as e:
      return str(e) + '\n===\n'

# file Origstartup.sh
@app.route('/origstartup.sh')
@app.route('/ORIGstartup.sh')
@app.route('/startuporig.sh')
def giveTheOrigStartFile():
   try:
      return send_file('rawfiles/startup.sh', attachment_filename='startup.sh') 
   except Exception as e:
      return str(e) + '\n===\n'

# file startup_wsgi.sh
@app.route('/startup_wsgi.sh')
def giveTheStartUwsgiFile():
   try:
      return send_file('startup_wsgi.sh', attachment_filename='startup_wsgi.sh') 
   except Exception as e:
      return str(e) + '\n===\n'


@app.route('/screenrc')
def giveTheScreenrcFile():
   try:
      return send_file('screenrc', attachment_filename='screenrc') 
   except Exception as e:
      return str(e)
@app.route('/screenrc.txt')
def giveTheScreenrcFileAsTxt():
   try:
      return send_file('screenrc', attachment_filename='screenrc.txt') 
   except Exception as e:
      return str(e)

@app.route('/vimrc')
def giveTheVimrcFile():
   try:
      return send_file('vimrc', attachment_filename='vimrc') 
   except Exception as e:
      return str(e)

@app.route('/iotCENT/')
@app.route('/iotCENTOS/')
@app.route('/iotCentOs/')
@app.route('/iotCentOS/')
@app.route('/iotcentos/')
@app.route('/iotcent/')
@app.route('/iotCen/')
@app.route('/iotcen/')
def giveCent():
   try:
      return send_file('iotcen', attachment_filename='iotcen.sh') 
   except Exception as e:
      return str(e)

@app.route('/iotFED/')
@app.route('/iotFedora/')
@app.route('/iotFed/')
@app.route('/iotfedora/')
@app.route('/iotfed/')
def giveFedora():
   try:
      return send_file('iotfed', attachment_filename='iotfed.sh') 
   except Exception as e:
      return str(e)

@app.route('/putty.exe/')
def givePuttyExe():
   try:
      return send_file('rawfiles/putty.exe', attachment_filename='putty.exe') 
   except Exception as e:
      return str(e)


@app.route('/iotUbuntu/')
@app.route('/iotUbu/')
@app.route('/iotubuntu/')
@app.route('/iotubu/')
@app.route('/iotu/')
@app.route('/iotauto/')
def giveUbuntu():
   try:
      return send_file('iotubu', attachment_filename='iotubu.sh') 
   except Exception as e:
      return str(e)

@app.route('/iot0825')
@app.route('/iot0825.tar')
def giveIOTtar():
   try:
      return send_file('../../iot0825.tar', attachment_filename='iot0825.tar') 
   except Exception as e:
      return str(e)

@app.route('/yingwa.zip/')
def giveYingWaZip():
   try:
      return send_file('rawfiles/yingwa.zip', attachment_filename='yingwa.zip') 
   except Exception as e:
      return str(e)


@app.route('/webdaindex/')
def giveWebDaIndex():
   try:
      return send_file('../lib/templates/web_da_index.html', attachment_filename='web_da_index.html.txt') 
   except Exception as e:
      return str(e)


@app.route('/webdatxt/')
@app.route('/webdatext/')
def giveWebDaText():
      return send_file('templates/web_da_index.txt', attachment_filename='web_da_index_html') 


@app.route('/webda/')
@app.route('/webdalist/')
@app.route('/getwebda/')
@app.route('/getWebda/')
def giveWebDaList():
   try:
      return send_file('templates/web_da_index.txt', attachment_filename='web_da_index.txt') 
   except Exception as e:
      return str(e)

@app.route('/newweb.py/')
@app.route('/wsgiweb.py/')
@app.route('/webwsgi.py/')
def giveNewUwsgiWebPy():
   try:
      return send_file('webWsgi.py', attachment_filename='web_wsgi.py') 
   except Exception as e:
      return str(e)


@app.route('/oldweb.py/')
@app.route('/oldWeb.py/')
@app.route('/webold.py/')
@app.route('/webOld.py/')
@app.route('/origweb.py/')
@app.route('/origWeb.py/')
@app.route('/weborig.py/')
@app.route('/webOrig.py/')
def giveOldWebPy():
   try:
      return send_file('webOrig.py', attachment_filename='web.py') 
   except Exception as e:
      return str(e)

@app.route('/web.py/')
def giveDaWebPy():
   try:
      return send_file('web.py', attachment_filename='web.py') 
   except Exception as e:
      return str(e)

@app.route('/webpy/')
def downloadDaWebPyNoDot():
   try:
      return send_file('web.py', attachment_filename='webpy') 
   except Exception as e:
      return str(e)

@app.route('/dai.js/')
def giveDaiJs():
   try:
      return send_file('rawfiles/dai.js', attachment_filename='dai.js') 
   except Exception as e:
      return str(e)

@app.route('/MsgManager.py/')
def giveLibMsgPy():
      return send_file('../lib/MsgManager.py', attachment_filename='MsgManager.py') 

@app.route('/csm.py/')
def giveLibCsmPy():
   try:
      return send_file('../lib/csm.py', attachment_filename='csm.py') 
   except Exception as e:
      return str(e)

@app.route('/csmpy/')
def downloadLibCsmPy():
   try:
      return send_file('../lib/csm.py', attachment_filename='csmpy') 
   except Exception as e:
      return str(e)

@app.route('/csmapi.py/')
def giveLibCsmApiDotPy():
   try:
      return send_file('../lib/csmapi.py', attachment_filename='csmapi.py') 
   except Exception as e:
      return str(e)

@app.route('/ec_config.py/')
def giveLibEcConfigDotPy():
   try:
      return send_file('../lib/ec_config.py', attachment_filename='ec_config.py') 
   except Exception as e:
      return str(e)

@app.route('/ccm.py/')
def giveLibCCmDotPy():
   try:
      return send_file('../lib/ccm/ccm.py', attachment_filename='ccm.py') 
   except Exception as e:
      return str(e)

#esm__main__.py
@app.route('/esm_initmain.py/')
@app.route('/esm__main__.py/')
def giveLibESMinitmainmainPy():
   try:
      return send_file('../lib/esm/__main__.py', attachment_filename='__main__.py') 
   except Exception as e:
      return str(e)

#esm_main.py
@app.route('/esm_main.py/')
def giveLibESMmainPy():
   try:
      return send_file('../lib/esm/esm_main.py', attachment_filename='esm_main.py') 
   except Exception as e:
      return str(e)

# ecsim.py
@app.route('/ecsim.py/')
def giveLibECSIMPy():
   try:
      return send_file('../lib/ecsim/ecsim.py', attachment_filename='ecsim.py') 
   except Exception as e:
      return str(e)


@app.route('/ccmindex/')
def giveLibCCMIndex():
   try:
      return send_file('../lib/ccm/templates/index.html', attachment_filename='index.html.txt') 
   except Exception as e:
      return str(e)

@app.route('/ccmgui/')
def giveLibCCMgui():
   try:
      return send_file('../lib/ccm/static/gui.js', attachment_filename='gui.js.txt') 
   except Exception as e:
      return str(e)

@app.route('/ccmmake/')
def giveLibCCMmake():
   try:
      return send_file('../lib/ccm/static/make.js', attachment_filename='make.js.txt') 
   except Exception as e:
      return str(e)

@app.route('/ccmajax/')
def giveLibCCMajax():
   try:
      return send_file('../lib/ccm/static/ajax.js', attachment_filename='ajax.js.txt') 
   except Exception as e:
      return str(e)

@app.route('/ccmjsmain/')
def giveLibCCMjsmain():
   try:
      return send_file('../lib/ccm/static/js/main.js', attachment_filename='main.js.txt') 
   except Exception as e:
      return str(e)

##########################################
@app.route('/esmexec_data_path.py/')
def giveESMEXECexecData():
   try:
      return send_file('../lib/esm/exec_data_path.py', attachment_filename='esmexec_data_path.py') 
   except Exception as e:
      return str(e)

@app.route('/esmcreate_data_paths.py/')
def giveESMcreate_data_paths():
   try:
      return send_file('../lib/esm/create_data_paths.py', attachment_filename='create_data_paths.py') 
   except Exception as e:
      return str(e)

@app.route('/esmdata_path.py/')
def giveESMDataPath():
   try:
      return send_file('../lib/esm/data_path.py', attachment_filename='data_path.py') 
   except Exception as e:
      return str(e)


@app.route('/esm_project.py/')
def giveESM_project():
   try:
      return send_file('../lib/esm/esm_project.py', attachment_filename='esm_project.py') 
   except Exception as e:
      return str(e)

#################################################
@app.route('/freefall2/')
def giveCSM_VP_freefall2():
   try:
      return send_file('./vp/py/Free_Fall2.py', attachment_filename='Free_Fall2.py') 
   except Exception as e:
      return str(e)

@app.route('/ballthrow2/')
def giveCSM_VP_ballthrow2():
   try:
      return send_file('./vp/py/Ball-throw2.py', attachment_filename='Ball-throw2.py') 
   except Exception as e:
      return str(e)





#################################################


@app.route('/db.py/')
def giveLibDBdotPy():
   try:
      return send_file('rawfiles/dbNUM.py', attachment_filename='db.py') 
   except Exception as e:
      return str(e)

@app.route('/ec_config.py/')
def giveLibECconfigPy():
   try:
      return send_file('../lib/ec_config.py', attachment_filename='ec_config.py') 
   except Exception as e:
      return str(e)

@app.route('/requirements.txt/')
@app.route('/requirements/')
def giveRequirements():
   try:
      return send_file('../requirements.txt', attachment_filename='requirements.txt') 
   except Exception as e:
      return str(e)

@app.route('/readme/')
def giveREADME():
   try:
      return send_file('../README.md', attachment_filename='readme.txt') 
   except Exception as e:
      return str(e)

@app.route('/readmecsm/')
def giveREADMECSM():
   try:
      return send_file('../README_CSM.rst', attachment_filename='readmeCSM.txt') 
   except Exception as e:
      return str(e)


@app.route('/web/')
@app.route('/webhtml/')
def giveTmplWebFile():
   try:
      return send_file('../lib/templates/web_da_index.html', attachment_filename='web_da_index.html') 
   except Exception as e:
      return str(e)

#####################################################################################################
#####################################################################################################
@app.route('/testj22/<name>/<what>',methods=['GET', 'PUT'])
def hell_testj22(name, what):
   return  jsonify({'Name':name, 'job':what}) # key=value形式的参数

@app.route('/testj',methods=['GET'])
def hell_testj00( ):
   return redirect('/testj/1st default string/Default 2nd String')

@app.route('/testj/<name>',methods=['GET', 'PUT'])
def hell_testj_has_one_argument(name):
   return redirect('/testj/{}/Default 2nd String'.format(name))

# to test sending data using GET method
# try  http://iottalk.vip/testj/Lin_Y_B/Chairman
@app.route('/testj/<name>/<what>',methods=['GET', 'PUT'])
def hell_testj(name, what):
   #theurl = '/testj22/{}/{}'.format(name,what)
   theurl = f'/testj22/{name}/{what}'
   #print( 'URL: ' + theurl)

   ans = '''<html><head><title>Test using JSON data</title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
 <style>
 .myfont { font-size:3.5vw; color:red; }
 .myfont3 { font-size:2.4vw; color:blue; }
 .button {
   background-color: #4CFF50;
   border: none; border-radius: 8px;
   font-size: 32px; color: blue;
   padding: 8px 16px;
   text-align: center; text-decoration: none;
   display: inline-block;
   margin: 4px 12px 8px;  /* 上 左 下 右 邊界 */
   cursor: pointer;
 }
 div.a{ position:absolute;
  top:46vh;
  left:38vw;
  width:68vw; clear:both;
 }
 </style>
 </head>'''
   ans += '\n<body style="background:yellow;font-size:3.2vw;color:blue">'
   ans += '這 是由 <a target=_blank href="/web.py">da/web.py</a> 內生出的網頁 -- by tsaiwn@cs.nctu.edu.tw '
   ans += '\n<br>測試時用 iottalk.vip/testj/第一字串/第二字串'
   ans += '\n<br> &nbsp; &nbsp;第一字串會被當 name, 第二字串會被當 job<br><br>'
   ans += '\n<a href="/testj22/{}/{}">'.format(name, what)
   ans += '點這讓 Server 用 JSON 資料型式回傳</a> (會蓋掉此頁面)<br>\n'

   ans += '''<br><font color=red class="myfont">回傳後你可以 google 一下看如何 檢視網頁Header </font>
<script>
window.onload = function() {
   //alert("Hello there");
} // windows.onload
function doCallBack(resp, stat) {
   // resp 是 JSON
   respStr = JSON.stringify(resp)
   //alert("in doCallBack: " + respStr)
   $("#echodata").html(respStr);
   $("#echostat").html("Status:"  +stat);
}

function doSubmit() {
  // ajax  to the server;  server 回傳 resp
    $.get( '''

   ans += '"' + theurl + '", '

   ans += '''
       function(ans, status) {
          doCallBack(ans, status);
       });
   // stop link reloading the page
   event.preventDefault();
}
</script>
'''
   ans += '''<br><font class="myfont3">
 我簡單說一下方法:<br>
 &nbsp;按滑鼠右鍵選檢查<br>
 &nbsp;進入開發者頁面點 Network 然後按 F5 <br>
 &nbsp;注意右半窗左邊(就是螢幕中間啦)<br>
 &nbsp;在 Name 下方有網址可以點,<br>
 &nbsp;點了右邊就會秀出 Header<br>
 &nbsp;也可查看其他相關資料 !</font>
 <hr style="border-top:3px solid green">
<button class="button" type="button" onclick="doSubmit(); return false;" style="font-size:24px;color:blue;"><b>
 按 這 從內部用 JQuery 做 /testj22/arg1/arg2 並處理回傳的 JSON</button>
<hr style="border-top:3px solid blue">
<div class="a">
 <table><tr><td width=88><td bgcolor=lightyellow><b>
 <font color=blue class="myfont3">
 <p id="echodata" cc="這到 </p>之間會被回傳的結果換掉">回傳的 JSON 資料會塞在這</p>
 </font><hr style="border:5px solid darkRed;" />
 <p id="echostat" >回傳的 Status 會在這</p>
 <br>
 </tr></table>
</div>

'''
   return ans

#####################################################################################################
#####################################################################################################
#####################################################################################################
def check_auth(username, password):
    """This function is called to check if a username /
      password combination is valid.
    """
    return username == 'iottalk' and password == 'secrettar'

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
     'Could not verify your access level for that URL.\n'
     'You have to login with proper credentials', 401,
     {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated


@app.route('/iotvip.tar')
@app.route('/vipiot.tar')
@app.route('/getvip.tar')
@requires_auth
def giveTheVIPArchive():
   try:
      return send_file('rawfiles/iotvip.tar', attachment_filename='iotvip.tar') 
   except Exception as e:
      return str(e)


@app.route('/tmpl.tar')
@requires_auth
def giveTMPLtar():
   try:
      return send_file('rawfiles/tmpl.tar', attachment_filename='templates.tar') 
   except Exception as e:
      return str(e)


#################################################
#####################################################################################################
@app.route('/echoform', methods = ['POST', 'GET'])
@app.route('/ansform', methods = ['POST', 'GET'])
def echoformtest( ):
   if request.method == 'GET':
      return redirect('/testform')
   data = request.form
   osinfo = "Unknown, maybe is Windows"
   nginxinfo = "empty nginx"
   try:
      osinfo = subprocess.check_output("cat /etc/*release", shell=True).decode("utf-8")
      nginxinfo =  subprocess.check_output("cat /etc/nginx/sites-enabled/*", shell=True).decode("utf-8")
   except:
     print("echoform error")
   return render_template("ansform.html",result = data, name='蔡文能 tsaiwn',nginx=nginxinfo, osinfo=osinfo)
 
@app.route('/ansform.txt')
def ansform_txt( ):
    return send_file('templates/ansform.html', attachment_filename='ansform.txt')

@app.route('/testform.txt')
@app.route('/formtest.txt')
def testform_txt( ):
    ans = '<html><body style="background:yellow;font-size:2.8vw;color:blue">這 /testform 是由 da/web.py 內生出的網頁, 請看 '
    ans += '<a href="/web.py">da/web.py</a><br>'
    ans += 'or 或 '
    ans += '<a href="/testform">點這重新測試 /testform</a><br>'
    ans += '<br><br></body></html>'
    return ans

@app.route('/testform')
@app.route('/formtest')
def formtest( ):
   ans='''<!DOCTYPE html>
   <html>
   <head>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
   <meta charset="UTF-8">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
   <style>
   .myfont{ font-size:2.4vw; color:blue; }
   .myfont3{ font-size:2.0vw; color:black; }
   </style></head>
   <body bgcolor="lightBlue">
   <p class="myfont"><font style="font-size:2.8vw; color:darkred;">
   請填寫資料然後點按底下的 Submit送出 !</font><br>
   <! form action="https://iottalk.vip/echoform" method="post" class="myfont3">
   <form action="/echoform" method="post" class="myfont">
      <fieldset style="width:58vw;border-color: #F00;">
      <legend style="font-weight: bold;color:darkred">填寫以下資料：</legend>
      First Data: <input type="text" name="data01"><br>
      2nd  Data: <font style="font-size:1.8vw">&nbsp;&nbsp;</font><input type="text" name="data02"><br>
      3th Data: <font style="font-size:1.5vw">&nbsp;&nbsp;</font> <input type="text" name="ggyy"><br>   <!--- 故意 -->
      User name:<input type="text" name="username" maxlength="10"><br>
      Password: <font style="font-size:1.8vw">&nbsp;&nbsp;</font><input type="password" name="passwd" maxlength="10"><br>
      </fieldset>
      	<input type="submit" value="Submit送出" style="background:#9f9;color:blue;position: relative;left: 35vw;">
   </form>
   </p>
   <p class="myfont3">測試用 POST method 把FORM資料送到
   <font color=blue size=6"><a href="/web.py">da/web.py</a></font>
   的 /echoform (捲到 /echoform 處看code)
   </p>
   <p class="myfont">你可以檢視網頁原始檔看這頁(FORM/action)如何送出資料以及送去何處?  </p>
   <hr style="border-top:5px solid #88f;" width="68%" align=left>
   </body>
   </html>'''
   return ans


@app.route('/userdocuments')
@app.route('/userdoc')
def doc_listing( ):
    doc_dir = 'docs/'
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    static_DIR =  os.path.join(BASE_DIR, 'static')
    doc_path = os.path.join(static_DIR, doc_dir)

    # Return 404 if path doesn't exist
    if not os.path.exists(doc_path):
        #return abort(404)
        return redirect('/404/')

    # Check if path is a file and serve
    if os.path.isfile(doc_path):
        return send_file(doc_path)

    # Show directory contents
    files = os.listdir(doc_path)
    return render_template('listfiles.html', files=files, docdir=doc_dir)


if __name__ == '__main__':
    app.run('0.0.0.0', port=int("8080"),debug=True, threaded=True)
