This repository has been archived by the owner on Apr 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
127 lines (107 loc) · 3.42 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
from requests.api import head
import uvicorn
from fastapi import FastAPI, HTTPException, BackgroundTasks
from pydantic import BaseModel
from typing import Optional
from deta import Deta
from dotenv import load_dotenv
import os
from datetime import datetime
import uuid
import requests
from operator import itemgetter
load_dotenv()
DETA_TOKEN = os.getenv("DETA_TOKEN")
PUSH_TOKEN = os.getenv("PUSH_TOKEN")
app = FastAPI()
deta = Deta(DETA_TOKEN)
tokendb = deta.Base("telemetry-tokens")
logdb = deta.Base("telemetry-logs")
class CreateToken(BaseModel):
app: str
description: str
class LogAction(BaseModel):
level: str
detail: str
timestamp: str
token: str
app: str
notify: bool
class Authorize(BaseModel):
app: str
token: str
def send_notification(notify, logapp, level, detail, timestamp):
if notify is True:
title = "{0} [{1}]".format(logapp, level)
body = "{0} - Timestamp: {1}".format(detail, timestamp)
requests.post("https://push.techulus.com/api/v1/notify/{0}?title={1}&body={2}".format(PUSH_TOKEN, title, body))
@app.get("/")
def get_root():
testlist = ["test", "test2"]
testlist.sort()
return {"msg": "Telemetry operated by berrysauce - Code/License at github.com/berrysauce/telemetry"}
@app.post("/token")
def post_session(item: CreateToken):
today = str(datetime.now())
token = str(uuid.uuid4())
tokendb.insert({
"app": item.app,
"description": item.description,
"token": token,
"created": today
})
return {
"msg": "Token created!",
"app": item.app,
"description": item.description,
"token": token
}
@app.post("/validate")
def post_validate(auth: Authorize):
try:
session = tokendb.fetch({"token": auth.token}).items[0]
except:
raise HTTPException(status_code=401, detail="Unauthorized")
if auth.app != session["app"]:
raise HTTPException(status_code=401, detail="Unauthorized")
else:
return {"valid": True}
@app.post("/log")
def post_log(log: LogAction, background_tasks: BackgroundTasks):
background_tasks.add_task(send_notification, log.notify, log.app, log.level, log.detail, log.timestamp)
try:
session = tokendb.fetch({"token": log.token}).items[0]
except:
raise HTTPException(status_code=401, detail="Unauthorized")
if log.app != session["app"]:
return {"msg": "Token is not valid for this app!"}
timestamp = datetime.strptime(log.timestamp, "%Y-%m-%d %H:%M:%S.%f")
localtime = datetime.utcnow()
latency = str(localtime - timestamp)
logdb.put({
"app": log.app,
"level": log.level,
"detail": log.detail,
"timestamp": log.timestamp,
"latency": latency
})
return {
"msg": "Action logged!",
"latency": latency
}
@app.post("/logs")
def post_logs(auth: Authorize, formatted: bool = False):
try:
session = tokendb.fetch({"token": auth.token}).items[0]
except:
raise HTTPException(status_code=401, detail="Unauthorized")
if auth.app != session["app"]:
return {"msg": "Token is not valid for this app!"}
logs = logdb.fetch({"app": auth.app}).items
if formatted is False:
return logs
else:
logs.sort(key=itemgetter("timestamp"))
return logs
if __name__ == "__main__":
uvicorn.run(app, host="localhost", port=80)