class Root: _cp_config = {'tools.sessions.on': True, 'tools.auth.on': True} auth = AuthController() restricted = RestrictedArea() @cherrypy.expose @require() def index(self): return """This page only requires a valid login.""" @cherrypy.expose def open(self): return """This page is open to everyone""" @cherrypy.expose @require(name_is("joe")) def only_for_joe(self): return """Hello Joe - this page is available to you only""" # This is only available if the user name is joe _and_ he's in group admin @cherrypy.expose @require(name_is("joe")) @require(member_of("admin") ) # equivalent: @require(name_is("joe"), member_of("admin")) def only_for_joe_admin(self): return """Hello Joe Admin - this page is available to you only"""
def __init__(self, server_rpc): Controller.__init__(self, server_rpc) self.auth = AuthController(server_rpc) self.sr = ServiceRequestController(server_rpc) self.col = CollectorController(server_rpc) self.dev = DeviceController(server_rpc) self.user = UserController(server_rpc) self.search = SearchController(server_rpc) self.src = SourceController(server_rpc)
class Root: _cp_config = { 'tools.sessions.on': True, 'tools.auth.on': True } auth = AuthController() restricted = RestrictedArea() def generatelogoutbutton(self): return """<form method="post" action="/auth/logout"><input type="submit" value="log out" />""" @cherrypy.expose @require() def generate(self): return open("generate.html") @cherrypy.expose @require() def index(self): s = "<html><body>This page only requires a valid login. You are logged in as: " + cherrypy.request.login s += self.generatelogoutbutton() s += "<br><br>" s += "<a href=/auth/logout>Logout</a><br>" if cherrypy.request.login == 'joe': s += "<a href=/only_for_joe>Only For Joe</a><br>" if member_of("admin"): s += "<a href=/only_for_joe_admin>Only For Joe Admin</a><br>" s += "<a href=/generate>Generate Random String</a><br>" s += "<a href=/open>Open page</a><br>" s += "</body></html>" return s @cherrypy.expose def open(self): s = "This page is open to everyone. " return s @cherrypy.expose @require(name_is("joe")) def only_for_joe(self): return """Hello Joe - this page is available to you only""" # This is only available if the user name is joe _and_ he's in group admin @cherrypy.expose @require(name_is("joe")) @require(member_of("admin")) # equivalent: @require(name_is("joe"), member_of("admin")) def only_for_joe_admin(self): return """Hello Joe Admin - this page is available to you only"""
class Root(): """main route class""" auth = AuthController() @cherrypy.expose @require(login_required()) def index(self): """home page""" template_index = env.get_template('index.html') return template_index.render() #Define Account Functions @cherrypy.expose def login(self): """login route""" template_index = env.get_template('login.html') return template_index.render() @cherrypy.expose def register(self, *args, **kwargs): """user registration route""" template_index = env.get_template('register.html') if cherrypy.request.method == "POST": username = cherrypy.request.params['username_input'] password = cherrypy.request.params['pwd_input'] hashed_password = bcrypt.hashpw( password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") group = cherrypy.request.params['group_input'] print("username: "******" , password: "******" group: " +group) user = User(username=username, password=hashed_password, user_group=group) session = Session() session.add(user) session.commit() raise cherrypy.HTTPRedirect("/login") return template_index.render()
def __init__(self, config_file): self.config_file = config_file self.conf = Config(self.config_file) self.auth = AuthController(self.config_file) self.api = API(self.config_file)
class Root(object): script = "" _cp_config = {'tools.sessions.on': True, 'tools.auth.on': True} auth = AuthController() @cherrypy.expose #devolve a página incial def index(self): cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/index.html', 'r').read() @cherrypy.expose def login(self): cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/login.html', 'r').read() @cherrypy.expose def register(self): cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/register.html', 'r').read() @cherrypy.expose def createUser(self, firstname_input, lastname_input, username_input, email_input, pwd_input): username = username_input firstname = firstname_input lastname = lastname_input password = pwd_input email = email_input print "username: "******" , password: "******" , email: " + email with sqlite3.connect('users.db') as cur: cur.execute( '''INSERT INTO users (username, firstname, lastname, password, email, groupname) VALUES (?,?,?,?,?,?)''', (username, firstname, lastname, password, email, 'user')) current_dir = os.path.dirname(os.path.abspath(__file__)) directory = current_dir + "/app/uploads/" + str(username) if not os.path.exists(directory): os.makedirs(directory) raise cherrypy.HTTPRedirect("/login") @cherrypy.expose @require(member_of("user")) def changeUser(self, newusername): username = cherrypy.request.login with sqlite3.connect('users.db') as cur: cur.execute( '''UPDATE users SET username = ? WHERE username LIKE ?''', ( newusername, username, )) return @cherrypy.expose @require(member_of("user")) def api(self): effects_ins = [ ("BGR2GRAY", "opencvfunction/BGR2GRAY"), ("canny", "opencvfunction/canny"), ("BGR2HSV", "opencvfunction/BGR2HSV"), ("BGR2HLS", "opencvfunction/BGR2HLS"), ("faceeyedetect", "opencvfunction/faceeyedetect"), ("eyedetect", "opencvfunction/eyedetect"), ("facedetect", "opencvfunction/facedetect"), ("blur", "opencvfunction/blur"), ("opening", "opencvfunction/opening"), ("gradient", "opencvfunction/gradient"), ("tophat", "opencvfunction/tophat"), ("blackhat", "opencvfunction/blackhat"), ("closing", "opencvfunction/closing"), ("erode", "opencvfunction/erode"), ("dilate", "opencvfunction/dilate"), ("simplethresholding", "opencvfunction/simplethresholding"), ("adaptivethresholding", "opencvfunction/adaptivethresholding"), ("medianblur", "opencvfunction/medianblur"), ("gaussianblur", "opencvfunction/gaussianblur"), ("resize", "opencvfunction/resize") ] with sqlite3.connect('users.db') as cur: c = cur.execute('''SELECT * FROM effects''') exist = c.fetchone() if exist is None: print "ADDING ELEMENTS TO DB" cur.executemany( '''INSERT INTO effects(effect_name,effect_filelocation) VALUES (?, ?)''', effects_ins) cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/api.html', 'r').read() @cherrypy.expose @require(member_of("user")) def info(self): username = cherrypy.request.login info = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT firstname, lastname FROM users WHERE username LIKE ?''', (username, )) info = c.fetchall() returnjson = '{"firstname" : "' + str( info[0][0]) + '", "lastname" : "' + str(info[0][1]) + '"}' returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) @cherrypy.expose @require(member_of("user")) def getScriptCode(self, effect_name): info = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT effect_filelocation FROM effects WHERE effect_name LIKE ?''', (effect_name, )) info = c.fetchall() print info[0][0] with open(info[0][0]) as fout: contents = json.load(fout) print contents cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(contents) @cherrypy.expose @require(member_of("user")) def account(self): cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/account_info.html', 'r').read() @cherrypy.expose @require(member_of("user")) def histPage(self): cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/image_history.html', 'r').read() @cherrypy.expose @require(member_of("user")) def accountinfo(self): username = cherrypy.request.login info = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT email FROM users WHERE username LIKE ?''', (username, )) info = c.fetchall() returnjson = '{"email" : "' + str( info[0][0]) + '", "username" : "' + str(username) + '"}' returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) @require(member_of("user")) @cherrypy.expose def getHistory(self): username = cherrypy.request.login infolist = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT filelocation, script, script_location, timest FROM images WHERE user LIKE ?''', (username, )) infolist = c.fetchall() returnjson = '[' for info in infolist: returnjson += '{"filelocation" : "' + str( info[0]) + '", "script" : ' + str( info[1]) + ', "script_location" : "' + str( info[2]) + '", "timestamp" : "' + str(info[3]) + '"},' returnjson = returnjson[:-1] returnjson += ']' print returnjson returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) @require(member_of("user")) @cherrypy.expose def saveToHistory(self): username = cherrypy.request.login filename = os.path.basename(cherrypy.request.headers['x-filename']) info1 = cherrypy.request.headers['info'] info = json.loads(info1) directory = os.path.dirname( os.path.abspath(__file__)) + "/app/uploads/" + str(username) if not os.path.exists(directory): os.makedirs(directory) destination = os.path.join(directory, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) altered_filename, hist_dest = createEffect(info, destination) script_dir = "/uploads/" + str(username) + '/' directory = "/uploads/" + str(username) + '/' + altered_filename script_name = scriptCreator(info, script_dir, altered_filename) script_dest = script_dir + script_name with sqlite3.connect('users.db') as cur: cur.execute( '''INSERT INTO images (filename, script, filelocation, user, script_location) VALUES (?,?,?,?,?)''', (altered_filename, str(info1), directory, str(username), script_dest)) return @require(member_of("user")) @cherrypy.expose def upload(self): filename = os.path.basename(cherrypy.request.headers['x-filename']) info = cherrypy.request.headers['info'] info = json.loads(info) print "\ninfo -->: " + str(info['effect']) + "\n" current_dir = os.path.dirname( os.path.abspath(__file__)) + "/app/uploads" destination = os.path.join(current_dir, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) altered_filename, hist_dest = createEffect(info, destination) if altered_filename == None: returnjson = '{"altered_filename" : "ERROR", "hist_dest" : "The selected effect combination is not allowed"}' else: script_name = scriptCreator(info, "/scripts_upload", altered_filename) returnjson = '{"altered_filename" : "' + str( '/uploads/' + altered_filename) + '", "script_name" : "' + str( script_name) + '", "hist_dest" : "' + str(hist_dest) + '"}' print "\n" + returnjson + "\n" returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) @require(member_of("user")) @cherrypy.expose def uploadMatch(self): filename = os.path.basename(cherrypy.request.headers['x-filename']) current_dir = os.path.dirname( os.path.abspath(__file__)) + "/app/uploads" destination = os.path.join(current_dir, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) print "/app/uploads/" + filename return "/app/uploads/" + filename ######################################################################################### # New functions @require(member_of("user")) @cherrypy.expose def submitNewFunc(self): username = cherrypy.request.login filename = os.path.basename(cherrypy.request.headers['x-filename']) functionInputName = os.path.basename( cherrypy.request.headers['functionInputName']) functionInputNumbArgs = os.path.basename( cherrypy.request.headers['functionInputNumbArgs']) directory = os.path.dirname( os.path.abspath(__file__)) + "/app/uploads/" + str(username) if not os.path.exists(directory): os.makedirs(directory) destination = os.path.join(directory, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) print "++++++++++++++++++++++++++++++++\n" print "filename: " + filename + "\tfunctionInputName: " + functionInputName + "\tfunctionInputNumbArgs: " + functionInputNumbArgs print "\ndestination: " + destination print "\n++++++++++++++++++++++++++++++++" with sqlite3.connect('users.db') as cur: cur.execute( '''INSERT INTO addedFunctions (func_name, numberofargs, functionfilelocation, user) VALUES (?,?,?,?)''', (functionInputName, functionInputNumbArgs, "/app/uploads/" + str(username) + "/" + filename, str(username))) return "/app/uploads/" + str(username) + "/" + filename ######################################################################################### # Load Added functions @require(member_of("user")) @cherrypy.expose def getAddedFunctions(self): username = cherrypy.request.login infolist = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT func_name, numberofargs, functionfilelocation FROM addedFunctions WHERE user LIKE ?''', (username, )) infolist = c.fetchall() print "infolist" print infolist if infolist == []: returnjson = '{"functionInputName" : "noaddedFunctions"}' returnmessage = json.loads(returnjson) print returnmessage cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) returnjson = '[' for info in infolist: returnjson += '{"functionInputName" : "' + info[ 0] + '", "functionInputNumbArgs" : ' + str( info[1]) + ', "functionfilelocation" : "' + info[2] + '"},' returnjson = returnjson[:-1] returnjson += ']' print returnjson returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) ######################################################################################### # Load custom scripts @require(member_of("user")) @cherrypy.expose def getCustomScriptList(self): username = cherrypy.request.login infolist = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT custom_name, effects FROM customScripts WHERE user LIKE ?''', (username, )) infolist = c.fetchall() print "infolist" print infolist if infolist == []: returnjson = '{"custom_name" : "nocustomScript"}' returnmessage = json.loads(returnjson) print returnmessage cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) returnjson = '[' for info in infolist: inf = json.loads(info[1]) returnjson += '{"custom_name" : "' + str( info[0]) + '", "effects" : ' + info[1] + '},' returnjson = returnjson[:-1] returnjson += ']' print returnjson returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) ######################################################################################### # Creation of custom script @require(member_of("user")) @cherrypy.expose def createCustomScript(self, script_lines, name): username = cherrypy.request.login print "\nscript_lines" + script_lines + "\n" with open("custom_Script.txt", "w") as text_file: text_file.write(script_lines) info = scriptParser("custom_Script.txt") returninfo = json.dumps(info) print "\ninfo -->: " + str(info) + "\n" with sqlite3.connect('users.db') as cur: cur.execute( '''INSERT INTO customScripts (custom_name, effects, user) VALUES (?,?,?)''', (name, returninfo, str(username))) cherrypy.response.headers["Content-Type"] = "application/json" return returninfo ######################################################################################### # Script related functions @require(member_of("user")) @cherrypy.expose def getScriptFile(self): list_of_files = glob.glob('app/scripts_upload/*') latest_file = max(list_of_files, key=os.path.getctime) file = open(latest_file, "r") return file @require(member_of("user")) @cherrypy.expose def scriptUpload(self): filename = os.path.basename(cherrypy.request.headers['x-filename']) current_dir = os.path.dirname( os.path.abspath(__file__)) + "/app/scripts_upload" destination = os.path.join(current_dir, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) Root.script = destination print "SCRIPT ----->>>>>>>>>>>" + Root.script return ('/scripts_upload/' + filename) @require(member_of("user")) @cherrypy.expose def viewScript(self): filename = os.path.basename(cherrypy.request.headers['x-filename']) print "FILE NAME ------->>>>>>>>>>>>> " + filename f = open('app/scripts_upload/' + filename, "r") contents = [] for line in f: contents.append(line) print contents return contents @require(member_of("user")) @cherrypy.expose def applyScript(self): filename = os.path.basename(cherrypy.request.headers['x-filename']) print "SCRIPT ----->>>> APPPPPPPPPLY >>>>>>>" + Root.script info = scriptParser(Root.script) returninfo = str(json.dumps(info['effect'])) print "\ninfo -->: " + str(info['effect']) + "\n" current_dir = os.path.dirname( os.path.abspath(__file__)) + "/app/uploads" destination = os.path.join(current_dir, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) altered_filename, hist_dest = createEffect(info, destination) if altered_filename == None: return else: returnjson = '{"altered_filename" : "' + str( '/uploads/' + altered_filename) + '", "script_info" : ' + str( returninfo) + ', "hist_dest" : "' + str(hist_dest) + '"}' print "\n\nRETURNJSON ----------- " + returnjson + "\n\n" returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage)
class Root(object): _cp_config = { 'tools.sessions.on': True, 'tools.auth.on': True, 'tools.sessions.locking': 'explicit' } auth = AuthController() def __init__(self): self.indexHtmlTemplate = Template( filename='templates/indexTemplate.html') self.lang = rospy.get_param("/system_lang", "en") #self.lang='en' #Load default dict fp = open('lang/en.txt', 'r') self.language = json.load(fp, 'utf-8') fp.close() #Load specific dict if different to english if self.lang != 'en': try: fp = open('lang/' + self.lang + '.txt', 'r') # self.language.update(json.load(fp)) self.language.update(json.load(fp)) fp.close() except IOError: print "Language error" self.lang = "en" #Post the system lang to ROS and set the Param if self.lang == "en" or self.lang == "es": rospy.set_param("/system_lang", self.lang) lang_pub = rospy.Publisher('/system_lang', String) lang_pub.publish(String(self.lang)) print "PUBLISHING NEW LANG: " + self.lang ''' else: #If language is unknown, set the ROS system language as english rospy.set_param("/system_lang", "en") lang_pub = rospy.Publisher('/system_lang', String) lang_pub.publish(String("en")) ''' def readLanFile(self): config = ConfigParser.ConfigParser() config.readfp(open("lang/en.txt")) allsections = config.sections() for i in allsections: if req.command == config.get(i, "input"): execparams = config.get(i, "command") result = commands.getoutput(execparams) return result return "Error, input not exist" def setCookieLang(self, lan): cookie = cherrypy.response.cookie cookie['language'] = lan cookie['language']['path'] = '/' cookie['language']['max-age'] = 360000 cookie['language']['version'] = 1 def readCookieLang(self): cookie = cherrypy.request.cookie try: res = cookie['language'].value except KeyError: print "KEY ERROR" res = "" return res @cherrypy.expose def index(self, new_lang="", activeTab=0): print "NEW LANG CHANGE REQUEST: " + new_lang if new_lang != "": self.change_language(new_lang) ''' else: cookielang=self.readCookieLang() if cookielang!="": self.change_language(cookielang) ''' return self.indexHtmlTemplate.render(language=self.language, tab=activeTab) #@cherrypy.expose #def test(self): #return "Login needed test service" def change_language(self, new_lang): #Load specific dict #Load default dict print "Comparing self.lang: " + self.lang + ", new_lang: " + new_lang if self.lang != new_lang: #self.setCookieLang(new_lang) fp = open('lang/en.txt', 'r') self.language = json.load(fp, 'utf-8') fp.close() try: fp = open('lang/' + new_lang + '.txt', 'r') # self.language.update(json.load(fp)) self.language.update(json.load(fp)) fp.close() self.lang = new_lang except IOError: print "Language error" #Post the system lang to ROS and set the Param if new_lang == "en" or new_lang == "es": rospy.set_param("/system_lang", new_lang) lang_pub = rospy.Publisher('/system_lang', String) lang_pub.publish(String(new_lang)) print "PUBLISHING NEW LANG: " + new_lang else: #If language is unknown, set the ROS system language as english rospy.set_param("/system_lang", "en") lang_pub = rospy.Publisher('/system_lang', String) lang_pub.publish(String("en")) cherrypy.root.checkers.set_language(self.language) cherrypy.root.training.set_language(self.language) cherrypy.root.settings.set_language(self.language) cherrypy.root.teleoperation.set_language(self.language) cherrypy.root.confWizard.set_language(self.language) cherrypy.root.voiceRecognition.set_language(self.language) cherrypy.root.xmms2.set_language(self.language) cherrypy.root.qbo_questions.set_language(self.language) cherrypy.root.launchersTab.set_language(self.language) cherrypy.root.recorder.set_language(self.language)
class Root: _cp_config = {'tools.sessions.on': True, 'tools.auth.on': True} auth = AuthController() @cherrypy.expose @require() def upload_view(self): html = check_login() html += """ <h2>Upload a file</h2> <form action='/upload_file' method='post' enctype='multipart/form-data'> File: <input type='file' name='videoFile'/> <br/> <input type='submit' value='Upload'/> </form> <h2>Download a file</h2> <a href='/'>Go to Downloads</a> """ html += footer return html @cherrypy.expose @require() def index(self, directory="static/download"): html = check_login() html += """<h2>Here are the files in the selected directory:</h2> <h3><a href="/upload_view"> Upload Files </a></h3> <table><tr><th>Files Available</th></tr> <a href="/?directory=%s"> Parent Directory [..] </a></br></br> """ % os.path.dirname(os.path.abspath(directory)) for filename in glob.glob(directory + '/*'): absPath = os.path.abspath(filename) if os.path.isdir(absPath): html += '<tr><td><a href="/?directory=' + absPath + '">' + os.path.basename( filename) + "/[Dir]</a> </tr></td>" else: html += '<tr><td><a href="/index_download?filepath=' + absPath + '">' + os.path.basename( filename) + "</a> </tr></td>" html += """ </table><br></div></body></html>""" return html @cherrypy.expose def register(self): page = header page += """ <h2> Register</h2><br> <form method="post" action="getdata"> Name : <input type="text" name="uname" required="required"/><br> Password : <input type="password" name="upasswd" required="required"/><br> Email : <input type="email" name="email" required="required"/><br> Phone No. : <input type="number" name="phno" required="required"/><br> Age : <input type="number" name="age" required="required"/><br> Group : <select name="group"> """ for x in range(1, groups + 1): page += """ <option value=" """ + str(x) + """" >""" + str( x) + """ </option>""" page += """</select><br> <input type="hidden" value="add" name="action"/> <input type="submit" value="Register"> </form></div></body></html>""" return page @cherrypy.expose @require() def remove(self): page = check_login() page += """ <h2> Remove</h2><br> <form method="post" action="getdata"> Name : <input type="text" name="uname"/><br> Password : <input type="password" value="" name="upasswd"/><br> Email : <input type="email" name="email" required="required"/><br> Phone No. : <input type="number" name="phno" required="required"/><br> Age : <input type="number" name="age" required="required"/><br> <input type="hidden" value="remove" name="action"/> <input type="submit" value="Remove"> </form></div></body></html>""" return page @cherrypy.expose def getdata(self, uname, upasswd, action, email, phno, age, group): if action == "add": e_pass = encrypt_handler.for_encrypt_pass(upasswd) adduser = db_handler.add_user(uname, e_pass) register = db_handler.register(uname, email, phno, age, group) group_info = db_handler.insert_to_group(uname, group) html = header html += """ <h1>Status : %s <br> %s <br> %s</h1> """ % ( adduser, register, group_info) elif action == "remove": adduser = db_handler.remove_user(uname) unregister = db_handler.unregister(uname, email, phno, age) remove_f_group = db_handler.delete_from_group(uname, group) html = header html += """ <h1>Status : %s <br> %s <br> %s </h1> """ % ( adduser, unregister, remove_f_group) html += "<h3><a href=/>Click to continue</a></h3></div></body></html>" return html @require() @cherrypy.config(**{'response.timeout': 3600}) # default is 300s @cherrypy.expose() def upload_file(self, videoFile): html = check_login() assert isinstance(videoFile, cherrypy._cpreqbody.Part) user = cherrypy.session['cur_user'] file = videoFile.filename destination = os.path.join( '/home/aristocrat/NetBeansProjects/SecureCloudGroupShare/static/download/', videoFile.filename) try: # Note that original link will be deleted by tempfile.NamedTemporaryFile os.link(videoFile.file.name, destination) out = db_handler.file_upload(user, file) except OSError, e: html += 'error occured : %s ' % (e) html += footer return html html += "ok, got it filename='%s' , %s" % (videoFile.filename, out) html += footer return html
class Root(object): auth = AuthController() restricted = RestrictedArea() object = Any_object() employee = Employee() timeline = Timeline() clients = Clients() ktree = KTree() account = Account() cases = Case() @cherrypy.expose @require(member_of("users")) def index(self): tmpl = lookup.get_template("dashboard.html") c = get_session_context(cherrypy.request.login) params = cherrypy.request.headers rwQueue.msg_delivery_for_user.delay(str(c['uuid'])) G.reload() return tmpl.render(params=params, session_context=c, G=G) @cherrypy.expose @require(member_of("admin")) def autoclassify_all_notlinked_objects(self): try: rwLearn.autoclassify_all_notlinked_objects() except Exception as e: return ShowError("Обновить автоклассификацию нельзя. " + str(e)) else: pass raise cherrypy.HTTPRedirect("/settings?menu=ktree") @cherrypy.expose @require(member_of("users")) def settings(self, menu=None): session_context = cherrypy.session.get('session_context') if not menu or menu == "": tmpl = lookup.get_template("settings_dashboard.html") session_context['back_ref'] = '/' session_context['menu'] = "settings" params = cherrypy.request.headers cherrypy.session['session_context'] = session_context return tmpl.render(params=params, session_context=session_context) elif menu == 'company': tmpl = lookup.get_template("settings_dashboard.html") session_context['back_ref'] = '/settings' session_context['menu'] = "company" elif menu == 'employee' or menu == 'accounts': tmpl = lookup.get_template("employee.html") session = rwObjects.Session() # если пользователь с правами администратора, выбираем всех сотрудников if 'admin' in session_context['groups']: users = session.query(rwObjects.Employee). \ filter_by(comp_id=session_context['comp_id']).all() obj_keys = users[0].get_attrs() f = users[0].get_fields() session_context['back_ref'] = '/settings' session_context['menu'] = "employee" # если пользователь с обычными правами, только свой профиль else: users = [rwObjects.get_by_uuid(session_context['uuid'])[0]] obj_keys = users[0].get_attrs() f = users[0].get_fields() session_context['back_ref'] = '/settings' session_context['menu'] = "accounts" linked_objects = dict() for user in users: refs = session.query(rwObjects.Reference). \ filter(rwObjects.sqlalchemy.and_(rwObjects.Reference.source_uuid == user.uuid, rwObjects.Reference.target_type == "accounts", rwObjects.Reference.link == 0)).all() linked_objects[user.uuid] = [] for ref in refs: linked_objects[user.uuid].append(rwObjects.get_by_uuid(ref.target_uuid)[0]) session.close() cherrypy.session['session_context'] = session_context return tmpl.render(obj=users, keys=obj_keys, session_context=session_context, view_f=f[1], all_f=f[0], linked=linked_objects) elif menu == 'clients': tmpl = lookup.get_template("settings_dashboard.html") session_context['back_ref'] = '/settings?menu=clients' elif menu == 'ktree': tmpl = lookup.get_template("ktree_settings.html") session = rwObjects.Session() tree = rwObjects.KnowledgeTree() session_context['back_ref'] = '/settings?menu=ktree' session_context['menu'] = "ktree_settings" return tmpl.render(obj=tree, session=session, session_context=session_context) else: print "меню без указания." tmpl = lookup.get_template("settings_dashboard.html") session_context['back_ref'] = '/settings' session_context['menu'] = "settings" params = cherrypy.request.headers return tmpl.render(params=params, session_context=session_context) @cherrypy.expose @require(member_of("users")) def help(self, menu=None): tmpl = lookup.get_template("help.html") session_context = cherrypy.session.get('session_context') return tmpl.render(session_context=session_context) @cherrypy.expose def open(self): return """This page is open to everyone""" @cherrypy.expose @require(name_is("joe")) def only_for_joe(self): return """Hello Joe - this page is available to you only""" # This is only available if the user name is joe _and_ he's in group admin @cherrypy.expose @require(name_is("joe")) @require(member_of("admin")) # equivalent: @require(name_is("joe"), member_of("admin")) def only_for_joe_admin(self): return """Hello Joe Admin - this page is available to you only"""
class PcapVisualisation: _cp_config = {'tools.sessions.on': True, 'tools.auth.on': True} auth = AuthController() restricted = PcapVisualisationAdmin() def __init__(self): self.dbPcaps = dbService("pcaps") self.dbUsers = dbService("users") def init(self): self.doc = dominate.document(title='Ahahaha') with self.doc.head: link(rel='stylesheet', href='css/style.css') link(rel='stylesheet', href='css/bootstrap.min.css') script(type='text/javascript', src='js/jquery.js') script(type='text/javascript', src="js/three.js") script(type='text/javascript', src="js/Projector.js") script(type='text/javascript', src="js/CanvasRenderer.js") script(type='text/javascript', src="js/OrbitControls.js") script(type='text/javascript', src='js/bootstrap.min.js') script(type='text/javascript', src='js/script.js') @cherrypy.expose # @require() def index(self): # self.init() # self.showMenu() # self.showChosenFile() self.home() return str(self.doc) @cherrypy.expose # @require() def home(self): self.init() self.showMenu() username = cherrypy.session.get(SESSION_KEY) with self.doc: with div(cls='container'): with div(cls='well well-sm'): if str(username) != "None": h3("Hi, %s" % username, align='center') else: h3("Hi", align='center') return str(self.doc) def showMenu(self): with self.doc.head: meta(charset="utf-8") meta( name="viewport", content= "width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" ) with nav(cls="navbar navbar-inverse"): with div(cls="container-fluid"): with div(cls="navbar-header"): a("HOME", cls="navbar-brand", href="/home") with ul(cls="nav navbar-nav"): with li(): a("Player", href="/player") with li(): a("Statistics", href="/statistics") # with li(): # a("Statistics existing Pcap", href="searchStatistics") # button("DANGER",cls="btn btn-danger navbar-btn") username = cherrypy.session.get(SESSION_KEY) print username with ul(cls="nav navbar-nav navbar-right"): if username is None or str(username) == "None": with li(): with a(href="/auth/register"): # span (" Sign Up", cls="glyphicon glyphicon-user") span("Sign Up") with li(): with a(href="/auth/login"): # span (cls="glyphicon glyphicon-log-in") span("Login") else: with li(): with a(href="/auth/logout"): span("Log out") # @cherrypy.expose # @require() # @require(member_of("administrator")) # def editUsers(self, **kwargs): # self.init() # self.showMenu() # nb = 0 # index = 0 # if "nb" in kwargs: # nb = kwargs["nb"] # if index in kwargs: # index = kwargs["index"] # values = self.dbUsers.getAll() # with self.doc: # with div (cls="container"): # with ul (cls="pagination"): # with li(): # a ("1", href="#") # with li(cls="active"): # a ("2", href="#") # with li(): # a ("3", href="#") # with li(): # a ("4", href="#") # with li(): # a ("5", href="#") # return str(self.doc) @cherrypy.expose @require() def player(self, filename=None): self.init() self.showMenu() filename = "a.pcap" with self.doc: with div(cls='well well-sm'): if filename is None: p("No file loaded") else: span(str(filename)) button("Play", cls='btn', id="plyerlink") return str(self.doc) @cherrypy.expose # @require() def statistics(self, success=False, filename=None): self.init() self.showMenu() rez = None with self.doc: with div(cls='well well-sm'): a("Upload File", cls="btn btn-primary", data_toggle="collapse", href="#collapseExample", role="button", aria_expanded="false", aria_controls="collapseExample") with div(): br() with div(cls="collapse", id="collapseExample"): with div(cls="card card-body"): self.showStatistics() with div(cls="well well-sm"): a("Search File", cls="btn btn-primary", data_toggle="collapse", href="#collapseExample2", role="button", aria_expanded="false", aria_controls="collapseExample2") with div(): br() with div(cls="collapse", id="collapseExample2"): with div(cls="card card-body"): self.chooseFile() if success: # filename , extension = os.path.splitext(filename) # filenamerez = ".".join([filename, "txt"]) # h4(filenamerez) filepathresults = os.path.join(cfg.RESULT_DIR, filename, "index.html") if not os.path.isfile(filepathresults): # procesez si creez fisier cu rezultate p("No results . Processing ...") # inspect file self.processFile(filename) rez = self.showResultsFile(filename) else: rez = self.showResultsFile(filename) if rez is None: return str(self.doc) return rez @cherrypy.expose @require() def showStatistics(self, filename=None, success=False): # self.init() # self.showMenu() if os.path.isdir(os.path.join(os.getcwd(), "upload")): shutil.rmtree(os.path.join(os.getcwd(), "upload")) os.makedirs(os.path.join(os.getcwd(), "upload")) # with self.doc: if filename is None: self.uploadFile() if success is not None: if success == True: br() br() with div(id="alertaupload"): div("Success, file uploaded!", cls="alert alert-success") else: # filename , extension = os.path.splitext(filename) # filenamerez = ".".join([filename, "txt"]) # h4(filenamerez) filepathresults = os.path.join(cfg.RESULT_DIR, filename, "index.html") if not os.path.isfile(filepathresults): # procesez si creez fisier cu rezultate p("No results . Processing ...") pathResults = self.processFile(filename) if not pathResults: self.showFileErrorMessage(filename) self.showResultsFile(filename) else: self.showResultsFile(filename) # return str(self.doc) @cherrypy.expose def showFileErrorMessage(self, filename): with div(cls="well well-sm"): h4("No results for file %s" % ntpath.basename(filename)) @cherrypy.expose @require() def searchStatistics(self): self.init() self.showMenu() self.chooseFile() return str(self.doc) @cherrypy.expose def uploadFile(self, success=None): uploadedFile = False uploadFolder = os.path.join(os.getcwd(), "upload") if os.path.isdir(uploadFolder): if len(os.listdir(uploadFolder)) == 1: uploadedFile = True filee = os.listdir(uploadFolder)[0] br() with form(id="uploadForm", action="uploadRedirect", method="post", enctype="multipart/form-data", cls='form-horizontal'): with div(cls="input-group"): with label(cls="input-group-btn"): with span("Browse", cls="btn btn-primary"): input(type="file", style="display: none;", name="myFile") with div(cls='col-sm-3'): if uploadedFile: print("neh") input(value=filee, type="text", cls="form-control", readonly="readonly") else: print("yes") input(type="text", cls="form-control", readonly="readonly") br() input(value="Upload", type="submit", cls='btn') def upload(self, myFile): if os.path.isdir(os.path.join(os.getcwd(), "upload")): shutil.rmtree(os.path.join(os.getcwd(), "upload")) os.makedirs(os.path.join(os.getcwd(), "upload")) if len(myFile.filename) == 0: return None dest = os.path.join(os.getcwd(), "upload", myFile.filename) size = 0 f = open(dest, "w") while True: data = myFile.file.read(8192) if not data: break f.write(data) size += len(data) f.close() return dest @cherrypy.expose def uploadRedirect(self, **kwargs): if "myFile" in kwargs: myFile = kwargs["myFile"] else: myFile = None success = False filename = None rez = self.upload(myFile) filename = kwargs["myFile"].filename if rez is not None: success = True if len(filename) == 0: filename = None raise cherrypy.HTTPRedirect("/statistics?success=%s&filename=%s" % (success, filename)) # return self.statistics(success=success, filename=filename) def chooseFile(self): dictToRepresent = {"name": "", "sha256": "", "md5": ""} # with self.doc: with form(action="/filterResults"): self.representDictionaryAsComboBox(dictToRepresent, readonly=False, givenid="searchFileCombobox", givenidInput="searchFileInput") br() with div(cls='container'): button("Search pcap", cls="btn", id="seachPcapBTN", type="submit") @cherrypy.expose def filterResults(self, filterName, filterValue): pass results = self.dbPcaps.search(filterName, filterValue) if results is None: pass raise cherrypy.HTTPRedirect("/statistics") else: if len(results) != 1: pass # error len pcaps is not 0 # for pcap in results: pcap = results[0] if "name" not in pcap: pass # error - no filename filename = pcap["name"] filename, extension = os.path.splitext(filename) filenamerez = ".".join([filename, "txt"]) h4(filenamerez) filepathresults = os.path.join(cfg.RESULT_DIR, filenamerez) if not os.path.isfile(filepathresults): # procesez si creez fisier cu rezultate p("No results . Processing ...") self.processFile(filename) success = True raise cherrypy.HTTPRedirect("/statistics?success=%s&filename=%s" % (success, filename)) # self.showResultsFile(filepathresults) def showResultsFile(self, filename): # filename = ntpath.basename(filepath) pathfileResults = os.path.join(cfg.RESULT_DIR, filename, "index.html") if not os.path.isfile(pathfileResults): self.showFileErrorMessage(filename) self.init() self.showMenu() with self.doc: with div(cls="well well-lg"): h3("File: %s" % str(filename)) with div(cls="container"): with div(cls="well well-sm"): self.showInspectionResults(filename) a("Inspection details", href="showInspectionResultsDetails?filename=%s" % filename) with div(cls="container"): with div(cls="well well-sm"): a("TCP/UDP Sessions", href="showResultsFileSession?filename=%s" % filename) with div(cls="well well-sm"): a("IP Count", href="showResultsFileIpCount?filename=%s" % filename) with div(cls="well well-sm"): a("TCP Port Count", href="showResultsFileTCPPortCount?filename=%s" % filename) with div(cls="well well-sm"): a("TCP Port Count", href="showResultsFileUDPPortCount?filename=%s" % filename) with div(cls="well well-sm"): a("IP Protocol Count", href="showResultsFileIpProtocolCount?filename=%s" % filename) with div(cls="well well-sm"): a("Ethernet Type Count", href="showResultsFileEthTypeCount?filename=%s" % filename) with div(cls="well well-sm"): a("Image Report", href="showResultsFileImageReport?filename=%s" % filename) with div(cls="well well-sm"): a("GET/POST Report", href="showResultsFileGetPostReport?filename=%s" % filename) with div(cls="well well-sm"): a("HTTP Proxy Log", href="showResultsFileHttpProxylog?filename=%s" % filename) def getBootstrapInclude(self): return """ <html><head> <title>Ahahaha</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head><body> """ def divideIndex(self, filename): #divide in : TCP/UDP sessions, IP count, TCP Port Count, IP Protocol Count, Ethernet Type Count if filename is None: print "none" return "FilePath is None" # if not os.path.isfile(filename): # print "not a file" # return "File Path not a file %s" % str(filename) pathIndex = os.path.join(cfg.RESULT_DIR, filename, "index.html") if not os.path.isfile(pathIndex): print "index" return "Path index not a file %s" % str(pathIndex) f = open(pathIndex, "r").read() soup = BeautifulSoup(f, "html.parser") a = soup.find_all("table") counter = 0 for tableContent in a: pathTable = os.path.join(cfg.RESULT_DIR, filename, "%d.html" % counter) fw = open(pathTable, "w") fw.write(str(tableContent)) fw.close() counter += 1 # for tableName in ["image.html", "getpost.html", "httplog.text"]: tableName = "image.html" pathTable = os.path.join(cfg.RESULT_DIR, filename, tableName) newPathTable = os.path.join(cfg.RESULT_DIR, filename, "%d.html" % counter) f = open(pathTable, "r") soup = BeautifulSoup(f, "html.parser") a = soup.find_all("table") fw = open(newPathTable, "w") fw.write(str(a[0])) fw.close() f.close() counter += 1 tableName = "getpost.html" newContent = "" pathTable = os.path.join(cfg.RESULT_DIR, filename, tableName) newPathTable = os.path.join(cfg.RESULT_DIR, filename, "%d.html" % counter) f = open(pathTable, "r") line = f.readline() while "HTTP GETs and POSTs" not in line: line = f.readline() while line: newContent += line line = f.readline() f.close() f = open(newPathTable, "w") f.write(newContent) f.close() counter += 1 tableName = "httplog.text" pathTable = os.path.join(cfg.RESULT_DIR, filename, tableName) newPathTable = os.path.join(cfg.RESULT_DIR, filename, "%d.html" % counter) f = open(pathTable) content = f.read() f.close() content.replace("\n", "<br>") f = open(newPathTable, "w") f.write(content) f.close() @cherrypy.expose # @require() def showInspectionResults(self, filename): p("verdict : infected") @cherrypy.expose def showInspectionResultsDetails(self, filename): self.init() self.showMenu() with self.doc: with div(cls='container'): with div(cls='well well-sm'): p("Filename %s " % str(filename)) return str(self.doc) @cherrypy.expose def showResultsFileSession(self, filename): TABLE_NUMBER = 0 tableHeads = """ <tr><th>Nb</th> <th>Date</th> <th>Seconds</th> <th>IP Src</th> <th>Type</th> <th>Bytes</th> <th>Session</th> </tr> """ Tabletitle = "TCP/UDP Sessions" result = self.getHtmlTable(filename, TABLE_NUMBER, tableHeads, Tabletitle) return result @cherrypy.expose def showResultsFileIpCount(self, filename): TABLE_NUMBER = 1 tableHeads = """ <tr> <th>IP</th> <th>Count</th> </tr> """ Tabletitle = "IP Count" result = self.getHtmlTable(filename, TABLE_NUMBER, tableHeads, Tabletitle) return result @cherrypy.expose def showResultsFileTCPPortCount(self, filename): TABLE_NUMBER = 2 tableHeads = """ <tr> <th>Port</th> <th>Count</th> </tr> """ Tabletitle = "TCP Port Count" result = self.getHtmlTable(filename, TABLE_NUMBER, tableHeads, Tabletitle) return result @cherrypy.expose def showResultsFileUDPPortCount(self, filename): TABLE_NUMBER = 3 tableHeads = """ <tr> <th>Port</th> <th>Count</th> </tr> """ Tabletitle = "UDP Port Count" result = self.getHtmlTable(filename, TABLE_NUMBER, tableHeads, Tabletitle) return result @cherrypy.expose def showResultsFileIpProtocolCount(self, filename): TABLE_NUMBER = 4 tableHeads = """ <tr> <th>Protocol</th> <th>Count</th> </tr> """ Tabletitle = "IP Protocol Count" result = self.getHtmlTable(filename, TABLE_NUMBER, tableHeads, Tabletitle) return result @cherrypy.expose def showResultsFileEthTypeCount(self, filename): TABLE_NUMBER = 5 tableHeads = """ <tr> <th>Ethernet Type</th> <th>Count</th> </tr> """ Tabletitle = "Ethernet Type Count" result = self.getHtmlTable(filename, TABLE_NUMBER, tableHeads, Tabletitle) return result @cherrypy.expose def showResultsFileImageReport(self, filename): TABLE_NUMBER = 6 tableHeads = """ <tr> <th>Nb</th> <th>Date</th> <th>Corresponded IPS</th> <th>Image</th> </tr> """ Tabletitle = "Images" result = self.getHtmlTable(filename, TABLE_NUMBER, tableHeads, Tabletitle) return result @cherrypy.expose def showResultsFileGetPostReport(self, filename): TABLE_NUMBER = 7 tableHeads = "" # <tr> # <th>Nb</th> # <th>Date</th> # <th>Method</th> # <th>Details</th> # </tr> # """ Tabletitle = "" result = self.getHtmlTable(filename, TABLE_NUMBER, tableHeads, Tabletitle) return result @cherrypy.expose def showResultsFileHttpProxylog(self, filename): TABLE_NUMBER = 8 tableHeads = "" Tabletitle = "HTTP Proxy Log" result = self.getHtmlTable(filename, TABLE_NUMBER, tableHeads, Tabletitle) return result def getHtmlTable(self, filename, TABLE_NUMBER, tableHeads, Tabletitle): tableName = "%d.html" % TABLE_NUMBER pathfileResults = os.path.join(cfg.RESULT_DIR, filename, tableName) if not os.path.isfile(pathfileResults): self.divideIndex(filename) try: f = open(pathfileResults, "r") except OSError: self.showFileErrorMessage(filename) print "Error on showResultsFileIpCount %s" % str(filename) return "" newResult = self.getBootstrapInclude() linee = "<div class='well well-sm'><h3> %s </h3></div>" % str( Tabletitle) while linee: linee = linee.replace("blue", "#008B8B") linee = linee.replace("red", "#B8860B") linee = linee.replace("<table", '<table class="table table-hover" ') linee = linee.replace("border=2", "") if "<table" in linee: newResult += linee newResult += tableHeads else: newResult += linee linee = f.readline() return newResult def representDictionary(self, dictToRepresent, readonly=True): # with self.doc: with div(cls='container'): with form(cls="form-horizontal"): with div(cls='form-group'): for key in sorted(dictToRepresent): label(key, cls="col-sm-2 control-label") with div(cls="col-sm-10"): if readonly: input(str(dictToRepresent[key]), value=dictToRepresent[key], cls='form-control', readonly="readonly", id=str(key), name="inputdictionary", maxlength=250) else: input(str(dictToRepresent[key]), value=dictToRepresent[key], cls='form-control', id=str(key), name="inputdictionary", maxlength=250) def representDictionaryAsComboBox(self, dictToRepresent, readonly=True, givenid="comboboxDefaultId", givenidInput="inputDefaultId"): with div(cls='col-sm-3'): with select(cls='combobox form-control col-sm-4', align="left", id=givenid, name="filterName"): for key in sorted(dictToRepresent): option(str(key), value=str(key)) input(cls="form-control", type="text", id=givenidInput, pattern=".{3,}", required="required", title="3 characters minimum", name="filterValue") def processFile(self, filepath): filename = ntpath.basename(filepath) pathFileIndexRezults = os.path.join(cfg.RESULT_DIR, filename, "index.html") if os.path.exists(pathFileIndexRezults): return pathFileIndexRezults currentPath = os.getcwd() pathResults = os.path.join(cfg.RESULT_DIR, filename) if not os.path.exists(pathResults): os.makedirs(pathResults) shutil.copy(os.path.join(os.getcwd(), "chaosreader0.94"), pathResults) os.chdir(pathResults) cmd = "perl chaosreader0.94 %s" % filepath print cmd try: p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() except Exception as e: os.chdir(currentPath) print "Could not process file with error %s " % str(e) return False os.chdir(currentPath) if os.path.isfile(pathFileIndexRezults): return pathFileIndexRezults return False def inspectFile(self, filename): pass '''
"cheetah compile -R %s --iext tmpl --nobackup --odir _templates" % (templatePath)): sys.path.append( os.path.join(os.path.dirname(__file__), "_templates/", "templates")) else: print "Failed to Compile Templates" exit(1) #mount a couple of wikis, one at root and one /rstwiki different configs for each cherrypy.tree.apps[''] = Wiki( '/', os.path.join(os.path.dirname(__file__), "wiki.conf")) cherrypy.tree.apps['/rstwiki-howto'] = Wiki( '/rstwiki-howto', os.path.join(os.path.dirname(__file__), "rstwiki_docs.conf")) cherrypy.tree.apps['/github'] = Github( '/github', os.path.join(os.path.dirname(__file__), "github.conf")) #mount the auth app (login/logout), todo wrap this in an app when the AuthController gets a makeover cherrypy.tree.mount(AuthController(), "/auth", os.path.join(os.path.dirname(__file__), "wiki.conf")) #add files in the template dir to autoreload monitoring for f in os.listdir(os.path.join(os.path.dirname(__file__), "templates")): cherrypy.engine.autoreload.files.add( os.path.join(os.path.dirname(__file__), "templates", f)) if __name__ == '__main__': cherrypy.config.update( os.path.join(os.path.dirname(__file__), 'global.conf')) cherrypy.engine.start() cherrypy.engine.block()
class WebInterface(object): def error_page_404(status, message, traceback, version): status_msg = "%s - %s" % (status, message) return serve_template(templatename="index.html", title="404 - Page Not Found", msg=status_msg) cherrypy.config.update({'error_page.404': error_page_404}) def handle_error(): cherrypy.response.status = 500 logger.error("500 Error: %s" % _cperror.format_exc()) cherrypy.response.body = [ "<html><body>Sorry, an error occured</body></html>" ] _cp_config = { 'tools.sessions.on': True, 'tools.sessions.timeout': 10080, 'tools.auth.on': True, 'error_page.404': error_page_404, 'request.error_response': handle_error } auth = AuthController() @require() def index(self, oauth_token=None): if oauth_token: status, msg = backend.validate_oauth(oauth_token) else: status, msg = '', '' return serve_template(templatename="index.html", title="Home", status=status, msg=msg) index.exposed = True @require() def oauth_request(self): authorize_token_url, status, msg = backend.redirect_oauth() if not authorize_token_url: return serve_template(templatename="index.html", title="Home", status=status, msg=msg) else: raise cherrypy.HTTPRedirect(authorize_token_url) oauth_request.exposed = True @require() def oauth_logout(self): jiraappy.JIRA_OAUTH_TOKEN = None jiraappy.JIRA_OAUTH_SECRET = None cherrystrap.config_write() jiraappy.JIRA_LOGIN_STATUS = None jiraappy.JIRA_LOGIN_USER = None status, msg = backend.ajaxMSG('success', 'Successfully logged out of JIRA OAuth') return serve_template(templatename="index.html", title="Home", status=status, msg=msg) oauth_logout.exposed = True @require() def listener(self): return serve_template(templatename="listener.html", title="Webhooks") listener.exposed = True @require() def caller(self, call=None, action=None): status, msg = '', '' if call == 'reindex': status, msg = jiraInt.reindex(action) return serve_template(templatename="caller.html", title="Call JIRA", status=status, msg=msg) caller.exposed = True @require() def operations(self, script=None, issue_list_input=None): status, msg = '', '' if jiraappy.JIRA_LOGIN_STATUS: consumer, client = backend.stored_oauth() if request.method == 'POST': script = request.params['script'] issue_list_input = request.params['issue_list_input'] issue_list = [x.strip() for x in issue_list_input.split(',')] if script == 'bulk-delete-worklogs' and issue_list_input: status, msg = jiraInt.bulkDeleteWorklogs(issue_list) else: status, msg = backend.ajaxMSG( 'failure', 'No issues entered for processing') else: pass else: status, msg = backend.ajaxMSG( 'failure', 'Can not operate on JIRA without being logged in') return serve_template(templatename="operations.html", title="Bulk Operations", status=status, msg=msg) operations.exposed = True @require() def config(self): http_look_dir = os.path.join(cherrystrap.PROG_DIR, 'static/interfaces/') http_look_list = [ name for name in os.listdir(http_look_dir) if os.path.isdir(os.path.join(http_look_dir, name)) ] config = {"http_look_list": http_look_list} return serve_template(templatename="config.html", title="Settings", config=config) config.exposed = True @require() def logs(self): return serve_template(templatename="logs.html", title="Log", lineList=cherrystrap.LOGLIST) logs.exposed = True @require() def shutdown(self): cherrystrap.config_write() cherrystrap.SIGNAL = 'shutdown' message = 'shutting down ...' return serve_template(templatename="shutdown.html", title="Exit", message=message, timer=10) return page shutdown.exposed = True @require() def restart(self): cherrystrap.SIGNAL = 'restart' message = 'restarting ...' return serve_template(templatename="shutdown.html", title="Restart", message=message, timer=15) restart.exposed = True @require() def shutdown(self): cherrystrap.config_write() cherrystrap.SIGNAL = 'shutdown' message = 'shutting down ...' return serve_template(templatename="shutdown.html", title="Exit", message=message, timer=15) return page shutdown.exposed = True @require() def update(self): cherrystrap.SIGNAL = 'update' message = 'updating ...' return serve_template(templatename="shutdown.html", title="Update", message=message, timer=30) update.exposed = True # Safe to delete this def, it's just there as a reference def template(self): return serve_template(templatename="template.html", title="Template Reference") template.exposed = True def checkGithub(self): # Make sure this is requested via ajax request_type = cherrypy.request.headers.get('X-Requested-With') if str(request_type).lower() == 'xmlhttprequest': pass else: status_msg = "This page exists, but is not accessible via web browser" return serve_template(templatename="index.html", title="404 - Page Not Found", msg=status_msg) from cherrystrap import versioncheck versioncheck.checkGithub() cherrystrap.IGNORE_UPDATES = False checkGithub.exposed = True def ignoreUpdates(self): # Make sure this is requested via ajax request_type = cherrypy.request.headers.get('X-Requested-With') if str(request_type).lower() == 'xmlhttprequest': pass else: status_msg = "This page exists, but is not accessible via web browser" return serve_template(templatename="index.html", title="404 - Page Not Found", msg=status_msg) cherrystrap.IGNORE_UPDATES = True ignoreUpdates.exposed = True def ajaxUpdate(self): # Make sure this is requested via ajax request_type = cherrypy.request.headers.get('X-Requested-With') if str(request_type).lower() == 'xmlhttprequest': pass else: status_msg = "This page exists, but is not accessible via web browser" return serve_template(templatename="index.html", title="404 - Page Not Found", msg=status_msg) return serve_template(templatename="ajaxUpdate.html") ajaxUpdate.exposed = True
class Root: #_cp_config = { # 'tools.sessions.on': True, # 'tools.auth.on': True #} auth = AuthController() vehDAO = VehiclesDAO() turnProbabilityDAO = TurnProbabilityDAO() trafficLightDAO = TrafficLightDAO() flowsDAO = FlowsDAO() studentGroupDAO = StudentGroupDAO() problemsDAO = ProblemsDAO() reasonDAO = ReasonDAO() simAssociationDAO = SimAssociationDAO() colabLogDAO = ColabLogDAO() def __init__(self, ospath): self.ospath = ospath @cherrypy.expose def prettify(self): #Use this method to test an internal function""" #rough_string = tostring(elem, 'utf-8') #reparsed = minidom.parseString(rough_string) #return reparsed.toprettyxml(indent=" ") SimulationEngine("53e4ef02d527600fa63a69f6").createFlowsXml() @cherrypy.expose @require() def index(self): #return open( self.ospath + '/static/TrafficSim.html') raise cherrypy.HTTPRedirect("/static/TrafficSim.html") @cherrypy.expose @require(has_role("admin")) def updateStepRate(self, steps): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simualtionID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format interface = UserDataInterface() interface.updateSimulationStepRate(simualtionID, steps) return {'response': {'status': "success"}} else: return {'response': {'status': "failure"}} @cherrypy.expose @cherrypy.tools.json_out() #@require(has_role("admin")) def setMaxSpeed(self, laneID, maxSpeed): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simualtionID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format #cherrypy.t_sim = trafficsim(e_queue, simualtionID) #e_queue.enqueue(cherrypy.t_sim.setMaxSpeed, [str(laneID), float(maxSpeed)], {}) return {'response': {'status': "success", 'speed': maxSpeed}} else: return {'response': {'status': "failure"}} @cherrypy.expose @cherrypy.tools.json_out() @require() def getGroupData(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": interface = UserDataInterface() username = cherrypy.request.login simulationID = interface.getSimulationid( username) #pass in this format siminfo = interface.getSimulationUserData(simulationID) simFolderId = interface.getSimulationFolder(simulationID, username) problem_id = self.problemsDAO.getProblemID(simulationID) problem = self.problemsDAO.readProblem(problem_id) interface.ensureSimulationExists(simFolderId) sim_folder = str(simFolderId) userDetails = interface.getUserDetails(username) firstname = userDetails.get('firstname') lastname = userDetails.get('lastname') groupname = userDetails.get('groupname') # In COLAB mode, rest of the junctions are returned in addition to the # one that a group is associated with assoc_junctions = interface.getJunctionsofOtherGroups( simulationID, username) logging.info('Returning login data for user: '******'response': { 'status': "success", 'siminfo': siminfo, 'sim_id': str(simulationID), 'sim_folder': sim_folder, 'username': cherrypy.request.login, 'firstname': firstname, 'lastname': lastname, 'groupname': groupname, 'assoc_junctions': assoc_junctions, 'problem_id': problem_id, 'problem_type': problem['type'] } } logging.info(response_data) return response_data else: return {'response': {'status': "failure"}} @cherrypy.expose @cherrypy.tools.json_out() def getAllGroupNames(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": groupNames = self.studentGroupDAO.readAllGroupNames() return { 'response': { 'status': "success", 'groups': groupNames["name"] } } else: return {'response': {'status': "failure"}} @cherrypy.expose @cherrypy.tools.json_out() def updateGroupUrl(self, group_id, user_id, problem_id, collaboration_url): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": self.studentGroupDAO.updateCollaborationUrl( group_id, collaboration_url) simulationID = UserDataInterface().getSimulationid(user_id) self.colabLogDAO.createLog(simulationID, user_id, problem_id) return {'response': {'status': "success"}} else: return {'response': {'status': "failure"}} @cherrypy.expose @cherrypy.tools.json_out() def colabHistory(self): users = [ 'user103', 'user104', 'user105', 'user106', 'user110', 'user111', 'user118', 'user123', 'user124', 'user125', 'user126', 'user127', 'user131', 'user132' ] cell_list = [] for usr in users: colab_logs = self.colabLogDAO.readCollaboration(usr) start_colab_time = datetime(2000, 10, 21, 0, 0) next_colab_time = datetime(2000, 10, 21, 0, 0) previous_colab_time = datetime(2000, 10, 21, 0, 0) for lg in colab_logs: next_colab_time = datetime.strptime(lg["colab_time"], "%Y-%m-%d %H:%M:%S.%f") diff_colab_time = (next_colab_time - previous_colab_time).total_seconds() if diff_colab_time > 160325397: start_colab_time = next_colab_time elif diff_colab_time > 10: end_colab_time = previous_colab_time duration = (end_colab_time - start_colab_time).total_seconds() cell = { "started on": str(start_colab_time), "ended on": str(end_colab_time), "user_id": str(lg["user_id"]), "simulation_id": str(lg["simulation_id"]), "problem_id": str(lg["problem_id"]), "duration": duration } cell_list.append(cell) start_colab_time = next_colab_time previous_colab_time = next_colab_time return cell_list @cherrypy.expose @cherrypy.tools.json_out() @require() def getGroupUrl(self, group_id): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": interface = UserDataInterface() simualtionID = interface.getSimulationid( cherrypy.request.login) #pass in this format groupinfo = interface.getSimulationUserData( simualtionID) #groupinfo["group_id"] studentgroup = self.studentGroupDAO.getCollaborationUrl(group_id) actual_time = datetime.now() last_update_time = datetime.strptime( studentgroup["last_update_time"], "%Y-%m-%d %H:%M:%S.%f") diff = (actual_time - last_update_time).total_seconds() #if has_role_of("admin"): if diff > 10: collaboration_url = studentgroup[ "collaboration_url_admin"] + "&group_name=" + group_id else: collaboration_url = studentgroup[ "collaboration_url"] + "?group_name=" + group_id return { 'response': { 'status': "success", 'collaboration_url': collaboration_url } } else: return {'response': {'status': "failure"}} @cherrypy.expose @cherrypy.tools.json_out() @require() def getGroupStatusAll(self, rows=None, sidx=None, _search=None, searchField=None, searchOper=None, searchString=None, page=None, sord=None, nd=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": studentgroups = self.studentGroupDAO.readAllGroupNames() actual_time = datetime.now() cell_list = [] for grp in studentgroups: last_update_time = datetime.strptime(grp["last_update_time"], "%Y-%m-%d %H:%M:%S.%f") diff = (actual_time - last_update_time).total_seconds() if diff > 10: collaboration_url = grp[ "collaboration_url_admin"] + "&group_name=" + str( grp["_id"]) cell = { "cell": [ str(grp["_id"]), "offline", grp["name"], collaboration_url ] } cell_list.append(cell) else: collaboration_url = grp[ "collaboration_url"] + "?gid=000000000000&group_name=" + str( grp["_id"]) cell = { "cell": [ str(grp["_id"]), "online", grp["name"], collaboration_url ] } cell_list.append(cell) return {'groups': cell_list} else: return {'response': {'status': "failure"}} @cherrypy.expose @cherrypy.tools.json_out() @require() def getVehicleResult(self, sim_id): interface = UserDataInterface() currentSimulationID = interface.getSimulationid(cherrypy.request.login) if str(currentSimulationID) == sim_id: # just a hack for now sim_id = ObjectId( interface.getSimulationFolder(ObjectId(sim_id), (cherrypy.request.login))) sim_exec_id = interface.getActiveSimulationExecId(sim_id) if (sim_exec_id is None): return {'response': {'status': "nosimexec"}} simInterface = SimulationExecutionInterface(sim_exec_id, sim_id) execResult = simInterface.getSimulationExecutionDetails() if execResult.get('simendtime') is not None: result = simInterface.getSimulationResult() return { 'response': { 'status': "success", 'resultdata': result, 'steps': execResult['steps'] } } else: return {'response': {'status': "notloaded"}} @cherrypy.expose @cherrypy.tools.json_out() @require() def getInductinLoopResult(self, sim_id, loop_id, flow_rate_agg): interface = UserDataInterface() currentSimulationID = interface.getSimulationid(cherrypy.request.login) if str(currentSimulationID) == sim_id: # just a hack for now sim_id = ObjectId( interface.getSimulationFolder(ObjectId(sim_id), (cherrypy.request.login))) sim_exec_id = interface.getActiveSimulationExecId(sim_id) if (sim_exec_id is None): return {'response': {'status': "nosimexec"}} simInterface = SimulationExecutionInterface(sim_exec_id, sim_id) execResult = simInterface.getSimulationExecutionDetails() if execResult.get('simendtime') is not None: result = simInterface.getInductionLoopResult( loop_id, flow_rate_agg) return {'response': {'status': "success", 'resultdata': result}} else: return {'response': {'status': "notloaded"}} @cherrypy.expose @cherrypy.tools.json_out() @require() def getInductionDataTable(self, sim_id, loop_id): interface = UserDataInterface() currentSimulationID = interface.getSimulationid(cherrypy.request.login) if str(currentSimulationID) == sim_id: # just a hack for now sim_id = ObjectId( interface.getSimulationFolder(ObjectId(sim_id), (cherrypy.request.login))) sim_exec_id = interface.getActiveSimulationExecId(sim_id) if (sim_exec_id is None): return {'response': {'status': "nosimexec"}} simInterface = SimulationExecutionInterface(sim_exec_id, sim_id) execResult = simInterface.getSimulationExecutionDetails() if execResult.get('simendtime') is not None: result = simInterface.getInductionDataTable(loop_id) return {'response': {'status': "success", 'resultdata': result}} else: return {'response': {'status': "notloaded"}} @cherrypy.expose @cherrypy.tools.json_out() @require() def getQueueResult(self, sim_id, loop_id): interface = UserDataInterface() currentSimulationID = interface.getSimulationid(cherrypy.request.login) if str(currentSimulationID) == sim_id: # just a hack for now sim_id = ObjectId( interface.getSimulationFolder(ObjectId(sim_id), (cherrypy.request.login))) sim_exec_id = interface.getActiveSimulationExecId(sim_id) if (sim_exec_id is None): return {'response': {'status': "nosimexec"}} simInterface = SimulationExecutionInterface(sim_exec_id, sim_id) execResult = simInterface.getSimulationExecutionDetails() if execResult.get('simendtime') is not None: result = simInterface.getQueueResult(loop_id) return {'response': {'status': "success", 'resultdata': result}} else: return {'response': {'status': "notloaded"}} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def startSimulation(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true" and has_privileges(): simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format logging.info('Starting simulation for user: '******' with Simulation id: ' + str(simulationID)) cloudInterface = CloudInterface() logging.info('Fetching assigned VM for simulation id: ' + str(simulationID)) vm = cloudInterface.assignVM(simulationID) if vm is None: logging.warning('VM could not assigned for user: '******' with Simulation id: ' + str(simulationID)) return {'response': 'notavailable'} private_ip = vm['private_IP'] key_name = vm['key_name'] logging.info('Starting simulation for id: ' + str(simulationID) + ' on VM:' + private_ip) trafficsim(private_ip, key_name, simulationID, cherrypy.request.login).start() #t_sim.start() logging.info('Simulation start command sent..') return {'response': str(simulationID)} else: logging.warning('Unable to authenticate..') return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def checkStartStatus(self): interface = UserDataInterface() simulationID = interface.getSimulationid(cherrypy.request.login) return {'response': interface.getSimulationRunningState(simulationID)} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def speedupSimulation(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true" and has_privileges(): interface = UserDataInterface() simulationID = interface.getSimulationid( cherrypy.request.login) #pass in this format logging.info('Speeding simulation for user: '******' with Simulation id: ' + str(simulationID)) interface.speedUpSimulationStepRate(simulationID) return {'response': "success"} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def finishSimulation(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true" and has_privileges(): interface = UserDataInterface() simulationID = interface.getSimulationid( cherrypy.request.login) #pass in this format logging.info('Finishing simulation for user: '******' with Simulation id: ' + str(simulationID)) interface.finishSimulation(simulationID) return {'response': "success"} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def restoreSimulationRate(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true" and has_privileges(): interface = UserDataInterface() simulationID = interface.getSimulationid( cherrypy.request.login) #pass in this format logging.info('Restoring simulation rate for user: '******' with Simulation id: ' + str(simulationID)) interface.restoreSimulationStepRate(simulationID) return {'response': "success"} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def setMode(self, user_mode=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": username = cherrypy.request.login interface = UserDataInterface() simulationID = interface.getSimulationid(username) logging.info('simulationID: ' + str(simulationID) + ' , username: '******', usermode: ' + user_mode) interface.setUserMode(username, user_mode) cloudInterface = CloudInterface() simFolderId = interface.getSimulationFolder(simulationID, username) interface.ensureSimulationExists(simFolderId) return { 'response': { 'status': "success", 'sim_folder': str(simFolderId), 'sim_id': str(simulationID) } } else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def readVehicles(self, rows=None, sidx=None, _search=None, searchField=None, searchOper=None, searchString=None, page=None, sord=None, nd=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format vehicles = self.vehDAO.readVehicles(simulationID) cell_list = [] for veh in vehicles: cell = { "id": str(veh["_id"]), "cell": [ str(veh["_id"]), str(veh["simulation_id"]), veh["name"], veh["accel"], veh["decel"], veh["sigma"], veh["max_speed"], veh["length"], veh["probability"] ] } cell_list.append(cell) #vehiclesJson ={"vehicles": cell_list} return {"vehicles": cell_list} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def readSimulations(self, rows=None, sidx=None, _search=None, searchField=None, searchOper=None, searchString=None, page=None, sord=None, nd=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": result = UserDataInterface().getSimulationHistoryTable( cherrypy.request.login) return {"sim_versions": result} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def saveSimVersion(self, sim_id, sim_label, shared_with): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": # no need to get sim id from user simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) interface = SimulationBackupInterface(simulationID) return interface.saveSimulationWithUserInput( sim_label, shared_with, cherrypy.request.login) else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def copySimVersionToCurrent(self, sim_id): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": currentSimulationID = UserDataInterface().getSimulationid( cherrypy.request.login) interface = SimulationBackupInterface(currentSimulationID) interface.copySimulationToCurrent(sim_id, cherrypy.request.login) return {'response': {'status': "success"}} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def deleteSimVersion(self, id, oper=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": # accepts object id format interface = SimulationBackupInterface(ObjectId(id)) interface.deleteSimulation(cherrypy.request.login) return {'response': {'status': "success"}} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def deleteVehicle(self, id, oper=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": self.vehDAO.deleteVehicle(id) return {'response': {'status': "success"}} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def updateVehicle(self, id, accel, decel, sigma, max_speed, length, probability, oper=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": self.vehDAO.updateVehicle(id, accel, decel, sigma, max_speed, length, probability) return {'response': {'status': "success"}} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def createVehicle(self, name, accel, decel, sigma, max_speed, length, probability, oper=None, id=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format self.vehDAO.createVehicle(simulationID, name, accel, decel, sigma, max_speed, length, probability) return {'response': {'status': "success"}} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def readAllFlows(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": user_id = cherrypy.request.login interface = UserDataInterface() simulationID = interface.getSimulationid(cherrypy.request.login) problem_id = self.problemsDAO.getProblemID(simulationID) user_mode = interface.getUserMode(user_id) # Find duplicates and discard them from the list # At the collaboration mode first discard duplicated flow points # then flow points with removable column equals to 1 from the remaining list ''' temp_flows = copy.deepcopy(flows) duplicates = {} for flow in temp_flows: if flow["point_name"] in duplicates.keys(): duplicates[flow["point_name"]] += 1 else: duplicates[flow["point_name"]] = 1 ''' cell_list = [] if (problem_id in ['3', '8']): pointList = ['A', 'B', 'Iwest', 'Lnorth'] elif (problem_id in ['6a', '6b', '6c']): pointList = ['A', 'Iwest'] else: pointList = ['A', 'B', 'C', 'D', 'Jnorth', 'Lnorth'] simIDs = self.simAssociationDAO.readAssociatedSimIDs(simulationID) for simID in simIDs: flows = self.flowsDAO.readAllFlows(simID) for flow in flows: cell = { "id": str(flow["_id"]), "simulation_id": str(flow["simulation_id"]), "point_name": flow["point_name"], "intersection_id": flow["intersection_id"], "latitude": flow["latitude"], "longitude": flow["longitude"], "flow_rate": flow["flow_rate"] } #cell = {"point_name": flow["point_name"]} if user_mode == "COLAB": # If there are duplicates in COLAB mode remove those points #if duplicates[flow["point_name"]] == 1 and flow["removable"] == "0": if any(flow["point_name"] in s for s in pointList): cell_list.append(cell) else: if any(flow["point_name"] in s for s in pointList): if flow["removable"] == "0": cell_list.append(cell) return {'response': {'status': "success", 'flows': cell_list}} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def readFlow(self, point_name): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) flow = self.flowsDAO.readFlow(simulationID, point_name) return { 'response': { 'status': "success", 'flow_rate': str(flow["flow_rate"]) } } else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def updateFlow(self, point_name, flow_rate): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) self.flowsDAO.updateFlow(simulationID, point_name, flow_rate) return {'response': {'status': "success"}} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def readTurnProbability(self, edge_id): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) turn = self.turnProbabilityDAO.readTurnProbability( simulationID, edge_id) return { 'response': { 'status': "success", 'left_turn': turn["left_turn"], 'right_turn': turn["right_turn"], 'go_straight': turn["go_straight"] } } else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def updateTurnProbability(self, edge_id, left_turn, right_turn, go_straight): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) self.turnProbabilityDAO.updateTurnProbability( simulationID, edge_id, left_turn, right_turn, go_straight) return {'response': {'status': "success"}} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def readTrafficLightLogic(self, intersection_id, light_index, rows=None, sidx=None, _search=None, searchField=None, searchOper=None, searchString=None, page=None, sord=None, nd=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) traffic_light_logic = self.trafficLightDAO.readTrafficLightLogic( simulationID, intersection_id) # Split phase info and return. Format is in Green!0!1-Red!2!3!4-Green!5-... cell_list = [] for tll in traffic_light_logic: links = tll["state"].split("-") state = "" cell = [] cell.append(str(tll["intersection_id"])) for link in links: state = link.split("!") cell.append(state[0]) cell.append(tll["duration"]) #cell = {"id":str(tll["_id"]), "cell": [str(tll["intersection_id"]), states, tll["duration"]]} cell_indv = {"id": str(tll["_id"]), "cell": cell} cell_list.append(cell_indv) logicJson = {"logic": cell_list} return logicJson else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def createTrafficLightLogic(self, intersection_id, state0, state1, state2, state3, state4, state5, state6, state7, traffic_light_links, duration, oper=None, id=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) # Put phases into Green!0!1-Red!2!3!4-Green!5-... format # traffic_light_links : 0!1-2!3!4-5!6 indexes = traffic_light_links.split("-") state = state0 + "!" + indexes[0] + "-" + state1 + "!" + indexes[ 1] + "-" + state2 + "!" + indexes[ 2] + "-" + state3 + "!" + indexes[ 3] + "-" + state4 + "!" + indexes[ 4] + "-" + state5 + "!" + indexes[ 5] + "-" + state6 + "!" + indexes[ 6] + "-" + state7 + "!" + indexes[7] self.trafficLightDAO.createTrafficLightLogic( simulationID, intersection_id, state, duration) return {'response': {'status': "success"}} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def updateTrafficLightLogic(self, id, duration, oper=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": self.trafficLightDAO.updateTrafficLightLogic(id, duration) return {'response': {'status': "success"}} else: return {'response': "failure"} ''' @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def updateTrafficLightLogic(self, id, state0, state1, state2, state3, state4, state5, state6, state7, traffic_light_links, duration, oper=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": logging.info("updateTrafficLightLogic" + traffic_light_links); indexes = traffic_light_links.split("-") state = state0 + "!" + indexes[0] + "-" + state1 + "!" + indexes[1] + "-" + state2 + "!" + indexes[2] + "-" + state3 + "!" + indexes[3] + "-" + state4 + "!" + indexes[4] + "-" + state5 + "!" + indexes[5] + "-" + state6 + "!" + indexes[6] + "-" + state7 + "!" + indexes[7] self.trafficLightDAO.updateTrafficLightLogic(id, state, duration) return {'response' : {'status': "success"}} else: return {'response' : "failure"} ''' @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def deleteTrafficLightLogic(self, id, oper=None): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": self.trafficLightDAO.deleteTrafficLightLogic(id) return {'response': {'status': "success"}} else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def readProblem(self, problem_id): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": problem = self.problemsDAO.readProblem(problem_id) return { 'response': { 'status': "success", 'title': problem["title"], 'description': problem["description"] } } else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def getProblemID(self): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) problem_id = self.problemsDAO.getProblemID(simulationID) return { 'response': { 'status': "success", 'problem_id': problem_id } } else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require(has_role("admin")) def updateProblem(self, problem_id): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": username = cherrypy.request.login simulationID = UserDataInterface().getSimulationid(username) interface = UserDataInterface() usermode = interface.getUserMode(username) if (usermode == 'COLAB' and (not interface.checkIfMasterSim(simulationID))): return {'response': "not_admin"} self.problemsDAO.updateProblem(simulationID, problem_id) problem = self.problemsDAO.readProblem(problem_id) return { 'response': { 'status': "success", 'title': problem["title"], 'problem_type': problem["type"] } } else: return {'response': "failure"} @cherrypy.expose @cherrypy.tools.json_out() @require() def createReason(self, desc): if cherrypy.session.get(SESSION_AUTH_KEY, None) is "true": simulationID = UserDataInterface().getSimulationid( cherrypy.request.login) #pass in this format user_id = cherrypy.request.login problem_id = self.problemsDAO.getProblemID(simulationID) self.reasonDAO.createReason(simulationID, user_id, problem_id, desc) return {'response': {'status': "success"}} else: return {'response': "failure"}
class Root(object): # Our toggle variable. wh = WareHouse() auth = AuthController() restricted = RestrictedArea() project = {} logger = False # global USERS # USERS = {u[0]: u[1] for u in wh.generic("select `user`, `pwd` FROM `users`")} def user_content(self, user): # ans = {} # sql_pns = 'SELECT `index`, `id`, `series` FROM projects WHERE user = "******"'.format(user) res_1 = self.wh.generic(sql_pns) ans_pns = {i[0]: {i[1]: i[2]} for i in res_1} user_projects = list(set(i[1] for i in res_1)) # ans_data = {} sql_data = 'SELECT * FROM data' res_2 = self.wh.generic(sql_data) res = [r for r in res_2 if r[2] in user_projects] res_projects = [i[2] for i in res] res_series = [i[3] for i in res] # for i in res_projects: ans_data[i] = {} for j in res_series: ans_data[i][j] = {k[0]: k[4:len(k)] for k in res if j == k[3]} # ans['projects'] = ans_pns ans['data'] = ans_data return ans # @require() @cherrypy.expose def index(self): # cherrypy.session.clear() # cherrypy.session.load() project['user'] = cherrypy.request.login # user_data = self.user_content(project['user']) # # project['id'] = 'Project MicroAlgae' # series come as a suggestion based on the number of series for each project # project['series'] = 'Series {}'.format( # len([list(set(i.values()))[0] for i in user_data['projects'].values()]) + 1) # tmpl = env.get_template("BioStatBMD.html") return tmpl.render(project=project, udata=user_data) # return serve_file(os.path.join(current_dir, 'BioStatBMD.html'), content_type='text/html') # return serve_file(os.path.join(current_dir, 'index.html'), content_type='text/html') # serves our index client page. @cherrypy.expose @cherrypy.tools.json_out() @cherrypy.tools.json_in() def time_switch(self): # When this page gets requested, it'll toggle the time feed updating # and return an OK message. if self.timeFeedEnabled: self.timeFeedEnabled = False else: self.timeFeedEnabled = True return "Feed Toggled" @cherrypy.expose @cherrypy.tools.json_out() @cherrypy.tools.json_in() def log(self): input_json = cherrypy.request.json self.logger = input_json['logger'] self.project = input_json['project'] return "Data now is being collected." @cherrypy.expose def feed(self): cherrypy.response.headers["Content-Type"] = "text/event-stream;charset=utf-8" data = self.wh.get() data_dict = ast.literal_eval(data) if self.logger: # date = time.strftime('%Y-%m-%d %H:%M:%S') # data_dict['date'] = str(date) data_dict['user'] = self.project["user"] data_dict['project'] = self.project["id"] data_dict['series'] = self.project["series"] # fields = [f for f in data_dict.keys() if f not in ['time']] # fields_s = ', '.join(fields) values = ['"{}"'.format(data_dict[g]) for g in fields] values_s = ', '.join(values) # print(fields_s, values_s) sql = 'INSERT INTO data ({}) VALUES ({});'.format(fields_s, values_s) stat = self.wh.generic(sql) # # # else: pass return "retry: 30000\nevent: time\n" + "data: " + data + "\n\n;" feed._cp_config = {'response.stream': True, 'tools.encode.encoding': 'utf-8'}
class Root: _cp_config = {'tools.sessions.on': True, 'tools.auth.on': True} auth = AuthController() restricted = RestrictedArea() @cherrypy.expose @require() def index(self): return """ This page only requires a valid login. <a href="auth/logout">LOUGOUT</a> """ def get_postform(self, msg="post", from_page="/", username=None): wall1 = wall.wall(username) wall1.body = \ """<form method="post" action="/post"> <input type="hidden" name="from_page" value="%(from_page)s" /> %(msg)s<br /> Post: <input type="text" name="message" /> <br /> <input type="submit" value="Post" /> """ %locals() wall1.pull(username) return wall1.return_html() def post_to_database(self, message, username): con = mdb.connect('localhost', 'testuser', 'test623', 'testdb') with con: cur = con.cursor() query = "INSERT INTO Message(Username, Post) VALUES('%(username)s', '%(message)s')" % locals( ) cur.execute(query) return None return u"database error" @cherrypy.expose @require() def post(self, message=None, from_page="/"): username = cherrypy.session.get(SESSION_KEY) if message == None: return self.get_postform(from_page=from_page, username=username) error_msg = self.post_to_database(message, username) if error_msg: return self.get_postform(self, error_msg, from_page, username) else: raise cherrypy.HTTPRedirect("/post") @cherrypy.expose def gethint(self, q): print "hello" print q return "no suggestion" @cherrypy.expose def open(self): home_page = html_page.html_page("html_src/showhint") return home_page.get_html() @cherrypy.expose @require(name_is("joe")) def only_for_joe(self): return """Hello Joe - this page is available to you only""" # This is only available if the user name is joe _and_ he's in group admin @cherrypy.expose @require(name_is("joe")) @require(member_of("admin") ) # equivalent: @require(name_is("joe"), member_of("admin")) def only_for_joe_admin(self): return """Hello Joe Admin - this page is available to you only"""
class AteeqHomeAutomation: _cp_config = { 'tools.sessions.on': True, 'tools.auth.on': True } auth = AuthController() GPIO.output(LED,0) @cherrypy.expose @require() def index(self): my_ip = ([(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]) return '''<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery Mobile: Theme Download</title> <link rel="stylesheet" href="static/ateeqsHA.min.css" /> <link rel="stylesheet" href="static/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="static/jquery.mobile.structure-1.4.5.min.css" /> <script src="static/jquery-1.11.1.min.js"></script> <script src="static/jquery.mobile-1.4.5.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#clear").click(function () {$.post('/request',{key_pressed:"empty"})}); $("#halt").click(function () {$.post('/request',{key_pressed:"halt"})}); $("#kodi").click(function () {$.post('/request',{key_pressed:"kodi"})}); $("#restart").click(function () {$.post('/request',{key_pressed:"restart"})}); $("#flip-1").change(function () {$.post('/request',{key_pressed:"power1_"+$(this).val()})}); $("#flip-2").change(function () {$.post('/request',{key_pressed:"power2_"+$(this).val()})}); $("#flip-3").change(function () {$.post('/request',{key_pressed:"power3_"+$(this).val()})}); $("#stream").change(function () {$.post('/request',{key_pressed:"stream_"+$(this).val()})}); $("#auto").change(function () {$.post('/request',{key_pressed:"auto_"+$(this).val()})}); }); </script> </head> <body> <div data-role="page" data-theme="a"> <div data-role="header" data-position="inline"> <h1>Ateeq's <br> Home Automation</h1> </div> <center> <div data-role="content" data-theme="a"> <div class="ui-field-contain"> <label for="auto">Automatic Mode:</label> <select name="auto" id="auto" data-role="flipswitch"> <option value="off">Off</option> <option value="on">On</option> </select> </div> <div class="ui-field-contain"> <label for="flip-1">Switch One:</label> <select name="flip-1" id="flip-1" data-role="flipswitch"> <option value="off">Off</option> <option value="on">On</option> </select> </div> <div class="ui-field-contain"> <label for="flip-2">Switch Two:</label> <select name="flip-2" id="flip-2" data-role="flipswitch"> <option value="off">Off</option> <option value="on">On</option> </select> </div> <div class="ui-field-contain"> <label for="flip-3">Switch Three** :</label> <select name="flip-3" id="flip-3" data-role="flipswitch"> <option value="off">Off</option> <option value="on">On</option> </select> </div> <div class="ui-field-contain"> <label for="stream">Stream Toggle: <a href="http://%s:8091/stream_webcam.html" data-transition="turn"> local! </a> & <a href="http://ateeqhomeautomationstream.ngrok.com/stream_webcam.html" data-transition="turn">Worldwide Stream!</a></label> <select name="stream" id="stream" data-role="flipswitch"> <option value="off">Off</option> <option value="on">On</option> </select> </div> <div class="ui-field-contain"> <label for="clear">Check Switches <a href="/sqldata" data-transition="turn">history</a></label> <form action="/reset"> <!--<input type="button" id="clear" data-inline="true" value="Clear History">--> <input type="submit" data-inline="true" data-transition="turn" value="Clear History"></form> </div> <div class="ui-field-contain"> <a href="/qrcode" data-transition="turn" >Click Here!</a> to get connected to this Wifi! </div> <div class="ui-field-contain"> <form method="post" action="processform"> <input type="email" name="email" placeholder="Enter the E-Mail ID!" value=""> <input type="submit" value="Submit"> </form> </div> <div class="ui-field-contain"> <input type="button" id="kodi" data-inline="true" value="Start KODI from here!"> </div> <div class="ui-field-contain"> <input type="button" id="halt" data-inline="true" value="ShutDown"> <input type="button" id="restart" data-inline="true" value="Reboot"> </div> <div class="ui-field-contain"> <p> **please dont use if in automatic mode!</p> </div> </center> </fieldset> </div> </div> </body> </html> ''' % (my_ip) @cherrypy.expose @require() def request(self, **data): def addstuff(switch,action): curTime=strftime("%Y/%m/%d_%H:%M:%S", localtime()) setdata = HAusage( switch = switch, action = action, time = curTime) print "Added" # Then to access the data do the following #print data key = data['key_pressed'].lower() if key == "auto_on": print "Auto Mode On!" os.system("sudo service home_auto_ateeq.sh start") addstuff('auto_switch','on') elif key == "auto_off": print "Auto Mode Off!" os.system("sudo service home_auto_ateeq.sh stop") addstuff('auto_switch','off') elif key == "power1_on": print "p1 On" GPIO.output(re1, 1) addstuff('switch_one','on') elif key == "power1_off": print "p1 Off" GPIO.output(re1, 0) addstuff('switch_one','off') elif key == "power2_on": print "p2 On" GPIO.output(re2, 1) addstuff('switch_two','on') elif key == "power2_off": print "p2 Off" GPIO.output(re2, 0) addstuff('switch_two','off') elif key == "power3_on": print "p3 On" GPIO.output(re3, 1) addstuff('switch_three','on') elif key == "power3_off": print "p3 Off" GPIO.output(re3, 0) addstuff('switch_three','off') elif key == "stream_on": print "Stream On!" subprocess.call("sudo service mjpg-streamer start", shell=True) elif key == "stream_off": print "Stream Off!" os.system("sudo service mjpg-streamer stop") elif key == "halt": os.system('echo "Shutting Down. Good Bye." | festival --tts') os.system('sudo init 0') elif key == "restart": os.system('echo "Restarting. Please wait." | festival --tts') os.system('sudo reboot') elif key == "kodi": os.system('echo "starting KODI. Please wait." | festival --tts') os.system('sudo -u pi screen -d -m -q kodi-standalone') else: print key @cherrypy.expose @require() def qrcode(self): return '''<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="static/ateeqsHA.min.css" /> <link rel="stylesheet" href="static/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="static/jquery.mobile.structure-1.4.5.min.css" /> <script src="static/jquery-1.11.1.min.js"></script> <script src="static/jquery.mobile-1.4.5.min.js"></script> </head> <body> <div data-role="page" data-theme="a"> <div data-role="header" data-position="inline"> <h1> Ateeq's <br> Home Automation </h1> </div> <center> <img src="/static/wifi.png" /><br> Scan this code with your Smart Phone usind Qr-Code scanner! </center> </div> </body> </html>''' @cherrypy.expose @require() def sqldata(self): reqdata = HAusage.select() template = Template('''<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery Mobile: Theme Download</title> <link rel="stylesheet" href="static/ateeqsHA.min.css" /> <link rel="stylesheet" href="static/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="static/jquery.mobile.structure-1.4.5.min.css" /> <script src="static/jquery-1.11.1.min.js"></script> <script src="static/jquery.mobile-1.4.5.min.js"></script> </head> <body> <div data-role="page" data-theme="a"> <div data-role="header" data-position="inline"> <h1> Ateeq's <br> Home Automation </h1> </div> <center> <h1>Switches that were Used</h1> <table border=1><tr><th>Switch</th><th>Action Made</th><th>Time</th></tr> #for $data in $reqdata <tr><td>$data.switch</td><td> $data.action</td><td>$data.time</td></tr> #end for </center> </div> </body> </html> ''', [locals(), globals()]) return template.respond() @cherrypy.expose @require() def processform(self, email): smtpserver = 'smtp.gmail.com:587' authreq = 1 smtpuser='******' smtppass='******' FROM = '*****@*****.**' TO = [email] SUBJECT = "Hi Greetings from Ateeq." TEXT = "Click on this Address to control devices http://ateeqhomeautomation.ngrok.com" # Prepare actual message message = """\From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) sender = '*****@*****.**' session = smtplib.SMTP(smtpserver) session.ehlo() session.starttls() if authreq: session.login(smtpuser,smtppass) smtpresult = session.sendmail(sender,email,message) if smtpresult: errstr = "" for recip in smtpresult.keys(): errstr = """Could not delivery mail to: %s Server said: %s %s %s""" % (email, smtpresult[email][0], smtpresult[email][1], errstr) raise smtplib.SMTPException, errstr return '''<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="static/ateeqsHA.min.css" /> <link rel="stylesheet" href="static/jquery.mobile.icons.min.css" /> <link rel="stylesheet" href="static/jquery.mobile.structure-1.4.5.min.css" /> <script src="static/jquery-1.11.1.min.js"></script> <script src="static/jquery.mobile-1.4.5.min.js"></script> </head> <body> <div data-role="page" data-theme="a"> <div data-role="header" data-position="inline"> <h1> Ateeq's <br> Home Automation </h1> </div> <center> <p1>Mail sent to %s </p1> </center> </div> </body> </html>''' % (email) @cherrypy.expose @require() def reset(self): # Drop existing table HAusage.dropTable(True) # Create new table HAusage.createTable() print " Cleared history " return '''