OnlineDatabase.cs 20 KB

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