OnlineDatabase.cs 21 KB

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