Ejemplo n.º 1
0
        internal BotUser AddToCacheFail(int userId, string lang = "ru")
        {
            int usr_from_id = userId;
            var uname       = "@";
            //add to cache
            BotUser usr = new BotUser();

            usr.user_id = usr_from_id;
            usr.when_user_registered = DateTimeOffset.Now;
            //usr.user_id = user.GetValueOrDefault();
            usr.userName     = uname;
            usr.chat_id      = userId;
            usr.first_name   = "";
            usr.last_name    = "";
            usr.current_Lang = (lang == "en" ? Langs.En : (lang == "farsi" ? Langs.Farsi : Langs.Ru));
            usr.user_culture = (lang == "en" ? CultureInfo.InvariantCulture :
                                (lang == "farsi" ? CultureInfo.GetCultureInfo("fa-IR") : CultureInfo.GetCultureInfo("ru-RU")));
            //usr.current_Lang = (lang == "en" ? Langs.En : Langs.Ru);
            //usr.user_culture = (lang == "en" ? CultureInfo.InvariantCulture : CultureInfo.GetCultureInfo("ru-RU"));
            MainParams.cashedUsers.Add(usr);
            return(usr);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// find user in db by user_id (if no in cache!)
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        internal BotUser FindUserInDb(int userId)
        {
            BotUser usr = new BotUser();

            usr.current_Lang = Langs.En;
            usr.user_culture = CultureInfo.InvariantCulture;
            try
            {
                using (FCatsBotEntities Context = new FCatsBotEntities())
                {
                    var user = Context.users.Where(ussr => ussr.user_id == userId).FirstOrDefault();
                    if (user == null)
                    {
                        return(usr);
                    }


                    usr.user_id = Convert.ToInt32(user.user_id);
                    usr.when_user_registered = user.datetime_user_registered;
                    //usr.user_id = user.GetValueOrDefault();
                    usr.userName   = user.user_name_fix;
                    usr.chat_id    = user.chat_id;
                    usr.first_name = user.user_first_name;
                    var lang = user.user_lang_var;
                    usr.current_Lang = (lang == "en" ? Langs.En : (lang == "farsi" ? Langs.Farsi : Langs.Ru));
                    usr.user_culture = (lang == "en" ? CultureInfo.InvariantCulture :
                                        (lang == "farsi" ? CultureInfo.GetCultureInfo("fa-IR") : CultureInfo.GetCultureInfo("ru-RU")));
                    //usr.current_Lang = (user.user_lang_var == "en" ? Langs.En : Langs.Ru);
                    //usr.user_culture = (user.user_lang_var == "en" ? CultureInfo.InvariantCulture : CultureInfo.GetCultureInfo("ru-RU"));
                    MainParams.cashedUsers.Add(usr);
                }
            }
            catch (Exception ex)
            {
                MainParams.nlog.Debug("***NewLogs; FindUserInDb!!! ;EX=;" + ex.Message + ";Source=" + ex.Source + ";stack=" + ex.StackTrace + ";e.inner=" + ex.InnerException);
                MainParams.nlog.Debug(ex);
            }
            return(usr);
        }
Ejemplo n.º 3
0
        internal CatForVote getMostLikedCat(int userId)
        {
            CatForVote res       = new CatForVote();
            BotUser    cachedUsr = MainParams.cashedUsers.Find(user => user.user_id == userId);

            if (cachedUsr == null)
            {
                cachedUsr = MainParams.datebase.FindUserInDb(userId);
                MainParams.nlog.Debug("cachedUsr NULL in getMostLikedCat!!!userId=" + userId);
                if (cachedUsr == null)
                {
                    cachedUsr = AddToCacheFail(userId);
                }
            }

            try
            {
                using (FCatsBotEntities Context = new FCatsBotEntities())
                {
                    //02.09.2016 - search max liked not viewed cats!
                    var        arr_cats_viewed_by_this_user = Context.cats_viewed_by_users.Where(catviewed => catviewed.user_id == userId).ToList();
                    List <int> arrviewed = new List <int>();
                    foreach (var item in arr_cats_viewed_by_this_user)
                    {
                        arrviewed.Add(item.cat_id);
                    }
                    var cats_not_viewed = Context.cats.Where(cat => arrviewed.Contains(cat.id) == false).ToList();
                    //int index = rnd.Next(0, cats_not_viewed.Count - 1);
                    var maxlikes  = cats_not_viewed.Max(cts => cts.likes_count);
                    var found_cat = cats_not_viewed.Where(cts => cts.likes_count == maxlikes).First();
                    //add to cats_viewed
                    cats_viewed_by_users viewed = new cats_viewed_by_users();
                    viewed.cat_id          = found_cat.id;
                    viewed.viewed          = true;
                    viewed.user_id         = userId;
                    viewed.liked           = false;
                    viewed.disliked        = false;
                    viewed.datetime_viewed = DateTime.Now;
                    viewed.file_id         = found_cat.file_id;
                    Context.cats_viewed_by_users.Add(viewed);
                    var catmain = Context.cats.FirstOrDefault(catt => catt.id == found_cat.id);
                    catmain.views_count++;
                    Context.SaveChanges();
                    //fill result
                    res.fileid   = found_cat.file_id.Trim();
                    res.likes    = found_cat.likes_count;
                    res.dislikes = found_cat.dislikes_count;
                    res.views    = found_cat.views_count;
                    res.id       = found_cat.id;
                    res.user_id  = userId;
                    res.from_url = found_cat.from_url;
                    //var user = Context.users
                    res.caption = string.Format(strings.getCatCaption(cachedUsr), found_cat.id) + " " + string.Format(strings.getViews(cachedUsr), found_cat.views_count);
                }
            }
            catch (Exception e)
            {
                MainParams.nlog.Debug("***NewLogs; DATABASE getMostLikedCat!!! ;EX=;" + e.Message + ";Source=" + e.Source + ";stack=" + e.StackTrace + ";e.inner=" + e.InnerException);
                MainParams.nlog.Debug(e);
            }
            return(res);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// register new user and add it to cache
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="username"></param>
        /// <param name="lang">en or ru</param>
        /// <returns></returns>
        internal bool registerUser(int userid, Message msg, string lang = "ru")
        {
            bool registerOk = false;

            try
            {
                int usr_from_id = userid;

                using (FCatsBotEntities Context = new FCatsBotEntities())
                {
                    //check if user exists
                    bool isUserExist = isUserRegistered(usr_from_id);// Context.users.Any(user => user.user_id == usr_from_id);

                    if (isUserExist)
                    {
                        //updateChatId_OldUsers(userid, msg);


                        //Console.WriteLine("User with id=" + usr_from_id + " EXIST!");
                        //MainParams.nlog.Trace("User with id=" + usr_from_id + " EXIST!");
                        //await Bot.SendTextMessageAsync(message.Chat.Id, "User with id=" + usr_from_id + " EXIST!", replyMarkup: new ReplyKeyboardHide());
                        //return false;
                    }
                    else
                    {
                        var uname = msg.From.Username;
                        //add to cache
                        BotUser usr = new BotUser();
                        usr.user_id = usr_from_id;
                        usr.when_user_registered = DateTimeOffset.Now;
                        //usr.user_id = user.GetValueOrDefault();
                        usr.userName     = uname;
                        usr.chat_id      = msg.Chat.Id;
                        usr.first_name   = msg.From.FirstName;
                        usr.last_name    = msg.From.LastName;
                        usr.current_Lang = (lang == "en" ? Langs.En : (lang == "farsi" ? Langs.Farsi : Langs.Ru));
                        usr.user_culture = (lang == "en" ? CultureInfo.InvariantCulture :
                                            (lang == "farsi" ? CultureInfo.GetCultureInfo("fa-IR") : CultureInfo.GetCultureInfo("ru-RU")));
                        // usr.current_Lang = (lang == "en" ? Langs.En : Langs.Ru);
                        // usr.user_culture = (lang == "en" ? CultureInfo.InvariantCulture : CultureInfo.GetCultureInfo("ru-RU"));
                        MainParams.cashedUsers.Add(usr);
                        //add to db
                        users newRecord = new users();
                        //newRecord.user_lang_var
                        newRecord.datetime_user_registered = DateTime.Now;
                        newRecord.user_id         = usr_from_id;
                        newRecord.user_name_fix   = "@" + uname;
                        newRecord.user_lang_var   = lang;
                        newRecord.chat_id         = msg.Chat.Id == 0 ? usr_from_id : msg.Chat.Id;
                        newRecord.user_first_name = msg.From.FirstName == null ? "-" : msg.From.FirstName;
                        newRecord.user_last_name  = msg.From.LastName == null ? "-" : msg.From.LastName;

                        if (newRecord.user_last_name.Length > 99)
                        {
                            newRecord.user_last_name = newRecord.user_last_name.Substring(0, 99);
                        }
                        if (newRecord.user_first_name.Length > 99)
                        {
                            newRecord.user_first_name = newRecord.user_first_name.Substring(0, 99);
                        }

                        //newRecord.
                        //newRecord.
                        Context.users.Add(newRecord);
                        MainParams.nlog.Trace("User Username @" + uname + " Registered! userid=" + userid);
                        Context.SaveChanges();


                        registerOk = true;
                    }
                }
            }
            //catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
            //{
            //    try
            //    {
            //        MainParams.nlog.Trace("***!!!!!!!!***********DbEntityValidationException ***********!!!!!!!!!!");
            //        foreach (var error in dbex.EntityValidationErrors)
            //        {
            //            foreach (var ver in error.ValidationErrors)
            //            {
            //                MainParams.nlog.Trace(ver.ErrorMessage + "; PropertyName=" + ver.PropertyName);
            //            }
            //            MainParams.nlog.Trace(error.Entry);
            //        }
            //    }
            //    catch (Exception exqw)
            //    { }
            //    MainParams.nlog.Debug(dbex);
            //}
            catch (Exception ex)
            {
                MainParams.nlog.Debug("***NewLogs; DATABASE registerUser!!! ;EX=;" + ex.Message + ";Source=" + ex.Source + ";stack=" + ex.StackTrace + ";e.inner=" + ex.InnerException);
                MainParams.nlog.Debug(ex);
            }
            return(registerOk);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// fill users cache on startup
        /// </summary>
        internal void fillUsersOnStart()
        {
            try
            {
                using (FCatsBotEntities Context = new FCatsBotEntities())
                {
                    MainParams.nlog.Trace("USERS COUNT=" + Context.users.Count());
                    if (Context.users.Count() > 0)
                    {
                        //fill cache cycle
                        foreach (var user in Context.users)
                        {
                            BotUser usr = new BotUser();

                            usr.user_id = Convert.ToInt32(user.user_id);
                            usr.when_user_registered = user.datetime_user_registered;
                            //usr.user_id = user.GetValueOrDefault();
                            usr.userName   = user.user_name_fix;
                            usr.chat_id    = user.chat_id;
                            usr.first_name = user.user_first_name;

                            usr.current_Lang = (user.user_lang_var == "en" ? Langs.En : (user.user_lang_var == "farsi" ? Langs.Farsi :Langs.Ru));
                            usr.user_culture = (user.user_lang_var == "en" ? CultureInfo.InvariantCulture :
                                                (user.user_lang_var == "farsi" ? CultureInfo.GetCultureInfo("fa-IR") : CultureInfo.GetCultureInfo("ru-RU")));
                            MainParams.cashedUsers.Add(usr);
                        }
                        MainParams.nlog.Trace("Cache USERS OK");
                        try
                        {
                            var usList = Context.users.Where(usst => usst.chat_id < 0).ToList();
                            foreach (var user in usList)
                            {
                                if (string.IsNullOrEmpty(user.user_first_name))
                                {
                                    user.user_first_name = "-";
                                }
                                if (user.user_first_name.Length > 99)
                                {
                                    user.user_first_name = user.user_first_name.Substring(0, 99);
                                }

                                if (string.IsNullOrEmpty(user.user_last_name))
                                {
                                    user.user_last_name = "-";
                                }
                                if (user.user_last_name.Length > 99)
                                {
                                    user.user_last_name = user.user_last_name.Substring(0, 99);
                                }


                                //replace chat id cycle
                                //MainParams.nlog.Trace("ERROR in fillUsersOnStart chat_id <=0; chat_id=" + user.chat_id + "; userId =" + user.user_id);
                                user.chat_id = user.user_id;
                            }
                            Context.SaveChanges();
                            MainParams.nlog.Trace("change chat id USERS OK");
                        }
                        //DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors'
                        catch (System.Data.Entity.Validation.DbEntityValidationException e2)
                        {
                            MainParams.nlog.Debug("***NewLogs; DATABASE DbEntityValidationException");
                            foreach (var dberr in e2.EntityValidationErrors)
                            {
                                MainParams.nlog.Debug("entry id=" + ((users)dberr.Entry.Entity).id);
                                foreach (var entryError in dberr.ValidationErrors)
                                {
                                    MainParams.nlog.Debug("entryError=" + entryError.ErrorMessage + " prop=" + entryError.PropertyName);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MainParams.nlog.Debug("***NewLogs; DATABASE fillUsersOnStart REPLACE cycle ;EX=;" + ex.Message + ";Source=" + ex.Source + ";stack=" + ex.StackTrace + ";e.inner=" + ex.InnerException);
                            MainParams.nlog.Debug(ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MainParams.nlog.Debug("***NewLogs; DATABASE fillUsersOnStart!!! ;EX=;" + ex.Message + ";Source=" + ex.Source + ";stack=" + ex.StackTrace + ";e.inner=" + ex.InnerException);
                MainParams.nlog.Debug(ex);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// moderate jpg/png url.
        /// if has cat - process it to Telegram file id.
        /// </summary>
        /// <param name="url">jpg/png url</param>
        /// <param name="userid">user id</param>
        /// <param name="sendToUserid">send to user(true) or to moderator</param>
        /// <param name="curuser">user to send</param>
        /// <param name="fromUrl">we got pic from url (true) or from cat api (false)</param>
        /// <returns>ModerationResult</returns>
        internal async Task <ModerationResult> moderateWUrl(string url, int userid, bool sendToUserid = false, BotUser curuser = null, bool fromUrl = false)
        {
            try
            {
                var urlImage = url;
                using (var client = new HttpClient())
                {
                    string json = "";
                    MainParams.nlog.Trace("Moderation url=" + url);
                    ModerationResult res = new ModerationResult(json);
                    res = await doLabels(urlImage);

                    MainParams.picturesCurrentDay++;
                    //parse url and process it to fileid
                    if (res.HasCatOrKittenClass)
                    {
                        Stream imageBytes = await client.GetStreamAsync(url);

                        Telegram.Bot.Types.FileToSend fs = new Telegram.Bot.Types.FileToSend();
                        fs.Content = imageBytes;
                        Uri uri = new Uri(url);
                        fs.Filename = Path.GetFileName(uri.AbsolutePath);

                        if (!fs.Filename.EndsWith("jpg"))
                        {
                            fs.Filename = fs.Filename + ".jpg";
                        }

                        string fileid = "";
                        if (!sendToUserid)
                        {
                            //to create file id - send message to moderator
                            var mesToModerator = await MainParams.TGBot.SendPhotoAsync(MainParams.moderator_id, fs, "cat from url #" + MainParams.catFromUrl);

                            fileid = mesToModerator.Photo.Last().FileId;
                            MainParams.nlog.Trace("Mess to Moderator sent; url=" + url);
                        }
                        else
                        {
                            string ans = "";
                            if (fromUrl)
                            {
                                ans = strings.getCatFromUrl(curuser);
                            }
                            else
                            {
                                ans = strings.getCatFromApi(curuser);
                            }

                            var mesToUser = await MainParams.TGBot.SendPhotoAsync(curuser.chat_id, fs, ans);

                            fileid = mesToUser.Photo.Last().FileId;
                        }


                        MainParams.catFromUrl++;

                        //string tableid = MainParams.datebase.updateJson(fileid, res.ToStringNoNewline(), userid, res.maxCatScore);

                        //add to cats table and delete from moderation

                        MainParams.datebase.ok_from_moderation_url(fileid, res.ToStringNoNewline(), userid, (float)res.maxCatScore, url);
                        fs.Content.Close();
                        imageBytes.Close();
                    }
                    else
                    {
                        //if no cats..send to user anyway and to manual moderation
                        if (sendToUserid)
                        {
                            Stream imageBytes = await client.GetStreamAsync(url);

                            Telegram.Bot.Types.FileToSend fs = new Telegram.Bot.Types.FileToSend();
                            fs.Content = imageBytes;
                            Uri uri = new Uri(url);
                            fs.Filename = Path.GetFileName(uri.AbsolutePath);
                            string ans = "";
                            if (fromUrl)
                            {
                                ans = strings.getCatFromUrl(curuser);
                            }
                            else
                            {
                                ans = strings.getCatFromApi(curuser);
                            }
                            var mesToUser = await MainParams.TGBot.SendPhotoAsync(curuser.chat_id, fs, ans);

                            var fileid = mesToUser.Photo.Last().FileId;
                            //add to manual moderation
                            MainParams.datebase.add_to_moderation(curuser.user_id, fileid);
                        }
                    }

                    return(res);
                }
            }
            catch (Exception e)
            {
                MainParams.nlog.Debug(e);
                Console.WriteLine("Google error " + e.Message);
            }
            return(new ModerationResult(""));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// moderate jpg/png url.
        /// if has cat - process it to Telegram file id.
        /// </summary>
        /// <param name="url">jpg/png url</param>
        /// <param name="userid">user id</param>
        /// <param name="sendToUserid">send to user(true) or to moderator</param>
        /// <param name="curuser">user to send</param>
        /// <param name="fromUrl">we got pic from url (true) or from cat api</param>
        /// <returns>ModerationResult</returns>
        internal async Task <ModerationResult> moderateWUrl(string url, int userid, bool sendToUserid = false, BotUser curuser = null, bool fromUrl = false)
        {
            try
            {
                var urlImage = url;
                using (var client = new HttpClient())
                {
                    string json = "";
                    //System.Net.WebUtility.UrlEncode
                    string fileUrl = Uri.EscapeUriString(urlImage);
                    string wurl    = watson_URL + string.Format("?api_key={0}&version={1}&url={2}", watson_apikey, watson_version, fileUrl);
                    MainParams.nlog.Trace("INCOMING url=" + urlImage);
                    //MainParams.nlog.Trace("WATSON url=" + wurl);
                    var response = await client.GetAsync(wurl);

                    json = await response.Content.ReadAsStringAsync();

                    ModerationResult res = new ModerationResult(json);

                    var modelClassifyResponse = await response.Content.ReadAsAsync <ClassifyResponse>();

                    foreach (var img in modelClassifyResponse.Images)
                    {
                        foreach (var score in img.Scores)
                        {
                            foreach (var cres in score.ClassResults)
                            {
                                res.AddClassScore(cres.ClassId, cres.Score, cres.TypeHierarchy);
                            }
                        }
                    }

                    MainParams.nlog.Trace("WATSON picturesCurrentDay;" + MainParams.picturesCurrentDay + "; JSON;" + res.ToStringNoNewline());
                    Console.WriteLine("Watson OK url=" + url);
                    MainParams.picturesCurrentDay++;
                    //parse url and process it to fileid
                    if (res.HasCatOrKittenClass)
                    {
                        Stream imageBytes = await client.GetStreamAsync(url);

                        Telegram.Bot.Types.FileToSend fs = new Telegram.Bot.Types.FileToSend();
                        fs.Content = imageBytes;
                        Uri uri = new Uri(url);
                        fs.Filename = Path.GetFileName(uri.AbsolutePath);
                        string fileid = "";
                        if (!sendToUserid)
                        {
                            //to create file id - send message to moderator
                            var mesToModerator = await MainParams.TGBot.SendPhotoAsync(MainParams.moderator_id, fs, "cat from url #" + MainParams.catFromUrl);

                            fileid = mesToModerator.Photo.Last().FileId;
                            MainParams.nlog.Trace("Mess to Moderator sent; url=" + url);
                        }
                        else
                        {
                            string ans = "";
                            if (fromUrl)
                            {
                                ans = strings.getCatFromUrl(curuser);
                            }
                            else
                            {
                                ans = strings.getCatFromApi(curuser);
                            }

                            var mesToUser = await MainParams.TGBot.SendPhotoAsync(curuser.chat_id, fs, ans);

                            fileid = mesToUser.Photo.Last().FileId;
                        }


                        MainParams.catFromUrl++;

                        //string tableid = MainParams.datebase.updateJson(fileid, res.ToStringNoNewline(), userid, res.maxCatScore);

                        //add to cats table and delete from moderation

                        MainParams.datebase.ok_from_moderation_url(fileid, res.ToStringNoNewline(), userid, (float)res.maxCatScore, url);
                        fs.Content.Close();
                        imageBytes.Close();
                    }
                    else
                    {
                        //if no cats..send to user anyway and to manual moderation
                        if (sendToUserid)
                        {
                            Stream imageBytes = await client.GetStreamAsync(url);

                            Telegram.Bot.Types.FileToSend fs = new Telegram.Bot.Types.FileToSend();
                            fs.Content = imageBytes;
                            Uri uri = new Uri(url);
                            fs.Filename = Path.GetFileName(uri.AbsolutePath);
                            string ans = "";
                            if (fromUrl)
                            {
                                ans = strings.getCatFromUrl(curuser);
                            }
                            else
                            {
                                ans = strings.getCatFromApi(curuser);
                            }
                            var mesToUser = await MainParams.TGBot.SendPhotoAsync(curuser.chat_id, fs, ans);

                            var fileid = mesToUser.Photo.Last().FileId;
                            //add to manual moderation
                            MainParams.datebase.add_to_moderation(curuser.user_id, fileid);
                        }
                    }

                    return(res);
                }
            }
            catch (Exception e)
            {
                MainParams.nlog.Debug(e);
                Console.WriteLine("Watson error " + e.Message);
            }
            return(new ModerationResult(""));
        }
Ejemplo n.º 8
0
 internal static bool checkFileSize(Telegram.Bot.Types.File file, Update update, BotUser curUser)
 {
     try
     {
         //return true if file bigger 20 MB
         if (file.FileSize > (1024 * 1024 * 20))
         {
             return(true);
         }
     }
     catch
     {
         return(true);
     }
     return(false);
 }