Skip to content

Commit

Permalink
stability-fix
Browse files Browse the repository at this point in the history
  • Loading branch information
GregorioMonari committed Mar 28, 2023
1 parent eb46816 commit d492191
Show file tree
Hide file tree
Showing 49 changed files with 231 additions and 191 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@
/.vscode
/4_UTILS
/5_RELEASES
/6_API_my2sec_executable
/6_API_my2sec_executable_OLD
/6_API_my2sec
/1_ActivityWatchProducer/PY/my2sec_OLD
192 changes: 96 additions & 96 deletions 1_ActivityWatchProducer/PY/my2sec/main/API_my2sec.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,24 @@
import socket
from manage_csv import CheckFile, ReadCSV, EventsToCSV, WorkingEvents, UpdateSelectionCSV, UpdateCurrentCSV
import numpy as np
import logging
import builtins
import datetime


app = Flask(__name__)
api = Api(app)
# disable default Flask logging
log = logging.getLogger('werkzeug')
log.disabled = True


def custom_print(*args, **kwargs):
now = datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")
prefix = "127.0.0.1 -- [{}] ".format(now)
sep = kwargs.get("sep", " ")
end = kwargs.get("end", "\n")
builtins.print(prefix, end="")
builtins.print(*args, sep=sep, end=end)


# rispondere sempre con l'hostname e il AW client name
Expand All @@ -40,75 +53,39 @@ class User(Resource):


def get(self):
#print(request.json)
try:
try:
#result = json.loads(request.json)["watcher-api-request"]["getAction"]
result = dict(request.json)["watcher-api-request"]["getAction"]
except Exception as ex:
print("NOT A VALID JSON: MAY BE EMPTY?")
print(ex)
result="Null"

if "Null"==result:
return make_response("HELLO!",200)

if "GetAWClient" == result:
return make_response(self.__watcher.GetAWClientName(), 200)

if "GetCurrentCSV" == result:
if CheckFile(self.path, '/apps_current.csv'):
res = ReadCSV(self.path, "/apps_current.csv")
if not res.empty:
return make_response(res.to_json(), 200)
raise Exception("impossible to open 'apps_current.csv'")
else: return make_response("'apps_current.csv' doesn't exist")

if "GetCurrentCSV-None" == result:
if CheckFile(self.path, '/apps_current.csv'):
res = ReadCSV(self.path, "/apps_current.csv")
if 'None' in list(set(res.working_selection)): return make_response(str(True), 200)
else: return make_response(str(False), 200)
else: return make_response("'apps_current.csv' doesn't exist")

if "GetSelectionCSV" == result:
if CheckFile(self.path, '/apps_selection.csv'):
res = ReadCSV(self.path, "/apps_selection.csv")
if not res.empty:
return make_response(res.to_json(), 200)
raise Exception("impossible to open 'apps_selection.csv'")
else: return make_response("'apps_selection.csv' doesn't exist")

if "GetWorkingEvents-AI-Filter" == result:
if CheckFile(self.path, '/apps_current.csv'):
res, err = WorkingEvents(self.path)
if err:
raise Exception(err)
return make_response(res.to_json(), 200)
else: return make_response("'apps_current.csv' doesn't exist")
pass

except Exception as ex:
print(ex)
return make_response("Bad Request (JSON error): {0}".format(ex), 400)


def post(self):
try:

# create a default message for errors
message = make_response("Bad Request (JSON error)", 400)

# try to parse the request
try: result = json.loads(request.json)

# try in a different way (sometimes in Java the parse phase is different)
except:
print("Ho trovato un errore: maybe JAVA?")
custom_print("WARNING: I get an error during the parsing phase (Java platform?). Trying with 'dict'...")
result = dict(request.json)
print("PARSATO CON JAVA")
print(result)

custom_print('API: Message received: ', result)
result = result["watcher-api-request"]

if "getAction" in list(result.keys()):
result = result["getAction"]
print(result)
#custom_print('API: The JSON contains a "getAction" key: {0}'.format(result))


if "GetAWClient" == result:
return make_response(self.__watcher.GetAWClientName(), 200)


if "GetCurrentCSV" == result:
if CheckFile(self.path, '/apps_current.csv'):
res = ReadCSV(self.path, "/apps_current.csv")
Expand All @@ -117,13 +94,15 @@ def post(self):
raise Exception("impossible to open 'apps_current.csv'")
else: return make_response("'apps_current.csv' doesn't exist")


if "GetCurrentCSV-None" == result:
if CheckFile(self.path, '/apps_current.csv'):
res = ReadCSV(self.path, "/apps_current.csv")
if 'None' in list(set(res.working_selection)): return make_response(str(True), 200)
else: return make_response(str(False), 200)
else: return make_response("'apps_current.csv' doesn't exist")


if "GetSelectionCSV" == result:
if CheckFile(self.path, '/apps_selection.csv'):
res = ReadCSV(self.path, "/apps_selection.csv")
Expand All @@ -132,6 +111,7 @@ def post(self):
raise Exception("impossible to open 'apps_selection.csv'")
else: return make_response("'apps_selection.csv' doesn't exist")


if "GetWorkingEvents-AI-Filter" == result:
if CheckFile(self.path, '/apps_current.csv'):
res, err = WorkingEvents(self.path)
Expand All @@ -147,64 +127,84 @@ def post(self):
self.__watcher.CreateAWClient(result["AWClient"])
return make_response("Client name: "+self.__watcher.GetAWClientName(), 200)


# change (and create) the AW client with the new name
if "AWServerParams" in list(result.keys()):
params = (result["AWServerParams"]["hostname"],int(result["AWServerParams"]["port"]))
self.__watcher.SetAWServerParams(params)
host, port = self.__watcher.GetAWServerParams()
return make_response("AW hostname: {0}, AW port: {1}".format(host,port), 200)

result = result["requestAction"]
if result["watchers-management"] == "START_ALL":
result = self.__watcher.Start()
return make_response(result[0], result[1])


if result["watchers-management"] == "STOP_ALL":
message, error = self.__watcher.Stop()
if error:
return make_response(str(message), 400)
query_result = self.__watcher.QueryAWCurrentWindow()
print(query_result)
#print(query_result)
if query_result.empty:
print("error or empty")
return make_response("empty or error query", 200)
message, err = EventsToCSV(self.path, query_result)
return make_response(str(message), 200)

if result["watchers-management"] == "SendCurrentCSV":
if CheckFile(self.path, '/apps_current.csv'):
tmp = ReadCSV(self.path, "/apps_current.csv")
if tmp[tmp.working_selection=='None'].empty:
msg, err = self.__watcher.SendToAWBucket(tmp)
if err:
return make_response(str(msg), 400)
else:
return make_response('there are some None values in the apps_current.csv', 400)
os.remove(self.path+"/apps_current.csv")
return make_response('events send to working bucket', 200)
else: return make_response("'apps_current.csv' doesn't exist")

if "SetWorkingEvents" in list(result["watchers-management"].keys()):
msg, err = UpdateSelectionCSV(pd.DataFrame(result["watchers-management"]["SetWorkingEvents"]), self.path)
if err:
make_response(str(msg), 400)
msg, err = UpdateCurrentCSV(self.path)
if err:
return make_response(str(msg), 400)
return make_response('all CSVs updated', 200)


except Exception as ex:
print(ex)
return make_response("Bad Request (JSON error)", 400)
if "requestAction" in list(result.keys()):
result = result["requestAction"]
#custom_print('API: The JSON contains a "requestAction" key: {0}'.format(result))

# start the scan
if result["watchers-management"] == "START_ALL":
result = self.__watcher.Start()

return make_response(result[0], result[1])


# stop the scan
if result["watchers-management"] == "STOP_ALL":
message, error = self.__watcher.Stop()

if error:
raise Exception(message)
custom_print('WATCHER: Scan stopped')
query_result = self.__watcher.QueryAWCurrentWindow()

# if there aren't AW results in the scan
if query_result.empty:
msg = "The ActivityWatch query is empty: no new events scanned"
custom_print("WARNING: ", msg)
return make_response(msg, 200)
message, err = EventsToCSV(self.path, query_result)
return make_response(str(message), 200)

if result["watchers-management"] == "SendCurrentCSV":
if CheckFile(self.path, '/apps_current.csv'):
tmp = ReadCSV(self.path, "/apps_current.csv")
if tmp[tmp.working_selection=='None'].empty:
msg, err = self.__watcher.SendToAWBucket(tmp)
if err:
return make_response(str(msg), 400)
else:
return make_response('there are some None values in the apps_current.csv', 400)
os.remove(self.path+"/apps_current.csv")
return make_response('events send to working bucket', 200)
else: return make_response("'apps_current.csv' doesn't exist")

if "SetWorkingEvents" in list(result["watchers-management"].keys()):
msg, err = UpdateSelectionCSV(pd.DataFrame(result["watchers-management"]["SetWorkingEvents"]), self.path)
if err:
make_response(str(msg), 400)
msg, err = UpdateCurrentCSV(self.path)
if err:
return make_response(str(msg), 400)
return make_response('all CSVs updated', 200)


# if the program arrives here, it means that the JSON doesn't contain the
# valid keys defined previously. So, the user must be to use a different JSON.
raise Exception("the JSON doesn't contain valid keys")

api.add_resource(User, '/user') # '/users' is our entry point


# if there are some issues during the parse phase
except Exception as ex:
custom_print("ERROR: {0}".format(ex))
return make_response("ERROR: {0}".format(ex), 400)


api.add_resource(User, '/user')


if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000) # run our Flask app

# run the app at 127.0.0.1 at port 5000
# with windows platform try with localhost instead 127.0.0.1
app.run(debug=False, host='127.0.0.1', port=5000)
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading

0 comments on commit d492191

Please sign in to comment.