OnlineDatabase.cs 22 KB

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