OnlineDatabase.cs 19 KB

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