Database.cs 26 KB

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