Beispiel #1
0
        /// <summary>
        /// Based on a supplied date in the past calculate a trend score
        /// that increments per day and is complemented by activities
        /// </summary>
        /// <param name="meme"></param>
        /// <returns></returns>
        private double CalculateTrendScore(IMeme meme)
        {
            double trendScore = 0;

            // Add a fixed score for every day greater than the base date
            trendScore += (meme.DateCreated - baseDate).Days * ScorePerDay;

            // Add a fixed score for each view
            trendScore += meme.Views * ScorePerView;

            // Add a fixed score for each like
            trendScore += meme.Likes * ScorePerLike;

            // Add a fixed score for each dislike (a negative)
            trendScore += meme.Dislikes * ScorePerDislike;

            // Add a fixed score for each comment
            trendScore += meme.UserCommentCount * ScorePerComment;

            // Add a fixed score for each reply
            trendScore += meme.ReplyCount * ScorePerReply;

            // Add a fixed score for each repost
            trendScore += meme.Reposts * ScorePerRepost;

            return(trendScore);
        }
Beispiel #2
0
        /// <summary>
        /// Repost the specified meme by the specified user
        /// </summary>
        /// <param name="meme"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public IMeme RepostMeme(IMeme meme, IUser user)
        {
            IRepost repost = new Repost
            {
                DateCreated = DateTime.Now.ToUniversalTime(),
                MemeId      = meme.RepostOfId ?? meme.Id,            // If the meme being reposted is also a repost then use the original meme as the "repost of" id
                UserId      = user.Id,
                UserName    = user.UserName
            };

            // Save the repost
            repository.Save(repost);

            // Increment the repost count of the meme and its creator
            meme = Reposted(meme);

            // Add repost to time line
            repository.Save(new TimeLine(user.Id, TimeLineEntry.Repost, repost.MemeId, meme.Id, null, null));

            // Update the number of reposts performed by this user
            user.Reposts++;

            // Save commentator
            repository.Save(user);

            return(meme);
        }
Beispiel #3
0
        /// <summary>
        /// Inser the comment and record on user time line
        /// </summary>
        /// <param name="userComment"></param>
        /// <returns></returns>
        public IUserComment PostUserComment(IUserComment userComment)
        {
            // Post the comment
            userComment = repository.Save(userComment);

            // Record on time line
            repository.Save(new TimeLine(userComment.UserId, TimeLineEntry.Comment, userComment.MemeId, userComment.Id, null, null));

            // Update the number of comments added by this user
            IUser user = repository.GetUser(userComment.UserId);

            if (user != null)
            {
                user.Comments++;

                // Save commentator
                repository.Save(user);
            }

            // Update the number of comments on the meme
            IMeme meme = repository.GetMeme(userComment.MemeId);

            if (meme != null)
            {
                meme.UserCommentCount++;

                // Save comment count
                memeBusiness.Save(meme);
            }
            return(userComment);
        }
Beispiel #4
0
        /// <summary>
        /// Adds a reply (with an id) to the replies of the supplied meme.
        /// The reply trend and date added are calculated before appending to the meme
        /// </summary>
        /// <param name="meme">The meme being replied to</param>
        /// <param name="replyMemeId">Id of the reply</param>
        /// <returns></returns>
        public IMeme AddReplyToMeme(IMeme meme, string replyMemeId)
        {
            IMeme replyMeme = repository.GetMeme(replyMemeId);

            if (replyMeme != null)
            {
                if (meme.ReplyIds == null)
                {
                    meme.ReplyIds = new List <IReply>();
                }

                // Add the repy id to the top of the list of replies. Set an hourly trend
                meme.ReplyIds.Insert(0, new Reply
                {
                    Id          = replyMemeId,
                    DateCreated = DateTime.UtcNow
                });

                meme.ReplyCount++;

                // Save the meme
                meme = Save(meme);

                // Add reply to time line of the replier
                repository.Save(new TimeLine(replyMeme.CreatedByUserId, TimeLineEntry.Reply, meme.Id, replyMeme.Id, null, null));

                // Update the number of replies added by the replier
                replyMeme.Creator.Replies++;

                repository.Save(replyMeme.Creator);
            }

            return(meme);
        }
Beispiel #5
0
        public HttpResponseMessage ReportMeme(string id, [FromBody] ReportModel report)
        {
            if (report == null || (report.Objection ?? "").Length == 0)
            {
                return(Request.CreateResponse(HttpStatusCode.PreconditionFailed));
            }
            string userId = User.Identity.UserId();
            // Retrieve the authenticated user
            IUser userProfile = repository.GetUser(userId);

            if (userProfile == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
            IMeme meme = repository.GetMeme(id);

            if (meme == null)
            {
                var responseNotFound = Request.CreateResponse(HttpStatusCode.NotFound);
                responseNotFound.Headers.Location = new Uri(Request.RequestUri, "/api/meme/" + id);
                return(responseNotFound);
            }

            // Report the meme as offensive under the users name
            meme = memeBusiness.ReportMeme(meme, report.Objection, userProfile);

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, meme);

            response.Headers.Location = new Uri(Request.RequestUri, "/api/meme/" + meme.Id);
            return(response);
        }
Beispiel #6
0
        public HttpResponseMessage RepostMeme(string id)
        {
            string userId = User.Identity.UserId();
            // Retrieve the authenticated user
            IUser userProfile = repository.GetUser(userId);

            if (userProfile == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
            IMeme meme = repository.GetMeme(id);

            if (meme == null)
            {
                var responseNotFound = Request.CreateResponse(HttpStatusCode.NotFound);
                responseNotFound.Headers.Location = new Uri(Request.RequestUri, "/api/meme/" + id);
                return(responseNotFound);
            }

            // Repost the meme under the users name
            meme = memeBusiness.RepostMeme(meme, userProfile);

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, meme);

            response.Headers.Location = new Uri(Request.RequestUri, "/api/meme/" + meme.Id);
            return(response);
        }
Beispiel #7
0
 public MemeController(IMeme memeService, IUserMeme userMemeService, ITheLoai theLoaiService, IMemeCanDuyet memeCanDuyetService)
 {
     this.memeService         = memeService;
     this.userMemeService     = userMemeService;
     this.theLoaiService      = theLoaiService;
     this.memeCanDuyetService = memeCanDuyetService;
 }
Beispiel #8
0
        public IHttpActionResult GetMemeTimeline(string id, int days, int maxCount)
        {
            TimelineGroupModel timelineGroupModel = new TimelineGroupModel
            {
                User           = null,
                TimelineGroups = new List <TimelineGroup>()
            };

            // Get the specified meme
            IMeme meme = repository.GetMeme(id);

            if (meme == null)
            {
                // Meme has been removed or the ID was invlide. No need to error out, handle gracefully
                return(Ok(timelineGroupModel));
            }

            // Determine the current user
            string currentUserId = User.Identity.UserId();
            var    currentUser   = repository.GetUser(currentUserId);

            // Restrict the activity returned to the current user and those he/she follows UNLESS THE CURRENT USER CREATED THE MEME
            bool includeActivityOfAllUsers = meme.CreatedByUserId == currentUserId;

            // Get the activity of the current user and those he/she follows (grouped by meme)
            List <string> userIds = new List <string> {
                currentUserId
            };

            userIds.AddRange(currentUser.FollowingIds.Select(x => x.Id));

            // Get all activity on this meme in the last X days, buy ANY user
            List <ITimeLine> memeActivities = repository.GetMemeTimeLine(id, days).OrderByDescending(x => x.DateOfEntry).ToList();


            // Create the timeline group with all activity on this meme by the current user and those he/she follows
            foreach (ITimeLine memeActivity in memeActivities)
            {
                // Was this activity performed the current user or  those he/she follows?
                if (userIds.Contains(memeActivity.UserId) || includeActivityOfAllUsers)
                {
                    // Add to model up to a max count
                    AddActivitytoTimeLineGroups(ref timelineGroupModel, memeActivity, maxCount);
                }
            }
            Debug.Assert(timelineGroupModel.TimelineGroups.Count <= 1, "Activity on single meme should only render one time line group!!!");

            // Ensure the timeline entries in each group are ordered descending by date of entry ... there should be only 1 group
            timelineGroupModel.TimelineGroups.ForEach(x =>
            {
                x.TimelineEntries = x.TimelineEntries.OrderByDescending(y => y.DateOfEntry).ToList();
            });

            // Order by date descending
            timelineGroupModel.TimelineGroups = timelineGroupModel.TimelineGroups.OrderByDescending(x => x.TimeStamp).ToList();

            return(Ok(timelineGroupModel));
        }
Beispiel #9
0
    internal static string GetMemeData(IMeme meme, bool includeWatermark)
    {
        if (meme is VideoMeme video)
        {
            return($"{meme.Name} - Length: {video.Length} - Rate: {meme.Rate}{(includeWatermark ? " - (c) InterWebz" : string.Empty)}");
        }

        return($"{meme.Name} - Rate: {meme.Rate}{(includeWatermark ? " - (c) InterWebz" : string.Empty)}");
    }
Beispiel #10
0
        /// <summary>
        /// Using the seed image and comment data in the meme supplied, create a meme image
        /// </summary>
        /// <param name="memeData"></param>
        /// <param name="seedImage"></param>
        /// <returns></returns>
        public byte[] GenerateMemeImage(IMeme memeData, byte[] seedImage)
        {
            using (MemoryStream ms = new MemoryStream(seedImage),
                   newMemoryStream = new MemoryStream())
            {
                SolidBrush shadowBrush;
                SolidBrush textBrush;
                // create the start Bitmap from the MemoryStream that contains the image
                Bitmap   memeBitmap = new Bitmap(ms);
                Graphics g          = Graphics.FromImage(memeBitmap);
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

                StringFormat strFormat = new StringFormat();
                foreach (IComment comment in memeData.Comments)
                {
                    float x = comment.Position.X, width = comment.Position.Width, y = comment.Position.Y, height = comment.Position.Height;

                    //ToDo: Apply formmating
                    strFormat.Alignment = StringAlignment.Near;
                    switch (comment.TextAlign)
                    {
                    case "left":
                        strFormat.Alignment = StringAlignment.Near;
                        break;

                    case "center":
                        strFormat.Alignment = StringAlignment.Center;
                        break;

                    case "right":
                        strFormat.Alignment = StringAlignment.Far;
                        break;
                    }
                    Font font = new Font(comment.FontFamily, float.Parse(comment.FontSize.Replace("pt", "")), FontStyle.Bold, GraphicsUnit.Point);

                    // Draw the shadow (really a border) by printing the text slightly to the left, then right, then above and below of the real text.
                    if (comment.TextShadow != "none")
                    {
                        shadowBrush = new SolidBrush(Color.FromName(comment.TextShadow));
                        g.DrawString(comment.Text, font, shadowBrush, new RectangleF(x - 1, y, x - 1 + width, y + height), strFormat);
                        g.DrawString(comment.Text, font, shadowBrush, new RectangleF(x + 1, y, x + 1 + width, y + height), strFormat);
                        g.DrawString(comment.Text, font, shadowBrush, new RectangleF(x, y - 1, x + width, y - 1 + height), strFormat);
                        g.DrawString(comment.Text, font, shadowBrush, new RectangleF(x, y + 1, x + width, y + 1 + height), strFormat);
                    }

                    textBrush = new SolidBrush(Color.FromName(comment.Color));

                    // Print the text
                    g.DrawString(comment.Text, font, textBrush, new RectangleF(x, y, x + width, y + height), strFormat);
                    //g.DrawString(comment.Text, font, textBrush, new RectangleF(1, 50, 250, 100), strFormat);
                }
                memeBitmap.Save(newMemoryStream, ImageFormat.Jpeg);

                return(newMemoryStream.ToArray());
            }
        }
Beispiel #11
0
        /// <summary>
        /// Using the seed image and comment data in the meme supplied, create a meme image 
        /// </summary>
        /// <param name="memeData"></param>
        /// <param name="seedImage"></param>
        /// <returns></returns>
        public byte[] GenerateMemeImage(IMeme memeData, byte[] seedImage)
        {
            using (MemoryStream ms = new MemoryStream(seedImage),
                                newMemoryStream = new MemoryStream())
            {
                SolidBrush shadowBrush;
                SolidBrush textBrush;
                // create the start Bitmap from the MemoryStream that contains the image
                Bitmap memeBitmap = new Bitmap(ms);
                Graphics g = Graphics.FromImage(memeBitmap);
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

                StringFormat strFormat = new StringFormat();
                foreach (IComment comment in memeData.Comments)
                {
                    float x = comment.Position.X, width = comment.Position.Width, y = comment.Position.Y, height = comment.Position.Height;

                    //ToDo: Apply formmating
                    strFormat.Alignment = StringAlignment.Near;
                    switch (comment.TextAlign)
                    {
                        case "left":
                            strFormat.Alignment = StringAlignment.Near;
                            break;
                        case "center":
                            strFormat.Alignment = StringAlignment.Center;
                            break;
                        case "right":
                            strFormat.Alignment = StringAlignment.Far;
                            break;
                    }
                    Font font = new Font(comment.FontFamily, float.Parse(comment.FontSize.Replace("pt", "")),FontStyle.Bold, GraphicsUnit.Point);

                    // Draw the shadow (really a border) by printing the text slightly to the left, then right, then above and below of the real text.
                    if (comment.TextShadow != "none")
                    {
                        shadowBrush = new SolidBrush(Color.FromName(comment.TextShadow));
                        g.DrawString(comment.Text, font, shadowBrush, new RectangleF(x - 1, y, x - 1 + width, y + height), strFormat);
                        g.DrawString(comment.Text, font, shadowBrush, new RectangleF(x + 1, y, x + 1 + width, y + height), strFormat);
                        g.DrawString(comment.Text, font, shadowBrush, new RectangleF(x, y - 1, x + width, y - 1 + height), strFormat);
                        g.DrawString(comment.Text, font, shadowBrush, new RectangleF(x, y + 1, x + width, y + 1 + height), strFormat);
                    }

                    textBrush = new SolidBrush(Color.FromName(comment.Color));

                    // Print the text
                    g.DrawString(comment.Text, font, textBrush, new RectangleF(x , y, x + width, y + height), strFormat);
                    //g.DrawString(comment.Text, font, textBrush, new RectangleF(1, 50, 250, 100), strFormat);

                }
                memeBitmap.Save(newMemoryStream, ImageFormat.Jpeg);

                return newMemoryStream.ToArray();
            }
        }
Beispiel #12
0
        /// <summary>
        /// Retrieved a lite meme model
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private MemeLiteModel GetMemeLite(string id)
        {
            IMeme meme = repository.GetMeme(id);

            if (meme == null)
            {
                return(null);
            }

            return(ToMemeLiteModel(meme));
        }
Beispiel #13
0
        /// <summary>
        /// Calculate the trend score and save the meme
        /// </summary>
        /// <param name="meme"></param>
        /// <returns></returns>
        public IMeme SaveMeme(IMeme meme)
        {
            bool isNew = false;

            // Get the number of user comments
            if (meme.Id != null)
            {
                meme.UserCommentCount = repository.GetUserCommentCount(meme.Id);
            }
            else
            {
                isNew = true;
            }

            // Meme is top leve if it has no reposnseToId
            meme.IsTopLevel = meme.ResponseToId == null;

            // Fall back on adding the text manually to the seed if mem image not supplied by client
            if (meme.ImageData == null || meme.ImageData.Length == 0)
            {
                // Get the seed image
                byte[] seedData = repository.GetSeed(meme.SeedId).ImageData;

                // Add the meme comments to the seed image to make the meme
                meme.ImageData = imageManager.GenerateMemeImage(meme, seedData);
            }

            // If this meme is a reply to another then update the reply trend to reflect the new data of this meme with in the reply list
            if (meme.IsTopLevel == false)
            {
                // This meme is a reply to another parent meme. Update the parent to reflect the new state of this meme
                this.UpdateReplyToMeme(meme);
            }

            // Save the meme
            var savedMeme = Save(meme);

            // Update the users time line and number of posts (Don't count replies)
            if (isNew && (savedMeme.ResponseToId ?? "").Length == 0)
            {
                repository.Save(new TimeLine(savedMeme.CreatedByUserId, TimeLineEntry.Post, savedMeme.Id, null, null, null));
                var creator = repository.GetUser(savedMeme.CreatedByUserId);
                if (creator != null)
                {
                    // Increment the number of posts by this user
                    creator.Posts++;
                    repository.Save(creator);
                }
            }
            // Add to the time line
            return(savedMeme);
        }
Beispiel #14
0
        public HttpResponseMessage Get(string id)
        {
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            IMeme meme = repository.GetMeme(id);

            if (meme == null)
            {
                return(this.Request.CreateResponse(HttpStatusCode.NotFound, "Invalid ID"));
            }
            result.Content = new ByteArrayContent(meme.ImageData);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            return(result);
        }
Beispiel #15
0
        /// <summary>
        /// Invoke firwe and forget to save the hash tags, calulate the hash tags new trend score and
        /// link the hash tag to the meme for speedy search by HashTag
        /// </summary>
        /// <param name="savedMeme"></param>
        /// <param name="previousTrendScore"></param>
        private void UpdateHashTags(IMeme savedMeme, double previousTrendScore)
        {
#pragma warning disable 4014
            Task.Run(() =>
            {
                // Update the trendscore of the meme's hash tags. Associate the hash tag and meme
                foreach (string hashTag in savedMeme.HashTags)
                {
                    hashTagBusiness.SaveMemeTags(hashTag, savedMeme.Id, previousTrendScore, savedMeme.TrendScore);
                }
            }).ConfigureAwait(false);
#pragma warning restore 4014
        }
Beispiel #16
0
        /// <summary>
        /// Save the meme. Calculate the meme trend score. Set the meme hash tags trend score.
        /// </summary>
        /// <param name="meme">Meme to save</param>
        /// <returns></returns>
        public IMeme Save(IMeme meme)
        {
            double previousTrendScore = meme.TrendScore;

            // Calculate the Trend score
            meme.TrendScore = CalculateTrendScore(meme);

            // Save meme
            IMeme savedMeme = repository.Save(meme);

            // On an new thread, update the trendscore of the meme's hash tags. Associate the hash tag and meme
            UpdateHashTags(savedMeme, previousTrendScore);

            return(savedMeme);
        }
Beispiel #17
0
        /// <summary>
        /// Repost a meme
        /// </summary>
        /// <param name="repost"></param>
        /// <returns></returns>
        public IMeme Save(IRepost repost)
        {
            IMeme newMemeFromOriginal = GetMeme(repost.MemeId);

            newMemeFromOriginal.RepostOfId      = repost.MemeId;
            newMemeFromOriginal.Id              = null;
            newMemeFromOriginal.DateCreated     = repost.DateCreated;
            newMemeFromOriginal.CreatedByUserId = repost.UserId;
            newMemeFromOriginal.CreatedBy       = repost.UserName;
            newMemeFromOriginal.Likes           = 0;
            newMemeFromOriginal.Dislikes        = 0;
            newMemeFromOriginal.Reposts         = 0;
            newMemeFromOriginal.Views           = 0;
            newMemeFromOriginal.IsTopLevel      = true;
            return(Save(newMemeFromOriginal));
        }
Beispiel #18
0
        public IHttpActionResult Get(string id)
        {
            IMeme meme = repository.GetMeme(id);

            if (meme == null)
            {
                return(NotFound());
            }
            ISeed seed = repository.GetSeed(meme.SeedId);

            return
                (Ok(
                     new
            {
                meme.Id,
                meme.CreatedBy,
                meme.CreatedByUserId,
                Creator = repository.GetUser(meme.CreatedByUserId),
                DateCreated = meme.DateCreated.ToLocalTime(),
                meme.Title,
                Comments = meme.Comments.Select(x =>
                {
                    x.Text = WebUtility.HtmlEncode(x.Text);
                    return x;
                }).ToList(),
                meme.ResponseToId,
                replyCount = meme.ReplyIds.Count,
                userCommentCount = repository.GetUserCommentCount(id),
                meme.Likes,
                meme.Dislikes,
                meme.Favourites,
                meme.Shares,
                meme.Views,
                meme.Reposts,
                seedImage =
                    new
                {
                    seed.Id,
                    seed.Width,
                    seed.Height,
                    image = "data:image/jpeg;base64," + imageManager.GetImageData(seed.ImageData)
                },
                meme.HashTags
            }));
        }
Beispiel #19
0
 public MemeLiteModel(IRepository repository, IMeme meme)
 {
     Id               = meme.Id;
     CreatedBy        = meme.CreatedBy;
     CreatedByUserId  = meme.CreatedByUserId;
     Creator          = meme.Creator;
     DateCreated      = meme.DateCreated.ToLocalTime();
     ResponseToId     = meme.ResponseToId;
     replyCount       = meme.ReplyIds.Count;
     userCommentCount = repository.GetUserCommentCount(meme.Id);
     Likes            = meme.Likes;
     Dislikes         = meme.Dislikes;
     Favourites       = meme.Favourites;
     Shares           = meme.Shares;
     Views            = meme.Views;
     Reposts          = meme.Reposts;
     RepostOfId       = meme.RepostOfId;
     HashTags         = meme.HashTags.Select(WebUtility.HtmlEncode).ToList();
 }
Beispiel #20
0
        /// <summary>
        /// Update the parent meme to reflect the new state of the supplied meme
        /// Recalculate and update the reply trend score of the supplied meme inside the reply list of the parent meme (identified by ResponseToId)
        /// </summary>
        /// <param name="replyMeme"></param>
        /// <returns></returns>
        public void UpdateReplyToMeme(IMeme replyMeme)
        {
            if (replyMeme != null && replyMeme.ResponseToId != null)
            {
                IMeme parentMeme = repository.GetMeme(replyMeme.ResponseToId);
                if (parentMeme.ReplyIds == null)
                {
                    // This meme is not a reply within the parent meme
                    return;
                }

                IReply reply = parentMeme.ReplyIds.FirstOrDefault(x => x.Id == replyMeme.Id);
                if (reply != null)
                {
                    // Save the parent meme to which the reply meme is a response to (with the updated reply trend scrore)
                    Save(parentMeme);
                }
            }
        }
Beispiel #21
0
        /// <summary>
        /// Report the specified meme as offensive by the specified user
        /// </summary>
        /// <param name="meme"></param>
        /// <param name="objection"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public IMeme ReportMeme(IMeme meme, string objection, IUser user)
        {
            IReport report = new Report
            {
                DateCreated = DateTime.Now.ToUniversalTime(),
                MemeId      = meme.Id,
                UserId      = user.Id,
                Objection   = objection
            };

            // Save the report
            repository.Save(report);

            // Up the report count of the meme
            meme.ReportCount++;
            Save(meme);

            return(meme);
        }
Beispiel #22
0
        /// <summary>
        /// Record interation with the meme.
        /// Increment count of likes, dislikes, views, shares
        /// </summary>
        /// <param name="likesIncrement"></param>
        /// <param name="dislikesIncrement"></param>
        /// <param name="viewsIncrement"></param>
        /// <param name="sharesIncrement"></param>
        /// <param name="favouritesIncrement"></param>
        /// <param name="memeId"></param>
        /// <returns></returns>
        // ReSharper disable once UnusedParameter.Local
        private HttpResponseMessage MemeInteraction(string memeId, int likesIncrement, int dislikesIncrement, int viewsIncrement, int sharesIncrement, int favouritesIncrement)
        {
            string userId = User.Identity.UserId();             // null if not signed in

            IMeme meme = repository.GetMeme(memeId);

            if (meme == null)
            {
                var responseNotFound = Request.CreateResponse(HttpStatusCode.NotFound);
                responseNotFound.Headers.Location = new Uri(Request.RequestUri, "/api/meme/" + memeId);
                return(responseNotFound);
            }

            // Update the meme
            meme = memeBusiness.UpdateMemeInteraction(memeId, userId, likesIncrement, dislikesIncrement, viewsIncrement, sharesIncrement, favouritesIncrement);

            var response = Request.CreateResponse(HttpStatusCode.OK, meme);

            response.Headers.Location = new Uri(Request.RequestUri, "/api/meme/" + meme.Id);
            return(response);
        }
Beispiel #23
0
        public HttpResponseMessage AddReply(string id, string replyMemeId)
        {
            User.Identity.UserId();

            IMeme meme = repository.GetMeme(id);

            if (meme == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            // Add the repy id to the meme, calculate a reply trend
            memeBusiness.AddReplyToMeme(meme, replyMemeId);

            // Update the meme
            memeBusiness.SaveMeme(meme);

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, meme);

            response.Headers.Location = new Uri(Request.RequestUri, "/api/meme/" + meme.Id);
            return(response);
        }
Beispiel #24
0
        /// <summary>
        /// Meme has been reposted
        /// </summary>
        /// <param name="meme"></param>
        /// <returns></returns>
        private IMeme Reposted(IMeme meme)
        {
            // Increment the repost count of the meme
            meme.Reposts++;

            // Save the meme and calculate it's new trend score
            SaveMeme(meme);

            // Increment the reposted number of the creator
            IUser creator = repository.GetUser(meme.CreatedByUserId);

            if (creator != null)
            {
                // Incrememnt the number of time this user has been reposted
                creator.Reposted++;

                // Save
                repository.Save(creator);
            }

            // If this is a repost then do the same for the original
            if (meme.RepostOfId != null)
            {
                IMeme original = repository.GetMeme(meme.RepostOfId);
                if (original != null)
                {
                    // A repost should always reference an original (not another repost)
                    if (original.RepostOfId != null)
                    {
                        throw new Exception(string.Format("Repost of a repost not allowed - {0} - {1}", meme.Id, meme.RepostOfId));
                    }

                    // Recursive call to update the original
                    Reposted(original);
                }
            }
            return(meme);
        }
Beispiel #25
0
        public IHttpActionResult GetMemeReplies(string id, int skip, int take)
        {
            IMeme meme           = repository.GetMeme(id);
            int   fullReplyCount = 0;

            if (meme == null)
            {
                return(NotFound());
            }

            List <MemeLiteModel> replies = new List <MemeLiteModel>();

            // No replies no list
            if (meme.ReplyIds != null)
            {
                // Gwet the full count of all replies (even if not all are being returned)
                fullReplyCount = meme.ReplyIds.Count;

                // Get the meme ids of the relevent replies
                IEnumerable <IReply> memeReplies = meme.ReplyIds
                                                   .OrderByDescending(x => x.TrendScore)
                                                   .ThenByDescending(y => y.DateCreated)
                                                   .Skip(skip)
                                                   .Take(take);
                // Create the list of reply memes
                foreach (IReply reply in memeReplies)
                {
                    MemeLiteModel replyMeme = this.GetMemeLite(reply.Id);
                    if (replyMeme != null)
                    {
                        replies.Add(replyMeme);
                    }
                }
            }

            return(Ok(new { fullReplyCount, replies }));
        }
Beispiel #26
0
        /// <summary>
        /// Calculate the trend score and save the meme
        /// </summary>
        /// <param name="meme"></param>
        /// <returns></returns>
        public IMeme SaveMeme(IMeme meme)
        {
            long userCommentCount = 0;

              // Get the number of user comments
              if (meme.Id != null)
              {
            userCommentCount = repository.GetUserCommentCount(meme.Id);
              }

              // Meme is top leve if it has no reposnseToId
              meme.IsTopLevel = meme.ResponseToId == null;

              // Calculate the meme trend score
              meme.TrendScore = trendManager.CalculateDailyTrendScore(meme, userCommentCount);

              // Fall back on adding the text manually to the seed if mem image not supplied by client
              if (meme.ImageData == null || meme.ImageData.Length == 0)
              {
            // Get the seed image
            byte[] seedData = repository.GetSeed(meme.SeedId).ImageData;

            // Add the meme comments to the seed image to make the meme
            meme.ImageData = imageManager.GenerateMemeImage(meme, seedData);
              }

              // If this meme is a reply to another then update the reply trend to reflect the new data of this meme with in the reply list
              if (meme.IsTopLevel == false)
              {
            // This meme is a reply to another parent meme. Update the parent to reflect the new state of this meme
            this.UpdateReplyToMeme(meme);
              }

              // Save the meme
              return repository.Save(meme);
        }
Beispiel #27
0
        /// <summary>
        /// Adds a reply (with an id) to the replies of the supplied meme.
        /// The reply trend and date added are calculated before appending to the meme
        /// </summary>
        /// <param name="meme"></param>
        /// <param name="replyMemeId"></param>
        /// <returns></returns>
        public IMeme AddReplyToMeme(IMeme meme, string replyMemeId)
        {
            IMeme replyMeme = repository.GetMeme(replyMemeId);
              if (replyMeme != null)
              {
            if (meme.ReplyIds == null)
            {
              meme.ReplyIds = new List<IReply>();
            }

            // Add the repy id to the top of the list of replies. Set an hourly trend
            meme.ReplyIds.Insert(0, new Reply
            {
              Id = replyMemeId,
              DateCreated = DateTime.UtcNow,
              TrendScore = trendManager.CalculateHourlyTrendScore(replyMeme, 0, meme.DateCreated)
            });

            // Save the meme
            meme = repository.Save(meme);
              }

              return meme;
        }
Beispiel #28
0
 public MemeCanDuyetsController(IMemeCanDuyet context, ITheLoai theLoaiService, IMeme memeService)
 {
     _context            = context;
     this.theLoaiService = theLoaiService;
     this.memeService    = memeService;
 }
Beispiel #29
0
 /// <summary>
 /// Convert a meme to a meme lite model
 /// </summary>
 /// <param name="meme"></param>
 /// <returns></returns>
 private MemeLiteModel ToMemeLiteModel(IMeme meme)
 {
     return(new MemeLiteModel(repository, meme));
 }
Beispiel #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="likesIncrement"></param>
        /// <param name="dislikesIncrement"></param>
        /// <param name="viewsIncrement"></param>
        /// <param name="sharesIncrement"></param>
        /// <param name="favouritesIncrement"></param>
        /// <param name="memeId"></param>
        /// <returns></returns>
        public IMeme UpdateMemeInteraction(string memeId, string userId, int likesIncrement, int dislikesIncrement, int viewsIncrement, int sharesIncrement, int favouritesIncrement)
        {
            IMeme meme = repository.GetMeme(memeId);

            if (meme == null)
            {
                throw new Exception("Object not found");
            }
            meme.Likes      += likesIncrement;
            meme.Dislikes   += dislikesIncrement;
            meme.Views      += viewsIncrement;
            meme.Shares     += sharesIncrement;
            meme.Favourites += favouritesIncrement;

            // Save meme
            meme = SaveMeme(meme);

            if (userId != null)
            {
                // Add like to time line
                if (likesIncrement > 0)
                {
                    repository.Save(new TimeLine(userId, TimeLineEntry.Like, meme.Id, null, null, null));
                }
                // Add dislike to time line
                if (dislikesIncrement > 0)
                {
                    repository.Save(new TimeLine(userId, TimeLineEntry.Dislike, meme.Id, null, null, null));
                }

                IUser user = repository.GetUser(userId);
                if (user != null)
                {
                    user.Likes      += likesIncrement;
                    user.Dislikes   += dislikesIncrement;
                    user.Views      += viewsIncrement;
                    user.Shares     += sharesIncrement;
                    user.Favourites += favouritesIncrement;

                    // Save meme creator
                    repository.Save(user);
                }
            }

            // What if this is a repost?
            if (meme.RepostOfId != null)
            {
                IMeme original = repository.GetMeme(meme.RepostOfId);
                if (original != null)
                {
                    // A repost should always reference an original (not another repost)
                    if (original.RepostOfId != null)
                    {
                        throw new Exception(string.Format("Repost of a repost not allowed - {0} - {1}", meme.Id, meme.RepostOfId));
                    }

                    // Recursive call of this operation to update the original
                    UpdateMemeInteraction(meme.RepostOfId, null, likesIncrement, dislikesIncrement, viewsIncrement, sharesIncrement, favouritesIncrement);
                }
            }
            // Update the meme
            return(meme);
        }
 public MemesController(IMeme context, ITheLoai theLoaiService)
 {
     _context            = context;
     this.theLoaiService = theLoaiService;
 }
Beispiel #32
0
 /// <summary>
 /// Persist the supplied seed and assign an ID
 /// </summary>
 /// <param name="meme"></param>
 /// <returns></returns>
 public IMeme Save(IMeme meme)
 {
     meme.Id = meme.Id ?? Guid.NewGuid().ToString("N");
       memeCollection.Save(meme.ToBsonDocument());
       return meme;
 }
Beispiel #33
0
 public static string GetMemeData(IMeme meme, bool copyright)
 {
     return(meme.GetData(copyright));
 }
Beispiel #34
0
 /// <summary>
 /// Persist the supplied meme and assign an ID
 /// </summary>
 /// <param name="meme"></param>
 /// <returns></returns>
 public IMeme Save(IMeme meme)
 {
     meme.Id = meme.Id ?? NewShortId();
     memeCollection.Save(meme.ToBsonDocument());
     return(meme);
 }
Beispiel #35
0
        /// <summary>
        /// Update the parent meme to reflect the new state of the supplied meme 
        /// Recalculate and update the reply trend score of the supplied meme inside the reply list of the parent meme (identified by ResponseToId)
        /// </summary>
        /// <param name="replyMeme"></param>
        /// <returns></returns>
        public void UpdateReplyToMeme(IMeme replyMeme)
        {
            if (replyMeme != null && replyMeme.ResponseToId != null)
              {
            IMeme parentMeme = repository.GetMeme(replyMeme.ResponseToId);
            if (parentMeme.ReplyIds == null)
            {
              // This meme is not a reply within the parent meme
              return;
            }

            IReply reply = parentMeme.ReplyIds.FirstOrDefault(x => x.Id == replyMeme.Id);
            if(reply != null)
            {
              // Update the hourly trend score of this meme as a reply to another meme
              reply.TrendScore = trendManager.CalculateHourlyTrendScore(replyMeme, repository.GetUserCommentCount(replyMeme.Id), parentMeme.DateCreated);

              // Save the parent meme to which the reply meme is a response to (with the updated reply trend scrore)
              repository.Save(parentMeme);
            }
              }
        }