Esempio n. 1
0
        public async Task CommentOnVideo(string Id, string Comment)
        {
            try
            {
                LogUtil.Log($"Commenting on video with ID {Id}.");
                var youtubeService = BuildService(await BuildCredential(YouTubeService.Scope.YoutubeUpload));

                // Define the CommentThread object, which will be uploaded as the request body.
                CommentThread commentThread = new CommentThread();

                // Add the snippet object property to the CommentThread object.
                CommentThreadSnippet snippet   = new CommentThreadSnippet();
                Comment        topLevelComment = new Comment();
                CommentSnippet commentSnippet  = new CommentSnippet()
                {
                    TextOriginal = Comment
                };
                topLevelComment.Snippet = commentSnippet;
                snippet.TopLevelComment = topLevelComment;
                snippet.VideoId         = Id;
                commentThread.Snippet   = snippet;

                // Define and execute the API request
                var           request  = youtubeService.CommentThreads.Insert(commentThread, "snippet");
                CommentThread response = await request.ExecuteAsync();

                LogUtil.Log($"CommentThread responseId: {response.Id}");
            }
            catch (Exception ex)
            {
                LogUtil.Log(ex, "There was an error while commenting.");
            }
        }
Esempio n. 2
0
        public IHttpActionResult AddComment(AddCommentDTO comment)
        {
            int CurrenUser = 0;

            using (var db = new UserDAL())
            {
                CurrenUser = db.GetUserByUserNameOrEmail(User.Identity.Name).UserID;
            }
            var newComment = new CommentThread
            {
                UserId      = CurrenUser,
                ThreadId    = comment.ThreadId,
                Content     = comment.CommentContent,
                Status      = true,
                CommentDate = DateTime.Now
            };

            using (var db = new ThreadDAL())
            {
                newComment = db.AddNewComment(newComment);
            }
            return(Ok(new HTTPMessageDTO {
                Status = WsConstant.HttpMessageType.SUCCESS, Data = newComment
            }));
        }
Esempio n. 3
0
        public void LoadCurrentCommentThread()
        {
            try
            {
                DataContractSerializer ser = new DataContractSerializer(typeof(CommentThread));

                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("currentcommentthread.txt", FileMode.Open, isf))
                    {
                        _commentThread = ser.ReadObject(stream) as CommentThread;
                    }
                }

                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("currentselectedcomment.txt", FileMode.Open, isf))
                    {
                        StreamReader sr = new StreamReader(stream);
                        _selectedComment = int.Parse(sr.ReadLine());
                        sr.Close();
                    }
                }
            }
            catch
            {
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string sStory, sComment;

            if (NavigationContext.QueryString.TryGetValue("Story", out sStory))
            {
                _story = int.Parse(sStory);
            }
            else
            {
                _story = 10;
            }
            if (NavigationContext.QueryString.TryGetValue("Comment", out sComment))
            {
                _comment = int.Parse(sComment);
                _thread  = CoreServices.Instance.GetCommentThread(_comment);
                if (_thread == null || _thread.RootComment.Count == 0)
                {
                    _thread = new CommentThread(_comment, _story);
                    _thread.PropertyChanged += ThreadCreated;
                    ProgressBar.Visibility   = Visibility.Visible;
                }
                else
                {
                    _comment   = CoreServices.Instance.GetSelectedComment();
                    staticLoad = true;
                }
                CommentsList.DataContext = _thread;
            }
        }
Esempio n. 5
0
        public async Task AddCommentAsync(VideoMetadataModel videoMetadata, CancellationToken cancellationToken)
        {
            _logger.LogTrace($"{GetType()} - BEGIN {nameof(AddVideoAsync)}");

            try
            {
                YouTubeService ytService = await _ytServiceProvider.CreateServiceAsync(cancellationToken);

                CommentThread commentThread = new CommentThread()
                {
                    Snippet = new CommentThreadSnippet
                    {
                        ChannelId       = _configuration.ChannelId,
                        VideoId         = GetVideoIdFromUrl(videoMetadata.VideoUrl),
                        TopLevelComment = new Comment
                        {
                            Snippet = new CommentSnippet
                            {
                                TextOriginal = videoMetadata.PinnedComment
                            }
                        }
                    }
                };

                CommentThreadsResource.InsertRequest req = ytService.CommentThreads.Insert(commentThread, SNIPPET_PART_PARAM);
                CommentThread res = await req.ExecuteAsync();
            }
            catch (Exception e)
            {
                _logger.LogError("An error occurred while adding comment to video", e);
                throw;
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Creates a new top-level comment. To add a reply to an existing comment, use the comments.insert method instead.
        /// Documentation https://developers.google.com/youtube/v3/reference/commentThreads/insert
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated YouTube service.</param>
        /// <param name="part">The part parameter identifies the properties that the API response will include. Set the parameter value to snippet. The snippet part has a quota cost of 2 units.</param>
        /// <param name="body">A valid YouTube v3 body.</param>
        /// <returns>CommentThreadResponse</returns>
        public static CommentThread Insert(YouTubeService service, string part, CommentThread body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (part == null)
                {
                    throw new ArgumentNullException(part);
                }

                // Make the request.
                return(service.CommentThreads.Insert(body, part).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request CommentThreads.Insert failed.", ex);
            }
        }
Esempio n. 7
0
        public static async Task <HttpStatusCode> AddCommentAsync <T>(
            ApplicationDbContext dbContext,
            string userId,
            CommentItemIds ids,
            Expression <Func <T, CommentThread> > commentThreadProperty,
            T commentTargetEntity,
            CommentRequest comment)
        {
            using (var transaction = dbContext.Database.BeginTransaction())
            {
                bool succeeded = false;
                try
                {
                    var text = await TextOperations.CreateTextAsync(
                        dbContext, comment.Message);

                    dbContext.UserTexts.Add(text);

                    var           commentThreadPropInfo = (PropertyInfo)((MemberExpression)commentThreadProperty.Body).Member;
                    CommentThread commentThread         = commentThreadPropInfo.GetValue(commentTargetEntity) as CommentThread;
                    if (commentThread == null)
                    {
                        commentThread = new CommentThread
                        {
                            Comments = new List <Comment>()
                        };
                        dbContext.CommentThreads.Add(commentThread);
                        commentThreadPropInfo.SetValue(commentTargetEntity, commentThread);
                    }

                    var commentEntity = new Comment
                    {
                        Text   = text,
                        Thread = commentThread,
                        UserId = userId
                    };
                    dbContext.Comments.Add(commentEntity);
                    commentThread.Comments.Add(commentEntity);

                    await dbContext.SaveChangesAsync();

                    transaction.Commit();
                    succeeded = true;

                    await UserOperations.NotifyMentionsAsync(
                        dbContext, "Comment", userId, text);

                    await SearchOperations.IndexCommentAsync(commentEntity, ids);

                    return(HttpStatusCode.OK);
                }
                finally
                {
                    if (!succeeded)
                    {
                        transaction.Rollback();
                    }
                }
            }
        }
Esempio n. 8
0
        // Updating comment
        private static async Task UpdateComment(object commentID)
        {
            string id             = (string)commentID;
            var    youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = key,
                HttpClientInitializer = credential,
                ApplicationName       = "YoutubeApp"
            });
            // Creating body of a comment with id of origin comment
            var commentThread              = new CommentThread();
            CommentThreadSnippet snippet   = new CommentThreadSnippet();
            Comment        topLevelComment = new Comment();
            CommentSnippet commentSnippet  = new CommentSnippet();

            commentSnippet.TextOriginal = GetRandomComment();
            topLevelComment.Snippet     = commentSnippet;
            snippet.TopLevelComment     = topLevelComment;
            snippet.VideoId             = VideoUrl;
            commentThread.Id            = id;
            commentThread.Snippet       = snippet;
            // Creating request and sending
            var query = youtubeService.CommentThreads.Update(commentThread, "snippet");

            try
            {
                var resp = await query.ExecuteAsync();

                Console.WriteLine("Комментарий изменен");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 9
0
        private static void SqlInsert(CommentThread passed, String source)
        {
            String comment = passed.Snippet.TopLevelComment.Snippet.TextDisplay.Replace("'", "`");

            if (comment.Substring(0, 1) == "+" && comment.Substring(1, 1) != " ")
            {
                Int32 index = comment.IndexOf(' ');
                comment = comment.Substring(index);
            }

            try
            {
                using (var conn = new SqlConnection("Data Source=PHD-SERVER;Initial Catalog=RawComments;Integrated Security=False;User ID=sa;Password="******"InsertComment", conn)
                    {
                        CommandType = CommandType.StoredProcedure
                    })
                    {
                        command.Parameters.Add(new SqlParameter("@Id", passed.Snippet.TopLevelComment.Id));
                        command.Parameters.Add(new SqlParameter("@Comment", comment));
                        command.Parameters.Add(new SqlParameter("@likeCount", passed.Snippet.TopLevelComment.Snippet.LikeCount));
                        command.Parameters.Add(new SqlParameter("@Source", source));
                        conn.Open();

                        Int32 rdr = command.ExecuteNonQuery();
                    }
            }
            catch (Exception)
            {  }
        }
        public CommentDataType CommentToDataType(CommentThread commentData)
        {
            var comment = new CommentDataType();

            comment.Author          = commentData.Snippet.TopLevelComment.Snippet.AuthorDisplayName;
            comment.AuthorThumbnail = commentData.Snippet.TopLevelComment.Snippet.AuthorProfileImageUrl;
            comment.Content         = commentData.Snippet.TopLevelComment.Snippet.TextDisplay;
            comment.DatePosted      = TimeSinceDate(commentData.Snippet.TopLevelComment.Snippet.PublishedAt);
            comment.Id        = commentData.Snippet.TopLevelComment.Id;
            comment.IsReplies = commentData.Replies != null;
            comment.LikeCount = commentData.Snippet.TopLevelComment.Snippet.LikeCount;

            if (commentData.Replies != null)
            {
                comment.ReplyCount = commentData.Replies.Comments.Count;
            }
            else
            {
                comment.ReplyCount = 0;
            }

            if (commentData.Replies != null)
            {
                foreach (var item in commentData.Replies.Comments)
                {
                    comment.Replies.Add(CommentToDataType(item));
                }
            }

            return(comment);
        }
Esempio n. 11
0
        public async Task <CommentThread> AddComment(
            string channelId,
            string videoId,
            string text)
        {
            var comment = new CommentThread();
            var snippet = new CommentThreadSnippet
            {
                ChannelId       = channelId,
                VideoId         = videoId,
                IsPublic        = true,
                TopLevelComment = new Comment
                {
                    Snippet = new CommentSnippet
                    {
                        ChannelId    = channelId,
                        VideoId      = videoId,
                        TextOriginal = text
                    }
                }
            };

            comment.Snippet = snippet;

            var request  = this.Youtube.CommentThreads.Insert(comment, CommentParts.Snippet);
            var response = await request.ExecuteAsync();

            return(response);
        }
Esempio n. 12
0
        private void RefreshClick(object sender, EventArgs e)
        {
            CommentThread thread = CommentsList.DataContext as CommentThread;

            thread.PropertyChanged += ThreadCreated;
            thread.Refresh();
            ProgressBar.Visibility = Visibility.Visible;
        }
Esempio n. 13
0
 public CommentThread AddNewComment(CommentThread comment)
 {
     using (var db = new Ws_DataContext())
     {
         var newComment = db.CommentThreads.Add(comment);
         db.SaveChanges();
         return(newComment);
     }
 }
Esempio n. 14
0
 public static CommentThreadModel Map(CommentThread objModel)
 {
     return(new CommentThreadModel
     {
         ID = objModel.ID,
         URL = objModel.URL,
         SectionId = objModel.SectionId,
         EntityID = objModel.EntityID
     });
 }
Esempio n. 15
0
        public MComment(CommentThread comment)
        {
            if (comment == null)
            {
                return;
            }

            if (comment.Snippet == null)
            {
                return;
            }

            if (comment.Snippet.TopLevelComment == null)
            {
                return;
            }

            var authorSnippet = comment.Snippet.TopLevelComment.Snippet;

            if (authorSnippet == null)
            {
                return;
            }

            if (!string.IsNullOrEmpty(authorSnippet.AuthorChannelUrl))
            {
                AuthorChannelId = GetChannelId(authorSnippet.AuthorChannelUrl);
            }
            AuthorDisplayName     = authorSnippet.AuthorDisplayName;
            AuthorProfileImageUrl = authorSnippet.AuthorProfileImageUrl;
            LikeCount             = authorSnippet.LikeCount;
            PublishedAt           = authorSnippet.PublishedAt;
            if (PublishedAt != null)
            {
                PublishedAtRaw = PublishedAt.Value.ToString("g");
            }
            TextDisplay = authorSnippet.TextDisplay;

            IsReplay = false;

            ReplayComments = new List <IComment>();
            if (comment.Replies == null)
            {
                return;
            }

            if (comment.Replies.Comments != null)
            {
                ReplayComments = comment.Replies.Comments.Select(c => new MComment(c));
            }
        }
Esempio n. 16
0
        public async Task <IActionResult> Post([FromBody] Video model)
        {
            // Check if user should be allowed access.
            string     userEmail  = User.GetEmail() ?? Constants.DefaultUserEmail;
            UserAccess userAccess = _progenyDbContext.UserAccessDb.SingleOrDefault(u =>
                                                                                   u.ProgenyId == model.ProgenyId && u.UserId.ToUpper() == userEmail.ToUpper());

            if (userAccess == null || userAccess.AccessLevel > 0)
            {
                return(Unauthorized());
            }

            Video vid = await _context.VideoDb.SingleOrDefaultAsync(v =>
                                                                    v.VideoLink == model.VideoLink && v.ProgenyId == model.ProgenyId);

            if (vid == null)
            {
                CommentThread commentThread = new CommentThread();
                await _context.CommentThreadsDb.AddAsync(commentThread);

                await _context.SaveChangesAsync();

                model.CommentThreadNumber = commentThread.Id;

                await _context.VideoDb.AddAsync(model);

                await _context.SaveChangesAsync();

                await _dataService.SetVideo(model.VideoId);

                Progeny prog = await _dataService.GetProgeny(model.ProgenyId);

                UserInfo userinfo = await _dataService.GetUserInfoByEmail(User.GetEmail());

                string       title   = "New Video added for " + prog.NickName;
                string       message = userinfo.FirstName + " " + userinfo.MiddleName + " " + userinfo.LastName + " added a new video for " + prog.NickName;
                TimeLineItem tItem   = new TimeLineItem();
                tItem.ProgenyId   = model.ProgenyId;
                tItem.ItemId      = model.VideoId.ToString();
                tItem.ItemType    = (int)KinaUnaTypes.TimeLineType.Video;
                tItem.AccessLevel = model.AccessLevel;
                await _azureNotifications.ProgenyUpdateNotification(title, message, tItem, userinfo.ProfilePicture);

                return(Ok(model));
            }

            model = vid;

            return(Ok(model));
        }
Esempio n. 17
0
        public async Task <CommentThread> AddComment([FromBody] AddComment commentInfo)
        {
            var user = await GetUserOrThrow();

            // Get the song because we'll need to increment its .CommentCount.
            var song = await DbSession.LoadRequiredAsync <Song>(commentInfo.SongId);

            // Get the comment thread for this song. It may be null; we created these on-demand.
            var commentThreadId = $"CommentThreads/{commentInfo.SongId}";
            var commentThread   = await DbSession.LoadOptionalAsync <CommentThread>(commentThreadId);

            if (commentThread == null)
            {
                commentThread = new CommentThread
                {
                    Id     = commentThreadId,
                    SongId = commentInfo.SongId
                };
                await DbSession.StoreAsync(commentThread, commentThread.Id);
            }

            // Add the comment and update the song's comment count.
            var newComment = new Comment
            {
                Content         = commentInfo.Content,
                Date            = DateTimeOffset.UtcNow,
                UserId          = user.Id,
                UserDisplayName = Comment.GetUserDisplayName(user)
            };

            commentThread.Comments.Add(newComment);
            song.CommentCount = commentThread.Comments.Count;

            // Store an activity for it.
            var commentActivity = new Activity
            {
                Id          = "Activities/",
                DateTime    = DateTimeOffset.UtcNow,
                Title       = $"{newComment.UserDisplayName} commented on {song.Name} by {song.Artist}",
                Description = newComment.Content,
                MoreInfoUri = song.GetSongShareLink(appSettings.Value.DefaultUrl),
                EntityId    = song.Id,
                Type        = ActivityType.Comment
            };

            await DbSession.StoreAsync(commentActivity);

            return(commentThread);
        }
Esempio n. 18
0
        public async Task <IComment> AddComment(string channelId, string videoId, string text)
        {
            if (!IsAuthorized)
            {
                return(null);
            }

            if (string.IsNullOrEmpty(text))
            {
                return(null);
            }

            // Insert channel comment by omitting videoId.
            // Create a comment snippet with text.
            var commentSnippet = new CommentSnippet {
                TextOriginal = text
            };

            // Create a top-level comment with snippet.
            var topLevelComment = new Comment {
                Snippet = commentSnippet
            };

            // Create a comment thread snippet with channelId and top-level comment.
            var commentThreadSnippet = new CommentThreadSnippet
            {
                ChannelId       = channelId,
                VideoId         = videoId,
                TopLevelComment = topLevelComment
            };

            // Create a comment thread with snippet.
            var commentThread = new CommentThread {
                Snippet = commentThreadSnippet
            };

            var youtubeService = _youTubeServiceControl.GetAuthorizedService();
            var request        = youtubeService.CommentThreads.Insert(commentThread, "snippet");

            request.Key = _youTubeServiceControl.ApiKey;

            var response = await request.ExecuteAsync();

            //небольшой хак. т.к. response не содержит текст((
            response.Snippet.TopLevelComment.Snippet.TextDisplay = text;
            return(new MComment(response));
        }
        private IEnumerable <Comment> GetComments()
        {
            CommentThread commentThread = null;

            while ((commentThread = _commentThreadProvider.GetNextCommentThread()) != null)
            {
                // Get the top comment
                yield return(commentThread.Snippet.TopLevelComment);

                // Finally get the rest of the comment in the comment thread
                foreach (var comment in _commentIterator.GetComments("snippet", commentThread.Id,
                                                                     CommentsResource.ListRequest.TextFormatEnum.PlainText))
                {
                    yield return(comment);
                }
            }
        }
Esempio n. 20
0
        private static XElement FormatThread(CommentThread thread)
        {
            XElement threadElem = new XElement("thread");

            threadElem.Add(new XAttribute("id", thread.Id));
            if (thread.Type == NoteType.Conflict)
            {
                threadElem.Add(new XAttribute("type", "conflict"));
            }
            threadElem.Add(FormatSelection(thread.ScriptureSelection));
            foreach (Comment comment in thread.ActiveComments)
            {
                threadElem.Add(FormatComment(comment));
            }

            return(threadElem);
        }
Esempio n. 21
0
        public async Task <IActionResult> Post([FromBody] Comment model)
        {
            Comment newComment = new Comment();

            newComment.Created             = DateTime.UtcNow;
            newComment.Author              = model.Author;
            newComment.CommentText         = model.CommentText;
            newComment.CommentThreadNumber = model.CommentThreadNumber;
            newComment.DisplayName         = model.DisplayName;

            await _context.CommentsDb.AddAsync(newComment);

            await _context.SaveChangesAsync();

            CommentThread cmntThread =
                await _context.CommentThreadsDb.SingleOrDefaultAsync(c => c.Id == model.CommentThreadNumber);

            cmntThread.CommentsCount = cmntThread.CommentsCount + 1;
            _context.CommentThreadsDb.Update(cmntThread);
            await _dataService.SetCommentsList(cmntThread.Id);

            await _context.SaveChangesAsync();

            await _dataService.SetComment(newComment.CommentId);

            string       title   = "New comment for " + model.Progeny.NickName;
            string       message = model.DisplayName + " added a new comment for " + model.Progeny.NickName;
            TimeLineItem tItem   = new TimeLineItem();

            tItem.ProgenyId   = model.Progeny.Id;
            tItem.ItemId      = model.ItemId;
            tItem.ItemType    = model.ItemType;
            tItem.AccessLevel = model.AccessLevel;
            UserInfo userinfo = await _dataService.GetUserInfoByUserId(model.Author);

            await _azureNotifications.ProgenyUpdateNotification(title, message, tItem, userinfo.ProfilePicture);

            return(Ok(newComment));
        }
        /// <summary>
        /// Gets the comments for the specified comment thread.
        /// </summary>
        /// <param name="commentThread">The comment thread to get comments for</param>
        /// <param name="maxResults">The maximum results to return</param>
        /// <returns>The list of comments</returns>
        public async Task <IEnumerable <Comment> > GetCommentsForCommentThread(CommentThread commentThread, int maxResults = 1)
        {
            Validator.ValidateVariable(commentThread, "commentThread");
            return(await this.YouTubeServiceWrapper(async() =>
            {
                List <Comment> results = new List <Comment>();
                string pageToken = null;
                do
                {
                    CommentsResource.ListRequest request = this.connection.GoogleYouTubeService.Comments.List("snippet");
                    request.ParentId = commentThread.Id;
                    request.MaxResults = Math.Min(maxResults, 50);
                    request.PageToken = pageToken;

                    CommentListResponse response = await request.ExecuteAsync();
                    results.AddRange(response.Items);
                    maxResults -= response.Items.Count;
                    pageToken = response.NextPageToken;
                } while (maxResults > 0 && !string.IsNullOrEmpty(pageToken));
                return results;
            }));
        }
Esempio n. 23
0
        public static IList <CommentDetails> GetComments(CommentThread commentThread)
        {
            if (commentThread == null)
            {
                return(new CommentDetails[0]);
            }

            return(commentThread.Comments
                   .OrderBy(c => c.Text.CreatedUtc)
                   .Select(
                       c =>
                       new CommentDetails
            {
                UserName = c.User.Name,
                UserId = c.UserId,
                AvatarUrl = UserOperations.GetAvatarUrl(c.User),
                Message = c.Text.Content,
                TimeAgo = TimeOperations.GetTimeAgo(c.Text.CreatedUtc),
                LikeUrl = $"/api/Comments/{c.CommentId}/Like",
                LikeGroups = LikeOperations.MakeLikeGroups(c.Text.Likes)
            })
                   .ToList());
        }
Esempio n. 24
0
        public async Task <IActionResult> Delete(int id)
        {
            Comment comment = await _context.CommentsDb.SingleOrDefaultAsync(c => c.CommentId == id);

            if (comment != null)
            {
                UserInfo userInfo = await _dataService.GetUserInfoByEmail(User.GetEmail());

                if (userInfo.UserId != comment.Author)
                {
                    return(Unauthorized());
                }

                CommentThread cmntThread =
                    await _context.CommentThreadsDb.SingleOrDefaultAsync(c => c.Id == comment.CommentThreadNumber);

                if (cmntThread.CommentsCount > 0)
                {
                    cmntThread.CommentsCount = cmntThread.CommentsCount - 1;
                    _context.CommentThreadsDb.Update(cmntThread);
                    await _context.SaveChangesAsync();

                    await _dataService.SetCommentsList(cmntThread.Id);
                }

                _context.CommentsDb.Remove(comment);
                await _context.SaveChangesAsync();

                await _dataService.RemoveComment(comment.CommentId, comment.CommentThreadNumber);

                return(NoContent());
            }
            else
            {
                return(NotFound());
            }
        }
Esempio n. 25
0
        // Sending comment
        private static async Task <string> SendComment(string url)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = key,
                HttpClientInitializer = credential,
                ApplicationName       = "YoutubeApp"
            });

            // Making a comment
            var commentThread              = new CommentThread();
            CommentThreadSnippet snippet   = new CommentThreadSnippet();
            Comment        topLevelComment = new Comment();
            CommentSnippet commentSnippet  = new CommentSnippet();

            commentSnippet.TextOriginal = GetRandomComment();
            topLevelComment.Snippet     = commentSnippet;
            snippet.TopLevelComment     = topLevelComment;
            snippet.VideoId             = url;
            commentThread.Snippet       = snippet;
            // Sending a query
            var query = youtubeService.CommentThreads.Insert(commentThread, "snippet");

            try
            {
                var resp = await query.ExecuteAsync();

                Console.WriteLine("Комментарий отправлен");
                return(resp.Id);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(string.Empty);
        }
        private async Task Run(string chanelIdORVideoId, YouTubeRating action, string comment)
        {
            var baseDir          = $"{AppDomain.CurrentDomain.BaseDirectory}\\ClientSecrets";
            var clientSecretFile = $"{baseDir}\\Config";

            var infos = File.ReadAllLines(clientSecretFile);
            var index = 0;

            var s = new ConsoleSpinner();

            do
            {
                var stillValid = index + 5 <= infos.Length;
                if (!stillValid)
                {
                    break;
                }

                // This is will be skip at first and final
                if (index > 0)
                {
                    var csCount = 0;
                    while (csCount < 30)
                    {
                        Thread.Sleep(100); // simulate some work being done
                        s.UpdateProgress();

                        csCount++;
                    }
                }
                //

                var email        = infos[index++];
                var clientID     = infos[index++];
                var clientSecret = infos[index++];
                var apiKey       = infos[index++];
                var chanelId     = infos[index++];

                Console.WriteLine($"{email}");
                Console.WriteLine("-----");

                var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new ClientSecrets()
                {
                    ClientId = clientID, ClientSecret = clientSecret
                },
                    // This OAuth 2.0 access scope allows for full read/write access to the
                    // authenticated user's account.
                    new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeForceSsl, YouTubeService.Scope.Youtubepartner },
                    chanelId,
                    CancellationToken.None,
                    new FileDataStore(baseDir, true)
                    );

                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApiKey = apiKey,
                });

                // Chanels List
                //var chanelsList = youtubeService.Channels.List("snippet,contentDetails,statistics");
                //chanelsList.Id = chanelId;
                //chanelsList.MaxResults = 1;

                //var chanels = await chanelsList.ExecuteAsync();
                //if (chanels != null)
                //    Console.WriteLine($"{chanels.Items[0].Snippet.Title}");
                //Console.WriteLine("-----");

                // SUB or UNSUB
                try
                {
                    switch (action)
                    {
                    case YouTubeRating.Sub:
                        var subBody = new Subscription();
                        subBody.Snippet           = new SubscriptionSnippet();
                        subBody.Snippet.ChannelId = chanelId;

                        var resourceId = new ResourceId();
                        resourceId.ChannelId       = chanelIdORVideoId; // "UCAuUUnT6oDeKwE6v1NGQxug";
                        subBody.Snippet.ResourceId = resourceId;

                        var subInsert    = youtubeService.Subscriptions.Insert(subBody, "snippet");
                        var ressubInsert = await subInsert.ExecuteAsync();

                        break;

                    case YouTubeRating.Unsub:
                        var subList = youtubeService.Subscriptions.List("snippet,contentDetails");
                        subList.ChannelId = chanelId;

                        var subs = await subList.ExecuteAsync();

                        var deleteId = String.Empty;

                        foreach (var item in subs.Items)
                        {
                            var needDelete = item.Snippet.ResourceId.ChannelId == chanelIdORVideoId;
                            if (needDelete)
                            {
                                deleteId = item.Id;
                                break;
                            }
                        }

                        if (String.IsNullOrEmpty(deleteId))
                        {
                            throw new Exception($"{chanelIdORVideoId} not found.");
                        }

                        var subDelete    = youtubeService.Subscriptions.Delete(deleteId);
                        var ressubDelete = await subDelete.ExecuteAsync();

                        break;

                    case YouTubeRating.Like:
                        var ratingLike    = youtubeService.Videos.Rate(chanelIdORVideoId, VideosResource.RateRequest.RatingEnum.Like);
                        var resratingLike = await ratingLike.ExecuteAsync();

                        //var aaa = youtubeService.Videos.GetRating(chanelIdORVideoId);
                        //var bbb = await aaa.ExecuteAsync();
                        break;

                    case YouTubeRating.Unlike:
                        var ratingUnlike    = youtubeService.Videos.Rate(chanelIdORVideoId, VideosResource.RateRequest.RatingEnum.None);
                        var resratingUnlike = await ratingUnlike.ExecuteAsync();

                        break;

                    case YouTubeRating.Dislike:
                        var ratingDislike    = youtubeService.Videos.Rate(chanelIdORVideoId, VideosResource.RateRequest.RatingEnum.Dislike);
                        var resratingDislike = await ratingDislike.ExecuteAsync();

                        break;

                    case YouTubeRating.Comment:
                        var comThreadBody = new CommentThread();

                        comThreadBody.Snippet = new CommentThreadSnippet()
                        {
                            ChannelId = chanelId, VideoId = chanelIdORVideoId
                        };
                        comThreadBody.Snippet.TopLevelComment         = new Comment();
                        comThreadBody.Snippet.TopLevelComment.Snippet = new CommentSnippet()
                        {
                            TextOriginal = comment
                        };

                        var commentThreadsInsert    = youtubeService.CommentThreads.Insert(comThreadBody, "snippet");
                        var rescommentThreadsInsert = await commentThreadsInsert.ExecuteAsync();

                        break;

                    default:
                        break;
                    }

                    Console.WriteLine($"{chanelIdORVideoId} OK");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{chanelIdORVideoId} failed with error: {ex.Message}");
                }

                Console.WriteLine("-----");
                Console.WriteLine(" ");
            } while (true);
        }
Esempio n. 27
0
        public async Task <IActionResult> Delete(int id)
        {
            Video video = await _context.VideoDb.SingleOrDefaultAsync(v => v.VideoId == id);

            if (video != null)
            {
                // Check if user should be allowed access.
                string     userEmail  = User.GetEmail() ?? Constants.DefaultUserEmail;
                UserAccess userAccess = _progenyDbContext.UserAccessDb.AsNoTracking().SingleOrDefault(u =>
                                                                                                      u.ProgenyId == video.ProgenyId && u.UserId.ToUpper() == userEmail.ToUpper());

                if (userAccess == null || userAccess.AccessLevel > 0)
                {
                    return(Unauthorized());
                }

                List <Comment> comments = _context.CommentsDb
                                          .Where(c => c.CommentThreadNumber == video.CommentThreadNumber).ToList();
                if (comments.Any())
                {
                    _context.CommentsDb.RemoveRange(comments);
                    _context.SaveChanges();

                    foreach (Comment deletedComment in comments)
                    {
                        await _dataService.RemoveComment(deletedComment.CommentId, deletedComment.CommentThreadNumber);
                    }
                }

                CommentThread cmntThread =
                    _context.CommentThreadsDb.SingleOrDefault(c => c.Id == video.CommentThreadNumber);
                if (cmntThread != null)
                {
                    _context.CommentThreadsDb.Remove(cmntThread);
                    _context.SaveChanges();
                    await _dataService.RemoveCommentsList(video.CommentThreadNumber);
                }
                _context.VideoDb.Remove(video);
                await _context.SaveChangesAsync();

                await _dataService.RemoveVideo(video.VideoId, video.ProgenyId);

                Progeny prog = await _dataService.GetProgeny(video.ProgenyId);

                UserInfo userinfo = await _dataService.GetUserInfoByEmail(User.GetEmail());

                string       title   = "Video deleted for " + prog.NickName;
                string       message = userinfo.FirstName + " " + userinfo.MiddleName + " " + userinfo.LastName + " deleted a video for " + prog.NickName;
                TimeLineItem tItem   = new TimeLineItem();
                tItem.ProgenyId   = video.ProgenyId;
                tItem.ItemId      = video.VideoId.ToString();
                tItem.ItemType    = (int)KinaUnaTypes.TimeLineType.Video;
                tItem.AccessLevel = 0;
                await _azureNotifications.ProgenyUpdateNotification(title, message, tItem, userinfo.ProfilePicture);

                return(NoContent());
            }
            else
            {
                return(NotFound());
            }
        }
Esempio n. 28
0
        public JsonResult GetTopRatedComments(string commentUrl = "", long entityId = 0, long sectionId = 0)
        {
            if (Request.IsAjaxRequest())
            {
                CommentThread thread = null;
                if (!string.IsNullOrEmpty(commentUrl))
                {
                    thread = _repoThread.GetSingle(x => x.SectionId == sectionId && x.EntityID == entityId);
                }

                long fileId = 0;
                if (thread != null)
                {
                    var lstcomments = _repoComments.GetList(x => x.ThreadID == thread.ID).OrderBy(x => x.ID).ToList();
                    var comments    = new List <CommentModel>();

                    foreach (Comment comment in lstcomments)
                    {
                        bool showLike      = false;
                        int  likeCount     = 0;
                        var  objEntityFile = _repoEntityFile.GetSingle(x => x.EntityId == comment.ProfileId && x.SectionId == 1);
                        if (objEntityFile != null)
                        {
                            fileId = objEntityFile.FileId ?? 0;
                        }
                        else
                        {
                            fileId = 0;
                        }


                        long currentProfileId = 0;
                        if (_repoUserProfile != null)
                        {
                            if (CurrentUser != null)
                            {
                                currentProfileId = _repoUserProfile.GetSingle(x => x.UserId == CurrentUser.UserId).Id;
                            }
                        }

                        var objLike = _repoLike.GetSingle(x => x.ProfileId == currentProfileId && x.EntityName == "comment" && x.EntityId == comment.ID);
                        if (objLike == null)
                        {
                            showLike = true;
                        }
                        //else
                        //{
                        likeCount = _repoLike.GetList(x => x.EntityName == "comment" && x.EntityId == comment.ID).Count();
                        //}
                        comments.Add(new CommentModel
                        {
                            ID              = comment.ID,
                            Body            = comment.Body,
                            Date            = String.Format("{0:d}", comment.Date),
                            ThreadID        = comment.ThreadID,
                            UserID          = comment.UserID,
                            UserName        = comment.UserName,
                            Email           = comment.Email,
                            ProfileId       = comment.ProfileId,
                            FileId          = fileId,
                            ShowLike        = showLike,
                            LikeCount       = likeCount,
                            CurrentUserRole = CurrentRole
                        });
                    }

                    var objSortedComments = new List <CommentModel>();
                    foreach (CommentModel comment in comments)
                    {
                        objSortedComments.Add(new CommentModel
                        {
                            ID              = comment.ID,
                            Body            = comment.Body,
                            Date            = String.Format("{0:d}", comment.Date),
                            ThreadID        = comment.ThreadID,
                            UserID          = comment.UserID,
                            UserName        = comment.UserName,
                            Email           = comment.Email,
                            ProfileId       = comment.ProfileId,
                            FileId          = comment.FileId,
                            ShowLike        = comment.ShowLike,
                            LikeCount       = comment.LikeCount,
                            CurrentUserRole = comment.CurrentUserRole
                        });
                    }

                    var lstSortedComments = objSortedComments.OrderByDescending(x => x.LikeCount).ToList();

                    return(Json(new { comments = lstSortedComments, commentcount = comments.Count }, JsonRequestBehavior.AllowGet));
                }
                return(Json(new { commentcount = 0 }, JsonRequestBehavior.AllowGet));
            }
            return(null);
        }
Esempio n. 29
0
        public JsonResult Get(string commentUrl = "", long entityId = 0, long sectionId = 0)
        {
            if (Request.IsAjaxRequest())
            {
                CommentThread thread = null;
                if (!string.IsNullOrEmpty(commentUrl))
                {
                    thread = _repoThread.GetSingle(x => x.SectionId == sectionId && x.EntityID == entityId);
                }

                long fileId = 0;
                if (thread != null)
                {
                    var lstcomments = _repoComments.GetList(x => x.ThreadID == thread.ID).OrderByDescending(x => x.Date).ToList();
                    var comments    = new List <CommentModel>();

                    foreach (Comment comment in lstcomments)
                    {
                        bool showLike      = false;
                        int  likeCount     = 0;
                        var  objEntityFile = _repoEntityFile.GetSingle(x => x.EntityId == comment.ProfileId && x.SectionId == 1);
                        if (objEntityFile != null)
                        {
                            fileId = objEntityFile.FileId ?? 0;
                        }
                        else
                        {
                            fileId = 0;
                        }


                        long currentProfileId = 0;
                        if (_repoUserProfile != null)
                        {
                            if (CurrentUser != null)
                            {
                                currentProfileId = _repoUserProfile.GetSingle(x => x.UserId == CurrentUser.UserId).Id;
                            }
                        }

                        var objLike = _repoLike.GetSingle(x => x.ProfileId == currentProfileId && x.EntityName == "comment" && x.EntityId == comment.ID);
                        if (objLike == null)
                        {
                            showLike = true;
                        }
                        //else
                        //{
                        likeCount = _repoLike.GetList(x => x.EntityName == "comment" && x.EntityId == comment.ID).Count();
                        //}
                        comments.Add(new CommentModel
                        {
                            ID              = comment.ID,
                            Body            = comment.Body,
                            Date            = String.Format("{0:d}", comment.Date),
                            ThreadID        = comment.ThreadID,
                            UserID          = comment.UserID,
                            UserName        = comment.UserName,
                            Email           = comment.Email,
                            ProfileId       = comment.ProfileId,
                            FileId          = fileId,
                            ShowLike        = showLike,
                            LikeCount       = likeCount,
                            CurrentUserRole = CurrentRole
                        });
                    }



                    // var allfiles = new Dictionary<string, List<object>>();
                    //////long fileId = 0;
                    //////if (thread != null)
                    //////{
                    //////    var lstcomments = _repoComments.GetList(x => x.ThreadID == thread.ID).OrderBy(x => x.ID).ToList();
                    //////    var comments = new List<CommentModel>();
                    //////    lstcomments.ForEach(x =>
                    //////    {
                    //////        var objEntityFile = _repoEntityFile.GetSingle(y => y.EntityId == x.ProfileId && y.SectionId == 1);
                    //////        if (objEntityFile != null)
                    //////        {
                    //////            fileId = objEntityFile.FileId ?? 0;
                    //////        }

                    //////        comments.Add(new CommentModel
                    //////        {
                    //////            ID = x.ID,
                    //////            Body = x.Body,
                    //////            Date = String.Format("{0:F}", x.Date),
                    //////            ThreadID = x.ThreadID,
                    //////            UserID = x.UserID,
                    //////            UserName = x.UserName,
                    //////            Email = x.Email,
                    //////            ProfileId = x.ProfileId,
                    //////            FileId = fileId
                    //////        });

                    //////        //allfiles.Add(x.ID.ToString(), GetFilesForComment(x.ID));
                    //////    });


                    return(Json(new { comments = comments, commentcount = comments.Count }, JsonRequestBehavior.AllowGet));
                }
                return(Json(new { commentcount = 0 }, JsonRequestBehavior.AllowGet));
            }
            return(null);
        }
Esempio n. 30
0
        public JsonResult Set(string commentBody, string commentUrl = "", int sectionId = 0, long entityID = 0)
        {
            if (Request.IsAjaxRequest())
            {
                CommentThread thread   = new CommentThread();
                var           threadID = Guid.NewGuid();

                if (!string.IsNullOrEmpty(commentUrl))
                {
                    //Only the url is known
                    //thread = _repoThread.GetSingle(x => x.URL == commentUrl);
                    thread = _repoThread.GetSingle(x => x.SectionId == sectionId && x.EntityID == entityID);
                    if (thread == null)
                    {
                        _repoThread.Add(new CommentThread
                        {
                            ID        = threadID,
                            URL       = commentUrl,
                            SectionId = sectionId,
                            EntityID  = entityID
                        });
                        _repoThread.Save();
                    }
                    else
                    {
                        threadID = thread.ID;
                    }
                }

                //bool showLike = false;

                var  userName  = "******";
                var  email     = "*****@*****.**";
                long profileId = 0;
                var  userId    = new Guid("f22511dc-37d7-456d-9da7-2b9dbbe316e0");
                if (CurrentUser != null)
                {
                    var objProfile = _repoUserProfile.GetSingle(x => x.UserId == CurrentUser.UserId);
                    if (objProfile != null)
                    {
                        profileId = objProfile.Id;
                        userName  = objProfile.FirstName;
                    }
                    userId = CurrentUser.UserId;
                }


                var comment = new Comment
                {
                    ThreadID  = threadID,
                    Body      = commentBody,
                    Date      = DateTime.Now,
                    UserName  = userName, //base.objCurrentUser.UserName,
                    UserID    = userId,   //new Guid("f22511dc-37d7-456d-9da7-2b9dbbe316e0"), //(Guid)base.objCurrentUser.ProviderUserKey,
                    Email     = email,    //base.objCurrentUser.Email
                    ProfileId = profileId
                };

                _repoComments.Add(comment);
                _repoComments.Save();

                long fileId        = 0;
                var  objEntityFile = _repoEntityFile.GetSingle(x => x.EntityId == comment.ProfileId && x.SectionId == 1);
                if (objEntityFile != null)
                {
                    fileId = objEntityFile.FileId ?? 0;
                }
                int likeCount = 0;
                var objLike   = _repoLike.GetSingle(x => x.ProfileId == profileId && x.EntityName == "comment" && x.EntityId == comment.ID);
                //if (objLike == null)
                //{
                //    showLike = true;
                //}
                if (objLike != null)
                {
                    likeCount = _repoLike.GetList(x => x.EntityName == "comment" && x.EntityId == comment.ID).Count();
                }

                var commentModelJSON = new CommentModel
                {
                    ID        = comment.ID,
                    Body      = comment.Body,
                    Date      = String.Format("{0:d}", comment.Date),
                    ThreadID  = comment.ThreadID,
                    Email     = comment.Email,
                    UserID    = comment.UserID,
                    UserName  = comment.UserName,
                    ProfileId = comment.ProfileId,
                    FileId    = fileId,
                    LikeCount = likeCount
                };

                // var files = this.GetFilesForComment(comment.ID);

                return(Json(new { comment = commentModelJSON, success = true }));
            }
            return(null);
        }