Database.cs 28 KB

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