OnlineDatabase.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Mono.Data.Sqlite;
  5. using System.Data;
  6. using System;
  7. using UnityEngine.Networking;
  8. using System.IO;
  9. public class OnlineDatabase : MonoBehaviour {
  10. private const string onlineQuestionsUrl = "nordh.xyz/narKampen/dbFiles/Question.php";
  11. private const string serverUrl = "nordh.xyz/narKampen/dbFiles/";
  12. string databaseUrl;
  13. string gameMode;
  14. int winAmount = -1;
  15. int questionTimer = -1;
  16. public GameObject questionCardPrefab;
  17. private static OnlineDatabase instance;
  18. public static OnlineDatabase Instance { get { return instance; } }
  19. private void Awake() {
  20. if (instance == null) {
  21. instance = this;
  22. }
  23. }
  24. internal List<CategoryPanel.Category> GetCategories(List<CategoryPanel.Category> list) {
  25. string response = CallOnlineDatabaseWithResponse("Categories.php", null);
  26. response = "{\"categoryList\" : " + response + " }";
  27. Categories categories = new Categories();
  28. JsonUtility.FromJsonOverwrite(response, categories);
  29. foreach (Category c in categories.categoryList) {
  30. CategoryPanel.Category cat = new CategoryPanel.Category();
  31. cat.color = new Color32((byte)c.r, (byte)c.g, (byte)c.b, (byte)c.a);
  32. cat.name = c.name;
  33. cat.id = c.id;
  34. list.Add(cat);
  35. }
  36. return list;
  37. }
  38. internal void SetupNewOnlineGame(int limitPerQuestion, int limitPerPlayer, int toWin, List<InviteSearchResult> inviteUsers) {
  39. List<int> playerIds = new List<int>();
  40. inviteUsers.ForEach(i => playerIds.Add(i.GetId()));
  41. int currentUser = Database.Instance.GetSignedInUser().Key;
  42. playerIds.Add(currentUser);
  43. var form = new WWWForm();
  44. form.AddField("currentUser", currentUser);
  45. form.AddField("winNumber", toWin);
  46. form.AddField("limitPerQuestion", limitPerQuestion);
  47. form.AddField("limitPerPlayer", limitPerPlayer);
  48. form.AddField("playerIds", String.Join(",", playerIds));
  49. Debug.Log(CallOnlineDatabaseWithResponse("NewOnlineGame.php", form));
  50. }
  51. [Serializable]
  52. public class Question {
  53. public string question;
  54. public string answer;
  55. public string id;
  56. public string category;
  57. public int r;
  58. public int g;
  59. public int b;
  60. public int a;
  61. }
  62. [Serializable]
  63. public class Questions {
  64. public List<Question> questionsList = new List<Question>();
  65. }
  66. [Serializable]
  67. public class PlayerInfo {
  68. public string username;
  69. public string status;
  70. }
  71. [Serializable]
  72. public class PlayerInfos {
  73. public List<PlayerInfo> playerInfoList = new List<PlayerInfo>();
  74. }
  75. [Serializable]
  76. public class GamePlayerInfo {
  77. public string username;
  78. public string userLockedQuestions;
  79. }
  80. [Serializable]
  81. public class GamePlayerInfos {
  82. public List<GamePlayerInfo> gamePlayerInfoList = new List<GamePlayerInfo>();
  83. }
  84. [Serializable]
  85. public class Category {
  86. public int r;
  87. public int g;
  88. public int b;
  89. public int a;
  90. public int id;
  91. public string name;
  92. }
  93. [Serializable]
  94. public class Categories {
  95. public List<Category> categoryList = new List<Category>();
  96. }
  97. [Serializable]
  98. public class OnlineGame {
  99. public string id;
  100. public string winNumber;
  101. public string answerTimer;
  102. public string roundTimeLimit;
  103. public string currentPlayer;
  104. public string round;
  105. public string startDate;
  106. public string LastPlayedDate;
  107. public string finishedDate;
  108. public string status;
  109. }
  110. [Serializable]
  111. public class OnlineGames {
  112. public List<OnlineGame> onlineGamesList = new List<OnlineGame>();
  113. }
  114. [Serializable]
  115. public class UserName {
  116. public string id;
  117. public string username;
  118. }
  119. [Serializable]
  120. public class UserNames {
  121. public List<UserName> usernamesList = new List<UserName>();
  122. }
  123. private void CallDatabase(string filename, WWWForm formData) {
  124. string postUrl = serverUrl + filename;
  125. UnityWebRequest www = UnityWebRequest.Post(postUrl, formData);
  126. www.SendWebRequest();
  127. if (www.isNetworkError || www.isHttpError) {
  128. Debug.Log(www.error);
  129. } else {
  130. while (!www.isDone) {
  131. }
  132. }
  133. }
  134. private string CallOnlineDatabaseWithResponse(string filename, WWWForm formData) {
  135. string postUrl = serverUrl + filename;
  136. UnityWebRequest www = UnityWebRequest.Post(postUrl, formData);
  137. www.SendWebRequest();
  138. if (www.isNetworkError || www.isHttpError) {
  139. Debug.Log(www.error);
  140. } else {
  141. while (!www.isDone) {
  142. }
  143. }
  144. return www.downloadHandler.text;
  145. }
  146. string questionString = "";
  147. string answerString = "";
  148. string idString = "";
  149. string categoryString = "";
  150. private int round = -1;
  151. private string SearchString;
  152. public string QuestionString { get => questionString; set => questionString = value; }
  153. private void Start() {
  154. if (instance == null) {
  155. instance = this;
  156. }
  157. }
  158. internal void SetLastPlayedDate(int gameId) {
  159. WWWForm form = new WWWForm();
  160. form.AddField("gameId", gameId);
  161. form.AddField("f", "SetLastPlayed");
  162. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  163. if (!response.Equals("")) {
  164. Debug.Log(response);
  165. }
  166. }
  167. internal void DeclineOnlineGame(string userName, int gameId) {
  168. WWWForm formData = new WWWForm();
  169. formData.AddField("userId", -1);
  170. formData.AddField("f", "decline");
  171. formData.AddField("gameId", gameId);
  172. formData.AddField("userName", userName);
  173. CallDatabase("OnlineGames.php", formData);
  174. }
  175. internal void AcceptOnlineGame(string userName, int gameId) {
  176. WWWForm formData = new WWWForm();
  177. formData.AddField("userId", -1);
  178. formData.AddField("f", "accept");
  179. formData.AddField("gameId", gameId);
  180. formData.AddField("userName", userName);
  181. CallDatabase("OnlineGames.php", formData);
  182. }
  183. internal List<OnlineGameScript> GetOnlineGames(int userId, string userName, GameObject prefab) {
  184. WWWForm formData = new WWWForm();
  185. formData.AddField("userId", userId);
  186. formData.AddField("f", "list");
  187. formData.AddField("gameId", -1);
  188. formData.AddField("userName", userName);
  189. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", formData);
  190. if (response.Equals("No games found for user")) {
  191. return null;
  192. }
  193. response = "{\"onlineGamesList\" : " + response + " }";
  194. OnlineGames og = new OnlineGames();
  195. JsonUtility.FromJsonOverwrite(response, og);
  196. GameObject onlineGameObject;
  197. OnlineGameScript ogs = null;
  198. List<OnlineGameScript> games = new List<OnlineGameScript>();
  199. foreach (OnlineGame game in og.onlineGamesList) {
  200. onlineGameObject = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  201. ogs = onlineGameObject.GetComponent<OnlineGameScript>();
  202. ogs.CurrentPlayer = game.currentPlayer;
  203. ogs.SetGameStatus(game.status);
  204. Int32.TryParse(game.id, out int gameId);
  205. List<KeyValuePair<string, string>> playerInfos = GetGameInfo(gameId);
  206. if (game.status.Equals("PENDING")) {
  207. string extraInfo = "";
  208. foreach (KeyValuePair<string, string> s in playerInfos) {
  209. if (s.Value.Equals("WAITING") && s.Key.Equals(userName)) {
  210. ogs.SetGameStatus("INVITED");
  211. extraInfo += s.Key + ",";
  212. } else if (s.Value.EndsWith("WAITING")) {
  213. extraInfo += s.Key + ",";
  214. }
  215. }
  216. extraInfo = extraInfo.TrimEnd(',');
  217. ogs.SetGameStatusText(extraInfo);
  218. } else if (game.status.Equals("OTHERS_TURN")) { // Wont work
  219. ogs.SetGameStatusText(game.currentPlayer);
  220. } else if (game.status.Equals("ACTIVE")) {
  221. ogs.SetGameStatusText(game.currentPlayer);
  222. } else {
  223. ogs.SetGameStatusText();
  224. }
  225. ogs.SetId(game.id);
  226. ogs.SetWinNumber(game.winNumber);
  227. ogs.SetAnswerTimer(game.answerTimer);
  228. ogs.SetRoundTimeLimit(game.roundTimeLimit);
  229. ogs.SetRound(game.round);
  230. ogs.StartDate = game.startDate;
  231. games.Add(ogs);
  232. ogs.PlayerInfos = playerInfos;
  233. }
  234. return games;
  235. }
  236. internal List<KeyValuePair<string, string>> GetGameInfo(int gameId) {
  237. List<KeyValuePair<string, string>> returnList = new List<KeyValuePair<string, string>>();
  238. WWWForm form = new WWWForm();
  239. form.AddField("f", "GetGameInfo");
  240. form.AddField("gameId", gameId);
  241. string response = CallOnlineDatabaseWithResponse("OnlineGameInfo.php", form);
  242. response = "{\"playerInfoList\" : " + response + " }";
  243. PlayerInfos pi = new PlayerInfos();
  244. JsonUtility.FromJsonOverwrite(response, pi);
  245. foreach (PlayerInfo p in pi.playerInfoList) {
  246. KeyValuePair<string, string> player = new KeyValuePair<string, string>(p.username, p.status);
  247. returnList.Add(player);
  248. }
  249. return returnList;
  250. }
  251. internal void SetQuestionsLost(int gameId, string playerName, int questionsLost) {
  252. WWWForm form = new WWWForm();
  253. form.AddField("f", "SetQuestionsLost");
  254. form.AddField("questionsLost", questionsLost);
  255. form.AddField("userName", playerName);
  256. form.AddField("gameId", gameId);
  257. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  258. if (!response.Equals("")) {
  259. Debug.Log(response);
  260. }
  261. }
  262. internal void RemoveGame(int gameId) {
  263. WWWForm form = new WWWForm();
  264. form.AddField("f", "DeleteGame");
  265. form.AddField("gameId", gameId);
  266. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  267. if (!response.Equals("")) {
  268. Debug.Log(response);
  269. }
  270. }
  271. public string GetCurrentPlayer(int gameId) {
  272. WWWForm form = new WWWForm();
  273. form.AddField("f", "CurrentPlayer");
  274. form.AddField("gameId", gameId);
  275. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  276. if (response.Equals("")) {
  277. Debug.Log("Something wrong with current player for game with id: " + gameId);
  278. }
  279. return response;
  280. }
  281. public void SetCurrentPlayer(int gameId, string currentPlayer) {
  282. WWWForm form = new WWWForm();
  283. form.AddField("f", "SetCurrentPlayer");
  284. form.AddField("gameId", gameId);
  285. form.AddField("currentPlayer", currentPlayer);
  286. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  287. if (!response.Equals("")) {
  288. Debug.Log(response);
  289. }
  290. }
  291. internal int GetPlayerPoints(int gameId, string playerName) {
  292. WWWForm form = new WWWForm();
  293. form.AddField("f", "GetPlayerPoints");
  294. form.AddField("gameId", gameId);
  295. form.AddField("userName", playerName);
  296. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  297. if (response.Equals("")) {
  298. Debug.Log("Something wrong with current player for game with id: " + gameId);
  299. }
  300. Int32.TryParse(response, out int playerPoints);
  301. return playerPoints;
  302. }
  303. internal void SetFinishedDate(int gameId, string finishedDate) {
  304. WWWForm form = new WWWForm();
  305. form.AddField("f", "SetFinishedDate");
  306. form.AddField("gameId", gameId);
  307. form.AddField("finishedDate", finishedDate);
  308. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  309. if (!response.Equals("")) {
  310. Debug.Log(response);
  311. }
  312. }
  313. internal void SetRoundValue(int gameId, int round) {
  314. WWWForm form = new WWWForm();
  315. form.AddField("f", "SetRound");
  316. form.AddField("gameId", gameId);
  317. form.AddField("round", round);
  318. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  319. if (!response.Equals("")) {
  320. Debug.Log(response);
  321. }
  322. }
  323. internal int GetRoundValue(int gameId) {
  324. WWWForm form = new WWWForm();
  325. form.AddField("f", "GetRound");
  326. form.AddField("gameId", gameId);
  327. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  328. if (response.Equals("")) {
  329. Debug.Log("Something wrong with getting round for game with id: " + gameId);
  330. }
  331. Int32.TryParse(response, out int round);
  332. return round;
  333. }
  334. internal List<KeyValuePair<string, int>> GetPlayersForGame(int gameId) {
  335. WWWForm form = new WWWForm();
  336. form.AddField("f", "GetPlayers");
  337. form.AddField("gameId", gameId);
  338. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  339. if (response.Equals("")) {
  340. Debug.Log("Something wrong with getting players from game with id: " + gameId);
  341. }
  342. response = response = "{\"gamePlayerInfoList\" : " + response + " }";
  343. GamePlayerInfos gpi = new GamePlayerInfos();
  344. JsonUtility.FromJsonOverwrite(response, gpi);
  345. List<KeyValuePair<string, int>> returnList = new List<KeyValuePair<string, int>>();
  346. foreach (GamePlayerInfo p in gpi.gamePlayerInfoList) {
  347. Int32.TryParse(p.userLockedQuestions, out int points);
  348. KeyValuePair<string, int> player = new KeyValuePair<string, int>(p.username, points);
  349. returnList.Add(player);
  350. }
  351. return returnList;
  352. }
  353. public string AnswerString { get => answerString; set => answerString = value; }
  354. public string IdString { get => idString; set => idString = value; }
  355. public string CategoryString { get => categoryString; set => categoryString = value; }
  356. internal int GetQuestionsLost(int gameId, string playerName) {
  357. WWWForm form = new WWWForm();
  358. form.AddField("f", "GetQuestionsLost");
  359. form.AddField("userName", playerName);
  360. form.AddField("gameId", gameId);
  361. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  362. if (response.Equals("")) {
  363. Debug.Log("Something wrong with getting questions lost from game with id: " + gameId + " and playername " + playerName);
  364. }
  365. Int32.TryParse(response, out int questionsLost);
  366. return questionsLost;
  367. }
  368. public string GetGameMode(int gameId) {
  369. if (this.gameMode == null) {
  370. string sql = "SELECT gameMode FROM game WHERE id = " + gameId;
  371. IDbConnection conn = new SqliteConnection(databaseUrl);
  372. conn.Open();
  373. IDbCommand cmd = conn.CreateCommand();
  374. cmd.CommandText = sql;
  375. IDataReader reader = cmd.ExecuteReader();
  376. while (reader.Read()) {
  377. this.gameMode = reader.GetString(0);
  378. }
  379. reader.Close();
  380. cmd.Dispose();
  381. conn.Close();
  382. }
  383. return this.gameMode;
  384. }
  385. internal int GetWinCondition(int gameId) {
  386. if (winAmount == -1) {
  387. WWWForm form = new WWWForm();
  388. form.AddField("gameId", gameId);
  389. form.AddField("f", "GetWinCondition");
  390. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  391. Int32.TryParse(response, out this.winAmount);
  392. }
  393. return this.winAmount;
  394. }
  395. public NewQuestion GetNewQuestion(List<int> userAnsweredQuestions, string userName) {
  396. int gameId = GameObject.Find("GameManager").GetComponent<GameManagerScript>().GameId;
  397. Question q = GetQuestionData(false);
  398. NewQuestion nq = NewQuestion.Instance();
  399. nq.questionString = q.question;
  400. nq.answerString = q.answer;
  401. nq.categoryString = q.category;
  402. nq.idString = q.id;
  403. Color32 questionCategoryColor = new Color32((byte)q.r, (byte)q.g, (byte)q.b, (byte)q.a);
  404. nq.SetQuestionCategoryColor(questionCategoryColor);
  405. return nq;
  406. }
  407. public void SavePlayersQuestion(List<int> questionsToSave, string playerNameValue, int gameId) {
  408. WWWForm form = new WWWForm();
  409. form.AddField("f", "SavePlayerQuestions");
  410. form.AddField("gameId", gameId);
  411. form.AddField("questionsToSave", String.Join(",",questionsToSave));
  412. form.AddField("userName", playerNameValue);
  413. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  414. if (!response.Equals("")) {
  415. Debug.Log(response);
  416. }
  417. }
  418. public List<QuestionCard> GetPlayerQuestions(int gameId, string playerName) {
  419. List<QuestionCard> questions = new List<QuestionCard>();
  420. WWWForm form = new WWWForm();
  421. form.AddField("f", "PlayerQuestions");
  422. form.AddField("gameId", gameId);
  423. form.AddField("userName", playerName);
  424. string response = CallOnlineDatabaseWithResponse("OnlineGameInfo.php", form);
  425. response = "{\"questionsList\" : " + response + "}";
  426. Questions ql = new Questions();
  427. JsonUtility.FromJsonOverwrite(response, ql);
  428. foreach (Question q in ql.questionsList) {
  429. GameObject question = Instantiate(questionCardPrefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  430. QuestionCard qc = question.GetComponent<QuestionCard>();
  431. qc.SetAnswerText(q.answer);
  432. qc.SetQuestionText(q.question);
  433. qc.idString = q.id;
  434. Color32 questionCategoryColor = new Color32((byte)q.r, (byte)q.g, (byte)q.b, (byte)q.a);
  435. qc.SetQuestionCategoryColor(questionCategoryColor);
  436. questions.Add(qc);
  437. }
  438. return questions;
  439. }
  440. private Question GetQuestionData(bool showAnswer) {
  441. WWWForm form = new WWWForm();
  442. string response = CallOnlineDatabaseWithResponse("Question.php", form);
  443. // Show result
  444. response = "{\"questionsList\" : [ " + response + " ]}";
  445. Questions qe = new Questions();
  446. JsonUtility.FromJsonOverwrite(response, qe);
  447. return qe.questionsList[0];
  448. }
  449. public List<UserName> GetUsersToInvite(string searchString) {
  450. string postUrl = "nordh.xyz/narKampen/dbFiles/PlayerSearch.php?";
  451. postUrl += "search=" + UnityWebRequest.EscapeURL(searchString);
  452. UserNames uNames = new UserNames();
  453. UnityWebRequest www = UnityWebRequest.Get(postUrl);
  454. www.SendWebRequest();
  455. if (www.isNetworkError || www.isHttpError) {
  456. Debug.Log(www.error);
  457. } else {
  458. while (!www.isDone) {
  459. }
  460. // Show result
  461. string jsonData = www.downloadHandler.text;
  462. jsonData = "{\"usernamesList\" : " + jsonData + " }";
  463. JsonUtility.FromJsonOverwrite(jsonData, uNames);
  464. }
  465. // TODO handle empty
  466. return uNames.usernamesList;
  467. }
  468. }