Database.cs 27 KB

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