Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
S2-group
GitHub Repository: S2-group/android-runner
Path: blob/master/AndroidRunner/Plugins/perfume_js/AddJS.py
630 views
1
import os, sys
2
import subprocess
3
from distutils.dir_util import copy_tree
4
from bs4 import BeautifulSoup
5
6
def bfs_dirs(root):
7
paths = [root]
8
9
while len(paths) > 0:
10
children = []
11
12
for parent in paths:
13
if parent.endswith(".gitignore"):
14
continue
15
16
for element in os.listdir(parent):
17
found_element = os.path.join(parent, element)
18
if os.path.isdir(found_element) and "googletagmanager" not in found_element:
19
children.append(found_element)
20
elif found_element.endswith("index.html") or found_element.endswith("index.htm"):#The entrance html file to the webpage needs to be called index.html or index.htm otherwise it won't add the JS code to read load times
21
if("index.html" in os.listdir(parent) and not(found_element.endswith("index.html"))):
22
continue
23
else:
24
return found_element
25
paths = children
26
27
return root
28
29
def add_js(directory, ip):
30
for cat in os.listdir(directory):
31
if cat == ".DS_Store" or cat == "RUN_WEBAPPS_README.md" or cat == "START_SERVER_IN_THIS_DIR":
32
continue
33
34
for site in os.listdir(directory + cat):
35
if site == ".DS_Store":
36
continue
37
38
path_to_html = bfs_dirs('{}{}/{}'.format(directory, cat, site))
39
if(path_to_html == '{}{}/{}'.format(directory, cat, site)):
40
continue
41
path_to_src = os.path.dirname(path_to_html)
42
print(path_to_html)
43
soup = BeautifulSoup(open(path_to_html, 'rb'), "lxml")
44
if(soup.find('head')):
45
perfumeSource = soup.new_tag('script')
46
perfumeSource['src'] ="/node_modules/perfume.js/dist/perfume.umd.min.js"
47
script = soup.new_tag('script')
48
script.string = "perfumeResults = []; function xml_http_post(url, data, callback) {var req = new XMLHttpRequest(); req.open(\"POST\", url, true); req.send(data);} const perfume = new Perfume({ analyticsTracker: (options) => { const { metricName, data, eventProperties, navigatorInformation } = options; perfumeResults.push(options); } }); function load_log() { setTimeout(function(){ objectToSend = \"{'perfumeResults':\"+JSON.stringify(perfumeResults)+\"}\"; xml_http_post(\""+ip+"\",objectToSend,null); },5000); };window.addEventListener ?window.addEventListener(\"load\",load_log, true) : window.attachEvent && window.attachEvent(\"onload\", load_log);"
49
soup.head.insert(0, perfumeSource)
50
soup.head.insert(1,script)
51
52
with open(path_to_html, "w") as file:
53
file.write(str(soup))
54
55
if __name__ == '__main__':
56
#USAGE: (python3 AddJS.py path/To/Directory/With/All/WebApplication/ IPADRRESS)
57
#NOTE: IPADDRESS should be in the form of http://IP:8080/ and IP is the ip address
58
add_js(sys.argv[1], sys.argv[2])
59
60