OnlineDatabase.cs 21 KB

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