Database.cs 28 KB

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