SQLiteUserData.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Data;
  30. using libsecondlife;
  31. using Mono.Data.SqliteClient;
  32. using OpenSim.Framework.Console;
  33. namespace OpenSim.Framework.Data.SQLite
  34. {
  35. /// <summary>
  36. /// A User storage interface for the SQLite database system
  37. /// </summary>
  38. public class SQLiteUserData : UserDataBase
  39. {
  40. private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  41. /// <summary>
  42. /// The database manager
  43. /// </summary>
  44. /// <summary>
  45. /// Artificial constructor called upon plugin load
  46. /// </summary>
  47. private const string SelectUserByUUID = "select * from users where UUID=:UUID";
  48. private const string SelectUserByName = "select * from users where username=:username and surname=:surname";
  49. private const string SelectFriendsByUUID = "select a.friendID, a.friendPerms, b.friendPerms from userfriends as a, userfriends as b where a.ownerID=:ownerID and b.ownerID=a.friendID and b.friendID=a.ownerID";
  50. private const string userSelect = "select * from users";
  51. private const string userFriendsSelect = "select a.ownerID as ownerID,a.friendID as friendID,a.friendPerms as friendPerms,b.friendPerms as ownerperms, b.ownerID as fownerID, b.friendID as ffriendID from userfriends as a, userfriends as b";
  52. private const string AvatarPickerAndSQL = "select * from users where username like :username and surname like :surname";
  53. private const string AvatarPickerOrSQL = "select * from users where username like :username or surname like :surname";
  54. private DataSet ds;
  55. private SqliteDataAdapter da;
  56. private SqliteDataAdapter daf;
  57. SqliteConnection g_conn;
  58. override public void Initialise()
  59. {
  60. SqliteConnection conn = new SqliteConnection("URI=file:userprofiles.db,version=3");
  61. TestTables(conn);
  62. // This sucks, but It doesn't seem to work with the dataset Syncing :P
  63. g_conn = conn;
  64. g_conn.Open();
  65. ds = new DataSet();
  66. da = new SqliteDataAdapter(new SqliteCommand(userSelect, conn));
  67. daf = new SqliteDataAdapter(new SqliteCommand(userFriendsSelect, conn));
  68. lock (ds)
  69. {
  70. ds.Tables.Add(createUsersTable());
  71. ds.Tables.Add(createUserAgentsTable());
  72. ds.Tables.Add(createUserFriendsTable());
  73. setupUserCommands(da, conn);
  74. da.Fill(ds.Tables["users"]);
  75. setupUserFriendsCommands(daf, conn);
  76. try
  77. {
  78. daf.Fill(ds.Tables["userfriends"]);
  79. }
  80. catch (SqliteSyntaxException)
  81. {
  82. m_log.Info("[SQLITE]: userfriends table not found, creating.... ");
  83. InitDB(conn);
  84. daf.Fill(ds.Tables["userfriends"]);
  85. }
  86. }
  87. return;
  88. }
  89. // see IUserData
  90. override public UserProfileData GetUserByUUID(LLUUID uuid)
  91. {
  92. lock (ds)
  93. {
  94. DataRow row = ds.Tables["users"].Rows.Find(Util.ToRawUuidString(uuid));
  95. if (row != null)
  96. {
  97. UserProfileData user = buildUserProfile(row);
  98. row = ds.Tables["useragents"].Rows.Find(Util.ToRawUuidString(uuid));
  99. if (row != null)
  100. {
  101. user.currentAgent = buildUserAgent(row);
  102. }
  103. return user;
  104. }
  105. else
  106. {
  107. return null;
  108. }
  109. }
  110. }
  111. // see IUserData
  112. override public UserProfileData GetUserByName(string fname, string lname)
  113. {
  114. string select = "surname = '" + lname + "' and username = '" + fname + "'";
  115. lock (ds)
  116. {
  117. DataRow[] rows = ds.Tables["users"].Select(select);
  118. if (rows.Length > 0)
  119. {
  120. UserProfileData user = buildUserProfile(rows[0]);
  121. DataRow row = ds.Tables["useragents"].Rows.Find(Util.ToRawUuidString(user.UUID));
  122. if (row != null)
  123. {
  124. user.currentAgent = buildUserAgent(row);
  125. }
  126. return user;
  127. }
  128. else
  129. {
  130. return null;
  131. }
  132. }
  133. }
  134. #region User Friends List Data
  135. override public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms)
  136. {
  137. string InsertFriends = "insert into userfriends(ownerID, friendID, friendPerms) values(:ownerID, :friendID, :perms)";
  138. using (SqliteCommand cmd = new SqliteCommand(InsertFriends, g_conn))
  139. {
  140. cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.UUID.ToString()));
  141. cmd.Parameters.Add(new SqliteParameter(":friendID", friend.UUID.ToString()));
  142. cmd.Parameters.Add(new SqliteParameter(":perms", perms));
  143. cmd.ExecuteNonQuery();
  144. }
  145. using (SqliteCommand cmd = new SqliteCommand(InsertFriends, g_conn))
  146. {
  147. cmd.Parameters.Add(new SqliteParameter(":ownerID", friend.UUID.ToString()));
  148. cmd.Parameters.Add(new SqliteParameter(":friendID", friendlistowner.UUID.ToString()));
  149. cmd.Parameters.Add(new SqliteParameter(":perms", perms));
  150. cmd.ExecuteNonQuery();
  151. }
  152. }
  153. override public void RemoveUserFriend(LLUUID friendlistowner, LLUUID friend)
  154. {
  155. string DeletePerms = "delete from friendlist where (ownerID=:ownerID and friendID=:friendID) or (ownerID=:friendID and friendID=:ownerID)";
  156. using (SqliteCommand cmd = new SqliteCommand(DeletePerms, g_conn))
  157. {
  158. cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.UUID.ToString()));
  159. cmd.Parameters.Add(new SqliteParameter(":friendID", friend.UUID.ToString()));
  160. cmd.ExecuteNonQuery();
  161. }
  162. }
  163. override public void UpdateUserFriendPerms(LLUUID friendlistowner, LLUUID friend, uint perms)
  164. {
  165. string UpdatePerms = "update friendlist set perms=:perms where ownerID=:ownerID and friendID=:friendID";
  166. using (SqliteCommand cmd = new SqliteCommand(UpdatePerms, g_conn))
  167. {
  168. cmd.Parameters.Add(new SqliteParameter(":perms", perms));
  169. cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.UUID.ToString()));
  170. cmd.Parameters.Add(new SqliteParameter(":friendID", friend.UUID.ToString()));
  171. cmd.ExecuteNonQuery();
  172. }
  173. }
  174. override public List<FriendListItem> GetUserFriendList(LLUUID friendlistowner)
  175. {
  176. List<FriendListItem> returnlist = new List<FriendListItem>();
  177. using (SqliteCommand cmd = new SqliteCommand(SelectFriendsByUUID, g_conn))
  178. {
  179. cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.UUID.ToString()));
  180. try
  181. {
  182. using (IDataReader reader = cmd.ExecuteReader())
  183. {
  184. while (reader.Read())
  185. {
  186. FriendListItem user = new FriendListItem();
  187. user.FriendListOwner = friendlistowner;
  188. user.Friend = new LLUUID((string)reader[0]);
  189. user.FriendPerms = Convert.ToUInt32(reader[1]);
  190. user.FriendListOwnerPerms = Convert.ToUInt32(reader[2]);
  191. returnlist.Add(user);
  192. }
  193. reader.Close();
  194. }
  195. }
  196. catch (Exception ex)
  197. {
  198. m_log.Error("[USER]: Exception getting friends list for user: " + ex.ToString());
  199. }
  200. }
  201. return returnlist;
  202. }
  203. #endregion
  204. override public void UpdateUserCurrentRegion(LLUUID avatarid, LLUUID regionuuid)
  205. {
  206. m_log.Info("[USER]: Stub UpdateUserCUrrentRegion called");
  207. }
  208. override public List<Framework.AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query)
  209. {
  210. List<Framework.AvatarPickerAvatar> returnlist = new List<Framework.AvatarPickerAvatar>();
  211. string[] querysplit;
  212. querysplit = query.Split(' ');
  213. if (querysplit.Length == 2)
  214. {
  215. using (SqliteCommand cmd = new SqliteCommand(AvatarPickerAndSQL, g_conn))
  216. {
  217. cmd.Parameters.Add(new SqliteParameter(":username", querysplit[0] + "%"));
  218. cmd.Parameters.Add(new SqliteParameter(":surname", querysplit[1] + "%"));
  219. using (IDataReader reader = cmd.ExecuteReader())
  220. {
  221. while (reader.Read())
  222. {
  223. Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar();
  224. user.AvatarID = new LLUUID((string) reader["UUID"]);
  225. user.firstName = (string) reader["username"];
  226. user.lastName = (string) reader["surname"];
  227. returnlist.Add(user);
  228. }
  229. reader.Close();
  230. }
  231. }
  232. }
  233. else if (querysplit.Length == 1)
  234. {
  235. using (SqliteCommand cmd = new SqliteCommand(AvatarPickerOrSQL, g_conn))
  236. {
  237. cmd.Parameters.Add(new SqliteParameter(":username", querysplit[0] + "%"));
  238. cmd.Parameters.Add(new SqliteParameter(":surname", querysplit[0] + "%"));
  239. using (IDataReader reader = cmd.ExecuteReader())
  240. {
  241. while (reader.Read())
  242. {
  243. Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar();
  244. user.AvatarID = new LLUUID((string) reader["UUID"]);
  245. user.firstName = (string) reader["username"];
  246. user.lastName = (string) reader["surname"];
  247. returnlist.Add(user);
  248. }
  249. reader.Close();
  250. }
  251. }
  252. }
  253. return returnlist;
  254. }
  255. /// <summary>
  256. /// Returns a user by UUID direct
  257. /// </summary>
  258. /// <param name="uuid">The user's account ID</param>
  259. /// <returns>A matching user profile</returns>
  260. override public UserAgentData GetAgentByUUID(LLUUID uuid)
  261. {
  262. try
  263. {
  264. return GetUserByUUID(uuid).currentAgent;
  265. }
  266. catch (Exception)
  267. {
  268. return null;
  269. }
  270. }
  271. /// <summary>
  272. /// Returns a session by account name
  273. /// </summary>
  274. /// <param name="name">The account name</param>
  275. /// <returns>The user's session agent</returns>
  276. override public UserAgentData GetAgentByName(string name)
  277. {
  278. return GetAgentByName(name.Split(' ')[0], name.Split(' ')[1]);
  279. }
  280. /// <summary>
  281. /// Returns a session by account name
  282. /// </summary>
  283. /// <param name="fname">The first part of the user's account name</param>
  284. /// <param name="lname">The second part of the user's account name</param>
  285. /// <returns>A user agent</returns>
  286. override public UserAgentData GetAgentByName(string fname, string lname)
  287. {
  288. try
  289. {
  290. return GetUserByName(fname, lname).currentAgent;
  291. }
  292. catch (Exception)
  293. {
  294. return null;
  295. }
  296. }
  297. override public void StoreWebLoginKey(LLUUID AgentID, LLUUID WebLoginKey)
  298. {
  299. DataTable users = ds.Tables["users"];
  300. lock (ds)
  301. {
  302. DataRow row = users.Rows.Find(Util.ToRawUuidString(AgentID));
  303. if (row == null)
  304. {
  305. m_log.Warn("[WEBLOGIN]: Unable to store new web login key for non-existant user");
  306. }
  307. else
  308. {
  309. UserProfileData user = GetUserByUUID(AgentID);
  310. user.webLoginKey = WebLoginKey;
  311. fillUserRow(row, user);
  312. da.Update(ds, "users");
  313. }
  314. }
  315. }
  316. /// <summary>
  317. /// Creates a new user profile
  318. /// </summary>
  319. /// <param name="user">The profile to add to the database</param>
  320. override public void AddNewUserProfile(UserProfileData user)
  321. {
  322. DataTable users = ds.Tables["users"];
  323. lock (ds)
  324. {
  325. DataRow row = users.Rows.Find(Util.ToRawUuidString(user.UUID));
  326. if (row == null)
  327. {
  328. row = users.NewRow();
  329. fillUserRow(row, user);
  330. users.Rows.Add(row);
  331. }
  332. else
  333. {
  334. fillUserRow(row, user);
  335. }
  336. // This is why we're getting the 'logins never log-off'.. because It isn't clearing the
  337. // useragents table once the useragent is null
  338. //
  339. // A database guy should look at this and figure out the best way to clear the useragents table.
  340. if (user.currentAgent != null)
  341. {
  342. DataTable ua = ds.Tables["useragents"];
  343. row = ua.Rows.Find(Util.ToRawUuidString(user.UUID));
  344. if (row == null)
  345. {
  346. row = ua.NewRow();
  347. fillUserAgentRow(row, user.currentAgent);
  348. ua.Rows.Add(row);
  349. }
  350. else
  351. {
  352. fillUserAgentRow(row, user.currentAgent);
  353. }
  354. }
  355. else
  356. {
  357. // I just added this to help the standalone login situation.
  358. //It still needs to be looked at by a Database guy
  359. DataTable ua = ds.Tables["useragents"];
  360. row = ua.Rows.Find(Util.ToRawUuidString(user.UUID));
  361. if (row == null)
  362. {
  363. // do nothing
  364. }
  365. else
  366. {
  367. row.Delete();
  368. ua.AcceptChanges();
  369. }
  370. }
  371. m_log.Info("[SQLITE]: " +
  372. "Syncing user database: " + ds.Tables["users"].Rows.Count + " users stored");
  373. // save changes off to disk
  374. da.Update(ds, "users");
  375. }
  376. }
  377. /// <summary>
  378. /// Creates a new user profile
  379. /// </summary>
  380. /// <param name="user">The profile to add to the database</param>
  381. /// <returns>True on success, false on error</returns>
  382. override public bool UpdateUserProfile(UserProfileData user)
  383. {
  384. try
  385. {
  386. AddNewUserProfile(user);
  387. return true;
  388. }
  389. catch (Exception)
  390. {
  391. return false;
  392. }
  393. }
  394. /// <summary>
  395. /// Creates a new user agent
  396. /// </summary>
  397. /// <param name="agent">The agent to add to the database</param>
  398. override public void AddNewUserAgent(UserAgentData agent)
  399. {
  400. // Do nothing. yet.
  401. }
  402. /// <summary>
  403. /// Transfers money between two user accounts
  404. /// </summary>
  405. /// <param name="from">Starting account</param>
  406. /// <param name="to">End account</param>
  407. /// <param name="amount">The amount to move</param>
  408. /// <returns>Success?</returns>
  409. override public bool MoneyTransferRequest(LLUUID from, LLUUID to, uint amount)
  410. {
  411. return true;
  412. }
  413. /// <summary>
  414. /// Transfers inventory between two accounts
  415. /// </summary>
  416. /// <remarks>Move to inventory server</remarks>
  417. /// <param name="from">Senders account</param>
  418. /// <param name="to">Receivers account</param>
  419. /// <param name="item">Inventory item</param>
  420. /// <returns>Success?</returns>
  421. override public bool InventoryTransferRequest(LLUUID from, LLUUID to, LLUUID item)
  422. {
  423. return true;
  424. }
  425. /// <summary>
  426. /// Returns the name of the storage provider
  427. /// </summary>
  428. /// <returns>Storage provider name</returns>
  429. override public string getName()
  430. {
  431. return "Sqlite Userdata";
  432. }
  433. /// <summary>
  434. /// Returns the version of the storage provider
  435. /// </summary>
  436. /// <returns>Storage provider version</returns>
  437. override public string GetVersion()
  438. {
  439. return "0.1";
  440. }
  441. /***********************************************************************
  442. *
  443. * DataTable creation
  444. *
  445. **********************************************************************/
  446. /***********************************************************************
  447. *
  448. * Database Definition Functions
  449. *
  450. * This should be db agnostic as we define them in ADO.NET terms
  451. *
  452. **********************************************************************/
  453. private static DataTable createUsersTable()
  454. {
  455. DataTable users = new DataTable("users");
  456. SQLiteUtil.createCol(users, "UUID", typeof (String));
  457. SQLiteUtil.createCol(users, "username", typeof (String));
  458. SQLiteUtil.createCol(users, "surname", typeof (String));
  459. SQLiteUtil.createCol(users, "passwordHash", typeof (String));
  460. SQLiteUtil.createCol(users, "passwordSalt", typeof (String));
  461. SQLiteUtil.createCol(users, "homeRegionX", typeof (Int32));
  462. SQLiteUtil.createCol(users, "homeRegionY", typeof (Int32));
  463. SQLiteUtil.createCol(users, "homeLocationX", typeof (Double));
  464. SQLiteUtil.createCol(users, "homeLocationY", typeof (Double));
  465. SQLiteUtil.createCol(users, "homeLocationZ", typeof (Double));
  466. SQLiteUtil.createCol(users, "homeLookAtX", typeof (Double));
  467. SQLiteUtil.createCol(users, "homeLookAtY", typeof (Double));
  468. SQLiteUtil.createCol(users, "homeLookAtZ", typeof (Double));
  469. SQLiteUtil.createCol(users, "created", typeof (Int32));
  470. SQLiteUtil.createCol(users, "lastLogin", typeof (Int32));
  471. SQLiteUtil.createCol(users, "rootInventoryFolderID", typeof (String));
  472. SQLiteUtil.createCol(users, "userInventoryURI", typeof (String));
  473. SQLiteUtil.createCol(users, "userAssetURI", typeof (String));
  474. SQLiteUtil.createCol(users, "profileCanDoMask", typeof (Int32));
  475. SQLiteUtil.createCol(users, "profileWantDoMask", typeof (Int32));
  476. SQLiteUtil.createCol(users, "profileAboutText", typeof (String));
  477. SQLiteUtil.createCol(users, "profileFirstText", typeof (String));
  478. SQLiteUtil.createCol(users, "profileImage", typeof (String));
  479. SQLiteUtil.createCol(users, "profileFirstImage", typeof (String));
  480. SQLiteUtil.createCol(users, "webLoginKey", typeof(String));
  481. // Add in contraints
  482. users.PrimaryKey = new DataColumn[] {users.Columns["UUID"]};
  483. return users;
  484. }
  485. private static DataTable createUserAgentsTable()
  486. {
  487. DataTable ua = new DataTable("useragents");
  488. // this is the UUID of the user
  489. SQLiteUtil.createCol(ua, "UUID", typeof (String));
  490. SQLiteUtil.createCol(ua, "agentIP", typeof (String));
  491. SQLiteUtil.createCol(ua, "agentPort", typeof (Int32));
  492. SQLiteUtil.createCol(ua, "agentOnline", typeof (Boolean));
  493. SQLiteUtil.createCol(ua, "sessionID", typeof (String));
  494. SQLiteUtil.createCol(ua, "secureSessionID", typeof (String));
  495. SQLiteUtil.createCol(ua, "regionID", typeof (String));
  496. SQLiteUtil.createCol(ua, "loginTime", typeof (Int32));
  497. SQLiteUtil.createCol(ua, "logoutTime", typeof (Int32));
  498. SQLiteUtil.createCol(ua, "currentRegion", typeof (String));
  499. SQLiteUtil.createCol(ua, "currentHandle", typeof (String));
  500. // vectors
  501. SQLiteUtil.createCol(ua, "currentPosX", typeof (Double));
  502. SQLiteUtil.createCol(ua, "currentPosY", typeof (Double));
  503. SQLiteUtil.createCol(ua, "currentPosZ", typeof (Double));
  504. // constraints
  505. ua.PrimaryKey = new DataColumn[] {ua.Columns["UUID"]};
  506. return ua;
  507. }
  508. private static DataTable createUserFriendsTable()
  509. {
  510. DataTable ua = new DataTable("userfriends");
  511. // table contains user <----> user relationship with perms
  512. SQLiteUtil.createCol(ua, "ownerID", typeof(String));
  513. SQLiteUtil.createCol(ua, "friendID", typeof(String));
  514. SQLiteUtil.createCol(ua, "friendPerms", typeof(Int32));
  515. SQLiteUtil.createCol(ua, "ownerPerms", typeof(Int32));
  516. SQLiteUtil.createCol(ua, "datetimestamp", typeof(Int32));
  517. return ua;
  518. }
  519. /***********************************************************************
  520. *
  521. * Convert between ADO.NET <=> OpenSim Objects
  522. *
  523. * These should be database independant
  524. *
  525. **********************************************************************/
  526. private static UserProfileData buildUserProfile(DataRow row)
  527. {
  528. // TODO: this doesn't work yet because something more
  529. // interesting has to be done to actually get these values
  530. // back out. Not enough time to figure it out yet.
  531. UserProfileData user = new UserProfileData();
  532. LLUUID.TryParse((String)row["UUID"], out user.UUID);
  533. user.username = (String) row["username"];
  534. user.surname = (String) row["surname"];
  535. user.passwordHash = (String) row["passwordHash"];
  536. user.passwordSalt = (String) row["passwordSalt"];
  537. user.homeRegionX = Convert.ToUInt32(row["homeRegionX"]);
  538. user.homeRegionY = Convert.ToUInt32(row["homeRegionY"]);
  539. user.homeLocation = new LLVector3(
  540. Convert.ToSingle(row["homeLocationX"]),
  541. Convert.ToSingle(row["homeLocationY"]),
  542. Convert.ToSingle(row["homeLocationZ"])
  543. );
  544. user.homeLookAt = new LLVector3(
  545. Convert.ToSingle(row["homeLookAtX"]),
  546. Convert.ToSingle(row["homeLookAtY"]),
  547. Convert.ToSingle(row["homeLookAtZ"])
  548. );
  549. user.created = Convert.ToInt32(row["created"]);
  550. user.lastLogin = Convert.ToInt32(row["lastLogin"]);
  551. user.rootInventoryFolderID = new LLUUID((String) row["rootInventoryFolderID"]);
  552. user.userInventoryURI = (String) row["userInventoryURI"];
  553. user.userAssetURI = (String) row["userAssetURI"];
  554. user.profileCanDoMask = Convert.ToUInt32(row["profileCanDoMask"]);
  555. user.profileWantDoMask = Convert.ToUInt32(row["profileWantDoMask"]);
  556. user.profileAboutText = (String) row["profileAboutText"];
  557. user.profileFirstText = (String) row["profileFirstText"];
  558. LLUUID.TryParse((String)row["profileImage"], out user.profileImage);
  559. LLUUID.TryParse((String)row["profileFirstImage"], out user.profileFirstImage);
  560. user.webLoginKey = new LLUUID((String) row["webLoginKey"]);
  561. return user;
  562. }
  563. private void fillUserRow(DataRow row, UserProfileData user)
  564. {
  565. row["UUID"] = Util.ToRawUuidString(user.UUID);
  566. row["username"] = user.username;
  567. row["surname"] = user.surname;
  568. row["passwordHash"] = user.passwordHash;
  569. row["passwordSalt"] = user.passwordSalt;
  570. row["homeRegionX"] = user.homeRegionX;
  571. row["homeRegionY"] = user.homeRegionY;
  572. row["homeLocationX"] = user.homeLocation.X;
  573. row["homeLocationY"] = user.homeLocation.Y;
  574. row["homeLocationZ"] = user.homeLocation.Z;
  575. row["homeLookAtX"] = user.homeLookAt.X;
  576. row["homeLookAtY"] = user.homeLookAt.Y;
  577. row["homeLookAtZ"] = user.homeLookAt.Z;
  578. row["created"] = user.created;
  579. row["lastLogin"] = user.lastLogin;
  580. row["rootInventoryFolderID"] = user.rootInventoryFolderID;
  581. row["userInventoryURI"] = user.userInventoryURI;
  582. row["userAssetURI"] = user.userAssetURI;
  583. row["profileCanDoMask"] = user.profileCanDoMask;
  584. row["profileWantDoMask"] = user.profileWantDoMask;
  585. row["profileAboutText"] = user.profileAboutText;
  586. row["profileFirstText"] = user.profileFirstText;
  587. row["profileImage"] = user.profileImage;
  588. row["profileFirstImage"] = user.profileFirstImage;
  589. row["webLoginKey"] = user.webLoginKey;
  590. // ADO.NET doesn't handle NULL very well
  591. foreach (DataColumn col in ds.Tables["users"].Columns)
  592. {
  593. if (row[col] == null)
  594. {
  595. row[col] = String.Empty;
  596. }
  597. }
  598. }
  599. private static UserAgentData buildUserAgent(DataRow row)
  600. {
  601. UserAgentData ua = new UserAgentData();
  602. ua.UUID = new LLUUID((String) row["UUID"]);
  603. ua.agentIP = (String) row["agentIP"];
  604. ua.agentPort = Convert.ToUInt32(row["agentPort"]);
  605. ua.agentOnline = Convert.ToBoolean(row["agentOnline"]);
  606. ua.sessionID = new LLUUID((String) row["sessionID"]);
  607. ua.secureSessionID = new LLUUID((String) row["secureSessionID"]);
  608. ua.regionID = new LLUUID((String) row["regionID"]);
  609. ua.loginTime = Convert.ToInt32(row["loginTime"]);
  610. ua.logoutTime = Convert.ToInt32(row["logoutTime"]);
  611. ua.currentRegion = new LLUUID((String) row["currentRegion"]);
  612. ua.currentHandle = Convert.ToUInt64(row["currentHandle"]);
  613. ua.currentPos = new LLVector3(
  614. Convert.ToSingle(row["currentPosX"]),
  615. Convert.ToSingle(row["currentPosY"]),
  616. Convert.ToSingle(row["currentPosZ"])
  617. );
  618. return ua;
  619. }
  620. private static void fillUserAgentRow(DataRow row, UserAgentData ua)
  621. {
  622. row["UUID"] = ua.UUID;
  623. row["agentIP"] = ua.agentIP;
  624. row["agentPort"] = ua.agentPort;
  625. row["agentOnline"] = ua.agentOnline;
  626. row["sessionID"] = ua.sessionID;
  627. row["secureSessionID"] = ua.secureSessionID;
  628. row["regionID"] = ua.regionID;
  629. row["loginTime"] = ua.loginTime;
  630. row["logoutTime"] = ua.logoutTime;
  631. row["currentRegion"] = ua.currentRegion;
  632. row["currentHandle"] = ua.currentHandle.ToString();
  633. // vectors
  634. row["currentPosX"] = ua.currentPos.X;
  635. row["currentPosY"] = ua.currentPos.Y;
  636. row["currentPosZ"] = ua.currentPos.Z;
  637. }
  638. /***********************************************************************
  639. *
  640. * Database Binding functions
  641. *
  642. * These will be db specific due to typing, and minor differences
  643. * in databases.
  644. *
  645. **********************************************************************/
  646. private void setupUserCommands(SqliteDataAdapter da, SqliteConnection conn)
  647. {
  648. da.InsertCommand = SQLiteUtil.createInsertCommand("users", ds.Tables["users"]);
  649. da.InsertCommand.Connection = conn;
  650. da.UpdateCommand = SQLiteUtil.createUpdateCommand("users", "UUID=:UUID", ds.Tables["users"]);
  651. da.UpdateCommand.Connection = conn;
  652. SqliteCommand delete = new SqliteCommand("delete from users where UUID = :UUID");
  653. delete.Parameters.Add(SQLiteUtil.createSqliteParameter("UUID", typeof(String)));
  654. delete.Connection = conn;
  655. da.DeleteCommand = delete;
  656. }
  657. private void setupUserFriendsCommands(SqliteDataAdapter daf, SqliteConnection conn)
  658. {
  659. daf.InsertCommand = SQLiteUtil.createInsertCommand("userfriends", ds.Tables["userfriends"]);
  660. daf.InsertCommand.Connection = conn;
  661. daf.UpdateCommand = SQLiteUtil.createUpdateCommand("userfriends", "ownerID=:ownerID and friendID=:friendID", ds.Tables["userfriends"]);
  662. daf.UpdateCommand.Connection = conn;
  663. SqliteCommand delete = new SqliteCommand("delete from userfriends where ownerID=:ownerID and friendID=:friendID");
  664. delete.Parameters.Add(SQLiteUtil.createSqliteParameter("ownerID", typeof(String)));
  665. delete.Parameters.Add(SQLiteUtil.createSqliteParameter("friendID", typeof(String)));
  666. delete.Connection = conn;
  667. daf.DeleteCommand = delete;
  668. }
  669. private void InitDB(SqliteConnection conn)
  670. {
  671. string createUsers = SQLiteUtil.defineTable(createUsersTable());
  672. string createFriends = SQLiteUtil.defineTable(createUserFriendsTable());
  673. SqliteCommand pcmd = new SqliteCommand(createUsers, conn);
  674. SqliteCommand fcmd = new SqliteCommand(createFriends, conn);
  675. conn.Open();
  676. try
  677. {
  678. pcmd.ExecuteNonQuery();
  679. }
  680. catch (System.Exception)
  681. {
  682. m_log.Info("[USERS]: users table already exists");
  683. }
  684. try
  685. {
  686. fcmd.ExecuteNonQuery();
  687. }
  688. catch (System.Exception)
  689. {
  690. m_log.Info("[USERS]: userfriends table already exists");
  691. }
  692. conn.Close();
  693. }
  694. private bool TestTables(SqliteConnection conn)
  695. {
  696. SqliteCommand cmd = new SqliteCommand(userSelect, conn);
  697. SqliteCommand fcmd = new SqliteCommand(userFriendsSelect, conn);
  698. SqliteDataAdapter pDa = new SqliteDataAdapter(cmd);
  699. SqliteDataAdapter fDa = new SqliteDataAdapter(cmd);
  700. DataSet tmpDS = new DataSet();
  701. DataSet tmpDS2 = new DataSet();
  702. try
  703. {
  704. pDa.Fill(tmpDS, "users");
  705. fDa.Fill(tmpDS2, "userfriends");
  706. }
  707. catch (SqliteSyntaxException)
  708. {
  709. m_log.Info("[DATASTORE]: SQLite Database doesn't exist... creating");
  710. InitDB(conn);
  711. }
  712. conn.Open();
  713. try
  714. {
  715. cmd = new SqliteCommand("select webLoginKey from users limit 1;", conn);
  716. cmd.ExecuteNonQuery();
  717. }
  718. catch (SqliteSyntaxException)
  719. {
  720. cmd = new SqliteCommand("alter table users add column webLoginKey text default '00000000-0000-0000-0000-000000000000';", conn);
  721. cmd.ExecuteNonQuery();
  722. pDa.Fill(tmpDS, "users");
  723. }
  724. finally
  725. {
  726. conn.Close();
  727. }
  728. return true;
  729. }
  730. }
  731. }