-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
314 lines (269 loc) · 8.78 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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import json
import logging
import os
import shutil
from typing import Any, Dict
import uuid
from PIL import Image
from fastapi import FastAPI, File, HTTPException, Path, Request, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from httpx import AsyncClient
from utils.genUsername import check_username_availability
from utils.getUsername import get_username
from utils.deployDocker import deploy, restart
from utils.matrixApi import generatePassword, get_email_from_username, register_user, set_display_name, set_profile
from models import AgentUpdate, BotList, Bots, Duplicate, Item
from utils.superagent import create_workflow, handleWorkflowBots, update_yaml
from prisma import Prisma
# Global Variables
MATRIX_API_URL = os.environ["MATRIX_URL"]
SUPERAGENT_API_URL = os.environ["SUPERAGENT_API_URL"]
app = FastAPI()
prisma = Prisma()
session = AsyncClient(follow_redirects=True)
app.mount("/static", StaticFiles(directory="uploaded_files"), name="static")
#public list as json
f = open('data.json')
data = json.load(f)
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.middleware("http")
async def log_requests(request: Request, call_next):
logging.info(request)
response = await call_next(request)
return response
@app.on_event("startup")
async def startup():
await prisma.connect()
@app.on_event("shutdown")
async def shutdown():
await prisma.disconnect()
@app.post("/add")
async def add_item(item: Item):
password = generatePassword(10)
try:
if item.bot_username != "":
bot_username = item.bot_username
else:
bot_username = check_username_availability("testworkflow")
reg_result = register_user(
bot_username, password, item.name)
logging.info(reg_result)
owner_id = await get_username(item.email_id)
env_vars = {
"HOMESERVER": MATRIX_API_URL,
"USER_ID": reg_result['user_id'],
"PASSWORD": password,
"DEVICE_ID": reg_result['device_id'],
"SUPERAGENT_URL": SUPERAGENT_API_URL,
"ID": item.id,
"API_KEY": item.api_key,
"TYPE": item.type,
"OWNER_ID": owner_id,
"STREAMING" : not item.streaming
}
token = reg_result['access_token']
if item.profile:
await set_profile(password, homeserver=MATRIX_API_URL, user_id=reg_result['user_id'], profile_url=item.profile)
deploy_bot = await deploy(username=bot_username, env=env_vars)
logging.info(deploy_bot)
await prisma.bot.create({
'username': owner_id,
'bot_username': reg_result['user_id'],
'password': password,
'api_key': item.api_key,
'id': item.id,
'email_id': item.email_id,
'name': item.name,
'desc': item.description,
'profile_photo': item.profile if item.profile else "",
'access_token': token,
'type': item.type,
'publish': item.publish,
'tags': item.tags.split(','),
'category' : item.category if item.category else "fun",
'streaming': not item.streaming
})
if item.type == "WORKFLOW" and not item.streaming:
await handleWorkflowBots(SUPERAGENT_API_URL, item.id, item.api_key, session, prisma, item.email_id, owner_id, item.publish_all)
return {"status": "created", "user_id": reg_result}
except Exception as e:
logging.error(e)
return {"status": f"error: {e}"}
@app.delete("/list/{username}/del")
async def delete_item(item: Item, username: str = Path(..., title="The username", description="Username of the user")):
items = await prisma.bot.delete(where={
'id': username
})
if item:
return items
raise HTTPException(status_code=404, detail="Item not found")
@app.get("/list/{username}")
async def get_list(username: str = Path(..., title="The username", description="Username of the user")):
public = await prisma.bot.find_many(
where={
"publish": True
}
)
items = await prisma.bot.find_many(where={
'username': username
})
if items:
return {"personal": items, "public": public}
return {"personal": [], "public": public}
@app.get("/agents/{agent_id}")
async def get_bot(agent_id):
get_bot = await prisma.bot.find_first(
where={
"id": agent_id
}
)
return get_bot
@app.get("/bot/{username}")
async def bot_info(username) -> Bots | None:
info = await prisma.bot.find_first(
where={
"bot_username": username
}
)
return info
@app.get("/user/{username}")
async def get_api(username):
data = await prisma.bot.find_first(
where={
"username": username
}
)
if data:
return {"email" : data.email_id }
data = get_email_from_username(username)
return {"email" : data}
@app.post("/bots/restart/{username}")
async def restart_bot(username):
bot_data = await prisma.bot.find_first(
where={
"bot_username": username
}
)
if bot_data:
res = await restart(username)
return res
raise HTTPException(detail="Username not found",status_code=401)
@app.post("/bots/{room_id}/check")
async def bots_check(botlist: BotList):
bots_data = await prisma.bot.find_many(
where={
"bot_username" : {
"in" : botlist.bots
}
}
)
result = { k:False for k in botlist.bots}
for i in bots_data:
result[i.bot_username] = True
return result
@app.post("/bots/{bot_username}/verify")
async def bots_verify(bot_username):
bots_data = await prisma.bot.find_first(
where={
"bot_username" : bot_username
}
)
if bots_data:
return True
return False
@app.post("/bots/update")
async def update_bot(item: AgentUpdate, agent_id):
get_bot = await prisma.bot.find_first(
where={
"id": agent_id
}
)
if get_bot:
if item.avatar_mxc:
get_mxc = await set_profile(get_bot.password, homeserver=MATRIX_API_URL, user_id=get_bot.bot_username, profile_url=item.avatar_mxc)
item.avatar_mxc = get_mxc
if item.name:
await set_display_name(get_bot.password, homeserver=MATRIX_API_URL, user_id=get_bot.bot_username, name=item.name)
get_bot = await prisma.bot.update(
where={
"id": agent_id
},
data=item.dict(exclude_none=True)
)
return get_bot
@app.get('/botlist', response_model=list[Bots])
async def bots_list(tag: str = None):
if tag is None:
data = await prisma.bot.find_many(
where={
"publish": True
}
)
else:
data = await prisma.bot.find_many(
where={
'tags': {
'has_every': [tag]
}
},
)
return data
@app.get("/public")
async def public_list():
return data
@app.post('/agent/duplicate/{username}')
async def agent_duplicate(item: Bots):
get_agent = await prisma.bot.find_first(
where={
"id": item.agent_id
}
)
if get_agent.type == "WORKFLOW":
workflow_data = await prisma.workflow.find_first(
where={
"username": item.username
}
)
workflow = await create_workflow(SUPERAGENT_API_URL, item.name, item.description, get_agent.api_key, session)
update_yaml(SUPERAGENT_API_URL,
workflow["id"], get_agent.api_key, workflow_data.yaml, session)
return True
@app.post("/upload_file")
async def upload_file(file: UploadFile = File(...)):
file_id = str(uuid.uuid4())
file_location = f"uploaded_files/{file_id}_{file.filename}"
with open(file_location, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
file_url = f"https://bots.spaceship.im/static/{file_id}_{file.filename}"
return JSONResponse({"url": file_url})
data_store = {}
@app.post("/save_data/{msg_id}")
async def save_data(msg_id, data: Dict[Any, Any]):
grad_output = await prisma.gradio.create(
data={
"id": msg_id,
"data" : data
}
)
if grad_output:
return {"success" : True}
return {"success" : False}
@app.get("/check_data/{msg_id}")
async def check_data(msg_id: str):
grad_data = await prisma.gradio.find_first(
where={
"id" : msg_id
}
)
if grad_data:
return grad_data
raise HTTPException(status_code=404, detail="Data not found")