SQLiteUserData.cs 33 KB

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