OnlineDatabase.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. public string playerToAct;
  111. }
  112. [Serializable]
  113. public class OnlineGames {
  114. public List<OnlineGame> onlineGamesList = new List<OnlineGame>();
  115. }
  116. [Serializable]
  117. public class UserName {
  118. public string id;
  119. public string username;
  120. }
  121. [Serializable]
  122. public class UserNames {
  123. public List<UserName> usernamesList = new List<UserName>();
  124. }
  125. private void CallDatabase(string filename, WWWForm formData) {
  126. string postUrl = serverUrl + filename;
  127. UnityWebRequest www = UnityWebRequest.Post(postUrl, formData);
  128. www.SendWebRequest();
  129. if (www.isNetworkError || www.isHttpError) {
  130. Debug.Log(www.error);
  131. } else {
  132. while (!www.isDone) {
  133. }
  134. }
  135. }
  136. private string CallOnlineDatabaseWithResponse(string filename, WWWForm formData) {
  137. string postUrl = serverUrl + filename;
  138. UnityWebRequest www = UnityWebRequest.Post(postUrl, formData);
  139. www.SendWebRequest();
  140. if (www.isNetworkError || www.isHttpError) {
  141. Debug.Log(www.error);
  142. } else {
  143. while (!www.isDone) {
  144. }
  145. }
  146. return www.downloadHandler.text;
  147. }
  148. string questionString = "";
  149. string answerString = "";
  150. string idString = "";
  151. string categoryString = "";
  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. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", formData);
  182. if (!response.Equals("")) {
  183. Debug.Log(response);
  184. }
  185. }
  186. internal List<OnlineGameScript> GetOnlineGames(int userId, string userName, GameObject prefab) {
  187. WWWForm formData = new WWWForm();
  188. formData.AddField("userId", userId);
  189. formData.AddField("f", "list");
  190. formData.AddField("gameId", -1);
  191. formData.AddField("userName", userName);
  192. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", formData);
  193. if (response.Equals("No games found for user") || response.Equals("")) {
  194. return null;
  195. }
  196. response = "{\"onlineGamesList\" : " + response + " }";
  197. OnlineGames og = new OnlineGames();
  198. JsonUtility.FromJsonOverwrite(response, og);
  199. GameObject onlineGameObject;
  200. OnlineGameScript ogs = null;
  201. List<OnlineGameScript> games = new List<OnlineGameScript>();
  202. foreach (OnlineGame game in og.onlineGamesList) {
  203. onlineGameObject = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  204. ogs = onlineGameObject.GetComponent<OnlineGameScript>();
  205. ogs.CurrentPlayer = game.currentPlayer;
  206. ogs.SetGameStatus(game.status);
  207. Int32.TryParse(game.id, out int gameId);
  208. List<KeyValuePair<string, string>> playerInfos = GetGameInfo(gameId);
  209. if (game.status.Equals("PENDING")) {
  210. string extraInfo = "";
  211. foreach (KeyValuePair<string, string> s in playerInfos) {
  212. if (s.Value.Equals("WAITING") && s.Key.Equals(userName, StringComparison.InvariantCultureIgnoreCase)) {
  213. ogs.SetGameStatus("INVITED");
  214. extraInfo += s.Key + ",";
  215. } else if (s.Value.EndsWith("WAITING")) {
  216. extraInfo += s.Key + ",";
  217. }
  218. }
  219. extraInfo = extraInfo.TrimEnd(',');
  220. ogs.SetGameStatusText(extraInfo);
  221. } else if (game.status.Equals("OTHERS_TURN")) {
  222. ogs.SetGameStatusText(game.playerToAct);
  223. } else if (game.status.Equals("ACTIVE")) {
  224. ogs.SetGameStatusText(game.playerToAct);
  225. } else {
  226. ogs.SetGameStatusText();
  227. }
  228. ogs.SetId(game.id);
  229. ogs.SetWinNumber(game.winNumber);
  230. ogs.SetAnswerTimer(game.answerTimer);
  231. ogs.SetRoundTimeLimit(game.roundTimeLimit);
  232. ogs.SetRound(game.round);
  233. ogs.StartDate = game.startDate;
  234. games.Add(ogs);
  235. ogs.PlayerInfos = playerInfos;
  236. }
  237. return games;
  238. }
  239. internal List<KeyValuePair<string, string>> GetGameInfo(int gameId) {
  240. List<KeyValuePair<string, string>> returnList = new List<KeyValuePair<string, string>>();
  241. WWWForm form = new WWWForm();
  242. form.AddField("f", "GetGameInfo");
  243. form.AddField("gameId", gameId);
  244. string response = CallOnlineDatabaseWithResponse("OnlineGameInfo.php", form);
  245. response = "{\"playerInfoList\" : " + response + " }";
  246. PlayerInfos pi = new PlayerInfos();
  247. JsonUtility.FromJsonOverwrite(response, pi);
  248. foreach (PlayerInfo p in pi.playerInfoList) {
  249. KeyValuePair<string, string> player = new KeyValuePair<string, string>(p.username, p.status);
  250. returnList.Add(player);
  251. }
  252. return returnList;
  253. }
  254. internal void SetQuestionsLost(int gameId, string playerName, int questionsLost) {
  255. WWWForm form = new WWWForm();
  256. form.AddField("f", "SetQuestionsLost");
  257. form.AddField("questionsLost", questionsLost);
  258. form.AddField("userName", playerName);
  259. form.AddField("gameId", gameId);
  260. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  261. if (!response.Equals("")) {
  262. Debug.Log(response);
  263. }
  264. }
  265. internal void RemoveGame(int gameId) {
  266. WWWForm form = new WWWForm();
  267. form.AddField("f", "DeleteGame");
  268. form.AddField("gameId", gameId);
  269. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  270. if (!response.Equals("")) {
  271. Debug.Log(response);
  272. }
  273. }
  274. public string GetCurrentPlayer(int gameId) {
  275. WWWForm form = new WWWForm();
  276. form.AddField("f", "CurrentPlayer");
  277. form.AddField("gameId", gameId);
  278. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  279. if (response.Equals("")) {
  280. Debug.Log("Something wrong with current player for game with id: " + gameId);
  281. }
  282. return response;
  283. }
  284. public void SetCurrentPlayer(int gameId, string currentPlayer) {
  285. WWWForm form = new WWWForm();
  286. form.AddField("f", "SetCurrentPlayer");
  287. form.AddField("gameId", gameId);
  288. form.AddField("userName", currentPlayer);
  289. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  290. if (!response.Equals("")) {
  291. Debug.Log(response);
  292. }
  293. }
  294. internal int GetPlayerPoints(int gameId, string playerName) {
  295. WWWForm form = new WWWForm();
  296. form.AddField("f", "GetPlayerPoints");
  297. form.AddField("gameId", gameId);
  298. form.AddField("userName", playerName);
  299. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  300. if (response.Equals("")) {
  301. Debug.Log("Something wrong with current player for game with id: " + gameId);
  302. }
  303. Int32.TryParse(response, out int playerPoints);
  304. return playerPoints;
  305. }
  306. internal void SetFinishedDate(int gameId, string finishedDate) {
  307. WWWForm form = new WWWForm();
  308. form.AddField("f", "SetFinishedDate");
  309. form.AddField("gameId", gameId);
  310. form.AddField("finishedDate", finishedDate);
  311. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  312. if (!response.Equals("")) {
  313. Debug.Log(response);
  314. }
  315. }
  316. internal void SetRoundValue(int gameId, int round) {
  317. WWWForm form = new WWWForm();
  318. form.AddField("f", "SetRound");
  319. form.AddField("gameId", gameId);
  320. form.AddField("round", round);
  321. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  322. if (!response.Equals("")) {
  323. Debug.Log(response);
  324. }
  325. }
  326. internal int GetRoundValue(int gameId) {
  327. WWWForm form = new WWWForm();
  328. form.AddField("f", "GetRound");
  329. form.AddField("gameId", gameId);
  330. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  331. if (response.Equals("")) {
  332. Debug.Log("Something wrong with getting round for game with id: " + gameId);
  333. }
  334. Int32.TryParse(response, out int round);
  335. return round;
  336. }
  337. internal List<KeyValuePair<string, int>> GetPlayersForGame(int gameId) {
  338. WWWForm form = new WWWForm();
  339. form.AddField("f", "GetPlayers");
  340. form.AddField("gameId", gameId);
  341. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  342. if (response.Equals("")) {
  343. Debug.Log("Something wrong with getting players from game with id: " + gameId);
  344. }
  345. response = response = "{\"gamePlayerInfoList\" : " + response + " }";
  346. GamePlayerInfos gpi = new GamePlayerInfos();
  347. JsonUtility.FromJsonOverwrite(response, gpi);
  348. List<KeyValuePair<string, int>> returnList = new List<KeyValuePair<string, int>>();
  349. foreach (GamePlayerInfo p in gpi.gamePlayerInfoList) {
  350. Int32.TryParse(p.userLockedQuestions, out int points);
  351. KeyValuePair<string, int> player = new KeyValuePair<string, int>(p.username, points);
  352. returnList.Add(player);
  353. }
  354. return returnList;
  355. }
  356. public string AnswerString { get => answerString; set => answerString = value; }
  357. public string IdString { get => idString; set => idString = value; }
  358. public string CategoryString { get => categoryString; set => categoryString = value; }
  359. internal int GetQuestionsLost(int gameId, string playerName) {
  360. WWWForm form = new WWWForm();
  361. form.AddField("f", "GetQuestionsLost");
  362. form.AddField("userName", playerName);
  363. form.AddField("gameId", gameId);
  364. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  365. if (response.Equals("")) {
  366. Debug.Log("Something wrong with getting questions lost from game with id: " + gameId + " and playername " + playerName);
  367. }
  368. Int32.TryParse(response, out int questionsLost);
  369. return questionsLost;
  370. }
  371. internal int GetWinCondition(int gameId) {
  372. if (winAmount == -1) {
  373. WWWForm form = new WWWForm();
  374. form.AddField("gameId", gameId);
  375. form.AddField("f", "GetWinCondition");
  376. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  377. Int32.TryParse(response, out this.winAmount);
  378. }
  379. return this.winAmount;
  380. }
  381. public NewQuestion GetNewQuestion(List<int> userAnsweredQuestions, string userName) {
  382. int gameId = GameObject.Find("GameManager").GetComponent<GameManagerScript>().GameId;
  383. Question q = GetQuestionData(false);
  384. NewQuestion nq = NewQuestion.Instance();
  385. nq.questionString = q.question;
  386. nq.answerString = q.answer;
  387. nq.categoryString = q.category;
  388. nq.idString = q.id;
  389. Color32 questionCategoryColor = new Color32((byte)q.r, (byte)q.g, (byte)q.b, (byte)q.a);
  390. nq.SetQuestionCategoryColor(questionCategoryColor);
  391. return nq;
  392. }
  393. public void SavePlayersQuestion(List<int> questionsToSave, string playerNameValue, int gameId) {
  394. WWWForm form = new WWWForm();
  395. form.AddField("f", "SavePlayerQuestions");
  396. form.AddField("gameId", gameId);
  397. form.AddField("questionsToSave", String.Join(",",questionsToSave));
  398. form.AddField("userName", playerNameValue);
  399. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  400. if (!response.Equals("")) {
  401. Debug.Log(response);
  402. }
  403. }
  404. public List<QuestionCard> GetPlayerQuestions(int gameId, string playerName) {
  405. List<QuestionCard> questions = new List<QuestionCard>();
  406. WWWForm form = new WWWForm();
  407. form.AddField("f", "PlayerQuestions");
  408. form.AddField("gameId", gameId);
  409. form.AddField("userName", playerName);
  410. string response = CallOnlineDatabaseWithResponse("OnlineGameInfo.php", form);
  411. response = "{\"questionsList\" : " + response + "}";
  412. Questions ql = new Questions();
  413. JsonUtility.FromJsonOverwrite(response, ql);
  414. foreach (Question q in ql.questionsList) {
  415. GameObject question = Instantiate(questionCardPrefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  416. QuestionCard qc = question.GetComponent<QuestionCard>();
  417. qc.SetAnswerText(q.answer);
  418. qc.SetQuestionText(q.question);
  419. qc.idString = q.id;
  420. Color32 questionCategoryColor = new Color32((byte)q.r, (byte)q.g, (byte)q.b, (byte)q.a);
  421. qc.SetQuestionCategoryColor(questionCategoryColor);
  422. questions.Add(qc);
  423. }
  424. return questions;
  425. }
  426. private Question GetQuestionData(bool showAnswer) {
  427. WWWForm form = new WWWForm();
  428. string response = CallOnlineDatabaseWithResponse("Question.php", form);
  429. // Show result
  430. response = "{\"questionsList\" : [ " + response + " ]}";
  431. Questions qe = new Questions();
  432. JsonUtility.FromJsonOverwrite(response, qe);
  433. return qe.questionsList[0];
  434. }
  435. public List<UserName> GetUsersToInvite(string searchString) {
  436. string postUrl = "nordh.xyz/narKampen/dbFiles/PlayerSearch.php?";
  437. postUrl += "search=" + UnityWebRequest.EscapeURL(searchString);
  438. UserNames uNames = new UserNames();
  439. UnityWebRequest www = UnityWebRequest.Get(postUrl);
  440. www.SendWebRequest();
  441. if (www.isNetworkError || www.isHttpError) {
  442. Debug.Log(www.error);
  443. } else {
  444. while (!www.isDone) {
  445. }
  446. // Show result
  447. string jsonData = www.downloadHandler.text;
  448. if (!jsonData.Equals("")) {
  449. jsonData = "{\"usernamesList\" : " + jsonData + " }";
  450. JsonUtility.FromJsonOverwrite(jsonData, uNames);
  451. }
  452. }
  453. // TODO handle empty
  454. return uNames.usernamesList;
  455. }
  456. }