Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
S2-group
GitHub Repository: S2-group/android-runner
Path: blob/master/AndroidRunner/Plugins/perfume_js/server.py
630 views
1
import threading
2
import time
3
import csv
4
import os
5
import http
6
from http.server import HTTPServer
7
import logging
8
9
navigationTime= {'fetchTime':0 , 'workerTime':0 , 'totalTime':0, 'downloadTime':0, 'timeToFirstByte':0, 'headerSize':0, 'dnsLookupTime': 0}
10
networkInf = {'downlink': 0, 'effectiveType': 0, 'rtt':0, 'saveData':False}
11
storageEstimate = {'quota':0, 'usage':0, 'caches':0, 'indexedDB':0, 'serviceWorker':0}
12
fpResult = {'fp':0}
13
fcpResult = {'fcp':0}
14
fidResult = {'fid':0}
15
lcpResult = {'lcp':0}
16
clsResult = {'cls':0}
17
tbtResult = {'tbt':0}
18
httpd = 0
19
20
class HTTPHandler(http.server.SimpleHTTPRequestHandler):
21
22
def do_POST(self):
23
logging.getLogger(self.__class__.__name__).info("POST request received")
24
length = int(self.headers['Content-Length']) # <--- Gets the size of data
25
data_string = self.rfile.read(length)
26
data_string = data_string.decode("utf-8")
27
logging.getLogger(self.__class__.__name__).debug(f"Data: {data_string}")
28
29
if 'perfumeResults' in data_string:
30
if 'navigationTiming' in data_string:
31
navigationTime['fetchTime'] = data_string.split("fetchTime\":")[1].split(",\"workerTime")[0]
32
navigationTime['workerTime'] = data_string.split("workerTime\":")[1].split(",\"totalTime")[0]
33
navigationTime['totalTime'] = data_string.split("totalTime\":")[1].split(",\"downloadTime")[0]
34
navigationTime['downloadTime'] = data_string.split("downloadTime\":")[1].split(",\"timeToFirstByte")[0]
35
navigationTime['timeToFirstByte'] = data_string.split("timeToFirstByte\":")[1].split(",\"headerSize")[0]
36
navigationTime['headerSize'] = data_string.split("headerSize\":")[1].split(",\"dnsLookupTime")[0]
37
navigationTime['dnsLookupTime'] = data_string.split("dnsLookupTime\":")[1].split("},\"eventProperties",1)[0]
38
39
if 'networkInformation' in data_string:
40
networkInf['downlink'] = data_string.split("downlink\":")[1].split(",\"effectiveType")[0]
41
networkInf['effectiveType'] = data_string.split("effectiveType\":\"")[1].split("\",\"rtt")[0]
42
networkInf['rtt'] = data_string.split("rtt\":")[1].split(",\"saveData")[0]
43
networkInf['saveData'] = data_string.split("saveData\":")[1].split("},\"eventProperties",1)[0]
44
45
if 'storageEstimate' in data_string:
46
storageEstimate['quota'] = data_string.split("quota\":")[1].split(",\"usage")[0]
47
storageEstimate['usage'] = data_string.split("usage\":")[1].split(",\"caches")[0]
48
storageEstimate['caches'] = data_string.split("caches\":")[1].split(",\"indexedDB")[0]
49
storageEstimate['indexedDB'] = data_string.split("indexedDB\":")[1].split(",\"serviceWorker")[0]
50
storageEstimate['serviceWorker'] = data_string.split("serviceWorker\":")[1].split("},\"eventProperties",1)[0]
51
52
if 'fp' in data_string:
53
fpResult['fp'] = data_string.split("fp\",\"data\":")[1].split(",\"eventProperties",1)[0]
54
55
if 'fcp' in data_string:
56
fcpResult['fcp'] = data_string.split("fcp\",\"data\":")[1].split(",\"eventProperties",1)[0]
57
58
if 'fid' in data_string:
59
fidResult['fid'] = data_string.split("fid\",\"data\":")[1].split(",\"eventProperties",1)[0]
60
61
if 'lcp' in data_string:
62
lcpResult['lcp'] = data_string.split("lcp\",\"data\":")[1].split(",\"eventProperties",1)[0]
63
64
if 'cls' in data_string:
65
clsResult['cls'] = data_string.split("cls\",\"data\":")[1].split(",\"eventProperties",1)[0]
66
67
if 'tbt' in data_string:
68
tbtResult['tbt'] = data_string.split("tbt\",\"data\":")[1].split(",\"eventProperties",1)[0]
69
70
outputDir = "perfume-output"
71
72
if not os.path.exists(outputDir):
73
os.makedirs(outputDir)
74
else:
75
logging.getLogger(self.__class__.__name__).debug(f"The directory {outputDir} already exists")
76
try:
77
file2 = open(outputDir + '/MyFile2_results_{}.txt'.format(time.strftime('%Y.%m.%d_%H%M%S')),"w+")
78
file2.write(data_string)
79
with 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.x
80
w = csv.DictWriter(f, navigationTime.keys())
81
w.writeheader()
82
w.writerow(navigationTime)
83
with 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.x
84
w = csv.DictWriter(f, networkInf.keys())
85
w.writeheader()
86
w.writerow(networkInf)
87
with 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.x
88
w = csv.DictWriter(f, storageEstimate.keys())
89
w.writeheader()
90
w.writerow(storageEstimate)
91
with 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.x
92
w = csv.DictWriter(f, fpResult.keys())
93
w.writeheader()
94
w.writerow(fpResult)
95
with 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.x
96
w = csv.DictWriter(f, fcpResult.keys())
97
w.writeheader()
98
w.writerow(fcpResult)
99
with 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.x
100
w = csv.DictWriter(f, fidResult.keys())
101
w.writeheader()
102
w.writerow(fidResult)
103
with 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.x
104
w = csv.DictWriter(f, lcpResult.keys())
105
w.writeheader()
106
w.writerow(lcpResult)
107
with 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.x
108
w = csv.DictWriter(f, clsResult.keys())
109
w.writeheader()
110
w.writerow(clsResult)
111
with 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.x
112
w = csv.DictWriter(f, tbtResult.keys())
113
w.writeheader()
114
w.writerow(tbtResult)
115
116
except Exception as ex:
117
logging.getLogger(self.__class__.__name__).error('error: ' + str(ex))
118
self.wfile.write(b'')
119
120
def start_server():
121
"""Start the server."""
122
server_address = ('', 8080)
123
global httpd
124
httpd = http.server.HTTPServer(server_address, HTTPHandler)
125
logging.getLogger("PerfumeJS").info(f"Listening on all interfaces, on port 8080, and serving directory: {os.getcwd()}")
126
httpd.serve_forever()
127
128
def stop_server():
129
"""Stop the server."""
130
global httpd
131
logging.getLogger("PerfumeJS").info("Shutting down server")
132
httpd.server_close()
133
134
if __name__ == '__main__':
135
start_server()
136
stop_server()
137
138