OnlineDatabase.cs 23 KB

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