Database.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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. public class Database : MonoBehaviour {
  10. private const string onlineQuestionsUrl = "nordh.xyz/narKampen/dbFiles/Question.php";
  11. private const string serverUrl = "nordh.xyz/narKampen/dbFiles/";
  12. string connectionType;
  13. string databaseUrl;
  14. string gameMode;
  15. int winAmount = -1;
  16. int questionTimer = -1;
  17. public GameObject questionCardPrefab;
  18. private static Database instance;
  19. public static Database Instance { get { return instance; } }
  20. IDbConnection conn;
  21. private void Awake() {
  22. if (instance == null) {
  23. instance = this;
  24. }
  25. }
  26. internal List<CategoryPanel.Category> GetCategories() {
  27. List<CategoryPanel.Category> list = new List<CategoryPanel.Category>();
  28. string sql = "SELECT name, r, g, b, a, id FROM category";
  29. IDbCommand cmd = GetConnection();
  30. cmd.CommandText = sql;
  31. IDataReader reader = cmd.ExecuteReader();
  32. while (reader.Read()) {
  33. CategoryPanel.Category cat = new CategoryPanel.Category();
  34. byte r = (byte)reader.GetInt32(1);
  35. byte g = (byte)reader.GetInt32(2);
  36. byte b = (byte)reader.GetInt32(3);
  37. byte a = (byte)reader.GetInt32(4);
  38. cat.color = new Color32(r, g, b, a);
  39. cat.name = reader.GetString(0);
  40. cat.id = reader.GetInt32(5);
  41. list.Add(cat);
  42. }
  43. CloseConnection();
  44. return list;
  45. }
  46. internal void SetupNewOnlineGame(int limitPerQuestion, int limitPerPlayer, int toWin, List<InviteSearchResult> inviteUsers) {
  47. List<int> playerIds = new List<int>();
  48. inviteUsers.ForEach(i => playerIds.Add(i.GetId()));
  49. int currentUser = Database.Instance.GetSignedInUser().Key;
  50. playerIds.Add(currentUser);
  51. var form = new WWWForm();
  52. form.AddField("currentUser", currentUser);
  53. form.AddField("winNumber", toWin);
  54. form.AddField("limitPerQuestion", limitPerQuestion);
  55. form.AddField("limitPerPlayer", limitPerPlayer);
  56. form.AddField("playerIds", String.Join(",", playerIds));
  57. Debug.Log(CallOnlineDatabaseWithResponse("NewOnlineGame.php", form));
  58. }
  59. [Serializable]
  60. public class Question {
  61. public string question;
  62. public string answer;
  63. public string id;
  64. public string category;
  65. }
  66. [Serializable]
  67. public class Questions {
  68. public List<Question> questionsList = new List<Question>();
  69. }
  70. [Serializable]
  71. public class PlayerInfo {
  72. public string username;
  73. public string status;
  74. }
  75. [Serializable]
  76. public class PlayerInfos {
  77. public List<PlayerInfo> playerInfoList = new List<PlayerInfo>();
  78. }
  79. [Serializable]
  80. public class OnlineGame {
  81. public string id;
  82. public string winNumber;
  83. public string answerTimer;
  84. public string roundTimeLimit;
  85. public string currentPlayer;
  86. public string round;
  87. public string startDate;
  88. public string LastPlayedDate;
  89. public string finishedDate;
  90. public string status;
  91. }
  92. [Serializable]
  93. public class OnlineGames {
  94. public List<OnlineGame> onlineGamesList = new List<OnlineGame>();
  95. }
  96. [Serializable]
  97. public class UserName {
  98. public string id;
  99. public string username;
  100. }
  101. [Serializable]
  102. public class UserNames {
  103. public List<UserName> usernamesList = new List<UserName>();
  104. }
  105. private void CallDatabase(string filename, WWWForm formData) {
  106. string postUrl = serverUrl + filename;
  107. UnityWebRequest www = UnityWebRequest.Post(postUrl, formData);
  108. www.SendWebRequest();
  109. if (www.isNetworkError || www.isHttpError) {
  110. Debug.Log(www.error);
  111. } else {
  112. while (!www.isDone) {
  113. }
  114. }
  115. }
  116. private string CallOnlineDatabaseWithResponse(string filename, WWWForm formData) {
  117. string postUrl = serverUrl + filename;
  118. UnityWebRequest www = UnityWebRequest.Post(postUrl, formData);
  119. www.SendWebRequest();
  120. if (www.isNetworkError || www.isHttpError) {
  121. Debug.Log(www.error);
  122. } else {
  123. while (!www.isDone) {
  124. }
  125. }
  126. return www.downloadHandler.text;
  127. }
  128. internal void SetLastPlayedDate(int gameId) {
  129. string sql = "UPDATE game SET lastPlayedDate = DATE() WHERE id = " + gameId;
  130. IDbCommand cmd = GetConnection();
  131. cmd.CommandText = sql;
  132. cmd.ExecuteNonQuery();
  133. cmd.Dispose();
  134. CloseConnection();
  135. }
  136. private IDbCommand GetConnection() {
  137. if (databaseUrl == null) { // ej bra lösning för online
  138. SetLocalOrOnline("Local");
  139. }
  140. conn = new SqliteConnection(databaseUrl);
  141. conn.Open();
  142. IDbCommand cmd = conn.CreateCommand();
  143. return cmd;
  144. }
  145. private void CloseConnection() {
  146. conn.Close();
  147. }
  148. string questionString = "";
  149. string answerString = "";
  150. string idString = "";
  151. string categoryString = "";
  152. private int round = -1;
  153. private string SearchString;
  154. public string QuestionString { get => questionString; set => questionString = value; }
  155. private void Start() {
  156. if (instance == null) {
  157. instance = this;
  158. }
  159. if (databaseUrl == null || databaseUrl.Equals("")) {
  160. SetLocalOrOnline("Local"); // Temporary, should not be needed after local testing
  161. }
  162. }
  163. internal void KeepSignedIn(string username, int userId, bool keepSigendIn) {
  164. int ksi = 0;
  165. if (keepSigendIn) {
  166. ksi = 1;
  167. }
  168. string sql = "INSERT OR REPLACE INTO userSettings (username, userId, keepSignedIn) VALUES ('" + username + "', " + userId + "," + ksi + ")";
  169. IDbCommand cmd = GetConnection();
  170. cmd.CommandText = sql;
  171. cmd.ExecuteNonQuery();
  172. CloseConnection();
  173. }
  174. internal bool IsKeepSignedIn() {
  175. string sql = "SELECT keepSignedIn FROM userSettings";
  176. IDbCommand cmd = GetConnection();
  177. cmd.CommandText = sql;
  178. IDataReader reader = cmd.ExecuteReader();
  179. int res = 0;
  180. while (reader.Read()) {
  181. res = reader.GetInt32(0);
  182. }
  183. return res == 1;
  184. }
  185. internal KeyValuePair<int, string> GetSignedInUser() {
  186. string sql = "SELECT userId, username FROM userSettings";
  187. IDbCommand cmd = GetConnection();
  188. cmd.CommandText = sql;
  189. int userId = -1;
  190. string username = "";
  191. IDataReader reader = cmd.ExecuteReader();
  192. while (reader.Read()) {
  193. userId = reader.GetInt32(0);
  194. username = reader.GetString(1);
  195. }
  196. CloseConnection();
  197. return new KeyValuePair<int, string>(userId, username);
  198. }
  199. internal void LogoutUser() {
  200. // string sql = "UPDATE userSettings SET keepSignedIn = 0";
  201. string sql = "DELETE FROM userSettings";
  202. IDbCommand cmd = GetConnection();
  203. cmd.CommandText = sql;
  204. cmd.ExecuteNonQuery();
  205. CloseConnection();
  206. }
  207. internal int GetQuestionTimer(int gameId) {
  208. if (questionTimer == -1) {
  209. string sql = "SELECT answerTimer FROM game WHERE id = " + gameId;
  210. if (databaseUrl == null) {
  211. SetLocalOrOnline("Local");
  212. }
  213. IDbCommand cmd = GetConnection();
  214. cmd.CommandText = sql;
  215. IDataReader reader = cmd.ExecuteReader();
  216. while (reader.Read()) {
  217. questionTimer = reader.GetInt32(0);
  218. }
  219. reader.Close();
  220. cmd.Dispose();
  221. }
  222. CloseConnection();
  223. return this.questionTimer;
  224. }
  225. internal void DeclineOnlineGame(string userName, int gameId) {
  226. WWWForm formData = new WWWForm();
  227. formData.AddField("userId", -1);
  228. formData.AddField("f", "decline");
  229. formData.AddField("gameId", gameId);
  230. formData.AddField("userName", userName);
  231. CallDatabase("OnlineGames.php", formData);
  232. }
  233. internal void AcceptOnlineGame(string userName, int gameId) {
  234. WWWForm formData = new WWWForm();
  235. formData.AddField("userId", -1);
  236. formData.AddField("f", "accept");
  237. formData.AddField("gameId", gameId);
  238. formData.AddField("userName", userName);
  239. CallDatabase("OnlineGames.php", formData);
  240. }
  241. internal List<OnlineGameScript> GetOnlineGames(int userId, string userName, GameObject prefab) {
  242. WWWForm formData = new WWWForm();
  243. formData.AddField("userId", userId);
  244. formData.AddField("f", "list");
  245. formData.AddField("gameId", -1);
  246. formData.AddField("userName", userName);
  247. string response = CallOnlineDatabaseWithResponse("OnlineGames.php", formData);
  248. if (response.Equals("No games found for user")) {
  249. return null;
  250. }
  251. response = "{\"onlineGamesList\" : " + response + " }";
  252. OnlineGames og = new OnlineGames();
  253. JsonUtility.FromJsonOverwrite(response, og);
  254. GameObject onlineGameObject;
  255. OnlineGameScript ogs = null;
  256. List<OnlineGameScript> games = new List<OnlineGameScript>();
  257. foreach (OnlineGame game in og.onlineGamesList) {
  258. onlineGameObject = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  259. ogs = onlineGameObject.GetComponent<OnlineGameScript>();
  260. ogs.SetGameStatus(game.status);
  261. Int32.TryParse(game.id, out int gameId);
  262. List<KeyValuePair<string, string>> playerInfos = GetGameInfo(gameId);
  263. if (game.status.Equals("PENDING")) {
  264. string extraInfo = "";
  265. foreach (KeyValuePair<string, string> s in playerInfos) {
  266. if (s.Value.Equals("WAITING") && s.Key.Equals(userName)) {
  267. ogs.SetGameStatus("INVITED");
  268. extraInfo += s.Key + ",";
  269. } else if (s.Value.EndsWith("WAITING")) {
  270. extraInfo += s.Key + ",";
  271. }
  272. }
  273. extraInfo = extraInfo.TrimEnd(',');
  274. ogs.SetGameStatusText(extraInfo);
  275. } else if (game.status.Equals("OTHERS_TURN")) { // Wont work
  276. ogs.SetGameStatusText(game.currentPlayer);
  277. } else {
  278. ogs.SetGameStatusText();
  279. }
  280. ogs.SetId(game.id);
  281. ogs.SetWinNumber(game.winNumber);
  282. ogs.SetAnswerTimer(game.answerTimer);
  283. ogs.SetRoundTimeLimit(game.roundTimeLimit);
  284. ogs.CurrentPlayer = game.currentPlayer;
  285. ogs.SetRound(game.round);
  286. ogs.StartDate = game.startDate;
  287. games.Add(ogs);
  288. ogs.PlayerInfos = playerInfos;
  289. }
  290. return games;
  291. }
  292. internal List<KeyValuePair<string, string>> GetGameInfo(int gameId) {
  293. List<KeyValuePair<string, string>> returnList = new List<KeyValuePair<string, string>>();
  294. WWWForm form = new WWWForm();
  295. form.AddField("gameId", gameId);
  296. string response = CallOnlineDatabaseWithResponse("OnlineGameInfo.php", form);
  297. response = "{\"playerInfoList\" : " + response + " }";
  298. PlayerInfos pi = new PlayerInfos();
  299. JsonUtility.FromJsonOverwrite(response, pi);
  300. foreach (PlayerInfo p in pi.playerInfoList) {
  301. KeyValuePair<string, string> player = new KeyValuePair<string, string>(p.username, p.status);
  302. returnList.Add(player);
  303. }
  304. return returnList;
  305. }
  306. internal List<LocalGameScript> GetLocalGames(GameObject prefab) {
  307. List<LocalGameScript> games = new List<LocalGameScript>();
  308. string sql = "SELECT game.*, name, localUsers.id as userId FROM game INNER JOIN localGamePlayers on game.id = localGamePlayers.gameId INNER JOIN localUsers on playerId = localUsers.id order by game.id ASC, userId ASC";
  309. IDbConnection conn = new SqliteConnection(databaseUrl);
  310. conn.Open();
  311. IDbCommand cmd = conn.CreateCommand();
  312. cmd.CommandText = sql;
  313. IDataReader reader = cmd.ExecuteReader();
  314. int currentGame = -1;
  315. GameObject localGame;
  316. LocalGameScript lgs = null;
  317. string currentPlayerName = "";
  318. int currentPoints = 0;
  319. while (reader.Read()) {
  320. if (currentGame != reader.GetInt32(0)) {
  321. localGame = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  322. lgs = localGame.GetComponent<LocalGameScript>();
  323. lgs.GameId = reader.GetInt32(0);
  324. lgs.GameMode = reader.GetString(1);
  325. lgs.QuestionsNeededToWin = reader.GetInt32(2).ToString();
  326. lgs.AnswerTimer = reader.GetInt32(3);
  327. lgs.NumberOfPlayers = reader.GetInt32(4).ToString();
  328. lgs.CurrentPlayer = reader.GetString(5);
  329. lgs.Round = reader.GetInt32(6).ToString();
  330. lgs.StartDate = reader.GetString(7);
  331. lgs.LastPlayedDate = reader.GetString(8);
  332. lgs.FinishedDate = reader.IsDBNull(9) ? "" : reader.GetString(9);
  333. currentPlayerName = reader.GetString(10);
  334. currentPoints = GetPlayerPoints(reader.GetInt32(0), currentPlayerName);
  335. lgs.AddPlayer(currentPlayerName, currentPoints);
  336. games.Add(lgs);
  337. } else if (currentGame == reader.GetInt32(0)) {
  338. currentPlayerName = reader.GetString(10);
  339. currentPoints = GetPlayerPoints(currentGame, currentPlayerName);
  340. lgs.AddPlayer(currentPlayerName, currentPoints);
  341. }
  342. currentGame = reader.GetInt32(0);
  343. }
  344. reader.Close();
  345. cmd.Dispose();
  346. conn.Close();
  347. return games;
  348. }
  349. internal void SetQuestionsLost(int gameId, string playerName, int questionsLost) {
  350. string sql = "UPDATE localGamePlayers SET questionsLost = questionsLost + " + questionsLost + " WHERE gameId = " + gameId + " AND playerId = (SELECT id FROM localUsers WHERE name = '" + playerName + "')";
  351. IDbConnection conn = new SqliteConnection(databaseUrl);
  352. conn.Open();
  353. IDbCommand cmd = conn.CreateCommand();
  354. cmd.CommandText = sql;
  355. cmd.ExecuteNonQuery();
  356. cmd.Dispose();
  357. conn.Close();
  358. }
  359. internal void RemoveGame(int gameId) {
  360. string sql = "DELETE FROM game WHERE id = " + gameId;
  361. List<LocalGameScript> games = new List<LocalGameScript>();
  362. IDbConnection conn = new SqliteConnection(databaseUrl);
  363. conn.Open();
  364. IDbCommand cmd = conn.CreateCommand();
  365. cmd.CommandText = sql;
  366. cmd.ExecuteNonQuery();
  367. string deleteLockedQuestionsSql = "DELETE FROM usersLockedQuestions WHERE gameId = " + gameId;
  368. cmd.CommandText = deleteLockedQuestionsSql;
  369. cmd.ExecuteNonQuery();
  370. cmd.Dispose();
  371. conn.Close();
  372. }
  373. public string GetCurrentPlayer(int gameId) {
  374. string sql = "SELECT currentPlayer FROM game WHERE id = " + gameId;
  375. IDbConnection conn = new SqliteConnection(databaseUrl);
  376. conn.Open();
  377. IDbCommand cmd = conn.CreateCommand();
  378. cmd.CommandText = sql;
  379. IDataReader reader = cmd.ExecuteReader();
  380. string currentPlayer = "";
  381. while (reader.Read()) {
  382. currentPlayer = reader.GetString(0);
  383. }
  384. reader.Close();
  385. cmd.Dispose();
  386. conn.Close();
  387. return currentPlayer;
  388. }
  389. public void SetCurrentPlayer(int gameId, string currentPlayer) {
  390. string sql = "UPDATE game SET currentPlayer = '" + currentPlayer + "' WHERE id = " + gameId;
  391. IDbConnection conn = new SqliteConnection(databaseUrl);
  392. conn.Open();
  393. IDbCommand cmd = conn.CreateCommand();
  394. cmd.CommandText = sql;
  395. cmd.ExecuteNonQuery();
  396. cmd.Dispose();
  397. conn.Close();
  398. }
  399. internal int GetPlayerPoints(int gameId, string playerName) {
  400. string sql = "SELECT count(*) FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" + playerName + "'";
  401. IDbConnection conn = new SqliteConnection(databaseUrl);
  402. conn.Open();
  403. IDbCommand cmd = conn.CreateCommand();
  404. cmd.CommandText = sql;
  405. IDataReader reader = cmd.ExecuteReader();
  406. int points = 0;
  407. while (reader.Read()) {
  408. points = reader.GetInt32(0);
  409. }
  410. reader.Close();
  411. cmd.Dispose();
  412. conn.Close();
  413. return points;
  414. }
  415. internal void SetFinishedDate(int gameId, string finishedDate) {
  416. string sql = "UPDATE game SET finishedDate = '" + finishedDate + "' WHERE id = " + gameId;
  417. IDbConnection conn = new SqliteConnection(databaseUrl);
  418. conn.Open();
  419. IDbCommand cmd = conn.CreateCommand();
  420. cmd.CommandText = sql;
  421. cmd.ExecuteNonQuery();
  422. cmd.Dispose();
  423. conn.Close();
  424. }
  425. internal void SetRoundValue(int gameId, int round) {
  426. string sql = "UPDATE game SET round = " + round + " WHERE id = " + gameId;
  427. IDbConnection conn = new SqliteConnection(databaseUrl);
  428. conn.Open();
  429. IDbCommand cmd = conn.CreateCommand();
  430. cmd.CommandText = sql;
  431. cmd.ExecuteNonQuery();
  432. cmd.Dispose();
  433. conn.Close();
  434. }
  435. internal int GetRoundValue(int gameId) {
  436. if (this.round == -1) {
  437. string sql = "SELECT round FROM game WHERE id = " + gameId;
  438. IDbConnection conn = new SqliteConnection(databaseUrl);
  439. conn.Open();
  440. IDbCommand cmd = conn.CreateCommand();
  441. cmd.CommandText = sql;
  442. IDataReader reader = cmd.ExecuteReader();
  443. while (reader.Read()) {
  444. this.round = reader.GetInt32(0);
  445. }
  446. reader.Close();
  447. cmd.Dispose();
  448. conn.Close();
  449. }
  450. return this.round;
  451. }
  452. internal List<KeyValuePair<string, int>> GetPlayersForGame(int gameId) {
  453. string sql = "SELECT name, (SELECT count(*) FROM usersLockedQuestions WHERE playerName = localUsers.name AND gameId = " + gameId + ") as numAnswers FROM localGamePlayers " +
  454. "LEFT JOIN localUsers ON localGamePlayers.playerId = localUsers.id " +
  455. "WHERE gameId = " + gameId;
  456. IDbConnection conn = new SqliteConnection(databaseUrl);
  457. conn.Open();
  458. IDbCommand cmd = conn.CreateCommand();
  459. cmd.CommandText = sql;
  460. IDataReader reader = cmd.ExecuteReader();
  461. List<KeyValuePair<string, int>> returnList = new List<KeyValuePair<string, int>>();
  462. while (reader.Read()) {
  463. KeyValuePair<string, int> player = new KeyValuePair<string, int>(reader.GetString(0), reader.GetInt32(1));
  464. returnList.Add(player);
  465. }
  466. return returnList;
  467. }
  468. public string AnswerString { get => answerString; set => answerString = value; }
  469. public string IdString { get => idString; set => idString = value; }
  470. public string CategoryString { get => categoryString; set => categoryString = value; }
  471. public void SetLocalOrOnline(string type) {
  472. gameMode = type;
  473. if (type.Equals("Local")) {
  474. string databaseName = "narKampenLocal.db";
  475. if (Application.platform == RuntimePlatform.Android) {
  476. databaseUrl = Application.persistentDataPath + "/" + databaseName;
  477. if (!File.Exists(databaseUrl)) {
  478. UnityWebRequest load = UnityWebRequest.Get("jar:file://" + Application.dataPath + "!/assets/" + databaseName);
  479. load.SendWebRequest();
  480. while (!load.isDone) { }
  481. File.WriteAllBytes(databaseUrl, load.downloadHandler.data);
  482. }
  483. databaseUrl = "URI=file:" + databaseUrl;
  484. } else {
  485. databaseUrl = "URI=file:" + Application.dataPath + "/narKampenLocal.db";
  486. }
  487. } else {
  488. databaseUrl = onlineQuestionsUrl;
  489. }
  490. connectionType = type;
  491. }
  492. internal int GetQuestionsLost(int gameId, string playerName) {
  493. string sql = "SELECT questionsLost FROM localGamePlayers WHERE gameId = " + gameId + " AND playerId = (SELECT id from localUsers WHERE name = '" + playerName + "')";
  494. IDbConnection conn = new SqliteConnection(databaseUrl);
  495. conn.Open();
  496. IDbCommand cmd = conn.CreateCommand();
  497. cmd.CommandText = sql;
  498. IDataReader reader = cmd.ExecuteReader();
  499. int returnValue = 0;
  500. while (reader.Read()) {
  501. returnValue = reader.GetInt32(0);
  502. }
  503. reader.Close();
  504. cmd.Dispose();
  505. conn.Close();
  506. return returnValue;
  507. }
  508. public string GetGameMode(int gameId) {
  509. if (this.gameMode == null) {
  510. string sql = "SELECT gameMode FROM game WHERE id = " + gameId;
  511. IDbConnection conn = new SqliteConnection(databaseUrl);
  512. conn.Open();
  513. IDbCommand cmd = conn.CreateCommand();
  514. cmd.CommandText = sql;
  515. IDataReader reader = cmd.ExecuteReader();
  516. while (reader.Read()) {
  517. this.gameMode = reader.GetString(0);
  518. }
  519. reader.Close();
  520. cmd.Dispose();
  521. conn.Close();
  522. }
  523. return this.gameMode;
  524. }
  525. public void LinkPlayersToLocalGame(List<string> playerNames, int gameId) {
  526. IDbConnection conn = new SqliteConnection(databaseUrl);
  527. conn.Open();
  528. string questionSql = "SELECT id FROM questions order by random() limit 1";
  529. IDbCommand cmd = conn.CreateCommand();
  530. cmd.CommandText = questionSql;
  531. IDataReader reader = cmd.ExecuteReader();
  532. int questionId = -1;
  533. while (reader.Read()) {
  534. questionId = reader.GetInt32(0);
  535. }
  536. foreach (string player in playerNames) {
  537. string sql = "SELECT id FROM localUsers WHERE name = '" + player + "'";
  538. int playerId;
  539. cmd = conn.CreateCommand();
  540. cmd.CommandText = sql;
  541. reader = cmd.ExecuteReader();
  542. if (reader.Read()) {
  543. playerId = reader.GetInt32(0);
  544. } else {
  545. reader.Close();
  546. sql = "INSERT INTO localUsers (name) VALUES ('" + player + "')";
  547. cmd.CommandText = sql;
  548. cmd.ExecuteNonQuery();
  549. cmd.CommandText = "SELECT last_insert_rowid()";
  550. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  551. playerId = (int)lastInsert64;
  552. }
  553. cmd.Dispose();
  554. reader.Close();
  555. LinkPlayerToGame(playerId, gameId);
  556. SavePlayersQuestion(questionId.ToString(), player, gameId);
  557. }
  558. IDbCommand cmd2 = conn.CreateCommand();
  559. cmd2.CommandText = "UPDATE game SET currentPlayer = '" + playerNames[0] + "' WHERE id = " + gameId;
  560. cmd2.ExecuteNonQuery();
  561. cmd2.Dispose();
  562. conn.Close();
  563. }
  564. private void LinkPlayerToGame(int playerId, int gameId) {
  565. string sql = "INSERT INTO localGamePlayers (gameId, playerId) VALUES (" + gameId + ", " + playerId + ")";
  566. SqliteConnection conn2 = new SqliteConnection(databaseUrl);
  567. conn2.Open();
  568. IDbCommand cmd = conn2.CreateCommand();
  569. cmd.CommandText = sql;
  570. cmd.ExecuteNonQuery();
  571. cmd.Dispose();
  572. conn2.Close();
  573. }
  574. internal int GetWinCondition(int gameId) {
  575. if (winAmount == -1) {
  576. string sql = "SELECT winNumber FROM game WHERE id = " + gameId;
  577. IDbConnection conn = new SqliteConnection(databaseUrl);
  578. conn.Open();
  579. IDbCommand cmd = conn.CreateCommand();
  580. cmd.CommandText = sql;
  581. IDataReader reader = cmd.ExecuteReader();
  582. while (reader.Read()) {
  583. this.winAmount = reader.GetInt32(0);
  584. }
  585. reader.Close();
  586. cmd.Dispose();
  587. conn.Close();
  588. }
  589. return this.winAmount;
  590. }
  591. public int SetupNewLocalGame(int winNumber, int numberOfPlayers, int questionTimer) {
  592. string sql = "INSERT INTO game (winNumber, numberOfPlayers, answerTimer, gameMode, startedDate) VALUES (" + winNumber + "," + numberOfPlayers + "," + questionTimer + ", 'Local', DATE())";
  593. IDbConnection conn = new SqliteConnection(databaseUrl);
  594. conn.Open();
  595. IDbCommand cmd = conn.CreateCommand();
  596. cmd.CommandText = sql;
  597. int status = cmd.ExecuteNonQuery();
  598. cmd.CommandText = "SELECT last_insert_rowid()";
  599. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  600. return (int)lastInsert64;
  601. }
  602. public NewQuestion GetNewQuestion(List<int> userAnsweredQuestions, string userName) {
  603. int gameId = GameObject.Find("GameManager").GetComponent<GameManagerScript>().GameId;
  604. Color32 questionCategoryColor = new Color32(0, 0, 20, 20);
  605. if (connectionType == null) {
  606. SetLocalOrOnline(GetGameMode(gameId));
  607. }
  608. if (connectionType == "Local") {
  609. IDbConnection conn = new SqliteConnection(databaseUrl);
  610. conn.Open();
  611. IDbCommand cmd = conn.CreateCommand();
  612. string answeredIds = String.Join(",", userAnsweredQuestions);
  613. string sql = "SELECT questions.id, question, answer, categoryId as category, name, category.R, category.G, category.B, category.A FROM questions INNER JOIN questionToCategory ON questions.id = questionToCategory.questionId INNER JOIN category on category.id = questionToCategory.categoryId WHERE questions.id NOT IN (" + answeredIds + ") AND questions.id NOT IN (SELECT questionId FROM questionsInGame WHERE gameId = " + gameId + " AND userId = (SELECT id from localUsers WHERE name = '" + userName + "')) ORDER BY RANDOM() limit 1";
  614. cmd.CommandText = sql;
  615. IDataReader reader = cmd.ExecuteReader();
  616. int id = -1;
  617. while (reader.Read()) {
  618. id = reader.GetInt32(0);
  619. string question = reader.GetString(1);
  620. int answer = reader.GetInt32(2);
  621. int catergoryId = reader.GetInt32(3);
  622. string categoryName = reader.GetString(4);
  623. idString = id.ToString();
  624. questionString = question;
  625. categoryString = catergoryId.ToString();
  626. answerString = answer.ToString();
  627. byte r = (byte)reader.GetInt32(5);
  628. byte g = (byte)reader.GetInt32(6);
  629. byte b = (byte)reader.GetInt32(7);
  630. byte a = (byte)reader.GetInt32(8);
  631. questionCategoryColor = new Color32(r, g, b, a);
  632. }
  633. reader.Close();
  634. string saveSentQuestionSql = "INSERT INTO questionsInGame (gameId, questionId, userId) VALUES (" + gameId + ", " + id + ", (SELECT id FROM localUsers WHERE name = '" + userName + "'))";
  635. cmd.CommandText = saveSentQuestionSql;
  636. cmd.ExecuteNonQuery();
  637. cmd.Dispose();
  638. conn.Close();
  639. } else { // Connect Through db
  640. Debug.Log("Online Call");
  641. StartCoroutine(GetQuestionData(false));
  642. }
  643. NewQuestion q = NewQuestion.Instance();
  644. q.questionString = questionString;
  645. q.answerString = answerString;
  646. q.categoryString = categoryString;
  647. q.idString = idString;
  648. q.SetQuestionCategoryColor(questionCategoryColor);
  649. return q;
  650. }
  651. public void SavePlayersQuestion(string questionId, string playerNameValue, int gameId) {
  652. if (databaseUrl == null) {
  653. SetLocalOrOnline(GetGameMode(gameId));
  654. }
  655. Int32.TryParse(questionId, out int qId);
  656. string sql = "INSERT OR IGNORE INTO usersLockedQuestions (playerName, questionId, gameId) VALUES ('" + playerNameValue + "'," + qId + "," + gameId + ")";
  657. IDbConnection conn = new SqliteConnection(databaseUrl);
  658. conn.Open();
  659. IDbCommand cmd = conn.CreateCommand();
  660. cmd.CommandText = sql;
  661. cmd.ExecuteReader();
  662. cmd.Dispose();
  663. conn.Close();
  664. }
  665. public List<QuestionCard> GetPlayerQuestions(int gameId, string playerNameValue) {
  666. if (databaseUrl == null) {
  667. SetLocalOrOnline(GetGameMode(gameId));
  668. }
  669. List<QuestionCard> questions = new List<QuestionCard>();
  670. if (connectionType.Equals("Local")) {
  671. string sql = "SELECT * FROM questions inner join questionToCategory on questions.id = questionToCategory.questionId INNER JOIN category ON category.id = questionToCategory.categoryId WHERE questions.id IN ( SELECT questionId FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" + playerNameValue + "') ORDER BY answer ASC";
  672. IDbConnection conn = new SqliteConnection(databaseUrl);
  673. conn.Open();
  674. IDbCommand cmd = conn.CreateCommand();
  675. cmd.CommandText = sql;
  676. IDataReader reader = cmd.ExecuteReader();
  677. while (reader.Read()) {
  678. GameObject question = Instantiate(questionCardPrefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  679. QuestionCard q = question.GetComponent<QuestionCard>();
  680. q.SetAnswerText(reader.GetInt32(2).ToString());
  681. q.SetQuestionText(reader.GetString(1));
  682. q.idString = reader.GetInt32(0).ToString();
  683. Color32 questionCategoryColor = new Color32((byte)reader.GetInt32(7), (byte)reader.GetInt32(8), (byte)reader.GetInt32(9), (byte)reader.GetInt32(10));
  684. q.SetQuestionCategoryColor(questionCategoryColor);
  685. questions.Add(q);
  686. }
  687. cmd.Dispose();
  688. conn.Close();
  689. }
  690. return questions;
  691. }
  692. private IEnumerator GetQuestionData(bool showAnswer) {
  693. UnityWebRequest www = UnityWebRequest.Get("nordh.xyz/narKampen/dbFiles/Question.php");
  694. yield return www.SendWebRequest();
  695. if (www.isNetworkError || www.isHttpError) {
  696. Debug.Log(www.error);
  697. } else {
  698. while (!www.isDone) {
  699. yield return null;
  700. }
  701. // Show result
  702. string jsonData = www.downloadHandler.text;
  703. jsonData = "{\"questionsList\" : [ " + jsonData + " ]}";
  704. Questions qe = new Questions();
  705. JsonUtility.FromJsonOverwrite(jsonData, qe);
  706. questionString = qe.questionsList[0].question;
  707. answerString = qe.questionsList[0].answer;
  708. idString = qe.questionsList[0].id;
  709. categoryString = qe.questionsList[0].category;
  710. }
  711. }
  712. public List<UserName> GetUsersToInvite(string searchString) {
  713. string postUrl = "nordh.xyz/narKampen/dbFiles/PlayerSearch.php?";
  714. postUrl += "search=" + UnityWebRequest.EscapeURL(searchString);
  715. UserNames uNames = new UserNames();
  716. UnityWebRequest www = UnityWebRequest.Get(postUrl);
  717. www.SendWebRequest();
  718. if (www.isNetworkError || www.isHttpError) {
  719. Debug.Log(www.error);
  720. } else {
  721. while (!www.isDone) {
  722. }
  723. // Show result
  724. string jsonData = www.downloadHandler.text;
  725. jsonData = "{\"usernamesList\" : " + jsonData + " }";
  726. JsonUtility.FromJsonOverwrite(jsonData, uNames);
  727. }
  728. // TODO handle empty
  729. return uNames.usernamesList;
  730. }
  731. }