Beispiel #1
0
 public void Dispose()
 {
     ThumbGenerator.Close();
     DBUpdateQueue.Close();
     host?.Stop();
     host?.Dispose();
 }
Beispiel #2
0
 /// <summary>
 /// Add a new Image to the DB
 /// </summary>
 /// <param name="model">ImageModel of the image to be added</param>
 /// <returns>ImageModel unchanged</returns>
 public static ImageModel AddImage(ImageModel model)
 {
     if (ImageExists(model))
     {
         model.fileUri = $@"{BASE_DIR}/{Uri.UnescapeDataString(model.fileUri)}";
         return(model);
     }
     using (NpgsqlConnection con = new NpgsqlConnection(CONNECTION_STRING))
     {
         con.Open();
         using (NpgsqlCommand cmd = con.CreateCommand())
         {
             cmd.CommandText = "SELECT nextval('images_index_seq');";
             model.id        = $"{cmd.ExecuteScalar()}{model.timeadded}".ToBase60();
             cmd.CommandText = $"INSERT INTO images (id, name, timeadded, fileuri, isnsfw) VALUES('{model.id}', '{model.name}', '{model.timeadded}', '{model.fileUri}', '{model.isnsfw}')";
             cmd.ExecuteNonQuery();
             if (model.tags != null)
             {
                 foreach (TagModel tag in model.tags)
                 {
                     AddTag(model.id, tag.id);
                 }
             }
         }
     }
     model.fileUri = $@"{BASE_DIR}/{Uri.UnescapeDataString(model.fileUri)}";
     ThumbGenerator.QueueThumb(model);
     return(model);
 }
        public async Task GenerateThumbFromWebsiteUrl_Failure()
        {
            var result = await ThumbGenerator.GenerateThumbnail("http://www.idontexistimprettysuremaybeIlladdrandom3243242.com", false);

            Assert.AreNotEqual(Status.Success, result.Status, "Expecting no thumb");
            Assert.AreEqual("", result.Response);
        }
Beispiel #4
0
 void GenerateThumbs()
 {
     CreateThread("RinDB.GenerateThumbs", () =>
     {
         ThumbGenerator.QueueThumb(RinDB.GetAll());
     });
 }
Beispiel #5
0
 public static void Init(string user, string pass, string db)
 {
     _user = user;
     _pass = pass;
     _db   = db;
     ThumbGenerator.Start();
     DBUpdateQueue.Start();
 }
Beispiel #6
0
        public async Task GenerateThumbFromImageUrl()
        {
            var result = await ThumbGenerator.GenerateThumbFromImageUrl("https://i.sli.mg/W2fsxZ.jpg", 5000);

            string path = Path.Combine(ThumbGenerator.DestinationPathThumbs, result);

            Assert.IsTrue(File.Exists(path), "Thumb did not get generated from image url");
            File.Delete(path);
        }
Beispiel #7
0
        public async Task GenerateThumbFromWebsiteUrl()
        {
            var result = await ThumbGenerator.GenerateThumbFromWebpageUrl("http://www.yahoo.com");

            string path = Path.Combine(ThumbGenerator.DestinationPathThumbs, result);

            Assert.IsTrue(File.Exists(path), "Thumb did not get generated from site html");
            File.Delete(path);
        }
        public async Task GenerateThumbFromWebsiteUrl()
        {
            var result = await ThumbGenerator.GenerateThumbnail("https://www.yahoo.com", false);

            var key = new FileKey(result.Response, FileType.Thumbnail);

            Assert.AreEqual(true, await FileManager.Instance.Exists(key), "Thumb did not get generated from image url");
            await FileManager.Instance.Delete(key);

            Assert.AreEqual(false, await FileManager.Instance.Exists(key), "Thumb did not delete");
        }
        public async Task GenerateThumbFromImageUrl()
        {
            var result = await ThumbGenerator.GenerateThumbnail("https://voat.co/graphics/voat-goat.png", false);

            var key = new FileKey(result.Response, FileType.Thumbnail);


            Assert.AreEqual(!VoatSettings.Instance.OutgoingTraffic.Enabled, await FileManager.Instance.Exists(key), "Thumb did not get generated from image url");
            await FileManager.Instance.Delete(key);

            Assert.AreEqual(false, await FileManager.Instance.Exists(key), "Thumb did not delete");
        }
        //[ExpectedException(typeof(WebException))]
        public async Task GenerateThumbFromImageUrl_Failure()
        {
            //await VoatAssert.ThrowsAsync<TaskCanceledException>(() => {
            //    return ThumbGenerator.GenerateThumbnail("https://idontexistimprettysuremaybeIlladdrandom3243242.co/graphics/voat-goat.png", false);
            //});
            var result = await ThumbGenerator.GenerateThumbnail("https://idontexistimprettysuremaybeIlladdrandom3243242.co/graphics/voat-goat.png", false);

            Assert.AreNotEqual(Status.Success, result.Status, "Expecting no thumb");
            Assert.AreEqual("", result.Response);

            //var result = await ThumbGenerator.GenerateThumbFromImageUrl("https://idontexistimprettysuremaybeIlladdrandom3243242.co/graphics/voat-goat.png", 5000, false);
            //Assert.AreEqual(null, result, "Expecting no thumb");
        }
Beispiel #11
0
        private Response GetOrGenerateThumb(ImageModel image)
        {
            string ext = Path.GetExtension(image.fileUri);

            if (!File.Exists($"{RinDB.THUMB_DIR}/{image.id}{ext}"))
            {
                if (!Directory.Exists(RinDB.THUMB_DIR))
                {
                    Directory.CreateDirectory(RinDB.THUMB_DIR);
                }
                ThumbGenerator.QueueThumb(image);
                return(Response.AsRedirect("/res/img/DefaultThumb.png"));
            }
            return(Response.FromImage($"{RinDB.THUMB_DIR}/{image.id}{ext}"));
        }
Beispiel #12
0
        void DoBuild(Dictionary <string, string[]> buildList)
        {
            foreach (string item in buildList.Keys)
            {
                Write($"Building: {item}...", false);
                string[] dir = Directory.GetFiles($@"{RinDB.BASE_DIR}/{item}", "*", SearchOption.AllDirectories);
                foreach (string f in dir)
                {
                    string file = f.Replace("\\", "/");
                    file = file.Replace($@"{RinDB.BASE_DIR}/", "");
                    string name  = Path.GetFileNameWithoutExtension(file);
                    long   epoch = long.Parse(name.Substring(1, name.IndexOf(']') - 1));
                    name = name.Remove(0, epoch.ToString().Length + 3);
                    name = Uri.EscapeDataString(name);
                    string id = file.ToBase60();

                    DBUpdateQueue.QueueCommand($"INSERT INTO images (id, fileuri, timeadded, name, isnsfw) VALUES('{id}', '{Uri.EscapeDataString(file)}', '{epoch}', '{name}', '{file.Contains("NSFW")}');");
                    //cmd.CommandText = $"INSERT INTO images (id, fileuri, timeadded, name, isnsfw) VALUES('{id}', '{Uri.EscapeDataString(file)}', '{epoch}', '{name}', '{file.Contains("NSFW")}');";
                    if (buildList[item] != null)
                    {
                        foreach (string tag in buildList[item])
                        {
                            string tagID = tag.ToBase60();
                            //cmd.CommandText += $"INSERT INTO tagmap VALUES('{tagID}{id}','{id}', '{tagID}');";
                            DBUpdateQueue.QueueCommand($"INSERT INTO tagmap VALUES('{tagID}{id}','{id}', '{tagID}');");
                        }
                    }
                    //cmd.ExecuteNonQuery();
                    ThumbGenerator.QueueThumb(new ImageModel()
                    {
                        id = id, fileUri = $@"{RinDB.BASE_DIR}/{file}"
                    });
                }
                Write(" Done!");
            }
        }
Beispiel #13
0
        public ActionResult Submit([Bind(Include = "Id,Votes,Name,Date,Type,Linkdescription,Title,Rank,MessageContent,Subverse")] Message message)
        {
            // abort if model state is invalid
            if (!ModelState.IsValid)
            {
                return(View());
            }

            // save temp values for the view in case submission fails
            ViewBag.selectedSubverse = message.Subverse;
            ViewBag.message          = message.MessageContent;
            ViewBag.title            = message.Title;
            ViewBag.linkDescription  = message.Linkdescription;

            // check if user is banned
            if (Utils.User.IsUserGloballyBanned(message.Name) || Utils.User.IsUserBannedFromSubverse(User.Identity.Name, message.Subverse))
            {
                ViewBag.SelectedSubverse = message.Subverse;
                return(View("~/Views/Home/Comments.cshtml", message));
            }

            // check if user has reached hourly posting quota for target subverse
            if (Utils.User.UserHourlyPostingQuotaForSubUsed(User.Identity.Name, message.Subverse))
            {
                ModelState.AddModelError("", "You have reached your hourly submission quota for this subverse.");
                return(View());
            }

            // check if user has reached daily posting quota for target subverse
            if (Utils.User.UserDailyPostingQuotaForSubUsed(User.Identity.Name, message.Subverse))
            {
                ModelState.AddModelError("", "You have reached your daily submission quota for this subverse.");
                return(View());
            }

            // verify recaptcha if user has less than 25 CCP
            var userCcp = Karma.CommentKarma(User.Identity.Name);

            if (userCcp < 25)
            {
                string encodedResponse    = Request.Form["g-Recaptcha-Response"];
                bool   isCaptchaCodeValid = (ReCaptchaUtility.Validate(encodedResponse) == "True" ? true : false);

                if (!isCaptchaCodeValid)
                {
                    ModelState.AddModelError("", "Incorrect recaptcha answer.");

                    // TODO
                    // SET PREVENT SPAM DELAY TO 0

                    return(View());
                }
            }

            // if user CCP or SCP is less than -50, allow only X submissions per 24 hours
            var userScp = Karma.LinkKarma(User.Identity.Name);

            if (userCcp <= -50 || userScp <= -50)
            {
                var quotaUsed = Utils.User.UserDailyPostingQuotaForNegativeScoreUsed(User.Identity.Name);
                if (quotaUsed)
                {
                    ModelState.AddModelError("", "You have reached your daily submission quota. Your current quota is " + Convert.ToInt32(ConfigurationManager.AppSettings["dailyPostingQuotaForNegativeScore"]) + " submission(s) per 24 hours.");
                    return(View());
                }
            }

            // abort if model state is invalid
            if (!ModelState.IsValid)
            {
                return(View("Submit"));
            }

            // check if subverse exists
            var targetSubverse = _db.Subverses.Find(message.Subverse.Trim());

            if (targetSubverse == null || message.Subverse.Equals("all", StringComparison.OrdinalIgnoreCase))
            {
                ModelState.AddModelError(string.Empty, "Sorry, The subverse you are trying to post to does not exist.");
                return(View("Submit"));
            }

            // check if subverse has "authorized_submitters_only" set and dissalow submission if user is not allowed submitter
            if (targetSubverse.authorized_submitters_only)
            {
                if (!Utils.User.IsUserSubverseModerator(User.Identity.Name, targetSubverse.name))
                {
                    // user is not a moderator, check if user is an administrator
                    if (!Utils.User.IsUserSubverseAdmin(User.Identity.Name, targetSubverse.name))
                    {
                        ModelState.AddModelError("", "You are not authorized to submit links or start discussions in this subverse. Please contact subverse moderators for authorization.");
                        return(View("Submit"));
                    }
                }
            }

            // everything was okay, process incoming submission

            // submission is a link post
            // generate a thumbnail if submission is a direct link to image or video
            if (message.Type == 2 && message.MessageContent != null && message.Linkdescription != null)
            {
                // strip unicode if title contains unicode
                if (Submissions.ContainsUnicode(message.Linkdescription))
                {
                    message.Linkdescription = Submissions.StripUnicode(message.Linkdescription);
                }
                // abort if title less than 10 characters
                if (message.Linkdescription.Length < 10)
                {
                    ModelState.AddModelError(string.Empty, "Sorry, the title may not be less than 10 characters.");
                    return(View("Submit"));
                }

                var domain = UrlUtility.GetDomainFromUri(message.MessageContent);

                // check if target subvere allows submissions from globally banned hostnames
                if (!targetSubverse.exclude_sitewide_bans)
                {
                    // check if hostname is banned before accepting submission
                    if (BanningUtility.IsHostnameBanned(domain))
                    {
                        ModelState.AddModelError(string.Empty, "Sorry, the hostname you are trying to submit is banned.");
                        return(View("Submit"));
                    }
                }

                // check if same link was submitted before and deny submission
                var existingSubmission = _db.Messages.FirstOrDefault(s => s.MessageContent.Equals(message.MessageContent, StringComparison.OrdinalIgnoreCase) && s.Subverse.Equals(message.Subverse, StringComparison.OrdinalIgnoreCase));

                // submission is a repost, discard it and inform the user
                if (existingSubmission != null)
                {
                    ModelState.AddModelError(string.Empty, "Sorry, this link has already been submitted by someone else.");

                    // todo: offer the option to repost after informing the user about it
                    return(RedirectToRoute(
                               "SubverseComments",
                               new
                    {
                        controller = "Comment",
                        action = "Comments",
                        id = existingSubmission.Id,
                        subversetoshow = existingSubmission.Subverse
                    }
                               ));
                }

                // check if user has reached daily crossposting quota
                if (Utils.User.DailyCrossPostingQuotaUsed(User.Identity.Name, message.MessageContent))
                {
                    ModelState.AddModelError("", "You have reached your daily crossposting quota for this URL.");
                    return(View());
                }

                // check if target subverse has thumbnails setting enabled before generating a thumbnail
                if (targetSubverse.enable_thumbnails)
                {
                    // try to generate and assign a thumbnail to submission model
                    message.Thumbnail = ThumbGenerator.ThumbnailFromSubmissionModel(message);
                }

                // flag the submission as anonymized if it was submitted to a subverse with active anonymized_mode
                if (targetSubverse.anonymized_mode)
                {
                    message.Anonymized = true;
                }
                else
                {
                    message.Name = User.Identity.Name;
                }

                // accept submission and save it to the database
                message.Subverse = targetSubverse.name;

                // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time
                message.Date  = DateTime.Now;
                message.Likes = 1;
                _db.Messages.Add(message);

                // update last submission received date for target subverse
                targetSubverse.last_submission_received = DateTime.Now;
                _db.SaveChanges();
            }
            else if (message.Type == 1 && message.Title != null)
            {
                // submission is a self post

                // strip unicode if message contains unicode
                if (Submissions.ContainsUnicode(message.Title))
                {
                    message.Title = Submissions.StripUnicode(message.Title);
                }
                // abort if title less than 10 characters
                if (message.Title.Length < 10)
                {
                    ModelState.AddModelError(string.Empty, "Sorry, the the message title may not be less than 10 characters.");
                    return(View("Submit"));
                }

                // accept submission and save it to the database
                // trim trailing blanks from subverse name if a user mistakenly types them
                message.Subverse = targetSubverse.name;

                // flag the submission as anonymized if it was submitted to a subverse with active anonymized_mode
                if (targetSubverse.anonymized_mode)
                {
                    message.Anonymized = true;
                }
                else
                {
                    message.Name = User.Identity.Name;
                }
                // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time
                message.Date  = DateTime.Now;
                message.Likes = 1;
                _db.Messages.Add(message);
                // update last submission received date for target subverse
                targetSubverse.last_submission_received = DateTime.Now;

                if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPreSave))
                {
                    message.MessageContent = ContentProcessor.Instance.Process(message.MessageContent, ProcessingStage.InboundPreSave, message);
                }

                _db.SaveChanges();

                if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPostSave))
                {
                    ContentProcessor.Instance.Process(message.MessageContent, ProcessingStage.InboundPostSave, message);
                }
            }

            return(RedirectToRoute(
                       "SubverseComments",
                       new
            {
                controller = "Comment",
                action = "Comments",
                id = message.Id,
                subversetoshow = message.Subverse
            }
                       ));
        }
Beispiel #14
0
        public async Task <ActionResult> Submit([Bind(Include = "Id,Votes,Name,Date,Type,Linkdescription,Title,Rank,MessageContent,Subverse")] Message message)
        {
            // check if user is banned
            if (Utils.User.IsUserBanned(message.Name))
            {
                ViewBag.SelectedSubverse = message.Subverse;
                return(View("~/Views/Home/Comments.cshtml", message));
            }

            // verify recaptcha if user has less than 25 CCP
            if (Karma.CommentKarma(User.Identity.Name) < 25)
            {
                const string captchaMessage     = "";
                var          isCaptchaCodeValid = ReCaptchaUtility.GetCaptchaResponse(captchaMessage, Request);

                if (!isCaptchaCodeValid)
                {
                    ModelState.AddModelError("", "Incorrect recaptcha answer.");
                    return(View());
                }
            }

            if (!ModelState.IsValid)
            {
                return(View());
            }

            // check if subverse exists
            var targetSubverse = _db.Subverses.Find(message.Subverse.Trim());

            if (targetSubverse != null && !message.Subverse.Equals("all", StringComparison.OrdinalIgnoreCase))
            {
                // check if subverse has "authorized_submitters_only" set and dissalow submission if user is not allowed submitter
                if (targetSubverse.authorized_submitters_only)
                {
                    if (!Utils.User.IsUserSubverseModerator(User.Identity.Name, targetSubverse.name))
                    {
                        // user is not a moderator, check if user is an administrator
                        if (!Utils.User.IsUserSubverseAdmin(User.Identity.Name, targetSubverse.name))
                        {
                            ModelState.AddModelError("", "You are not authorized to submit links or start discussions in this subverse. Please contact subverse moderators for authorization.");
                            return(View());
                        }
                    }
                }

                // submission is a link post
                // generate a thumbnail if submission is a direct link to image or video
                if (message.Type == 2 && message.MessageContent != null && message.Linkdescription != null)
                {
                    var domain = UrlUtility.GetDomainFromUri(message.MessageContent);

                    // check if hostname is banned before accepting submission
                    if (BanningUtility.IsHostnameBanned(domain))
                    {
                        ModelState.AddModelError(string.Empty, "Sorry, the hostname you are trying to submit is banned.");
                        return(View());
                    }

                    // check if same link was submitted before and deny submission
                    var existingSubmission = _db.Messages.FirstOrDefault(s => s.MessageContent.Equals(message.MessageContent, StringComparison.OrdinalIgnoreCase) && s.Subverse == message.Subverse);

                    // submission is a repost, discard it and inform the user
                    if (existingSubmission != null)
                    {
                        ModelState.AddModelError(string.Empty, "Sorry, this link has already been submitted by someone else.");

                        // todo: offer the option to repost after informing the user about it
                        return(RedirectToRoute(
                                   "SubverseComments",
                                   new
                        {
                            controller = "Comment",
                            action = "Comments",
                            id = existingSubmission.Id,
                            subversetoshow = existingSubmission.Subverse
                        }
                                   ));
                    }

                    // check if target subverse has thumbnails setting enabled before generating a thumbnail
                    if (targetSubverse.enable_thumbnails)
                    {
                        // try to generate and assign a thumbnail to submission model
                        message.Thumbnail = ThumbGenerator.ThumbnailFromSubmissionModel(message);
                    }

                    // flag the submission as anonymized if it was submitted to a subverse with active anonymized_mode
                    if (targetSubverse.anonymized_mode)
                    {
                        message.Anonymized = true;
                    }
                    else
                    {
                        message.Name = User.Identity.Name;
                    }

                    // accept submission and save it to the database
                    message.Subverse = targetSubverse.name;
                    // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time
                    message.Date  = DateTime.Now;
                    message.Likes = 1;
                    _db.Messages.Add(message);

                    // update last submission received date for target subverse
                    targetSubverse.last_submission_received = DateTime.Now;
                    await _db.SaveChangesAsync();
                }
                else if (message.Type == 1 && message.Title != null)
                {
                    // submission is a self post
                    // accept submission and save it to the database
                    // trim trailing blanks from subverse name if a user mistakenly types them
                    message.Subverse = targetSubverse.name;
                    // flag the submission as anonymized if it was submitted to a subverse with active anonymized_mode
                    if (targetSubverse.anonymized_mode)
                    {
                        message.Anonymized = true;
                    }
                    else
                    {
                        message.Name = User.Identity.Name;
                    }
                    // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time
                    message.Date  = DateTime.Now;
                    message.Likes = 1;
                    _db.Messages.Add(message);
                    // update last submission received date for target subverse
                    targetSubverse.last_submission_received = DateTime.Now;

                    if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPreSave))
                    {
                        message.MessageContent = ContentProcessor.Instance.Process(message.MessageContent, ProcessingStage.InboundPreSave, message);
                    }

                    await _db.SaveChangesAsync();

                    if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPostSave))
                    {
                        ContentProcessor.Instance.Process(message.MessageContent, ProcessingStage.InboundPostSave, message);
                    }
                }

                return(RedirectToRoute(
                           "SubverseComments",
                           new
                {
                    controller = "Comment",
                    action = "Comments",
                    id = message.Id,
                    subversetoshow = message.Subverse
                }
                           ));
            }
            ModelState.AddModelError(string.Empty, "Sorry, The subverse you are trying to post to does not exist.");
            return(View());
        }
Beispiel #15
0
        public async Task <ActionResult> UserPreferencesAbout([Bind(Include = "Shortbio, Avatarfile")] UserAboutViewModel model)
        {
            // save changes
            using (var db = new whoaverseEntities())
            {
                var userPreferences = db.Userpreferences.Find(User.Identity.Name);
                var tmpModel        = new Userpreference();

                if (userPreferences == null)
                {
                    // create a new record for this user in userpreferences table
                    tmpModel.Shortbio = model.Shortbio;
                    tmpModel.Username = User.Identity.Name;
                }

                if (model.Avatarfile != null && model.Avatarfile.ContentLength > 0)
                {
                    // check uploaded file size is < 300000 bytes (300 kilobytes)
                    if (model.Avatarfile.ContentLength < 300000)
                    {
                        try
                        {
                            using (var img = Image.FromStream(model.Avatarfile.InputStream))
                            {
                                if (img.RawFormat.Equals(ImageFormat.Jpeg) || img.RawFormat.Equals(ImageFormat.Png))
                                {
                                    // resize uploaded file
                                    ThumbGenerator.GenerateAvatar(img, User.Identity.Name, model.Avatarfile.ContentType);
                                    if (userPreferences == null)
                                    {
                                        tmpModel.Avatar = User.Identity.Name + ".jpg";
                                    }
                                    else
                                    {
                                        userPreferences.Avatar = User.Identity.Name + ".jpg";
                                    }
                                }
                                else
                                {
                                    // uploaded file was invalid
                                    ModelState.AddModelError("", "Uploaded file is not recognized as an image.");
                                    return(RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat }));
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // uploaded file was invalid
                            ModelState.AddModelError("", "Uploaded file is not recognized as an image.");
                            return(RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat }));
                        }
                    }
                    else
                    {
                        // refuse to save the file and explain why
                        ModelState.AddModelError("", "Uploaded image may not exceed 300 kb, please upload a smaller image.");
                        return(RedirectToAction("Manage", new { Message = ManageMessageId.UploadedFileToolarge }));
                    }
                }

                if (userPreferences == null)
                {
                    db.Userpreferences.Add(tmpModel);
                    await db.SaveChangesAsync();
                }
                else
                {
                    userPreferences.Shortbio = model.Shortbio;
                    userPreferences.Username = User.Identity.Name;
                    await db.SaveChangesAsync();
                }
            }

            return(RedirectToAction("Manage"));
        }
        public async Task <ActionResult> UserPreferencesAbout([Bind(Include = "Bio, Avatarfile")] UserAboutViewModel model)
        {
            ViewBag.UserName = User.Identity.Name;
            // save changes
            using (var db = new voatEntities())
            {
                var userPreferences = GetUserPreference(db);

                if (model.Avatarfile != null && model.Avatarfile.ContentLength > 0)
                {
                    // check uploaded file size is < 300000 bytes (300 kilobytes)
                    if (model.Avatarfile.ContentLength < 300000)
                    {
                        try
                        {
                            using (var img = Image.FromStream(model.Avatarfile.InputStream))
                            {
                                if (img.RawFormat.Equals(ImageFormat.Jpeg) || img.RawFormat.Equals(ImageFormat.Png))
                                {
                                    // resize uploaded file
                                    var thumbnailResult = await ThumbGenerator.GenerateAvatar(img, User.Identity.Name, model.Avatarfile.ContentType);

                                    if (thumbnailResult)
                                    {
                                        userPreferences.Avatar = User.Identity.Name + ".jpg";
                                    }
                                    else
                                    {
                                        // unable to generate thumbnail
                                        ModelState.AddModelError("", "Uploaded file is not recognized as a valid image.");
                                        return(RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat }));
                                    }
                                }
                                else
                                {
                                    // uploaded file was invalid
                                    ModelState.AddModelError("", "Uploaded file is not recognized as an image.");
                                    return(RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat }));
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // uploaded file was invalid
                            ModelState.AddModelError("", "Uploaded file is not recognized as an image.");
                            return(RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat }));
                        }
                    }
                    else
                    {
                        // refuse to save the file and explain why
                        ModelState.AddModelError("", "Uploaded image may not exceed 300 kb, please upload a smaller image.");
                        return(RedirectToAction("Manage", new { Message = ManageMessageId.UploadedFileToolarge }));
                    }
                }

                var bio = model.Bio.TrimSafe();

                if (String.IsNullOrEmpty(bio))
                {
                    userPreferences.Bio = "I tried to delete my bio but they gave me this instead";
                }
                else if (bio == STRINGS.DEFAULT_BIO)
                {
                    userPreferences.Bio = null;
                }
                else
                {
                    userPreferences.Bio = bio;
                }
                await db.SaveChangesAsync();
            }

            ClearUserCache();

            return(RedirectToAction("Manage"));
        }
        public async Task <ActionResult> UserPreferencesAbout([Bind("Bio, Avatarfile")] UserAboutViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("Manage", model));
            }

            ViewBag.UserName = User.Identity.Name;

            string avatarKey = null;

            //ThumbGenerator.GenerateThumbnail
            if (model.Avatarfile != null)
            {
                try
                {
                    var stream = model.Avatarfile.OpenReadStream();
                    var result = await ThumbGenerator.GenerateAvatar(stream, model.Avatarfile.FileName, model.Avatarfile.ContentType);

                    if (result.Success)
                    {
                        avatarKey = result.Response;
                    }
                    else
                    {
                        ModelState.AddModelError("Avatarfile", result.Message);
                        return(View("Manage", model));
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("Avatarfile", "Uploaded file is not recognized as a valid image.");
                    return(RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat }));
                }
            }

            var bio = model.Bio.TrimSafe();

            //This is a hack
            var context = new VoatOutOfRepositoryDataContextAccessor();

            using (var repo = new Repository(User, context))
            {
                var p = await repo.GetUserPreferences(User.Identity.Name);

                if (bio != p.Bio)
                {
                    if (String.IsNullOrEmpty(bio))
                    {
                        p.Bio = "I tried to delete my bio but they gave me this instead";
                    }
                    else if (bio == STRINGS.DEFAULT_BIO)
                    {
                        p.Bio = null;
                    }
                    else
                    {
                        p.Bio = bio;
                    }
                }
                if (!String.IsNullOrEmpty(avatarKey))
                {
                    p.Avatar = avatarKey;
                }
                await context.SaveChangesAsync();
            }

            /*
             * using (var db = new VoatUIDataContextAccessor())
             * {
             *  var userPreferences = GetUserPreference(db);
             *
             *  if (model.Avatarfile != null && model.Avatarfile.ContentLength > 0)
             *  {
             *      // check uploaded file size is < 300000 bytes (300 kilobytes)
             *      if (model.Avatarfile.ContentLength < 300000)
             *      {
             *          try
             *          {
             *              using (var img = Image.FromStream(model.Avatarfile.InputStream))
             *              {
             *                  if (img.RawFormat.Equals(ImageFormat.Jpeg) || img.RawFormat.Equals(ImageFormat.Png))
             *                  {
             *                      // resize uploaded file
             *                      var thumbnailResult = await ThumbGenerator.GenerateAvatar(img, User.Identity.Name, model.Avatarfile.ContentType);
             *                      if (thumbnailResult)
             *                      {
             *                          userPreferences.Avatar = User.Identity.Name + ".jpg";
             *                      }
             *                      else
             *                      {
             *                          // unable to generate thumbnail
             *                          ModelState.AddModelError("", "Uploaded file is not recognized as a valid image.");
             *                          return RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat });
             *                      }
             *                  }
             *                  else
             *                  {
             *                      // uploaded file was invalid
             *                      ModelState.AddModelError("", "Uploaded file is not recognized as an image.");
             *                      return RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat });
             *                  }
             *              }
             *          }
             *          catch (Exception)
             *          {
             *              // uploaded file was invalid
             *              ModelState.AddModelError("", "Uploaded file is not recognized as an image.");
             *              return RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat });
             *          }
             *      }
             *      else
             *      {
             *          // refuse to save the file and explain why
             *          ModelState.AddModelError("", "Uploaded image may not exceed 300 kb, please upload a smaller image.");
             *          return RedirectToAction("Manage", new { Message = ManageMessageId.UploadedFileToolarge });
             *      }
             *  }
             *
             *  var bio = model.Bio.TrimSafe();
             *
             *  if (String.IsNullOrEmpty(bio))
             *  {
             *      userPreferences.Bio = "I tried to delete my bio but they gave me this instead";
             *  }
             *  else if (bio == STRINGS.DEFAULT_BIO)
             *  {
             *      userPreferences.Bio = null;
             *  }
             *  else
             *  {
             *      userPreferences.Bio = bio;
             *  }
             *  await db.SaveChangesAsync();
             * }
             */
            ClearUserCache();

            return(RedirectToAction("Manage"));
        }
Beispiel #18
0
        public async Task <ActionResult> Submit([Bind(Include = "Id,Votes,Name,Date,Type,Linkdescription,Title,Rank,MessageContent,Subverse")] Message message)
        {
            if (ModelState.IsValid)
            {
                //check if subverse exists
                if (db.Subverses.Find(message.Subverse) != null && message.Subverse != "all")
                {
                    //check if username is admin and get random username instead
                    if (message.Name == "system")
                    {
                        message.Name = GrowthUtility.GetRandomUsername();
                        Random r    = new Random();
                        int    rInt = r.Next(6, 17);
                        message.Likes = (short)rInt;
                    }

                    //generate a thumbnail if submission is a link submission and a direct link to image
                    if (message.Type == 2)
                    {
                        try
                        {
                            string domain = Whoaverse.Utils.UrlUtility.GetDomainFromUri(message.MessageContent);

                            //if domain is youtube, try generating a thumbnail for the video
                            if (domain == "youtube.com")
                            {
                                string thumbFileName = ThumbGenerator.GenerateThumbFromYoutubeVideo(message.MessageContent);
                                message.Thumbnail = thumbFileName;
                            }
                            else
                            {
                                string extension = Path.GetExtension(message.MessageContent);

                                if (extension != String.Empty && extension != null)
                                {
                                    if (extension == ".jpg" || extension == ".JPG" || extension == ".png" || extension == ".PNG" || extension == ".gif" || extension == ".GIF")
                                    {
                                        string thumbFileName = ThumbGenerator.GenerateThumbFromUrl(message.MessageContent);
                                        message.Thumbnail = thumbFileName;
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            //unable to generate a thumbnail, don't use any
                        }
                    }

                    //trim trailing blanks from subverse name if a user mistakenly types them
                    message.Subverse = message.Subverse.Trim();

                    db.Messages.Add(message);
                    await db.SaveChangesAsync();

                    //get newly generated message ID and execute ranking and self upvoting
                    Votingtracker tmpVotingTracker = new Votingtracker();
                    tmpVotingTracker.MessageId  = message.Id;
                    tmpVotingTracker.UserName   = message.Name;
                    tmpVotingTracker.VoteStatus = 1;
                    db.Votingtrackers.Add(tmpVotingTracker);
                    await db.SaveChangesAsync();

                    return(RedirectToRoute(
                               "SubverseComments",
                               new
                    {
                        controller = "Home",
                        action = "Comments",
                        id = message.Id,
                        subversetoshow = message.Subverse
                    }
                               ));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Sorry, The subverse you are trying to post to does not exist.");
                    return(View());
                }
            }
            else
            {
                return(View());
            }
        }