Пример #1
0
        public void TestMethod2()
        {
            var method = typeof(Program).GetMethod("SetTitleBody", BindingFlags.Static | BindingFlags.NonPublic);
            var post   = new TelegramPost();

            method?.Invoke(obj: null, parameters: new Object[] { post, "title<br>body" });
        }
Пример #2
0
        /// <summary>
        /// Добавить сущность TelegramPost в базу без проверки на наличие.
        /// </summary>
        /// <param name="db"></param>
        /// <param name="channel"></param>
        /// <param name="post"></param>
        /// <returns></returns>
        public static TelegramPost AddTelegramPostToDb(Db db, TelegramChannel channel, TLMessage post)
        {
            //Добавить в базу сущность TelegramPost
            TelegramPost newPost = new TelegramPost()
            {
                ChannelTelegramId = channel.TelegramId,
                ChannelUsername   = channel.Username,
                TelegramId        = post.Id,
                WriteTime         = Const.StartDate.AddSeconds(post.Date),

                Content = post.Message ?? (post?.Media as TLMessageMediaPhoto)?.Caption ?? null,
            };

            if (post?.EditDate != null)
            {
                newPost.EditTime = Const.StartDate.AddSeconds((long)post.EditDate);
            }
            else
            {
                newPost.EditTime = Const.StartDate.AddSeconds((long)post.Date);
            }

            db.TelegramPosts.Add(newPost);
            db.SaveChanges();
            return(newPost);
        }
Пример #3
0
        public async Task SaveAsync(TelegramPost telegramPost)
        {
            if (telegramPost == null)
            {
                throw new ArgumentNullException(nameof(telegramPost));
            }
            if (telegramPost.AttachmentUri == null)
            {
                return;
            }

            switch (telegramPost.PostType)
            {
            case TelegramPostType.Text:
                break;

            case TelegramPostType.Photo:
                await SaveFileToFtpAsync(telegramPost);

                break;

            case TelegramPostType.Video:
                await SaveFileToFtpAsync(telegramPost);

                break;

            case TelegramPostType.File:
                throw new NotImplementedException();

            case TelegramPostType.Sticker:
                throw new NotImplementedException();
            }
        }
Пример #4
0
        /// <summary>
        /// Запускаем ежечасно, желательно в отдельном потоке, поставить приоритет потока на высокий, а потом выполнять параллельно.
        /// </summary>
        public void Process(object intChannelDelaySeconds)
        {
            this.RequestsDelaySeconds = (int)intChannelDelaySeconds;


            using (Db db = new Db(HelperDatabase.DB_OPTIONS))
            {
                //1) Взять из базы список всех каналов.
                List <TelegramChannel> channels = DbMethods.GetAllChannels(db);

                if (channels == null || channels.Count == 0)
                {
                    Debug.Error("Нет каналов в базе для сбора статистики!");
                    return;
                }

                //Thread.Sleep(this.RequestsDelaySeconds);
                Thread.Sleep(new Random(Convert.ToInt32(DateTime.Now.Ticks % 100000)).Next(10, 20) * 1000);

                //Запускаем цикл по каналам
                //Получить запросом канал Добавить в базу кол-во подписчиков канала на текущий час.

                foreach (var channel in channels)
                {
                    Debug.Log($"Берем статистику канала [{channel.Username}]");

                    var channelInfo = ChannelMethods.GetAllInfoChannel(GlobalVars.Client, channel.Username).Result;
                    DbMethods.AddStatisticsChannelToDb(db, channelInfo);


                    //Взять все посты у канала, через запрос.
                    var posts = ChannelMethods.GetAllPosts(GlobalVars.Client, channel.Username).Result;
                    foreach (var post in posts)
                    {
                        var p = post as TLMessage;

                        if (Equals(p, null))
                        {
                            continue;
                        }

                        //Если пост новый и еще не добавлен в базу, то добавить в базу.
                        TelegramPost telePost = DbMethods.AddTelegramPostIfNeed(db, channel, p);
                        DbMethods.AddStatisticsPostToDb(db, channel, p);
                    }

                    //Делаем задержку по времени, чтобы не банили запросы за превыщение лимита
                    //Берем данные по каналу, по его постам и делаем задержку.
                    //Thread.Sleep(this.RequestsDelaySeconds * 1000);
                    Thread.Sleep(new Random(Convert.ToInt32(DateTime.Now.Ticks % 100000)).Next(10, 20) * 1000);
                }

                Debug.Log("Сбор статистики завершен!");
            }
        }
Пример #5
0
        public void Save(TelegramPost telegramPost)
        {
            using (var file = File.CreateText(Path.Combine(_directory, $"{telegramPost.Id}.json")))
            {
                var serializer = new JsonSerializer();
                serializer.Serialize(file, telegramPost);
            }

            using (var file = File.CreateText(Path.Combine(_directory, $"{telegramPost.Id}.txt")))
            {
                file.Write(telegramPost.TextRaw);
            }
        }
Пример #6
0
        public async Task SaveAsync(TelegramPost telegramPost)
        {
            if (telegramPost == null)
            {
                throw new ArgumentNullException(nameof(telegramPost));
            }

            using (var ctx = new TelegtoolsContext())
            {
                ctx.TelegramPosts.Add(telegramPost);
                await ctx.SaveChangesAsync();
            }
        }
Пример #7
0
        public void Save(TelegramPost telegramPost)
        {
            if (telegramPost == null)
            {
                throw new ArgumentNullException(nameof(telegramPost));
            }

            using (var ctx = new TelegtoolsContext())
            {
                ctx.TelegramPosts.Add(telegramPost);
                ctx.SaveChanges();
            }
        }
Пример #8
0
        private string SavePath(TelegramPost post)
        {
            if (post?.AttachmentUri == null)
            {
                return(string.Empty);
            }
            var dotIndex = post.AttachmentUri.ToString().LastIndexOf('.');

            if (dotIndex == -1)
            {
                return(string.Empty);
            }
            var ext = post.AttachmentUri.ToString().Substring(dotIndex);

            return(Path.Combine(_directory, $"{post.Id}{ext}"));
        }
Пример #9
0
        public void GetPost_Test_01()
        {
            // Arrange
            PostsController controller = new PostsController();

            // Act
            Task <IHttpActionResult> task = controller.GetPost(ChannelName, 3);

            task.Wait();
            TelegramPost result =
                (task.Result as System.Web.Http.Results.OkNegotiatedContentResult <TelegramPost>)?.Content;

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(3, result.Id);
        }
Пример #10
0
        private string UploadPath(TelegramPost post)
        {
            if (post?.AttachmentUri == null)
            {
                return(string.Empty);
            }
            var dotIndex = post.AttachmentUri.ToString().LastIndexOf('.');

            if (dotIndex == -1)
            {
                return(string.Empty);
            }
            var ext = post.AttachmentUri.ToString().Substring(dotIndex);

            return($"/{post.Date.Year}/{post.Id}{ext}");
        }
Пример #11
0
        private async Task SaveFileToFtpAsync(TelegramPost telegramPost)
        {
            var path = UploadPath(telegramPost);
            var req  = WebRequest.Create(telegramPost.AttachmentUri);

            using (var response = req.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (stream != null)
                    {
                        //var image = Image.FromStream(stream);
                        await UploadFileToFtp(stream, path);
                    }
                }
            }
        }
Пример #12
0
        public void Save_A_TelegramPost_To_Database()
        {
            var post = new TelegramPost
            {
                Id            = 1,
                Author        = "a",
                Body          = "TEST",
                PossibleTitle = "T",
                DateString    = DateTime.Now.ToString(CultureInfo.InvariantCulture),
                ViewCount     = "0",
                WebRaw        = "<test>"
            };

            int actual;

            using (var ctx = new TelegtoolsContext())
            {
                ctx.TelegramPosts.Add(post);
                actual = ctx.SaveChanges();
            }

            Assert.AreEqual(1, actual);
        }
Пример #13
0
        public void Save(TelegramPost telegramPost)
        {
            if (string.IsNullOrWhiteSpace(telegramPost?.AttachmentUri?.AbsolutePath))
            {
                return;
            }

            var req = WebRequest.Create(telegramPost.AttachmentUri);

            using (var response = req.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    //var image = Image.FromStream(stream);
                    if (stream != null)
                    {
                        using (var file = File.Create(SavePath(telegramPost)))
                        {
                            stream.CopyTo(file);
                        }
                    }
                }
            }
        }
Пример #14
0
        public async void ImportPhone()
        {
            string       addr         = @"http://vadim.info/Content/Downloads/jgjhgayqo67yqre.json";
            TelegramPost telegramPost = new TelegramPost();



            var client = new HttpClient();



            client.BaseAddress = new Uri(addr);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync(addr);

            //                       ToTelegram("Authorization: " + ZadarmaApiConfig.key + ":" + fullQueryStr);

            if (response.IsSuccessStatusCode)
            {
                List <RootobjectPhoneItems> phones = await response.Content.ReadAsAsync <List <RootobjectPhoneItems> >();

                RootobjectPhoneItems tempPhoneModel;


                //                    telegramPost.MessagePostDirectBot(chatId, searhRezult.Count().ToString());
                try {
                    foreach (RootobjectPhoneItems phone in phones)
                    {
                        tempPhoneModel = new RootobjectPhoneItems {
                            //                            Id = phone.Id,
                            FirstName       = phone.FirstName,
                            LastName        = phone.LastName,
                            Organization    = phone.Organization,
                            PhoneStationary = phone.PhoneStationary,
                            PhoneHandheld   = phone.PhoneHandheld,
                            PhoneMobile     = phone.PhoneMobile,
                            email           = phone.email,
                            Service         = phone.Service,
                            Birthday        = phone.Birthday,
                            MiddleName      = phone.MiddleName
                        };


                        _context.RootobjectPhoneItems.Add(tempPhoneModel);
                        _context.Dispose();


                        //                        context.SaveChanges();
                        telegramPost.MessagePostDirectBot(ConfigTelegram.TestChatId, "Готово");
                    }
                }
                catch (Exception ex)
                {
                    await TelegramBot.Get().SendTextMessageAsync(ConfigTelegram.TestChatId, "Ошибка: " + ex.Message);
                }


                //                    telegramPost.MessageEditDirectBot(chatId, messageId, text);

                //                    telegramPost.MessagePostDirectBot(chatId, text);
            }
        }
Пример #15
0
 public Task SaveAsync(TelegramPost telegramPost)
 {
     throw new NotImplementedException();
 }
Пример #16
0
 public void Save(TelegramPost telegramPost)
 {
     throw new NotImplementedException();
 }
Пример #17
0
        public async Task GetPhone(long chatId, int messageId, string search)
        {
            string searchString = search.ToLower();

            string       addr         = @"http://vadim.info/Content/Downloads/jgjhgayqo67yqre.json";
            TelegramPost telegramPost = new TelegramPost();



            using (var client = new HttpClient())
            {
                CultureInfo cultureInfo = new CultureInfo("ru-RU");


                //                CultureInfo culture = new CultureInfo("ru-RU");

                client.BaseAddress = new Uri(addr);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                //                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("month=8"));
                //                telegramPost.MessageDirectBot("Authorization: ");

                // HTTP GET
                HttpResponseMessage response = await client.GetAsync(addr);

                //                       ToTelegram("Authorization: " + ZadarmaApiConfig.key + ":" + fullQueryStr);

                if (response.IsSuccessStatusCode)
                {
                    try {
                        List <RootobjectPhoneItems> phones = await response.Content.ReadAsAsync <List <RootobjectPhoneItems> >();

                        string text = "";

                        IEnumerable <RootobjectPhoneItems> searhRezult = phones
                                                                         .Where(e =>
                                                                                e.LastName.ToLower().Contains(searchString) ||
                                                                                e.FirstName.ToLower().Contains(searchString) ||
                                                                                e.MiddleName.ToLower().Contains(searchString) ||
                                                                                e.Service.ToLower().Contains(searchString) ||
                                                                                e.Organization.ToLower().Contains(searchString)

                                                                                ).OrderBy(e => e.LastName);

                        telegramPost.MessagePostDirectBot(chatId, "Найдено: " + searhRezult.Count().ToString());

                        Thread.Sleep(50);

                        foreach (RootobjectPhoneItems phone in searhRezult)
                        {
                            text = string.Format(
                                "<b>{0} {1}</b> \r\n"
                                + "{7}\r\n"

                                + "\r\n"
                                + "{2}"
                                //                           + "\r\n"
                                + "{3}"

                                + "{4}"
                                + "{5}"
                                + "{6}"
                                + "\r\n"
                                + "{8} \r\n"
                                //                          + "---------------------------------------- \r\n"
//  + phone.email
                                + "\r\n"

                                , phone.FirstName,
                                phone.LastName,
                                !(string.IsNullOrEmpty(phone.Organization))? "Компания: " + phone.Organization + "\r\n" : phone.Organization,
                                !(string.IsNullOrEmpty(phone.PhoneStationary)) ? "\U0000260E Стационарный телефон: " + phone.PhoneStationary + " \r\n" : phone.PhoneStationary,
                                phone.PhoneHandheld != null  ? "\U0001F4DE Переносная трубка: " + phone.PhoneHandheld + " \r\n" : null,
                                !(string.IsNullOrEmpty(phone.PhoneMobile)) ? "\U0001F4F1 +7" + phone.PhoneMobile + " \r\n" : phone.PhoneMobile,
                                !(string.IsNullOrEmpty(phone.email))? "\U00002709 " + phone.email : phone.email,
                                phone.Service,
                                !(string.IsNullOrEmpty(phone.Birthday)) ? "День рождения: " + (DateTime.Parse(phone.Birthday, cultureInfo)).ToString("d MMMM", cultureInfo) : phone.Birthday

                                );

                            Thread.Sleep(50);
                            telegramPost.MessagePostDirectBot(chatId, text);
                        }

                        //                    telegramPost.MessageEditDirectBot(chatId, messageId, text);

                        //                    telegramPost.MessagePostDirectBot(chatId, text);
                    }
                    catch (Exception ex)
                    {
                        await TelegramBot.Get().SendTextMessageAsync(ConfigTelegram.TestChatId, "Ошибка: " + ex.Message);
                    }
                }
            }
        }