Database.cs 25 KB

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