server.nim 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # author: Ethosa
  2. import
  3. asyncdispatch,
  4. db_sqlite,
  5. akane
  6. proc userExists(connect: DbConn, username: string): bool =
  7. for row in connect.rows(sql"SELECT username FROM users"):
  8. if row[0] == username:
  9. return true
  10. return false
  11. proc addUser(connect: DbConn, username: string) =
  12. if not connect.userExists(username):
  13. connect.exec(sql"INSERT INTO users VALUES (?)", username)
  14. when isMainModule:
  15. var db = open("users.db", "", "", "")
  16. db.exec(sql"CREATE TABLE IF NOT EXISTS users (username text)")
  17. proc main {.gcsafe.} =
  18. var
  19. server = newServer()
  20. timed_chat = %*[]
  21. server.pages:
  22. "/":
  23. await request.answer("Hello, World!")
  24. startswith("/enter"):
  25. var data = await parseQuery(request)
  26. if "username" in data:
  27. db.addUser($data["username"])
  28. await request.sendJson(%*{"response": 0})
  29. else:
  30. await request.sendJson(
  31. %*{
  32. "response": 1,
  33. "data": {
  34. "text": "You need to specify a username!"
  35. }})
  36. startswith("/send"):
  37. var data = await parseQuery(request)
  38. if "username" in data and "msg" in data:
  39. if db.userExists($data["username"]):
  40. timed_chat.add(data["username"])
  41. timed_chat.add(data["msg"])
  42. await request.sendJson(%*{"response": 0})
  43. else:
  44. await request.sendJson(
  45. %*{
  46. "response": 1,
  47. "data": {
  48. "text": "This user isn't registered!"
  49. }})
  50. else:
  51. await request.sendJson(
  52. %*{
  53. "response": 1,
  54. "data": {
  55. "text": "You need to specify a msg and username!"
  56. }})
  57. startswith("/getchat"):
  58. var response = %*{}
  59. response["response"] = %0
  60. response["data"] = timed_chat
  61. await request.sendJson(response)
  62. server.start()
  63. main()