Path: blob/master/AndroidRunner/Plugins/perfume_js/server.py
630 views
import threading1import time2import csv3import os4import http5from http.server import HTTPServer6import logging78navigationTime= {'fetchTime':0 , 'workerTime':0 , 'totalTime':0, 'downloadTime':0, 'timeToFirstByte':0, 'headerSize':0, 'dnsLookupTime': 0}9networkInf = {'downlink': 0, 'effectiveType': 0, 'rtt':0, 'saveData':False}10storageEstimate = {'quota':0, 'usage':0, 'caches':0, 'indexedDB':0, 'serviceWorker':0}11fpResult = {'fp':0}12fcpResult = {'fcp':0}13fidResult = {'fid':0}14lcpResult = {'lcp':0}15clsResult = {'cls':0}16tbtResult = {'tbt':0}17httpd = 01819class HTTPHandler(http.server.SimpleHTTPRequestHandler):2021def do_POST(self):22logging.getLogger(self.__class__.__name__).info("POST request received")23length = int(self.headers['Content-Length']) # <--- Gets the size of data24data_string = self.rfile.read(length)25data_string = data_string.decode("utf-8")26logging.getLogger(self.__class__.__name__).debug(f"Data: {data_string}")2728if 'perfumeResults' in data_string:29if 'navigationTiming' in data_string:30navigationTime['fetchTime'] = data_string.split("fetchTime\":")[1].split(",\"workerTime")[0]31navigationTime['workerTime'] = data_string.split("workerTime\":")[1].split(",\"totalTime")[0]32navigationTime['totalTime'] = data_string.split("totalTime\":")[1].split(",\"downloadTime")[0]33navigationTime['downloadTime'] = data_string.split("downloadTime\":")[1].split(",\"timeToFirstByte")[0]34navigationTime['timeToFirstByte'] = data_string.split("timeToFirstByte\":")[1].split(",\"headerSize")[0]35navigationTime['headerSize'] = data_string.split("headerSize\":")[1].split(",\"dnsLookupTime")[0]36navigationTime['dnsLookupTime'] = data_string.split("dnsLookupTime\":")[1].split("},\"eventProperties",1)[0]3738if 'networkInformation' in data_string:39networkInf['downlink'] = data_string.split("downlink\":")[1].split(",\"effectiveType")[0]40networkInf['effectiveType'] = data_string.split("effectiveType\":\"")[1].split("\",\"rtt")[0]41networkInf['rtt'] = data_string.split("rtt\":")[1].split(",\"saveData")[0]42networkInf['saveData'] = data_string.split("saveData\":")[1].split("},\"eventProperties",1)[0]4344if 'storageEstimate' in data_string:45storageEstimate['quota'] = data_string.split("quota\":")[1].split(",\"usage")[0]46storageEstimate['usage'] = data_string.split("usage\":")[1].split(",\"caches")[0]47storageEstimate['caches'] = data_string.split("caches\":")[1].split(",\"indexedDB")[0]48storageEstimate['indexedDB'] = data_string.split("indexedDB\":")[1].split(",\"serviceWorker")[0]49storageEstimate['serviceWorker'] = data_string.split("serviceWorker\":")[1].split("},\"eventProperties",1)[0]5051if 'fp' in data_string:52fpResult['fp'] = data_string.split("fp\",\"data\":")[1].split(",\"eventProperties",1)[0]5354if 'fcp' in data_string:55fcpResult['fcp'] = data_string.split("fcp\",\"data\":")[1].split(",\"eventProperties",1)[0]5657if 'fid' in data_string:58fidResult['fid'] = data_string.split("fid\",\"data\":")[1].split(",\"eventProperties",1)[0]5960if 'lcp' in data_string:61lcpResult['lcp'] = data_string.split("lcp\",\"data\":")[1].split(",\"eventProperties",1)[0]6263if 'cls' in data_string:64clsResult['cls'] = data_string.split("cls\",\"data\":")[1].split(",\"eventProperties",1)[0]6566if 'tbt' in data_string:67tbtResult['tbt'] = data_string.split("tbt\",\"data\":")[1].split(",\"eventProperties",1)[0]6869outputDir = "perfume-output"7071if not os.path.exists(outputDir):72os.makedirs(outputDir)73else:74logging.getLogger(self.__class__.__name__).debug(f"The directory {outputDir} already exists")75try:76file2 = open(outputDir + '/MyFile2_results_{}.txt'.format(time.strftime('%Y.%m.%d_%H%M%S')),"w+")77file2.write(data_string)78with open(outputDir + '/navigationTiming_results_{}.csv'.format(time.strftime('%Y.%m.%d_%H%M%S')), 'w') as f: # Just use 'w' mode in 3.x 'w' mode in 3.x79w = csv.DictWriter(f, navigationTime.keys())80w.writeheader()81w.writerow(navigationTime)82with open(outputDir + '/networkInformation_results_{}.csv'.format(time.strftime('%Y.%m.%d_%H%M%S')), 'w') as f: # Just use 'w' mode in 3.x 'w' mode in 3.x83w = csv.DictWriter(f, networkInf.keys())84w.writeheader()85w.writerow(networkInf)86with open(outputDir + '/storageEstimate_results_{}.csv'.format(time.strftime('%Y.%m.%d_%H%M%S')), 'w') as f: # Just use 'w' mode in 3.x 'w' mode in 3.x87w = csv.DictWriter(f, storageEstimate.keys())88w.writeheader()89w.writerow(storageEstimate)90with open(outputDir + '/fp_results_{}.csv'.format(time.strftime('%Y.%m.%d_%H%M%S')), 'w') as f: # Just use 'w' mode in 3.x 'w' mode in 3.x91w = csv.DictWriter(f, fpResult.keys())92w.writeheader()93w.writerow(fpResult)94with open(outputDir + '/fcp_results_{}.csv'.format(time.strftime('%Y.%m.%d_%H%M%S')), 'w') as f: # Just use 'w' mode in 3.x 'w' mode in 3.x95w = csv.DictWriter(f, fcpResult.keys())96w.writeheader()97w.writerow(fcpResult)98with open(outputDir + '/fid_results_{}.csv'.format(time.strftime('%Y.%m.%d_%H%M%S')), 'w') as f: # Just use 'w' mode in 3.x 'w' mode in 3.x99w = csv.DictWriter(f, fidResult.keys())100w.writeheader()101w.writerow(fidResult)102with open(outputDir + '/lcp_results_{}.csv'.format(time.strftime('%Y.%m.%d_%H%M%S')), 'w') as f: # Just use 'w' mode in 3.x 'w' mode in 3.x103w = csv.DictWriter(f, lcpResult.keys())104w.writeheader()105w.writerow(lcpResult)106with open(outputDir + '/cls_results_{}.csv'.format(time.strftime('%Y.%m.%d_%H%M%S')), 'w') as f: # Just use 'w' mode in 3.x 'w' mode in 3.x107w = csv.DictWriter(f, clsResult.keys())108w.writeheader()109w.writerow(clsResult)110with open(outputDir + '/tbt_results_{}.csv'.format(time.strftime('%Y.%m.%d_%H%M%S')), 'w') as f: # Just use 'w' mode in 3.x 'w' mode in 3.x111w = csv.DictWriter(f, tbtResult.keys())112w.writeheader()113w.writerow(tbtResult)114115except Exception as ex:116logging.getLogger(self.__class__.__name__).error('error: ' + str(ex))117self.wfile.write(b'')118119def start_server():120"""Start the server."""121server_address = ('', 8080)122global httpd123httpd = http.server.HTTPServer(server_address, HTTPHandler)124logging.getLogger("PerfumeJS").info(f"Listening on all interfaces, on port 8080, and serving directory: {os.getcwd()}")125httpd.serve_forever()126127def stop_server():128"""Stop the server."""129global httpd130logging.getLogger("PerfumeJS").info("Shutting down server")131httpd.server_close()132133if __name__ == '__main__':134start_server()135stop_server()136137138