public async Task <bool> AddPostAsync(Guid userId, NewPostRequest newpost)
        {
            byte[] uploadToBytes = null;

            if (newpost.Upload != null && newpost.Upload.Length > 0)
            {
                uploadToBytes = Convert.FromBase64String(newpost.Upload);
            }

            Post post = new Post
            {
                Title  = newpost.Title,
                Upload = uploadToBytes,
                Body   = newpost.Body,
                Date   = newpost.Date,
                TAGS   = newpost.TAGS,
                Owner  = userId,
                likes  = 0
            };

            datacontext.Posts.Add(post);
            var added = await datacontext.SaveChangesAsync();

            return(added > 0);
        }
        public async Task <IActionResult> AddPublication(NewPostRequest request)
        {
            var user = await _userService.GetBySecretKey(request.Key);

            if (user == null)
            {
                _logger.Write(LogEventLevel.Warning, $"Somebody tried to login with this key: `{request.Key}`. Text: `{request.Comment}`");

                return(StatusCode((int)HttpStatusCode.Forbidden, "Incorrect security key"));
            }

            try
            {
                var publication = await _webAppPublicationService.CreatePublication(request, user);

                if (publication != null)
                {
                    return(Created(publication.ShareUrl, publication));
                }

                return(BadRequest());
            }
            catch (DuplicateNameException ex)
            {
                _logger.Write(LogEventLevel.Error, "Error while creating new publication", ex);

                return(StatusCode((int)HttpStatusCode.Conflict, ex.Message));
            }
            catch (Exception ex)
            {
                _logger.Write(LogEventLevel.Error, "Error while creating new publication", ex);

                return(BadRequest(ex.Message));
            }
        }
        public IActionResult NewPost([FromBody] NewPostRequest request)
        {
            Post post = new Post(request, currentUser);

            context.Posts.Add(post);
            context.SaveChanges();

            return(Created("", new PostResponse(post, currentUser)));
        }
Exemple #4
0
        public async Task <IActionResult> AddPost(Guid userId, [FromBody] NewPostRequest newpost)
        {
            var added = await postService.AddPostAsync(userId, newpost);

            if (added)
            {
                return(Ok());
            }

            return(BadRequest());
        }
Exemple #5
0
        public Task <Post> CreateNewPostAsync(string teamName, NewPost post)
        {
            var url = BuildStringBuilderWithTeamName(teamName);

            url.Append("/posts");

            var postObject = new NewPostRequest {
                post = post
            };

            return(PostMessage <NewPostRequest, Post>(url.ToString(), postObject));
        }
        public Post Add(NewPostRequest newPost)
        {
            var post = new Post();

            post.Id       = Guid.NewGuid();
            post.PostedOn = DateTime.Now;
            post.PostedBy = newPost.PostedBy;
            post.Text     = newPost.Text;
            post.Type     = newPost.Type;
            post.AssetUrl = newPost.AssetUrl;
            _posts.Add(post);
            return(post);
        }
    private static IReadOnlyCollection <string> GetTags(NewPostRequest request)
    {
        if (request == null || string.IsNullOrWhiteSpace(request.Tags))
        {
            return(ImmutableList <string> .Empty);
        }

        return(request.Tags
               .Split(' ')
               .Where(o => !string.IsNullOrWhiteSpace(o))
               .Select(o => o.Trim())
               .ToImmutableList());
    }
Exemple #8
0
        public Post Post([FromBody] NewPostRequest post)
        {
            var sub = User.FindFirst(ClaimTypes.GivenName); //.Claims.Where(x => x.Type == ClaimTypes.NameIdentifier).FirstOrDefault();

            if (sub != null)
            {
                post.PostedBy = sub.Value.ToString();
            }
            else
            {
                post.PostedBy = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            }
            return(_repo.Add(post));
        }
Exemple #9
0
        public IActionResult Add([FromBody] NewPostRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(GetModelStateErrors(ModelState)));
            }

            var resp = AddPost(request);

            if (resp.ResponseCode != ResponseCode.Success)
            {
                return(BadRequest(resp.ResponseMessage));
            }

            return(Ok(resp));
        }
    public async Task <PublicationViewModel> CreatePublication(NewPostRequest request, User user)
    {
        var extractor = new X.Web.MetaExtractor.Extractor();

        var metadata = await extractor.ExtractAsync(request.Link);

        var existingPublication = await _publicationService.Get(new Uri(metadata.Url));

        if (existingPublication != null)
        {
            throw new DuplicateNameException("Publication with this URL already exist");
        }

        var languageCode = _languageAnalyzer.GetTextLanguage(metadata.Description);
        var languageId   = await _localizationService.GetLanguageId(languageCode) ?? Core.Language.EnglishId;

        var player     = EmbeddedPlayerFactory.CreatePlayer(request.Link);
        var playerCode = player != null ? await player.GetEmbeddedPlayerUrl(request.Link) : null;

        var publication = await _publicationService.CreatePublication(
            metadata,
            user.Id,
            languageId,
            playerCode,
            request.CategoryId,
            request.Comment);

        if (publication != null)
        {
            var model = new PublicationViewModel(publication, _settings.WebSiteUrl);

            //If we can embed main content into site page, so we can share this page.
            var url = string.IsNullOrEmpty(model.EmbeddedPlayerCode) ? model.RedirectUrl : model.ShareUrl;

            var services = await GetServices(publication);

            foreach (var service in services)
            {
                await service.Send(request.Comment, url, GetTags(request));
            }

            return(model);
        }

        throw new Exception("Can't save publication to database");
    }
        public IActionResult EditPost(int id, [FromBody] NewPostRequest request)
        {
            Post post = context.Posts.Include(p => p.Owner)
                        .FirstOrDefault(p => p.Id == id);

            if (post == null)
            {
                return(NotFound());
            }
            else if (post.Owner.GUID != currentUser.GUID)
            {
                return(Forbid());
            }

            post.Body = request.Body;
            context.SaveChanges();
            return(Ok(new PostResponse(post)));
        }
Exemple #12
0
        private ApiResponse AddPost(NewPostRequest request)
        {
            var apiResp = new ApiResponse
            {
                ResponseCode = ResponseCode.Fail
            };

            var postDto = new Dto.Post
            {
                BlogId    = request.BlogId,
                Content   = request.Content,
                Title     = request.Title,
                CreatedAt = DateTime.Now
            };

            _postBusiness.Add(postDto);

            apiResp.ResponseCode = ResponseCode.Success;
            return(apiResp);
        }
        public async Task <IActionResult> AddPublicaton(NewPostRequest request)
        {
            DAL.User user = _userManager.GetBySecretKey(request.Key);

            if (user == null)
            {
                return(StatusCode((int)HttpStatusCode.Forbidden));
            }

            var extractor = new X.Web.MetaExtractor.Extractor();

            var metadata = await extractor.Extract(new Uri(request.Link));


            var publication = new DAL.Publication
            {
                Title       = metadata.Title,
                Description = metadata.Description,
                Link        = metadata.Url,
                Image       = metadata.Image.FirstOrDefault(),
                Type        = metadata.Type,
                DateTime    = DateTime.Now,
                UserId      = user.Id,
                CategoryId  = request.CategoryId,
                Comment     = request.Comment
            };

            publication = await _publicationManager.Save(publication);

            if (publication != null)
            {
                var model = new PublicationViewModel(publication, Settings.Current.WebSiteUrl);

                await _telegramManager.Send(request.CategoryId, request.Comment, request.Link);

                return(Created(new Uri($"{Core.Settings.Current.WebSiteUrl}post/{publication.Id}"), model));
            }

            return(StatusCode((int)HttpStatusCode.BadRequest));
        }
        public async Task <ActionResult <NewPostResponse> > NewPost([FromBody] NewPostRequest req)
        {
            try
            {
                await HttpContext.Session.LoadAsync().ConfigureAwait(false);

                if (!HttpContext.Session.Keys.Contains("Id"))
                {
                    return(Unauthorized());
                }

                User user = this._db.User.Where(u => u.Id == HttpContext.Session.GetInt32("Id")).FirstOrDefault();
                user.Post.Add(new Post()
                {
                    Address     = req.Address,
                    Description = req.Description,
                    Latitude    = req.Latitude,
                    Longitude   = req.Longitude,
                    TimePosted  = DateTime.UtcNow,
                    Title       = req.Title,
                    TimeDue     = req.DueDate
                });

                await this._db.SaveChangesAsync().ConfigureAwait(false);

                return(new NewPostResponse()
                {
                    statusCode = WebTypes.StatusCode.OK, errorMessage = "Posted succesfully!"
                });
            } catch (Exception e)
            {
                this._logger.LogError(e, "Fucky wuckie happened!", null);
                return(new NewPostResponse()
                {
                    statusCode = WebTypes.StatusCode.ERROR, errorMessage = "Server error!"
                });
            }
        }
        public Task <List <PostId> > ProcessAsync(NewPostRequest input)
        {
            // Note: Your real system integration would happen here.

            ////Create a new blog post in Vellum
            // input.BlogId
            // input.title
            // input.description
            // input.link =
            // //Need to loop through categories...
            // input.categories[]

            ////Publish the post, if requested
            //input.Publish

            //Return the id - the slug
            return(Task.FromResult(new List <PostId>
            {
                new PostId
                {
                    Id = "/blogs/blog1",
                }
            }));
        }
Exemple #16
0
        public async Task <IActionResult> AddPublication(NewPostRequest request)
        {
            var user = await _userManager.GetBySecretKey(request.Key);

            if (user == null)
            {
                _logger.Write(LogLevel.Warning, $"Somebody tried to login with this key: `{request.Key}`. Text: `{request.Comment}`");

                return(StatusCode((int)HttpStatusCode.Forbidden, "Incorrect security key"));
            }

            var extractor        = new X.Web.MetaExtractor.Extractor();
            var languageAnalyzer = new LanguageAnalyzerService(_settings.CognitiveServicesTextAnalyticsKey, _logger);

            try
            {
                var metadata = await extractor.ExtractAsync(request.Link);

                var existingPublication = await _publicationManager.Get(new Uri(metadata.Url));

                if (existingPublication != null)
                {
                    return(StatusCode((int)HttpStatusCode.Conflict, "Publication with this URL already exist"));
                }

                var languageCode = languageAnalyzer.GetTextLanguage(metadata.Description);
                var languageId   = await _localizationManager.GetLanguageId(languageCode) ?? Language.EnglishId;

                var image = metadata.Images.FirstOrDefault();

                var publication = new DAL.Publication
                {
                    Title       = metadata.Title,
                    Description = metadata.Description,
                    Link        = metadata.Url,
                    Image       = string.IsNullOrWhiteSpace(image) || image.Length > 250 ? string.Empty : image,
                    Type        = "article",
                    DateTime    = DateTime.Now,
                    UserId      = user.Id,
                    CategoryId  = request.CategoryId,
                    Comment     = request.Comment,
                    LanguageId  = languageId
                };

                var player = EmbeddedPlayerFactory.CreatePlayer(request.Link);

                if (player != null)
                {
                    publication.EmbededPlayerCode = await player.GetEmbeddedPlayerUrl(request.Link);
                }

                publication = await _publicationManager.Save(publication);

                if (publication != null)
                {
                    var model = new PublicationViewModel(publication, _settings.WebSiteUrl);

                    //If we can embed main content into site page, so we can share this page.
                    var url = string.IsNullOrEmpty(model.EmbededPlayerCode) ? model.Link : model.ShareUrl;

                    foreach (var crossPostManager in _crossPostManagers)
                    {
                        await crossPostManager.Send(request.CategoryId, request.Comment, url);
                    }

                    return(Created(new Uri(model.ShareUrl), model));
                }

                throw new Exception("Can't save publication to database");
            }
            catch (Exception ex)
            {
                _logger.Write(LogLevel.Error, "Error while creating new publication", ex);

                return(BadRequest(ex.Message));
            }
        }
 public Post(NewPostRequest request, CurrentUser user) : base(request.Body, user.GUID)
 {
     FilePaths = null; // TODO
 }
        public async Task <IActionResult> AddPublicaton(NewPostRequest request)
        {
            var user = _userManager.GetBySecretKey(request.Key);

            if (user == null)
            {
                return(StatusCode((int)HttpStatusCode.Forbidden));
            }

            var extractor        = new X.Web.MetaExtractor.Extractor();
            var languageAnalyzer = new LanguageAnalyzer(Settings.Current.CognitiveServicesTextAnalyticsKey);

            try
            {
                var metadata = await extractor.Extract(new Uri(request.Link));

                var languageCode = languageAnalyzer.GetTextLanguage(metadata.Description);
                var languageId   = _localizationManager.GetLanguageId(languageCode) ?? Language.EnglishId;

                var publication = new DAL.Publication
                {
                    Title       = metadata.Title,
                    Description = metadata.Description,
                    Link        = metadata.Url,
                    Image       = metadata.Image.FirstOrDefault(),
                    Type        = metadata.Type,
                    DateTime    = DateTime.Now,
                    UserId      = user.Id,
                    CategoryId  = request.CategoryId,
                    Comment     = request.Comment,
                    LanguageId  = languageId
                };

                if (EmbededPlayer.GetPlayerSoure(request.Link) != null)
                {
                    var player = new EmbededPlayer(request.Link);
                    publication.EmbededPlayerCode = player.Render();
                }

                publication = await _publicationManager.Save(publication);

                if (publication != null)
                {
                    var model = new PublicationViewModel(publication, Settings.Current.WebSiteUrl);

                    //If we can embed main content into site page, so we can share this page.
                    var url = string.IsNullOrEmpty(model.EmbededPlayerCode) ? model.Link : model.ShareUrl;

                    await _crossPostManager.Send(request.CategoryId, request.Comment, url);

                    return(Created(new Uri(model.ShareUrl), model));
                }
                else
                {
                    throw new Exception("Can't save publication to databse");
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }