Exemplo n.º 1
0
        public void StartSearch(int interval)
        {
            SetTimer(interval);
            _timer.Start();

            foreach (var prefs in _usersContext.Preferences)
            {
                if (prefs.GroupId > 0 && !string.IsNullOrEmpty(prefs.Keyword))
                {
                    var keywords     = PrepareKeywords(prefs.Keyword);
                    var wallGeParams = new WallGetParams
                    {
                        Count   = 50,
                        OwnerId = -prefs.GroupId
                    };

                    var getResult = _api.Wall.Get(wallGeParams);
                    var posts     = getResult.WallPosts;

                    foreach (var post in posts)
                    {
                        var searchResult = _keywordSearcher.LookIntoPost(post, keywords);
                        if (!searchResult.Contains)
                        {
                            continue;
                        }
                    }
                }
            }
        }
Exemplo n.º 2
0
 public WallGetObject GetWallInfo(ParserParams @params)
 {
     try
     {
         long groupId;
         var  w_pars = new WallGetParams();
         if (long.TryParse(@params.Domain, out groupId))
         {
             w_pars.OwnerId = groupId;
         }
         else
         {
             w_pars.Domain = @params.Domain;
         }
         WallGetObject wall = api.Wall.Get(
             new WallGetParams
         {
             OwnerId = groupId,
             Count   = 0
         });
         return(wall);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
     return(null);
 }
Exemplo n.º 3
0
        public IEnumerable <Post> GetWallMessage(long userId, ulong offset = 0, int limit = 0)
        {
            ;
            var wallGetParams = new WallGetParams
            {
                OwnerId = userId,
                Count   = 100,
                Offset  = offset,
                Fields  = WallFilter.All
            };
            var response = _vkApi.Wall.Get(wallGetParams);
            var result   = new List <Post>();

            while ((response?.WallPosts?.Any() ?? false) && (limit == 0 || result.Count < limit))
            {
                result.AddRange(response.WallPosts);
                wallGetParams.Offset += 100;
                try
                {
                    Console.WriteLine(result.Count);
                    response = _vkApi.Wall.Get(wallGetParams);
                }
                catch
                {
                    response = null;
                }
            }

            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// This methods gets all posts from clients wall
        /// </summary>
        /// <returns> WallObject instance </returns>
        public virtual List <Post> GetAllPosts(DateTime timeFrom, DateTime timeTo)
        {
            List <Post>   curPosts   = new List <Post>();
            WallGetParams wallParams = new WallGetParams {
                OwnerId = VkId
            };

            try
            {
                WallGetObject wall = Api.Get().Wall.Get(wallParams, true);
                foreach (Post post in wall.WallPosts)
                {
                    var innerPosts = post.CopyHistory;
                    foreach (var innerPost in innerPosts)
                    {
                        if (innerPost.Date.Value.Date <= timeTo && post.Date.Value.Date >= timeFrom)
                        {
                            curPosts.Add(innerPost);
                        }
                    }
                    if (post.Date.Value.Date <= timeTo && post.Date.Value.Date >= timeFrom)
                    {
                        curPosts.Add(post);
                    }
                }
            }
            catch
            {
                // bug in library caused by generic casting
                // https://github.com/vknet/vk/pull/744
            }

            return(curPosts);
        }
Exemplo n.º 5
0
		public WallGetObject Get(WallGetParams @params)
		{
			if (@params.Filter != null && @params.Filter == WallFilter.Suggests && @params.OwnerId >= 0)
			{
				throw new ArgumentException("OwnerID must be negative in case filter equal to Suggests", "ownerId");
			}

			return _vk.Call("wall.get", @params, @params.Filter != WallFilter.Suggests && @params.Filter != WallFilter.Postponed);
		}
Exemplo n.º 6
0
        public WallGetObject Get(WallGetParams @params)
        {
            if (@params.Filter != null && @params.Filter == WallFilter.Suggests && @params.OwnerId >= 0)
            {
                throw new ArgumentException("OwnerID must be negative in case filter equal to Suggests", "ownerId");
            }

            return(_vk.Call("wall.get", @params, true));           //, @params.Filter != WallFilter.Suggests && @params.Filter != WallFilter.Postponed);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Возвращает список записей со стены пользователя или сообщества.
        /// </summary>
        /// <param name="params">Входные параметры.</param>
        /// <param name="skipAuthorization">Если <c>true</c>, то пропустить авторизацию</param>
        /// <returns>
        /// В случае успеха возвращается запрошенный список записей со стены.
        /// </returns>
        /// <exception cref="System.ArgumentException">OwnerID must be negative in case filter equal to Suggests;ownerId</exception>
        /// <remarks>
        /// Страница документации ВКонтакте http://vk.com/dev/wall.get
        /// </remarks>
        public WallGetObject Get(WallGetParams @params, bool skipAuthorization = false)
        {
            if (@params.Filter != null && @params.Filter == WallFilter.Suggests && @params.OwnerId >= 0)
            {
                throw new ArgumentException("OwnerID must be negative in case filter equal to Suggests", nameof(@params));
            }

            return(_vk.Call("wall.get", @params, skipAuthorization));//, @params.Filter != WallFilter.Suggests && @params.Filter != WallFilter.Postponed);
        }
Exemplo n.º 8
0
        public List <PostDomain> GetLastPosts(string authorId, ulong postsCount)
        {
            User  user  = null;
            Group group = null;

            try
            {
                user = VkApi.Users
                       .Get(new List <string> {
                    authorId
                })
                       .First();
            }
            catch (InvalidUserIdException)
            {
                try
                {
                    group = VkApi.Groups
                            .GetById(null, authorId, null)
                            .First();
                }
                catch (VkApiException)
                {
                    return(null);
                }
            }

            var authorName    = user == null ? group.Name : $"{user.FirstName} {user.LastName}";
            var wallGetParams = new WallGetParams
            {
                // Для группы идентификатор сохраняется со знаком '-'
                OwnerId = user?.Id ?? -group.Id,
                Count   = postsCount,
                Filter  = WallFilter.Owner
            };

            WallGetObject wallGetObject;

            try
            {
                wallGetObject = VkApi.Wall.Get(wallGetParams);
            }
            catch (VkApiException)
            {
                return(null);
            }

            return(wallGetObject
                   .WallPosts
                   .Select(post => new PostDomain(authorId, authorName, post.Text))
                   .ToList());
        }
Exemplo n.º 9
0
        public List <Post> GetPostsBeforeDT(ParserParams @params, DateTime time, ulong offset = 0)
        {
            List <Post> posts = new List <Post>();

            try
            {
                long          groupId;
                WallGetObject wall;
                var           w_pars = new WallGetParams();
                if (long.TryParse(@params.Domain, out groupId))
                {
                    w_pars.OwnerId = groupId;
                }
                else
                {
                    w_pars.Domain = @params.Domain;
                }
                w_pars.Count = 100;

                for (ulong i = 0;; i += 100)
                {
                    w_pars.Offset = offset + i;
                    wall          = api.Wall.Get(w_pars);

                    if (wall.WallPosts.Count == 0)
                    {
                        return(posts);
                    }
                    foreach (var p in wall.WallPosts)
                    {
                        if (p.Date <= time)
                        {
                            return(posts);
                        }
                        posts.Add(
                            new Post(
                                p.Reposts == null ? 0 : p.Reposts.Count,
                                p.Likes == null ? 0 : p.Likes.Count,
                                p.Views == null ? 0 : p.Views.Count,
                                p.Comments == null ? 0 : p.Comments.Count,
                                p.Date.Value
                                ));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return(posts);
        }
Exemplo n.º 10
0
        public IEnumerable <string> GetPosts(int count, string userId)
        {
            Authorize();

            var parameters = new WallGetParams()
            {
                Domain = userId,
                Count  = (ulong)count
            };
            var posts  = _api.Wall.Get(parameters);
            var result = posts.WallPosts.Select(p => p.Text);

            return(result);
        }
Exemplo n.º 11
0
        void SaveLikesFromPostToFile(long GroupID, long PostID, FileStream fstream)
        {
            int AllLikesCount = 0;

            WallGetParams wallParam = new WallGetParams();

            wallParam.OwnerId = GroupID;
            wallParam.Count   = maxPostFromVkDatabase;


            WallGetObject wallObjects = vkApi.Wall.Get(wallParam);



            foreach (var post_it in wallObjects.WallPosts)
            {
                AllLikesCount = post_it.Likes.Count;
                if (post_it.Id != PostID)
                {
                    continue;
                }

                LikesGetListParams likeParams = new LikesGetListParams();
                likeParams.Type     = LikeObjectType.Post;
                likeParams.ItemId   = PostID;
                likeParams.Extended = true;
                likeParams.OwnerId  = GroupID;
                likeParams.Count    = 1000;

                uint i = 0;
                while (AllLikesCount > 0) // выбираем по 1000 id(максимум)
                {
                    VkCollection <long> likes = vkApi.Likes.GetList(likeParams);
                    foreach (var itLike in likes)
                    {
                        PrintFoFile(fstream, itLike.ToString()); //запись каждого id  в файл
                    }
                    AllLikesCount -= (int)maxSingleOffser;
                    i++;
                    likeParams.Offset = i * maxSingleOffser; // увеличиваем каждый раз смещение
                    Thread.Sleep(300);                       // чтобы избежать "Too many requests per second
                }


                Console.WriteLine(post_it.Likes.Count);
                Console.WriteLine(AllLikesCount);
                ;
            }
        }
Exemplo n.º 12
0
        private static Post GetLatestPost(VkApi api, ApiConfiguration apiConfiguration)
        {
            var wallGetParams = new WallGetParams
            {
                Domain = apiConfiguration.TargetGroup,
                Count  = WallGetCount,
                Offset = WallGetOffset,
                Filter = WallFilter.All
            };

            WallGetObject getResult  = api.Wall.Get(wallGetParams);
            Post          latestPost = getResult.WallPosts.FirstOrDefault(x => !x.IsPinned.HasValue || !x.IsPinned.Value);

            return(latestPost);
        }
Exemplo n.º 13
0
        SortedSet <long> SaveUsersIDFromPostToList(long GroupID, long PostID)
        {
            SortedSet <long> UsersID = new SortedSet <long>();
            int AllLikesCount        = 0;

            WallGetParams wallParam = new WallGetParams();

            wallParam.OwnerId = GroupID;
            wallParam.Count   = maxPostFromVkDatabase;


            WallGetObject wallObjects = vkApi.Wall.Get(wallParam);



            foreach (var post_it in wallObjects.WallPosts)
            {
                AllLikesCount = post_it.Likes.Count;
                if (post_it.Id != PostID)
                {
                    continue;
                }

                LikesGetListParams likeParams = new LikesGetListParams();
                likeParams.Type     = LikeObjectType.Post;
                likeParams.ItemId   = PostID;
                likeParams.Extended = true;
                likeParams.OwnerId  = GroupID;
                likeParams.Count    = 1000;

                uint i = 0;
                while (AllLikesCount > 0) // выбираем по 1000 id(максимум)
                {
                    VkCollection <long> likes = vkApi.Likes.GetList(likeParams);

                    foreach (var itLike in likes)
                    {
                        UsersID.Add(itLike);
                    }
                    AllLikesCount -= (int)maxSingleOffser;
                    i++;
                    likeParams.Offset = i * maxSingleOffser; // увеличиваем каждый раз смещение
                    Thread.Sleep(300);                       // чтобы избежать "Too many requests per second
                }
            }
            return(UsersID);
        }
Exemplo n.º 14
0
        public List <Post> GetPosts(ParserParams @params, ulong offset = 0)
        {
            List <Post> posts = new List <Post>();

            try
            {
                long          groupId;
                WallGetObject wall;
                var           w_pars = new WallGetParams();
                if (long.TryParse(@params.Domain, out groupId))
                {
                    w_pars.OwnerId = groupId;
                }
                else
                {
                    w_pars.Domain = @params.Domain;
                }

                for (ulong i = 0; i < @params.Count; i += 100)
                {
                    w_pars.Count  = Math.Min(@params.Count - i, 100);
                    w_pars.Offset = offset + i;
                    wall          = api.Wall.Get(w_pars);
                    try
                    {
                        posts.AddRange(wall.WallPosts.Select(x =>
                                                             new Post(
                                                                 x.Reposts.Count,
                                                                 x.Likes.Count,
                                                                 // x.Views.Count,
                                                                 x.Comments.Count,
                                                                 x.Date.Value
                                                                 )));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return(posts);
        }
Exemplo n.º 15
0
        int GetNumberOfComments(long PostID)
        {
            WallGetParams wallGetParams = new WallGetParams();

            wallGetParams.OwnerId = chosenGroup().groupID;
            wallGetParams.Count   = ulong.Parse(numberOfPosts.Text);
            WallGetObject wallObjects = vkApi.Wall.Get(wallGetParams);

            foreach (var post_it in wallObjects.WallPosts)
            {
                if (post_it.Id == PostID)
                {
                    return(post_it.Comments.Count);
                }
            }
            return(-1);
        }
Exemplo n.º 16
0
        public async Task <IEnumerable <PostInfo> > GetLastPostInfoAsync(string username, ulong countPost)
        {
            var userId = await base.GetUserId(username);

            var requestParams = new WallGetParams()
            {
                Count   = countPost,
                OwnerId = userId
            };

            var response = await api.Wall.GetAsync(requestParams);

            return(response.WallPosts.Select(p => new PostInfo()
            {
                Text = p.Text
            }).ToList());
        }
Exemplo n.º 17
0
        public List <Post> GetPostsByGroupId(long groupId, VkApi api, ulong?count = null)
        {
            var   posts = new List <Post>();
            ulong step  = 100;

            if (count < step)
            {
                step = count.Value;
            }
            ulong offset     = 0;
            ulong totalCount = 0;

            do
            {
                try
                {
                    var param = new WallGetParams()
                    {
                        OwnerId = -groupId,
                        Filter  = WallFilter.Owner,
                        Count   = step,
                        Offset  = offset,
                    };
                    var getResult  = api.Wall.Get(param);
                    var postsChunk = getResult.WallPosts.Select(p => p).ToList();
                    posts.AddRange(postsChunk);
                    offset       = offset + step;
                    param.Offset = offset;
                    totalCount   = getResult.TotalCount;
                    Console.Clear();
                    Console.WriteLine($"Total posts count {posts.Count}.");
                }
                catch
                {
                    offset = offset + 1;
                }
            } while (!count.HasValue ? offset < totalCount : offset < count.Value);

            var orderredPosts = posts.Where(p => p.Likes != null && p.Likes.Count > 0)
                                .OrderByDescending(p => p.Date)
                                .ThenByDescending(p => p.Likes.Count)
                                .ToList();

            return(orderredPosts);
        }
Exemplo n.º 18
0
        public static ReadOnlyCollection <Post> GetPosts(this IVkApi vkApi, string id, int postCount)
        {
            var wallGetParams = new WallGetParams {
                Count = (ulong)postCount
            };

            if (long.TryParse(id, out var ownerId))
            {
                wallGetParams.OwnerId = ownerId;
            }
            else
            {
                var vkObj = vkApi.Utils.ResolveScreenName(id);
                wallGetParams.OwnerId = vkObj?.Id ?? throw new Exception("Invalid screen name (id).");
            }

            return(vkApi.Wall.Get(wallGetParams).WallPosts);
        }
Exemplo n.º 19
0
        private void ShowPostsButton_Click(object sender, EventArgs e)
        {
            Posts.Name = "Posts";
            Posts.Rows.Clear();
            this.Controls.Add(Posts);
            Posts.ColumnCount = 2;

            Posts.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy;
            Posts.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            Posts.ColumnHeadersDefaultCellStyle.Font      = new Font(Posts.Font, FontStyle.Bold);
            Posts.AutoSizeRowsMode         = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
            Posts.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
            Posts.CellBorderStyle          = DataGridViewCellBorderStyle.Single;
            Posts.GridColor         = Color.Black;
            Posts.RowHeadersVisible = false;
            Posts.Columns[0].Name   = "Post ID";
            Posts.Columns[1].Name   = "Text";

            try
            {
                uint          AllLikesCount = 0;
                WallGetParams wallParam     = new WallGetParams();
                wallParam.OwnerId = chosenGroup().groupID;
                wallParam.Count   = ulong.Parse(numberOfPosts.Text);


                WallGetObject wallObjects = vkApi.Wall.Get(wallParam);

                foreach (var post_it in wallObjects.WallPosts)
                {
                    AllLikesCount = (uint)post_it.Likes.Count;
                    long     PostID = long.Parse(post_it.Id.ToString());
                    string[] row    = { PostID.ToString(), post_it.Text };
                    Posts.Rows.Add(row);
                }


                Posts.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

                Posts.Columns[0].Width = 60;
                Posts.Columns[1].Width = 360;
            }
            catch (Exception except) { MessageBox.Show(except.Message, "Error!\n"); }
        }
Exemplo n.º 20
0
        public IEnumerable <Post> GetPosts()
        {
            WallGetParams parametrs = new WallGetParams
            {
                OwnerId = -72869598
            };

            try
            {
                VkNet.Model.WallGetObject posts = new VkNet.Model.WallGetObject();
                parametrs.Count = api.Wall.Get(parametrs).TotalCount - db.Count.TotalCount;
                if (parametrs.Count > 0)
                {
                    posts    = api.Wall.Get(parametrs);
                    db.Count = new TotalCountPosts {
                        Id           = 0
                        , TotalCount = db.Count.TotalCount + parametrs.Count
                    };
                }
                if (posts.WallPosts.Count != 0)
                {
                    foreach (var el in posts.WallPosts)
                    {
                        Post post = new Post
                        {
                            Id              = el.Id,
                            Date            = el.Date,
                            Message         = el.Text,
                            LastConfirmDate = el.Date
                        };
                        if (!db.GetAll().Where(x => x.Date == x.Date).Where(x => x.Message.Equals(post.Message)).Any())
                        {
                            System.Console.WriteLine(post.Message);
                            db.Add(post);
                        }
                    }
                }
                return(db.Get());
            }
            catch
            {
                return(db.Get());
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Загружаем посты из ВК
        /// </summary>
        /// <returns></returns>
        internal async Task <IEnumerable <Notice> > GetNotices()
        {
            var result = new List <Notice>();
            var g      = groups.SelectMany(x => x.Value).Distinct();

            foreach (long groupId in g)
            {
                WallGetParams getParams = new WallGetParams()
                {
                    OwnerId = groupId,
                    Count   = 10,
                };

                var wallGetObjects = await api.Wall.GetAsync(getParams);

                foreach (Post item in wallGetObjects.WallPosts)
                {
                    if (IsNew(item))
                    {
                        List <string> photos = new List <string>();
                        foreach (var atch in item.Attachments)
                        {
                            if (atch.Type.Name == "Photo")
                            {
                                photos.Add(GetPhotoUrl($"{groupId}_{atch.Instance.Id}_{atch.Instance.AccessKey}"));
                            }
                        }

                        result.Add(new Notice()
                        {
                            Id        = (long)item.Id,
                            GroupId   = groupId,
                            FullText  = item.Text,
                            Date      = item.Date,
                            Source    = 0,
                            Url       = $"https://vk.com/wall{groupId}_{item.Id}",
                            PhotosUrl = photos,
                        });
                    }
                }
            }

            return(result);
        }
Exemplo n.º 22
0
        private void btnGetWall_Click(object sender, RoutedEventArgs e)
        {
            listGet.Clear();
            chkAll.IsChecked = false;
            int key         = GetPeopleList.FirstOrDefault(x => x.Value == (string)cmbFri.Text).Key;
            var _wallParams = new WallGetParams();

            _wallParams.OwnerId = key;
            int offset = 0;

            _wallParams.Count = 100;
            var _wall = App.AuthPublic.Wall.Get(_wallParams);

            foreach (var w in _wall.WallPosts)
            {
            }

            var _user = new User();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Получение последних postsCount постов со страницы пользователя/группы.
        /// </summary>
        /// <param name="identifier"></param>
        /// <returns></returns>
        public IEnumerable <string> GetLastPosts(string identifier)
        {
            var searchParams = new WallGetParams();

            // если передан цифровой идентификатор - ищем по нему
            if (Parser.TryGetId(identifier, out long longId))
            {
                searchParams.OwnerId = longId;
            }
            // иначе - по короткому адресу
            else
            {
                searchParams.Domain = identifier;
            }

            var wall = _vkApi.Wall.Get(searchParams);

            return(wall.WallPosts.OrderByDescending(post => post.Date).Take(Configuration.PostCount).Select(p => p.Text).ToList());
        }
Exemplo n.º 24
0
        public List <Post> GetPostsByGroupId(long groupId, VkApi api, DateTime minDate)
        {
            var         posts        = new List <Post>();
            const ulong step         = 100;
            ulong       offset       = 0;
            ulong       totalCount   = 0;
            DateTime?   lastPostDate = null;

            do
            {
                try
                {
                    var param = new WallGetParams
                    {
                        OwnerId = -groupId,
                        Filter  = WallFilter.Owner,
                        Count   = step,
                        Offset  = offset,
                    };
                    var getResult  = api.Wall.Get(param);
                    var postsChunk = getResult.WallPosts.Select(p => p).ToList();
                    posts.AddRange(postsChunk);
                    offset      += step;
                    param.Offset = offset;
                    totalCount   = getResult.TotalCount;
                    Console.Write("\r{0}  ", $"Total posts count {posts.Count}.");
                    var lastPost = posts.OrderByDescending(p => p.Date).Last();
                    lastPostDate = lastPost.Date;
                }
                catch
                {
                    offset += 1;
                }
            } while (offset < totalCount && lastPostDate > minDate);

            var orderedPosts = posts
                               .OrderByDescending(p => p.Date)
                               .ToList();

            return(orderedPosts);
        }
Exemplo n.º 25
0
        private async Task <PostsCollection> LoadWallPosts()
        {
            long            latestOldPostId = -1;
            PostsCollection res             = new PostsCollection();
            int             loadCount       = FirstLoadCount; // TODO: how to calculate

            var getParams = new WallGetParams()
            {
                OwnerId = _model.WallId
            };
            WallGetObject wallGetRes = null;


            _api.Wall.Get(getParams);


            DownloadingPostsOptions downloadingPostsOptions = new DownloadingPostsOptions(_model.WallId, loadInFirstCount, WallFilter.All, _wallWatcherOptions.TimeForReconnecting);

            // если _prePublishedList пустой, то грузим не до самого нового имющегося поста (так как его у нас нет), а за MonitoringLimits(период и/или количество)
            if (!_postsProvider.AnyExistingPosts(_model.WallId, _publishedType, 0))
            {
                List <Post> publishedPosts = _api.Wall.GetPosts(_logger, downloadingPostsOptions, _model.MonitoringLimits);
                res.AddPosts(publishedPosts);
            }
            else
            {
                res.AddPosts(GetNewAndOldPublishedPosts(downloadingPostsOptions, out latestOldPostId));
            }

            // Download suggests and postpone
            downloadingPostsOptions.CountInFirstLoad = MaxLoadCount;
            downloadingPostsOptions.WallFilter       = WallFilter.Suggests;
            res.AddPosts(_api.Wall.GetPosts(_logger, downloadingPostsOptions));
            downloadingPostsOptions.WallFilter = WallFilter.Postponed;
            res.AddPosts(_api.Wall.GetPosts(_logger, downloadingPostsOptions));
            return(res);
        }
Exemplo n.º 26
0
 /// <inheritdoc />
 public Task <WallGetObject> GetAsync(WallGetParams @params, bool skipAuthorization = false)
 {
     return(TypeHelper.TryInvokeMethodAsync(func: () => Get(@params: @params, skipAuthorization: skipAuthorization)));
 }
Exemplo n.º 27
0
 public List <Post> GetWallPosts(WallGetParams prms)
 {
     RaiseLog(LogSeverity.Debug, "GetWallPosts request");
     return(new List <Post>(_vkApi.Wall.Get(prms).WallPosts));
 }
Exemplo n.º 28
0
 /// <summary>
 /// Returns a list of posts on a user wall or community wall.
 /// </summary>
 /// <param name="methodParams">A <see cref="WallGetParams"/> object with the params.</param>
 /// <returns>Returns a <see cref="List{T}"/> of <see cref="Post"/> objects.</returns>
 public async Task<Response<ItemsList<Post>>> Get(WallGetParams methodParams)
     => await Request<ItemsList<Post>>("get", methodParams, true);
Exemplo n.º 29
0
        /// <summary>
        /// Returns vkontakte posts by community groups
        /// </summary>
        /// <returns>
        /// Returns a list of vkontakte posts.
        /// </returns>
        internal static async Task <List <ISocialPost> > GetAsync(VkontakteSettings vkontakteSettings, Dictionary <string, byte> communities)
        {
            var result = new List <VkontaktePost>();

            try
            {
                using var api = new VkApi();
                api.Authorize(new ApiAuthParams
                {
                    AccessToken = vkontakteSettings.ServiceKey
                });

                _communityGroups = (await api.Groups.GetByIdAsync(communities.Select(x =>
                {
                    if (long.TryParse(x.Key, out var groupId))
                    {
                        return(Math.Abs(groupId).ToString());
                    }

                    return(x.Key);
                }), null, GroupsFields.All)).ToList();

                foreach (var communityGroup in communities)
                {
                    try
                    {
                        var wallGetParams = new WallGetParams {
                            Count = communityGroup.Value
                        };
                        if (long.TryParse(communityGroup.Key, out var groupId))
                        {
                            wallGetParams.OwnerId = groupId;
                        }
                        else
                        {
                            wallGetParams.Domain = communityGroup.Key;
                        }

                        var wall = await api.Wall.GetAsync(wallGetParams);

                        var communityGroupPosts = wall?.WallPosts;
                        if (communityGroupPosts != null)
                        {
                            result.AddRange(communityGroupPosts.Select(communityGroupPost => GetVkontaktePost(communityGroupPost, communityGroup.Key)));
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.LogError(e, "Unhandled error while getting original vkontakte posts");
                    }
                }

                var postsWithoutDuplicates = result.GroupBy(p => p.PostId).Select(g => g.First()).ToList();

                // remove reposted duplicates
                var postIds = postsWithoutDuplicates.Select(x => x.PostId).ToList();
                for (int i = 0; i < postsWithoutDuplicates.Count; i++)
                {
                    if (postsWithoutDuplicates[i].CopyHistory.Select(x => x.PostId).Intersect(postIds).Any())
                    {
                        postsWithoutDuplicates.RemoveAt(i);
                    }
                }

                //ToDo: exclude duplicates for reposted posts!
                // fill posts with empty Text, PostedImage and PostedVideo from CopyHistory
                foreach (var post in postsWithoutDuplicates)
                {
                    if (string.IsNullOrWhiteSpace(post.Text) && post.CopyHistory.Any() && string.IsNullOrWhiteSpace(post.PostedImage) && post.PostedVideo == null)
                    {
                        post.Text = $"Reposted: {GetPostText(post)}";
                    }
                }

                // set correct name for posts from user
                var users = await api.Users.GetAsync(postsWithoutDuplicates
                                                     .Where(x => x.OwnerId != null && x.FromId != null && x.OwnerId != x.FromId)
                                                     .Select(x => x.FromId.ToString()));

                foreach (var post in postsWithoutDuplicates.Where(x => x.OwnerId != null && x.FromId != null && x.OwnerId != x.FromId))
                {
                    var user = users.FirstOrDefault(x => x.Id == post.FromId);
                    if (user?.LastName != null)
                    {
                        post.Name = $"{user.FirstName} {user.LastName}";
                    }
                }

                var sortedPosts = postsWithoutDuplicates.OrderByDescending(x => x.CreatedDate).Cast <ISocialPost>().ToList();

                return(sortedPosts);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Unhandled error while getting original vkontakte posts");
            }

            return(new List <ISocialPost>());
        }
Exemplo n.º 30
0
 /// <inheritdoc />
 public async Task <WallGetObject> GetAsync(WallGetParams @params, bool skipAuthorization = false)
 {
     return(await TypeHelper.TryInvokeMethodAsync(() => _vk.Wall.Get(@params, skipAuthorization)));
 }
Exemplo n.º 31
0
        public async Task <List <Post> > GetUserWallPostsViaWallGetAsync(User user)
        {
            List <Post> result = new List <Post>();

            ulong maxPostsBatch = 100;
            ulong postsOffset   = 0;
            bool  postsFinished = false;
            // community with dash
            //long targetGroup = -83415396;
            // user
            long targetObject = user.Id;

            while (!postsFinished)
            {
                WallGetParams wallGetParams = new WallGetParams
                {
                    OwnerId = targetObject,
                    //wallGetParams.Fields = GroupsFields.All;
                    Filter   = WallFilter.Owner,
                    Offset   = postsOffset,
                    Extended = false,
                    Count    = maxPostsBatch
                };

                WallGetObject requestResult = new WallGetObject();

                try
                {
                    // ограничение 5000 запросов в день
                    requestResult = await ServiceApi.Wall.GetAsync(wallGetParams);
                }
                catch (CannotBlacklistYourselfException e)
                {
                    //10361 - неизвестная проблема, пользователь закрыл все посты
                    Console.WriteLine("Error getting wall posts via VK API: " + e);
                }
                catch (NullReferenceException e)
                {
                    //336185 - неизвестная проблема, Audioplaylist
                    Console.WriteLine("Error getting wall posts via VK API: " + e);
                }
                catch (RateLimitReachedException e)
                {
                    Console.WriteLine("Error getting wall posts via VK API: " + e);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error getting wall posts via VK API: " + e);
                }

                if (requestResult.WallPosts != null)
                {
                    result.AddRange(requestResult.WallPosts);

                    if (requestResult.WallPosts.Count < (int)maxPostsBatch)
                    {
                        postsFinished = true;
                    }
                    else
                    {
                        postsOffset = (ulong)result.Count;
                    }
                }
                else
                {
                    postsFinished = true;
                }
            }

            return(result);
        }
Exemplo n.º 32
0
        public void DoSearch()
        {
            using (var usersContext = _serviceProvider.GetRequiredService <IUsersContext>())
            {
                var allPrefs = usersContext.Preferences.Include(u => u.User);
                foreach (var prefs in allPrefs)
                {
                    try
                    {
                        if (!ValidForSearch(prefs))
                        {
                            continue;
                        }

                        var keywords     = PrepareKeywords(prefs.Keyword);
                        var wallGeParams = new WallGetParams
                        {
                            Count   = 50,
                            OwnerId = prefs.TargetType == PreferenceType.VkGroup ? -prefs.TargetId : prefs.TargetId
                        };

                        Thread.Sleep(1000);

                        var getResult = _api.Wall.Get(wallGeParams);
                        var posts     = getResult.WallPosts;

                        foreach (var post in posts.Reverse())
                        {
                            var searchResult = _keywordSearcher.LookIntoPost(post, keywords);
                            if (!searchResult.Contains)
                            {
                                continue;
                            }

                            if (post.Date <= prefs.LastNotifiedPostTime)
                            {
                                continue;
                            }

                            prefs.LastNotifiedPostTime = post.Date ?? DateTime.Now;
                            _userNotifier.NotifyUser(prefs, post.Id.Value, searchResult.Word);
                        }
                    }
                    catch (UserAuthorizationFailException ex)
                    {
                        _logger.Error($"UserAuthorizationException. {ex}");
                        //if (!_api.IsAuthorized)
                        {
                            _logger.Info($"VkApi wasn't authorized. Authorizing..");
                            _api.SimpleAuthorize(_settings.Vkontakte);
                            _logger.Info($"SimpleAuthorize passed. New vk auth status = {_api.IsAuthorized}");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(ex, $"Error while fetching VK groups. Pref: {prefs.ToShortString()}. Exception message: {ex}");
                    }
                }
                usersContext.SaveChanges();
            }
        }