/// <summary>
        /// Gets a user setting from the database
        /// </summary>
        /// <typeparam name="T">The type the setting should be (bool, int, string)</typeparam>
        /// <param name="user">What user the setting comes from</param>
        /// <param name="field">The name of the setting</param>
        /// <param name="db">The database TelegramBotDbContext</param>
        /// <param name="def">The default value for the field</param>
        /// <returns></returns>
        public static T GetSetting <T>(this TelegramBotUser user, string field, TelegramBotDbContext db, object def)
        {
            //if (db.Connection.State != ConnectionState.Open)
            //    db.Connection.Open();
            ////verify settings exist
            //var columns = new SQLiteCommand("PRAGMA table_info(users)", db.Connection).ExecuteReader();
            //var t = default(T);

            //while (columns.Read())
            //{
            //    if (String.Equals(columns[1].ToString(), field))
            //    {
            //        var result = new SqliteCommand($"select {field} from users where ID = {user.ID}", db.Connection).ExecuteScalar();
            //        if (t != null && t.GetType() == typeof(bool))
            //        {
            //            result = (result.ToString() == "1"); //make it a boolean value
            //        }
            //        return (T)result;
            //    }
            //}
            //var type = "BLOB";
            //if (t == null)
            //    type = "TEXT";
            //else if (t.GetType() == typeof(int))
            //    type = "INTEGER";
            //else if (t.GetType() == typeof(bool))
            //    type = "INTEGER";

            //new SqliteCommand($"ALTER TABLE users ADD COLUMN {field} {type} DEFAULT {(type == "INTEGER" ? def : $"'{def}'")};", db.Connection)
            //    .ExecuteNonQuery();
            //return (T)def;
            throw new NotImplementedException();
        }
        private async Task <bool> ValidateUserCommand(User from, string command, Message message)
        {
            if (!Users.Contains(from.Id))
            {
                Logger.Info($"First message received from {from.Id}");
                var user = new TelegramBotUser(from);
                Users.Add(user);
                UnitOfWork.Do(u => u.Users.AddOrUpdate(user));
            }

            if (!commands.Keys.Contains(command))
            {
                return(true);
            }

            if (Settings.Instance.WhitelistMode && Users.Get(from.Id)?.Role < UserRole.Registered)
            {
                await RequestPurchase(message).ConfigureAwait(false);

                return(true);
            }

            if (Users.Get(from.Id)?.Role < commands[command].role)
            {
                await SendBlockText(message, $"You do not have access to {command}").ConfigureAwait(false);

                return(true);
            }

            return(false);
        }
Пример #3
0
        public static TelegramBotUser AddOrUpdate(
            this IList <TelegramBotUser> users,
            TelegramBotUser user
            )
        {
            if (users.Contains(user.Id))
            {
                users.Remove(users.Get(user.Id));
            }

            users.Add(user);

            return(user);
        }
        public static TelegramBotUser GetTarget(this Message message, string args, TelegramBotUser sourceUser, ITelegramBotDbContext db)
        {
            if (message == null)
            {
                return(sourceUser);
            }
            if (message?.ReplyToMessage != null)
            {
                var m      = message.ReplyToMessage;
                var userid = m.ForwardFrom?.Id ?? m.From.Id;
                return(db.TelegramBotUsers.AsNoTracking().FirstOrDefault(x => x.UserId == userid) ?? sourceUser);
            }
            if (String.IsNullOrWhiteSpace(args))
            {
                return(sourceUser);
            }
            //check for a user mention
            var  mention     = message?.Entities.FirstOrDefault(x => x.Type == MessageEntityType.Mention);
            var  textmention = message?.Entities.FirstOrDefault(x => x.Type == MessageEntityType.TextMention);
            long id          = 0;
            var  username    = "";

            if (mention != null)
            {
                username = message.Text.Substring(mention.Offset + 1, mention.Length - 1);
            }
            else if (textmention != null)
            {
                id = textmention.User.Id;
            }
            TelegramBotUser result = null;

            if (!String.IsNullOrEmpty(username))
            {
                result = db.TelegramBotUsers.AsNoTracking().FirstOrDefault(
                    x => x.UserName.ToUpper() == username.ToUpper());
            }
            else if (id != 0)
            {
                result = db.TelegramBotUsers.AsNoTracking().FirstOrDefault(x => x.UserId == id);
            }
            else
            {
                result = db.TelegramBotUsers.AsNoTracking().ToList().FirstOrDefault(
                    x =>
                    String.Equals(x.UserId.ToString(), args, StringComparison.InvariantCultureIgnoreCase) ||
                    String.Equals(x.UserName, args.Replace("@", ""), StringComparison.InvariantCultureIgnoreCase));
            }
            return(result ?? sourceUser);
        }
        public static void Save(this TelegramBotUser u, TelegramBotDbContext db)
        {
            if (u.ID == null || !ExistsInDb(u, db))
            {
                using (var tx = db.Database.BeginTransaction())
                {
                    try
                    {
                        db.Users.Add(u);
                        db.SaveChanges();
                        u.ID = db.Users.FirstOrDefault(c => c.UserId == u.UserId).ID;
                    }
                    catch { }
                }

                //db.Database.ExecuteSqlCommand(
                //    "insert into users (Name, UserId, UserName, FirstSeen, LastHeard, Points, Location, Debt, LastState, Greeting, Grounded, GroundedBy, IsBotAdmin, LinkingKey, Description) VALUES (@Name, @UserId, @UserName, @FirstSeen, @LastHeard, @Points, @Location, @Debt, @LastState, @Greeting, @Grounded, @GroundedBy, @IsBotAdmin, @LinkingKey, @Description)",
                //    u);
                //u.ID =
                //    db.Database.Query<int>(
                //        $"SELECT ID FROM Users WHERE UserId = @UserId", u)
                //        .First();
            }
            else
            {
                //using(var tx = db.Database.BeginTransaction())
                //{
                //    try
                //    {
                //        db.Users.Update(u);
                //        db.SaveChanges();
                //        tx.Commit();
                //    }
                //    catch { }
                //}

                //db.ExecuteNonQuery(
                //    "UPDATE users SET Name = @Name, UserId = @UserId, UserName = @UserName, FirstSeen = @FirstSeen, LastHeard = @LastHeard, Points = @Points, Location = @Location, Debt = @Debt, LastState = @LastState, Greeting = @Greeting, Grounded = @Grounded, GroundedBy = @GroundedBy, IsBotAdmin = @IsBotAdmin, LinkingKey = @LinkingKey, Description = @Description WHERE ID = @ID",
                //    u);
            }
        }
        /// <summary>
        /// Sets a user setting to the database
        /// </summary>
        /// <typeparam name="T">The type the setting should be (bool, int, string)</typeparam>
        /// <param name="user">What user the setting comes from</param>
        /// <param name="field">The name of the setting</param>
        /// <param name="db">The database TelegramBotDbContext</param>
        /// <param name="def">The default value for the field</param>
        /// <returns></returns>
        public static bool SetSetting <T>(this TelegramBotUser user, string field, TelegramBotDbContext db, object def, object value)
        {
            //try
            //{
            //    if (db.Connection.State != ConnectionState.Open)
            //        db.Connection.Open();
            //    //verify settings exist
            //    var columns = new SQLiteCommand("PRAGMA table_info(users)", db.Connection).ExecuteReader();
            //    var t = default(T);
            //    var type = "BLOB";
            //    if (t == null)
            //        type = "TEXT";
            //    else if (t.GetType() == typeof(int))
            //        type = "INTEGER";
            //    else if (t.GetType() == typeof(bool))
            //        type = "INTEGER";
            //    bool settingExists = false;
            //    while (columns.Read())
            //    {
            //        if (String.Equals(columns[1].ToString(), field))
            //        {
            //            settingExists = true;
            //        }
            //    }
            //    if (!settingExists)
            //    {
            //        new SQLiteCommand($"ALTER TABLE users ADD COLUMN {field} {type} DEFAULT {(type == "INTEGER" ? def : $"'{def}'")};", db.Connection)
            //            .ExecuteNonQuery();
            //    }

            //    new SQLiteCommand($"UPDATE users set {field} = {(type == "INTEGER" ? (t != null && t.GetType() == typeof(bool)) ? (bool)value ? "1" : "0" : value : $"'{value}'")} where ID = {user.ID}", db.Connection).ExecuteNonQuery();

            //    return true;
            //}
            //catch
            //{
            //    return false;
            //}
            throw new NotImplementedException();
        }
 public static void Save(this TelegramBotUser u, ITelegramBotDbContext db)
 {
     if (u.Id == 0 || !ExistsInDb(u, db))
     {
         try
         {
             db.TelegramBotUsers.Add(u);
             db.SaveChanges();
             u.Id = db.TelegramBotUsers.FirstOrDefault(c => c.UserId == u.UserId).Id;
         }
         catch { }
     }
     else
     {
         try
         {
             // db.Users.Update(u);
             //   db.SaveChanges();
         }
         catch (Exception e)
         {
         }
     }
 }
 public static void RemoveFromDb(this TelegramBotUser user, ITelegramBotDbContext db)
 {
     db.TelegramBotUsers.Remove(user);
     db.SaveChanges();
 }
 public static bool ExistsInDb(this TelegramBotUser user, ITelegramBotDbContext db)
 {
     return(db.TelegramBotUsers.AsNoTracking().Any(i => i.Id == user.Id));
 }