Database.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. string connectionType;
  11. string databaseUrl;
  12. string gameMode;
  13. int winAmount = -1;
  14. public GameObject questionCardPrefab;
  15. [Serializable]
  16. public class Question {
  17. public string question;
  18. public string answer;
  19. public string id;
  20. public string category;
  21. }
  22. [Serializable]
  23. public class Questions {
  24. public List<Question> questionsList = new List<Question>();
  25. }
  26. internal void SetLastPlayedDate(int gameId) {
  27. string sql = "UPDATE game SET lastPlayedDate = DATE() WHERE id = " + gameId;
  28. IDbConnection conn = new SqliteConnection(databaseUrl);
  29. conn.Open();
  30. IDbCommand cmd = conn.CreateCommand();
  31. cmd.CommandText = sql;
  32. cmd.ExecuteNonQuery();
  33. cmd.Dispose();
  34. conn.Close();
  35. }
  36. string questionString = "";
  37. string answerString = "";
  38. string idString = "";
  39. string categoryString = "";
  40. private int round = -1;
  41. public string QuestionString { get => questionString; set => questionString = value; }
  42. private void Start() {
  43. if (databaseUrl == null || databaseUrl.Equals("")) {
  44. SetLocalOrOnline("Local"); // Temporary, shoild not be needed after local testing
  45. }
  46. }
  47. internal int GetQuestionTimer(int gameId) {
  48. string sql = "SELECT answerTimer FROM game WHERE id = " + gameId;
  49. if (databaseUrl == null) {
  50. SetLocalOrOnline("Local");
  51. }
  52. IDbConnection conn = new SqliteConnection(databaseUrl);
  53. conn.Open();
  54. IDbCommand cmd = conn.CreateCommand();
  55. cmd.CommandText = sql;
  56. IDataReader reader = cmd.ExecuteReader();
  57. int answerTime = 15;
  58. while (reader.Read()) {
  59. answerTime = reader.GetInt32(0);
  60. }
  61. reader.Close();
  62. cmd.Dispose();
  63. conn.Close();
  64. return answerTime;
  65. }
  66. internal void GetOnlineGames(int userId) {
  67. string sql = "SELECT * FROM games WHERE userId = " + userId;
  68. }
  69. internal List<LocalGameScript> GetLocalGames(GameObject prefab) {
  70. List<LocalGameScript> games = new List<LocalGameScript>();
  71. 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";
  72. IDbConnection conn = new SqliteConnection(databaseUrl);
  73. conn.Open();
  74. IDbCommand cmd = conn.CreateCommand();
  75. cmd.CommandText = sql;
  76. IDataReader reader = cmd.ExecuteReader();
  77. int currentGame = -1;
  78. GameObject localGame;// = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  79. LocalGameScript lgs = null;//= localGame.GetComponent<LocalGameScript>();
  80. string currentPlayerName = "";
  81. int currentPoints = 0;
  82. while (reader.Read()) {
  83. if (currentGame != reader.GetInt32(0)) {
  84. localGame = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  85. lgs = localGame.GetComponent<LocalGameScript>();
  86. lgs.GameId = reader.GetInt32(0);
  87. lgs.GameMode = reader.GetString(1);
  88. lgs.QuestionsNeededToWin = reader.GetInt32(2).ToString();
  89. lgs.AnswerTimer = reader.GetInt32(3);
  90. lgs.NumberOfPlayers = reader.GetInt32(4).ToString();
  91. lgs.CurrentPlayer = reader.GetString(5);
  92. lgs.Round = reader.GetInt32(6).ToString();
  93. lgs.StartDate = reader.GetValue(7) != DBNull.Value ? reader.GetString(7) : "";
  94. lgs.LastPlayedDate = reader.GetValue(8) != DBNull.Value ? reader.GetString(8) : "";
  95. lgs.FinishedDate = reader.GetValue(9) != DBNull.Value ? reader.GetString(9) : "";
  96. currentPlayerName = reader.GetString(10);
  97. currentPoints = GetPlayerPoints(reader.GetInt32(0), currentPlayerName);
  98. lgs.AddPlayer(currentPlayerName, currentPoints);
  99. games.Add(lgs);
  100. } else if (currentGame == reader.GetInt32(0)) {
  101. currentPlayerName = reader.GetString(10);
  102. currentPoints = GetPlayerPoints(currentGame, currentPlayerName);
  103. lgs.AddPlayer(currentPlayerName, currentPoints);
  104. }
  105. currentGame = reader.GetInt32(0);
  106. }
  107. reader.Close();
  108. cmd.Dispose();
  109. conn.Close();
  110. return games;
  111. }
  112. public string GetCurrentPlayer(int gameId) {
  113. string sql = "SELECT currentPlayer FROM game WHERE id = " + gameId;
  114. IDbConnection conn = new SqliteConnection(databaseUrl);
  115. conn.Open();
  116. IDbCommand cmd = conn.CreateCommand();
  117. cmd.CommandText = sql;
  118. IDataReader reader = cmd.ExecuteReader();
  119. string currentPlayer = "";
  120. while (reader.Read()) {
  121. currentPlayer = reader.GetString(0);
  122. }
  123. reader.Close();
  124. cmd.Dispose();
  125. conn.Close();
  126. return currentPlayer;
  127. }
  128. public void SetCurrentPlayer(int gameId, string currentPlayer) {
  129. string sql = "UPDATE game SET currentPlayer = '" + currentPlayer + "' WHERE id = " + gameId;
  130. IDbConnection conn = new SqliteConnection(databaseUrl);
  131. conn.Open();
  132. IDbCommand cmd = conn.CreateCommand();
  133. cmd.CommandText = sql;
  134. cmd.ExecuteNonQuery();
  135. cmd.Dispose();
  136. conn.Close();
  137. }
  138. internal int GetPlayerPoints(int gameId, string playerName) {
  139. string sql = "SELECT count(*) FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" +playerName + "'";
  140. IDbConnection conn = new SqliteConnection(databaseUrl);
  141. conn.Open();
  142. IDbCommand cmd = conn.CreateCommand();
  143. cmd.CommandText = sql;
  144. IDataReader reader = cmd.ExecuteReader();
  145. int points = 0;
  146. while (reader.Read()) {
  147. points = reader.GetInt32(0);
  148. }
  149. reader.Close();
  150. cmd.Dispose();
  151. conn.Close();
  152. return points;
  153. }
  154. internal void SetFinishedDate(int gameId, string finishedDate) {
  155. string sql = "UPDATE game SET finishedDate = '" + finishedDate + "' WHERE id = " + gameId;
  156. IDbConnection conn = new SqliteConnection(databaseUrl);
  157. conn.Open();
  158. IDbCommand cmd = conn.CreateCommand();
  159. cmd.CommandText = sql;
  160. cmd.ExecuteNonQuery();
  161. cmd.Dispose();
  162. conn.Close();
  163. }
  164. internal void SetRoundValue(int gameId, int round) {
  165. string sql = "UPDATE game SET round = " + round + " WHERE id = " + gameId;
  166. IDbConnection conn = new SqliteConnection(databaseUrl);
  167. conn.Open();
  168. IDbCommand cmd = conn.CreateCommand();
  169. cmd.CommandText = sql;
  170. cmd.ExecuteNonQuery();
  171. cmd.Dispose();
  172. conn.Close();
  173. }
  174. internal int GetRoundValue(int gameId) {
  175. if (this.round == -1) {
  176. string sql = "SELECT round FROM game WHERE id = " + gameId;
  177. IDbConnection conn = new SqliteConnection(databaseUrl);
  178. conn.Open();
  179. IDbCommand cmd = conn.CreateCommand();
  180. cmd.CommandText = sql;
  181. IDataReader reader = cmd.ExecuteReader();
  182. while (reader.Read()) {
  183. this.round = reader.GetInt32(0);
  184. }
  185. reader.Close();
  186. cmd.Dispose();
  187. conn.Close();
  188. }
  189. return this.round;
  190. }
  191. internal List<KeyValuePair<string, int>> GetPlayersForGame(int gameId) {
  192. string sql = "SELECT name, (SELECT count(*) FROM usersLockedQuestions WHERE playerName = localUsers.name AND gameId = " + gameId + ") as numAnswers FROM localGamePlayers " +
  193. "LEFT JOIN localUsers ON localGamePlayers.playerId = localUsers.id " +
  194. "WHERE gameId = " + gameId;
  195. IDbConnection conn = new SqliteConnection(databaseUrl);
  196. conn.Open();
  197. IDbCommand cmd = conn.CreateCommand();
  198. cmd.CommandText = sql;
  199. IDataReader reader = cmd.ExecuteReader();
  200. List<KeyValuePair<string, int>> returnList = new List<KeyValuePair<string, int>>();
  201. while (reader.Read()) {
  202. KeyValuePair<string, int> player = new KeyValuePair<string, int>(reader.GetString(0), reader.GetInt32(1));
  203. returnList.Add(player);
  204. }
  205. return returnList;
  206. }
  207. public string AnswerString { get => answerString; set => answerString = value; }
  208. public string IdString { get => idString; set => idString = value; }
  209. public string CategoryString { get => categoryString; set => categoryString = value; }
  210. public void SetLocalOrOnline(string type) {
  211. gameMode = type;
  212. string databaseName = "narKampenLocal.db";
  213. if (type.Equals("Local")) {
  214. if (Application.platform == RuntimePlatform.Android) {
  215. databaseUrl = Application.persistentDataPath + "/" + databaseName;
  216. if (!File.Exists(databaseUrl)) {
  217. UnityWebRequest load = UnityWebRequest.Get("jar:file://" + Application.dataPath + "!/assets/" + databaseName);
  218. // WWW load = new WWW("jar:file://" + Application.dataPath + "!/assets/" + databaseName);
  219. //while (!load.isDone) { }
  220. load.SendWebRequest();
  221. File.WriteAllBytes(databaseUrl, load.downloadHandler.data);
  222. //File.WriteAllBytes(databaseUrl, load.bytes);
  223. }
  224. databaseUrl = "URI=file:" + databaseUrl;
  225. } else {
  226. databaseUrl = "URI=file:" + Application.dataPath + "/narKampenLocal.db";
  227. }
  228. } else {
  229. databaseUrl = "nordh.xyz/narKampen/dbFiles/dbAccess.php";
  230. }
  231. connectionType = type;
  232. }
  233. public string GetGameMode(int gameId) {
  234. if (this.gameMode == null) {
  235. string sql = "SELECT gameMode FROM game WHERE id = " + gameId;
  236. IDbConnection conn = new SqliteConnection(databaseUrl);
  237. conn.Open();
  238. IDbCommand cmd = conn.CreateCommand();
  239. cmd.CommandText = sql;
  240. IDataReader reader = cmd.ExecuteReader();
  241. while (reader.Read()) {
  242. this.gameMode = reader.GetString(0);
  243. }
  244. reader.Close();
  245. cmd.Dispose();
  246. conn.Close();
  247. }
  248. return this.gameMode;
  249. }
  250. public void LinkPlayersToLocalGame(List<string> playerNames, int gameId) {
  251. IDbConnection conn = new SqliteConnection(databaseUrl);
  252. conn.Open();
  253. string questionSql = "SELECT id FROM questions order by random() limit 1";
  254. IDbCommand cmd = conn.CreateCommand();
  255. cmd.CommandText = questionSql;
  256. IDataReader reader = cmd.ExecuteReader();
  257. int questionId = -1;
  258. while (reader.Read()) {
  259. questionId = reader.GetInt32(0);
  260. }
  261. foreach (string player in playerNames) {
  262. string sql = "SELECT id FROM localUsers WHERE name = '" + player + "'";
  263. int playerId;
  264. cmd = conn.CreateCommand();
  265. cmd.CommandText = sql;
  266. reader = cmd.ExecuteReader();
  267. if (reader.Read()) {
  268. playerId = reader.GetInt32(0);
  269. } else {
  270. reader.Close();
  271. sql = "INSERT INTO localUsers (name) VALUES ('" + player + "')";
  272. cmd.CommandText = sql;
  273. cmd.ExecuteNonQuery();
  274. cmd.CommandText = "SELECT last_insert_rowid()";
  275. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  276. playerId = (int)lastInsert64;
  277. }
  278. cmd.Dispose();
  279. reader.Close();
  280. LinkPlayerToGame(playerId, gameId);
  281. SavePlayersQuestion(questionId.ToString(), player, gameId);
  282. }
  283. IDbCommand cmd2 = conn.CreateCommand();
  284. cmd2.CommandText = "UPDATE game SET currentPlayer = '" + playerNames[0] + "' WHERE id = " + gameId;
  285. cmd2.ExecuteNonQuery();
  286. cmd2.Dispose();
  287. conn.Close();
  288. }
  289. private void LinkPlayerToGame(int playerId, int gameId) {
  290. string sql = "INSERT INTO localGamePlayers (gameId, playerId) VALUES (" + gameId + ", " + playerId + ")";
  291. SqliteConnection conn2 = new SqliteConnection(databaseUrl);
  292. conn2.Open();
  293. IDbCommand cmd = conn2.CreateCommand();
  294. cmd.CommandText = sql;
  295. cmd.ExecuteNonQuery();
  296. cmd.Dispose();
  297. conn2.Close();
  298. }
  299. internal int GetWinCondition(int gameId) {
  300. if (winAmount == -1) {
  301. string sql = "SELECT winNumber FROM game WHERE id = " + gameId;
  302. IDbConnection conn = new SqliteConnection(databaseUrl);
  303. conn.Open();
  304. IDbCommand cmd = conn.CreateCommand();
  305. cmd.CommandText = sql;
  306. IDataReader reader = cmd.ExecuteReader();
  307. while (reader.Read()) {
  308. this.winAmount = reader.GetInt32(0);
  309. }
  310. reader.Close();
  311. cmd.Dispose();
  312. conn.Close();
  313. }
  314. return this.winAmount;
  315. }
  316. public int SetupNewLocalGame(int winNumber, int numberOfPlayers, int questionTimer) {
  317. string sql = "INSERT INTO game (winNumber, numberOfPlayers, answerTimer, gameMode, startedDate) VALUES (" + winNumber + "," + numberOfPlayers + "," + questionTimer + ", 'Local', DATE())";
  318. IDbConnection conn = new SqliteConnection(databaseUrl);
  319. conn.Open();
  320. IDbCommand cmd = conn.CreateCommand();
  321. cmd.CommandText = sql;
  322. int status = cmd.ExecuteNonQuery();
  323. cmd.CommandText = "SELECT last_insert_rowid()";
  324. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  325. return (int)lastInsert64;
  326. }
  327. public NewQuestion GetNewQuestion() {
  328. if (connectionType == null) {
  329. int gameId = GameObject.Find("GameManager").GetComponent<GameManagerScript>().GameId;
  330. SetLocalOrOnline(GetGameMode(gameId));
  331. }
  332. if (connectionType == "Local") {
  333. IDbConnection conn = new SqliteConnection(databaseUrl);
  334. conn.Open();
  335. IDbCommand cmd = conn.CreateCommand();
  336. string sql = "SELECT questions.id, question, answer, categoryId as category, name FROM questions INNER JOIN questionToCategory ON questions.id = questionToCategory.questionId INNER JOIN category on category.id = questionToCategory.categoryId ORDER BY RANDOM() limit 1";
  337. cmd.CommandText = sql;
  338. IDataReader reader = cmd.ExecuteReader();
  339. while (reader.Read()) {
  340. int id = reader.GetInt32(0);
  341. string question = reader.GetString(1);
  342. int answer = reader.GetInt32(2);
  343. int catergoryId = reader.GetInt32(3);
  344. string categoryName = reader.GetString(4);
  345. idString = id.ToString();
  346. questionString = question;
  347. categoryString = catergoryId.ToString();
  348. answerString = answer.ToString();
  349. }
  350. reader.Close();
  351. cmd.Dispose();
  352. conn.Close();
  353. } else { // Connect Through db
  354. Debug.Log("Online Call");
  355. StartCoroutine(GetQuestionData(false));
  356. }
  357. NewQuestion q = NewQuestion.Instance();
  358. q.questionString = questionString;
  359. q.answerString = answerString;
  360. q.categoryString = categoryString;
  361. q.idString = idString;
  362. return q;
  363. }
  364. public void SavePlayersQuestion(string questionId, string playerNameValue, int gameId) {
  365. if (databaseUrl == null) {
  366. SetLocalOrOnline(GetGameMode(gameId));
  367. }
  368. Int32.TryParse(questionId, out int qId);
  369. string sql = "INSERT OR IGNORE INTO usersLockedQuestions (playerName, questionId, gameId) VALUES ('" + playerNameValue + "'," + qId + "," + gameId + ")";
  370. IDbConnection conn = new SqliteConnection(databaseUrl);
  371. conn.Open();
  372. IDbCommand cmd = conn.CreateCommand();
  373. cmd.CommandText = sql;
  374. cmd.ExecuteReader();
  375. cmd.Dispose();
  376. conn.Close();
  377. }
  378. public List<QuestionCard> GetPlayerQuestions(int gameId, string playerNameValue) {
  379. if (databaseUrl == null) {
  380. SetLocalOrOnline(GetGameMode(gameId));
  381. }
  382. List<QuestionCard> questions = new List<QuestionCard>();
  383. if (connectionType.Equals("Local")) {
  384. string sql = "SELECT * FROM questions WHERE id IN ( SELECT questionId FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" + playerNameValue + "') ORDER BY answer ASC";
  385. IDbConnection conn = new SqliteConnection(databaseUrl);
  386. conn.Open();
  387. IDbCommand cmd = conn.CreateCommand();
  388. cmd.CommandText = sql;
  389. IDataReader reader = cmd.ExecuteReader();
  390. while (reader.Read()) {
  391. GameObject question = Instantiate(questionCardPrefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  392. QuestionCard q = question.GetComponent<QuestionCard>();
  393. q.SetAnswerText(reader.GetInt32(2).ToString());
  394. q.SetQuestionText(reader.GetString(1));
  395. q.idString = reader.GetInt32(0).ToString();
  396. questions.Add(q);
  397. }
  398. cmd.Dispose();
  399. conn.Close();
  400. }
  401. return questions;
  402. }
  403. private IEnumerator GetQuestionData(bool showAnswer) {
  404. UnityWebRequest www = UnityWebRequest.Get("nordh.xyz/narKampen/dbFiles/dbAccess.php");
  405. yield return www.SendWebRequest();
  406. if (www.isNetworkError || www.isHttpError) {
  407. Debug.Log(www.error);
  408. } else {
  409. while (!www.isDone) {
  410. yield return null;
  411. }
  412. // Show result
  413. string jsonData = www.downloadHandler.text;
  414. jsonData = "{\"questionsList\" : [ " + jsonData + " ]}";
  415. Questions qe = new Questions();
  416. JsonUtility.FromJsonOverwrite(jsonData, qe);
  417. /* if (qe.questionsList.Count > 0 && questionText != null) {
  418. if (showAnswer && answerText != null) {
  419. answerText.text = qe.questionsList[0].answer;
  420. }
  421. questionText.text = qe.questionsList[0].question;
  422. } */
  423. questionString = qe.questionsList[0].question;
  424. answerString = qe.questionsList[0].answer;
  425. idString = qe.questionsList[0].id;
  426. categoryString = qe.questionsList[0].category;
  427. }
  428. }
  429. }