OnlineDatabase.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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. ogs.LastPlayedDate = game.lastPlayedDate;
  243. games.Add(ogs);
  244. ogs.PlayerInfos = playerInfos;
  245. }
  246. return games;
  247. }
  248. internal List<KeyValuePair<string, string>> GetGameInfo(int gameId) {
  249. List<KeyValuePair<string, string>> returnList = new List<KeyValuePair<string, string>>();
  250. WWWForm form = new WWWForm();
  251. form.AddField("f", "GetGameInfo");
  252. form.AddField("gameId", gameId);
  253. string response = CallOnlineDatabaseWithResponse("OnlineGameInfo.php", form);
  254. response = "{\"playerInfoList\" : " + response + " }";
  255. PlayerInfos pi = new PlayerInfos();
  256. JsonUtility.FromJsonOverwrite(response, pi);
  257. foreach (PlayerInfo p in pi.playerInfoList) {
  258. KeyValuePair<string, string> player = new KeyValuePair<string, string>(p.username, p.status);
  259. returnList.Add(player);
  260. }
  261. return returnList;
  262. }
  263. internal void SetQuestionsLost(int gameId, string playerName, int questionsLost) {
  264. WWWForm form = new WWWForm();
  265. form.AddField("f", "SetQuestionsLost");
  266. form.AddField("questionsLost", questionsLost);
  267. form.AddField("userName", playerName);
  268. form.AddField("gameId", gameId);
  269. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  270. if (!response.Equals("")) {
  271. Debug.Log(response);
  272. }
  273. }
  274. internal void RemoveGame(int gameId) {
  275. WWWForm form = new WWWForm();
  276. form.AddField("f", "DeleteGame");
  277. form.AddField("gameId", gameId);
  278. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  279. if (!response.Equals("")) {
  280. Debug.Log(response);
  281. }
  282. }
  283. public string GetCurrentPlayer(int gameId) {
  284. WWWForm form = new WWWForm();
  285. form.AddField("f", "CurrentPlayer");
  286. form.AddField("gameId", gameId);
  287. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  288. if (response.Equals("")) {
  289. Debug.Log("Something wrong with current player for game with id: " + gameId);
  290. }
  291. return response;
  292. }
  293. public void SetCurrentPlayer(int gameId, string currentPlayer) {
  294. WWWForm form = new WWWForm();
  295. form.AddField("f", "SetCurrentPlayer");
  296. form.AddField("gameId", gameId);
  297. form.AddField("userName", currentPlayer);
  298. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  299. if (!response.Equals("")) {
  300. Debug.Log(response);
  301. }
  302. }
  303. internal int GetPlayerPoints(int gameId, string playerName) {
  304. WWWForm form = new WWWForm();
  305. form.AddField("f", "GetPlayerPoints");
  306. form.AddField("gameId", gameId);
  307. form.AddField("userName", playerName);
  308. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  309. if (response.Equals("")) {
  310. Debug.Log("Something wrong with current player for game with id: " + gameId);
  311. }
  312. Int32.TryParse(response, out int playerPoints);
  313. return playerPoints;
  314. }
  315. internal void SetFinishedDate(int gameId, string finishedDate) {
  316. WWWForm form = new WWWForm();
  317. form.AddField("f", "SetFinishedDate");
  318. form.AddField("gameId", gameId);
  319. form.AddField("finishedDate", finishedDate);
  320. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  321. if (!response.Equals("")) {
  322. Debug.Log(response);
  323. }
  324. }
  325. internal void SetRoundValue(int gameId, int round) {
  326. WWWForm form = new WWWForm();
  327. form.AddField("f", "SetRound");
  328. form.AddField("gameId", gameId);
  329. form.AddField("round", round);
  330. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  331. if (!response.Equals("")) {
  332. Debug.Log(response);
  333. }
  334. }
  335. internal int GetRoundValue(int gameId) {
  336. WWWForm form = new WWWForm();
  337. form.AddField("f", "GetRound");
  338. form.AddField("gameId", gameId);
  339. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  340. if (response.Equals("")) {
  341. Debug.Log("Something wrong with getting round for game with id: " + gameId);
  342. }
  343. Int32.TryParse(response, out int round);
  344. return round;
  345. }
  346. internal List<KeyValuePair<string, int>> GetPlayersForGame(int gameId) {
  347. WWWForm form = new WWWForm();
  348. form.AddField("f", "GetPlayers");
  349. form.AddField("gameId", gameId);
  350. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  351. if (response.Equals("")) {
  352. Debug.Log("Something wrong with getting players from game with id: " + gameId);
  353. }
  354. response = response = "{\"gamePlayerInfoList\" : " + response + " }";
  355. GamePlayerInfos gpi = new GamePlayerInfos();
  356. JsonUtility.FromJsonOverwrite(response, gpi);
  357. List<KeyValuePair<string, int>> returnList = new List<KeyValuePair<string, int>>();
  358. foreach (GamePlayerInfo p in gpi.gamePlayerInfoList) {
  359. Int32.TryParse(p.userLockedQuestions, out int points);
  360. KeyValuePair<string, int> player = new KeyValuePair<string, int>(p.username, points);
  361. returnList.Add(player);
  362. }
  363. return returnList;
  364. }
  365. public string AnswerString { get => answerString; set => answerString = value; }
  366. public string IdString { get => idString; set => idString = value; }
  367. public string CategoryString { get => categoryString; set => categoryString = value; }
  368. internal int GetQuestionsLost(int gameId, string playerName) {
  369. WWWForm form = new WWWForm();
  370. form.AddField("f", "GetQuestionsLost");
  371. form.AddField("userName", playerName);
  372. form.AddField("gameId", gameId);
  373. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  374. if (response.Equals("")) {
  375. Debug.Log("Something wrong with getting questions lost from game with id: " + gameId + " and playername " + playerName);
  376. }
  377. Int32.TryParse(response, out int questionsLost);
  378. return questionsLost;
  379. }
  380. internal int GetWinCondition(int gameId) {
  381. if (winAmount == -1) {
  382. WWWForm form = new WWWForm();
  383. form.AddField("gameId", gameId);
  384. form.AddField("f", "GetWinCondition");
  385. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  386. Int32.TryParse(response, out this.winAmount);
  387. }
  388. return this.winAmount;
  389. }
  390. public NewQuestionData newQuestionData;
  391. public NewQuestionData GetNewQuestion(List<int> userAnsweredQuestions, string userName) {
  392. int gameId = GameObject.Find("GameManager").GetComponent<GameManagerScript>().GameId;
  393. Question q = GetQuestionData(false);
  394. Color32 categoryColor = new Color32((byte)q.r, (byte)q.g, (byte)q.b, (byte)q.a);
  395. // Color32 questionCategoryColor = new Color32((byte)q.r, (byte)q.g, (byte)q.b, (byte)q.a);
  396. Int32.TryParse(q.category, out int categoryId);
  397. Int32.TryParse(q.id, out int questionId);
  398. NewQuestionData questionData = new NewQuestionData(q.answer, q.question, q.categoryName, categoryId, questionId, categoryColor);
  399. return questionData;
  400. }
  401. public void SavePlayersQuestion(List<int> questionsToSave, string playerNameValue, int gameId) {
  402. WWWForm form = new WWWForm();
  403. form.AddField("f", "SavePlayerQuestions");
  404. form.AddField("gameId", gameId);
  405. form.AddField("questionsToSave", String.Join(",",questionsToSave));
  406. form.AddField("userName", playerNameValue);
  407. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", form);
  408. if (!response.Equals("")) {
  409. Debug.Log(response);
  410. }
  411. }
  412. public List<NewQuestionData> GetPlayerQuestions(int gameId, string playerName) {
  413. List<NewQuestionData> questions = new List<NewQuestionData>();
  414. WWWForm form = new WWWForm();
  415. form.AddField("f", "PlayerQuestions");
  416. form.AddField("gameId", gameId);
  417. form.AddField("userName", playerName);
  418. string response = CallOnlineDatabaseWithResponse("OnlineGameInfo.php", form);
  419. response = "{\"questionsList\" : " + response + "}";
  420. Questions ql = new Questions();
  421. JsonUtility.FromJsonOverwrite(response, ql);
  422. foreach (Question q in ql.questionsList) {
  423. /*GameObject question = Instantiate(questionCardPrefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  424. NewQuestionData qc = question.GetComponent<NewQuestionData>();
  425. */
  426. Color categoryColor = new Color(q.r, q.g, q.b, q.a);
  427. // Color32 questionCategoryColor = new Color32((byte)q.r, (byte)q.g, (byte)q.b, (byte)q.a);
  428. Int32.TryParse(q.category, out int categoryId);
  429. Int32.TryParse(q.id, out int questionId);
  430. NewQuestionData questionData = new NewQuestionData(q.answer, q.question, q.categoryName, categoryId, questionId, categoryColor);
  431. questions.Add(questionData);
  432. }
  433. return questions;
  434. }
  435. private Question GetQuestionData(bool showAnswer) {
  436. WWWForm form = new WWWForm();
  437. string response = CallOnlineDatabaseWithResponse("Question.php", form);
  438. // Show result
  439. response = "{\"questionsList\" : [ " + response + " ]}";
  440. Questions qe = new Questions();
  441. JsonUtility.FromJsonOverwrite(response, qe);
  442. return qe.questionsList[0];
  443. }
  444. public List<UserName> GetUsersToInvite(string searchString) {
  445. string postUrl = "narkampen.nordh.xyz/narKampen/dbFiles/PlayerSearch.php?";
  446. postUrl += "search=" + UnityWebRequest.EscapeURL(searchString);
  447. UserNames uNames = new UserNames();
  448. UnityWebRequest www = UnityWebRequest.Get(postUrl);
  449. www.SendWebRequest();
  450. if (www.isNetworkError || www.isHttpError) {
  451. Debug.Log(www.error);
  452. } else {
  453. while (!www.isDone) {
  454. }
  455. // Show result
  456. string jsonData = www.downloadHandler.text;
  457. if (!jsonData.Equals("")) {
  458. jsonData = "{\"usernamesList\" : " + jsonData + " }";
  459. JsonUtility.FromJsonOverwrite(jsonData, uNames);
  460. }
  461. }
  462. // TODO handle empty
  463. return uNames.usernamesList;
  464. }
  465. internal void SendNextPlayerMessage(int gameId, String nextPlayer)
  466. {
  467. WWWForm form = new WWWForm();
  468. form.AddField("gameId", gameId);
  469. form.AddField("playerName", nextPlayer);
  470. form.AddField("title", LocalizationManager.Instance.GetText("FCM_NEXT_PLAYER_TITLE"));
  471. List<KeyValuePair<string, int>> players = OnlineDatabase.Instance.GetPlayersForGame(gameId);
  472. StringBuilder sb = new StringBuilder();
  473. foreach (KeyValuePair<String, int> player in players)
  474. {
  475. sb.AppendLine(player.Key + " (" + player.Value + ")");
  476. }
  477. String message = String.Format(LocalizationManager.Instance.GetText("FCM_NEXT_PLAYER_MESSAGE"),sb.ToString());
  478. form.AddField("message", message);
  479. form.AddField("type", "FCMNextPlayer");
  480. //string response = CallOnlineDatabaseWithResponse("FCMNextPlayer.php", form);
  481. CallDatabase("FCMMessageing.php", form);
  482. }
  483. internal void SendInviteForNewGame(int gameId, List<String> Players, String inviter) {
  484. WWWForm form = new WWWForm();
  485. form.AddField("gameId", gameId);
  486. int index = 0;
  487. foreach(String player in Players) {
  488. form.AddField("player" + index++, player);
  489. }
  490. form.AddField("title", LocalizationManager.Instance.GetText("FCM_NEW_GAME_TITLE"));
  491. form.AddField("message", String.Format(LocalizationManager.Instance.GetText("FCM_NEW_GAME_MESSAGE"), inviter));
  492. form.AddField("type", "InviteMessage");
  493. CallDatabase("FCMMessageing.php", form);
  494. }
  495. internal void UpdatePlayerToken(int userId, string myToken)
  496. {
  497. WWWForm form = new WWWForm();
  498. form.AddField("userId", userId);
  499. form.AddField("token", myToken);
  500. form.AddField("f", "UpdatePlayerToken");
  501. CallDatabase("OnlineGames.php", form);
  502. }
  503. }