Exemple #1
0
        public string UploadMediaObject(MediaObject image, string relativeUrl = "/posts/image")
        {
            var settings = new HttpRequestSettings
            {
                Content  = image,
                Url      = ApiBaseUrl + relativeUrl,
                HttpVerb = "POST"
            };

            settings.Headers.Add("Authorization", $"Bearer {AuthenticationToken}");

            string imageUrl = null;

            try
            {
                imageUrl = HttpUtils.JsonRequest <string>(settings);
            }
            catch (Exception ex)
            {
                SetError("Failed to upload media object: " + ex.Message);
            }

            return(imageUrl);
        }
        /// <summary>
        /// Processes render field pipline.
        /// </summary>
        /// <param name="args">
        /// The render field argument list.
        /// </param>
        public new void Process(RenderFieldArgs args)
        {
            if (args.FieldTypeKey != "image")
              {
            return;
              }

              MediaObject mediaObject = new MediaObject
              {
            // Database = Context.Database.Name,
            // DataSource = args.Item.ID.ToString(),
            Item = args.Item,
            FieldName = args.FieldName,
            FieldValue = args.FieldValue,
            RenderParameters = args.Parameters
              };
              args.WebEditParameters.AddRange(args.Parameters);
              RenderFieldResult result = new RenderFieldResult(HtmlUtil.RenderControl(mediaObject));

              args.Result.FirstPart = result.FirstPart;
              args.Result.LastPart = result.LastPart;
              args.DisableWebEditContentEditing = true;
              args.WebEditClick = "return Sitecore.WebEdit.editControl($JavascriptParameters, 'webedit:chooseimage')";
        }
Exemple #3
0
        internal void Initialize(WaveFormat inputformat, WaveFormat outputformat)
        {
            Ratio = (decimal)outputformat.BytesPerSecond / inputformat.BytesPerSecond;
            lock (LockObj)
            {
                Resampler = new WMResampler();

                MediaObject mediaObject = Resampler.MediaObject;
                if (!mediaObject.SupportsInputFormat(0, inputformat))
                {
                    throw new NotSupportedException("Inputformat not supported.");
                }
                mediaObject.SetInputType(0, inputformat);

                if (!mediaObject.SupportsOutputFormat(0, outputformat))
                {
                    throw new NotSupportedException("Outputformat not supported.");
                }
                mediaObject.SetOutputType(0, outputformat);

                InputBuffer  = new MediaBuffer(inputformat.BytesPerSecond / 2);
                OutputBuffer = new DmoOutputDataBuffer(outputformat.BytesPerSecond / 2);
            }
        }
Exemple #4
0
        protected void InitCom(WaveFormat inputformat, WaveFormat outputformat)
        {
            lock (_lockObj)
            {
                var source = BaseStream;
                _resampler = new WMResampler();

                MediaObject mediaObject = _resampler.MediaObject;
                if (!mediaObject.SupportsInputFormat(0, inputformat))
                {
                    throw new NotSupportedException("Inputformat not supported.");
                }
                mediaObject.SetInputType(0, inputformat);

                if (!mediaObject.SupportsOutputFormat(0, outputformat))
                {
                    throw new NotSupportedException("Outputformat not supported.");
                }
                mediaObject.SetOutputType(0, outputformat);

                _inputBuffer  = new MediaBuffer(inputformat.BytesPerSecond / 2);
                _outputBuffer = new DmoOutputDataBuffer(outputformat.BytesPerSecond / 2);
            }
        }
Exemple #5
0
        public MediaObjectInfo NewMediaObject(string blogid, string username, string password, MediaObject mediaObject)
        {
            ValidateUser(username, password);
            byte[] bytes = Convert.FromBase64String(mediaObject.bits);
            string path  = _blog.SaveFile(bytes, mediaObject.name).GetAwaiter().GetResult();

            return(new MediaObjectInfo {
                url = path
            });
        }
        public IActionResult RandomSuggestion(int id)
        {
            string userId = Common.ExtensionMethods.getUserId(this.User);

            //query database for all undeleted, uncompleted results belonging to the user not yet suggested today.
            List <MediaObject> mediaObjects = context.MediaObjects.
                                              Include(s => s.MediaSubType).
                                              Where(u => u.OwnerId == userId).
                                              Where(d => d.Deleted == false).
                                              Where(c => c.Completed == false).
                                              Where(l => int.Parse(l.LastSuggested.ToString("yyyyMMdd")) < int.Parse(DateTime.Now.ToString("yyyyMMdd"))).
                                              ToList();
            List <MediaObject> randomMedia = new List <MediaObject>();

            if (id != 0)
            {
                mediaObjects = mediaObjects.Where(i => i.SubTypeID == id).ToList();
            }

            //SuggestionViewModel suggestionViewModel = new SuggestionViewModel(context.SubTypes.ToList());
            int numSuggestion = 3;

            //ensure the while loop does not continue needlessly when too few items in list
            if (mediaObjects.Count <= numSuggestion)
            {
                foreach (MediaObject mediaObject in mediaObjects)
                {
                    mediaObject.SuggestedCount += 1;
                    mediaObject.LastSuggested   = DateTime.Now;
                }
                context.SaveChanges();

                SuggestionViewModel suggestionViewModelB = new SuggestionViewModel {
                    MediaObjects = mediaObjects
                };

                return(View(suggestionViewModelB));
            }
            else
            {
                while (randomMedia.Count < numSuggestion)
                {
                    Random      rand     = new Random();
                    int         index    = rand.Next(0, mediaObjects.Count);
                    MediaObject theMedia = mediaObjects[index];

                    if (randomMedia.Contains(theMedia) == false)
                    {
                        randomMedia.Add(theMedia);
                        theMedia.SuggestedCount += 1;
                        theMedia.LastSuggested   = DateTime.Now;
                    }
                }
            }

            context.SaveChanges();

            SuggestionViewModel suggestionViewModelA = new SuggestionViewModel {
                MediaObjects = randomMedia
            };

            return(View(suggestionViewModelA));
        }
        public IActionResult Edit(EditMediaObjectViewModel editMediaObjectViewModel)
        {
            if (ModelState.IsValid)
            {
                string      userId        = Common.ExtensionMethods.getUserId(this.User);
                bool        countUpdate   = false;
                MediaObject editCandidate = context.MediaObjects.
                                            Where(u => u.OwnerId == userId).
                                            Where(i => i.ID == editMediaObjectViewModel.ID).
                                            SingleOrDefault();

                //compare existing values to new values
                if (editCandidate.Title != editMediaObjectViewModel.Title)
                {
                    editCandidate.Title = editMediaObjectViewModel.Title;
                    countUpdate         = true;
                }
                if (editCandidate.SubTypeID != editMediaObjectViewModel.SubTypeID)
                {
                    editCandidate.SubTypeID = editMediaObjectViewModel.SubTypeID;
                    countUpdate             = true;
                }
                if (editCandidate.RecommendSource != editMediaObjectViewModel.RecommendSource)
                {
                    editCandidate.RecommendSource = editMediaObjectViewModel.RecommendSource;
                    countUpdate = true;
                }
                //check if Interest value has changed
                if (editCandidate.Interest != editMediaObjectViewModel.Interest)
                {
                    //check if value is in range
                    if (1 <= editMediaObjectViewModel.Interest & editMediaObjectViewModel.Interest <= 10)
                    {
                        //check if new value is > existing value, if not don't count the update
                        if (editMediaObjectViewModel.Interest > editCandidate.Interest)
                        {
                            countUpdate = true;
                        }
                        editCandidate.Interest = editMediaObjectViewModel.Interest;
                    }
                }
                if (editCandidate.Image != editMediaObjectViewModel.Image)
                {
                    editCandidate.Image = editMediaObjectViewModel.Image;
                    countUpdate         = true;
                }

                //strip double values
                //started
                List <bool> startedBools = StripAndConvertIntArrayToListBool(editMediaObjectViewModel.StartedValue);
                //completed
                List <bool> completedBools = StripAndConvertIntArrayToListBool(editMediaObjectViewModel.CompletedValue);

                //check if Started value has changed, then add to UpdateCount
                if (editCandidate.Started != startedBools[0])
                {
                    editCandidate.Started = startedBools[0];
                    countUpdate           = true;
                }
                //check if Completed value has changed
                if (editCandidate.Completed != completedBools[0])
                {
                    editCandidate.Completed = completedBools[0];
                    countUpdate             = true;
                }
                if (countUpdate)
                {
                    editCandidate.UpdateCount += 1;
                }

                context.SaveChanges();
            }

            //Then check for deleted Id and pass any to the DeletePrompt route
            if (editMediaObjectViewModel.DeletedIDs != null)
            {
                List <MediaObject> mediaToDelete = new List <MediaObject>();
                mediaToDelete = ArrayIdsToListMediaObjects(editMediaObjectViewModel.DeletedIDs);
                return(View("DeletePrompt", mediaToDelete));
            }

            return(Redirect("/Media/Details?id=" + editMediaObjectViewModel.ID));
        }
Exemple #8
0
        public MediaObject GetMediaObject(string file)
        {
            if (!VideoExt.Contains(Path.GetExtension(file)))
            {
                return(null);
            }

            MediaObject mo = new MediaObject();

            mo.FileInfo = new FileInfo(file);

            Process process = new Process
            {
                StartInfo =
                {
                    FileName               = ffprobe_exe,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    Arguments              = " \"" + file + "\""
                },
                EnableRaisingEvents = true
            };

            Regex durationRegex = new Regex(@"Duration: (?<DURATION>[^ ]+),.*bitrate: (?<BITRATE>[0-9]+)", RegexOptions.Compiled);
            Regex videoStream   = new Regex(@"Stream .*Video: (?<INFO>.*)", RegexOptions.Compiled);
            Regex audioStream   = new Regex(@"Stream .*Audio: (?<INFO>.*)", RegexOptions.Compiled);

            process.Start();

            while (true)
            {
                var line = process.StandardError.ReadLine();
                if (line == null || line == string.Empty)
                {
                    break;
                }

                Match m;
                m = durationRegex.Match(line);
                if (m.Success)
                {
                    mo.Duration = TimeSpan.Parse(m.Groups["DURATION"].Value);
                    mo.Bitrate  = int.Parse(m.Groups["BITRATE"].Value);
                }

                m = videoStream.Match(line);
                if (m.Success)
                {
                    string[] VideoStreamInfo = StreamStringSplit(m.Groups["INFO"].Value);
                    // mo.Video = m.Groups["INFO"].Value.Split(',')[0].Trim();
                    mo.Video = VideoStreamInfo[0];
                    int bitrate;
                    if (int.TryParse(VideoStreamInfo[3].Trim().Split(' ')[0], out bitrate) && bitrate < mo.Bitrate)
                    {
                        mo.Bitrate = bitrate;
                    }
                    mo.Resolution = VideoStreamInfo[2].Split(' ')[0];
                }

                m = audioStream.Match(line);
                if (m.Success)
                {
                    mo.Audio = m.Groups["INFO"].Value.Split(',')[0];
                }
            }

            process.Dispose();
            if (mo.Duration == TimeSpan.Zero || mo.Bitrate == 0 || mo.Video == string.Empty)
            {
                return(null);
            }
            return(mo);
        }
        /// <summary>
        /// Parses each of the images in the document and posts them to the server.
        /// Updates the HTML with the returned Image Urls
        /// </summary>
        /// <param name="html">HTML that contains images</param>
        /// <param name="filename">image file name</param>
        /// <param name="wrapper">blog wrapper instance that sends</param>
        /// <param name="metaData">metadata containing post info</param>
        /// <returns>update HTML string for the document with updated images</returns>
        private string SendImages(string html, string filename, MetaWeblogWrapper wrapper, WeblogPostMetadata metaData)
        {
            var basePath = Path.GetDirectoryName(filename);
            var baseName = Path.GetFileName(basePath);

            baseName = mmFileUtils.SafeFilename(baseName);

            var doc = new HtmlDocument();

            doc.LoadHtml(html);
            try
            {
                // send up normalized path images as separate media items
                var images = doc.DocumentNode.SelectNodes("//img");
                if (images != null)
                {
                    foreach (HtmlNode img in images)
                    {
                        string imgFile = img.Attributes["src"]?.Value as string;
                        if (imgFile == null)
                        {
                            continue;
                        }

                        if (!imgFile.StartsWith("http://") && !imgFile.StartsWith("https://"))
                        {
                            imgFile = Path.Combine(basePath, imgFile.Replace("/", "\\"));
                            if (File.Exists(imgFile))
                            {
                                var media = new MediaObject()
                                {
                                    Type = mmFileUtils.GetImageMediaTypeFromFilename(imgFile),
                                    Bits = File.ReadAllBytes(imgFile),
                                    Name = baseName + "/" + Path.GetFileName(imgFile)
                                };
                                var mediaResult = wrapper.NewMediaObject(media);
                                img.Attributes["src"].Value = mediaResult.URL;

                                // use first image as featured image
                                if (string.IsNullOrEmpty(metaData.FeaturedImageUrl))
                                {
                                    metaData.FeaturedImageUrl = mediaResult.URL;
                                }
                                if (string.IsNullOrWhiteSpace(metaData.FeatureImageId))
                                {
                                    metaData.FeatureImageId = mediaResult.Id;
                                }
                            }
                        }
                    }

                    html = doc.DocumentNode.OuterHtml;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error posting images to Weblog: " + ex.Message,
                                mmApp.ApplicationName,
                                MessageBoxButton.OK,
                                MessageBoxImage.Exclamation);
                mmApp.Log(ex);
                return(null);
            }

            return(html);
        }
Exemple #10
0
 public Task <MediaObjectInfo> NewMediaObjectAsync(string blogid, string username, string password, MediaObject mediaObject)
 {
     throw new NotImplementedException();
 }
Exemple #11
0
        MediaObjectInfo IMetaWeblog.NewMediaObject(string blogid, string username, string password, MediaObject mediaObject)
        {
            ValidateUser(username, password);
            var imagePhysicalPath = Context.Server.MapPath(ConfigurationManager.AppSettings["uploadsPath"]);
            var imageWebPath      = VirtualPathUtility.ToAbsolute(ConfigurationManager.AppSettings["UploadsPath"]);

            imagePhysicalPath = Path.Combine(imagePhysicalPath, mediaObject.name);
            var directoryPath = Path.GetDirectoryName(imagePhysicalPath).Replace("/", "\\");

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            File.WriteAllBytes(imagePhysicalPath, mediaObject.bits);


            return(new MediaObjectInfo()
            {
                url = Path.Combine(imageWebPath, mediaObject.name)
            });
        }
 Task <MediaObjectInfo> IMetaWeblogProvider.NewMediaObjectAsync(string blogid, string username, string password, MediaObject mediaObject)
 {
     throw new NotImplementedException();
 }
Exemple #13
0
        /// <summary>Deletes the media object asynchronous.</summary>
        /// <param name="param">The parameter.</param>
        /// <returns></returns>
        internal async Task <bool> DeleteMediaObjectAsync(MediaObject param)
        {
            HttpResponseMessage result = await _httpClient.DeleteAsync(new Uri(MediaObjectsBaseUri, "MediaObjects/" + param.ID.ToString()));

            return(result.IsSuccessStatusCode);
        }
Exemple #14
0
        public MediaObjectInfo NewMediaObject(string blogid, string username, string password, MediaObject mediaObject)
        {
            if (!validateUser(username, password))
            {
                return(null);
            }

            byte[] bytes = Convert.FromBase64String(mediaObject.bits);

            var path = _imageService.SaveImage(bytes, mediaObject.name).GetAwaiter().GetResult();

            _logger.LogInformation($"Uploaded image via metaweblog {path}");

            return(new MediaObjectInfo {
                url = path
            });
        }
 public async Task RemoveAsync(MediaObject MediaObject, CancellationToken token)
 {
     context.MediaObjects.Remove(MediaObject);
     await SaveAsync(token);
 }
 public async Task AddAsync(MediaObject MediaObject, CancellationToken token)
 {
     await context.MediaObjects.AddAsync(MediaObject, token);
 }
        public async Task <MediaObjectInfo> NewMediaObjectAsync(string blogid, string username, string password, MediaObject mediaObject)
        {
            EnsureUser(username, password);

            try
            {
                // TODO: Check extension names

                var bits = Convert.FromBase64String(mediaObject.bits);

                var pFilename = _fileNameGenerator.GetFileName(mediaObject.name);
                var filename  = await _blogImageStorage.InsertAsync(pFilename, bits);

                var imageUrl = $"{Helper.ResolveRootUrl(null, _blogConfig.GeneralSettings.CanonicalPrefix, true)}image/{filename}";

                MediaObjectInfo objectInfo = new MediaObjectInfo {
                    url = imageUrl
                };
                return(objectInfo);
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                throw new MetaWeblogException(e.Message);
            }
        }
Exemple #18
0
        public MediaObjectInfo NewMediaObject(string blogid, string username, string password, MediaObject mediaObject)
        {
            EnsureUser(username, password).Wait();

            var bits = Convert.FromBase64String(mediaObject.bits);
            var op   = _imageService.StoreImage(mediaObject.name, bits);

            op.Wait();
            if (!op.IsCompletedSuccessfully)
            {
                throw op.Exception;
            }
            var url = op.Result;

            // Create the response
            MediaObjectInfo objectInfo = new MediaObjectInfo();

            objectInfo.url = url;

            return(objectInfo);
        }
    public Task <MediaObjectInfo> NewMediaObjectAsync(string blogid, string username, string password, MediaObject mediaObject)
    {
        EnsureUser(username, password);

        return(TryExecuteAsync(async() =>
        {
            // TODO: Check extension names

            var bits = Convert.FromBase64String(mediaObject.bits);

            var pFilename = _fileNameGenerator.GetFileName(mediaObject.name);
            var filename = await _blogImageStorage.InsertAsync(pFilename, bits);

            var imageUrl = $"{Helper.ResolveRootUrl(null, _blogConfig.GeneralSettings.CanonicalPrefix, true)}image/{filename}";

            var objectInfo = new MediaObjectInfo {
                url = imageUrl
            };
            return objectInfo;
        }));
    }
Exemple #20
0
        public async Task <MediaObjectInfo> NewMediaObjectAsync(string blogId, string username, string password, MediaObject mediaObject)
        {
            ValidateUser(username);

            if (mediaObject is null)
            {
                throw new ArgumentNullException(nameof(mediaObject));
            }

            byte[] bytes = Convert.FromBase64String(mediaObject.bits);
            string path  = await _blog.SaveFile(bytes, mediaObject.name).ConfigureAwait(false);

            return(new MediaObjectInfo {
                url = path
            });
        }
    object IMetaWeblog.NewMediaObject(string blogid, string username, string password, MediaObject media)
    {
        ValidateUser(username, password);

        string path = Blog.SaveFileToDisk(media.bits, Path.GetExtension(media.name));

        return(new { url = path });
    }
Exemple #22
0
		/// <summary>
		/// Creates a new media object.
		/// </summary>
		/// <param name="mediaObject">The media object.</param>
		/// <returns></returns>
		public virtual MediaObjectInfo NewMediaObject(MediaObject mediaObject)
		{
			return wrapper.NewMediaObject(this.BlogID, this.Username, this.Password, mediaObject);
		}
Exemple #23
0
        /// <summary>
        ///     Reads a resampled sequence of bytes from the <see cref="DmoResampler" /> and advances the position within the
        ///     stream by the
        ///     number of bytes read.
        /// </summary>
        /// <param name="buffer">
        ///     An array of bytes. When this method returns, the <paramref name="buffer" /> contains the specified
        ///     byte array with the values between <paramref name="offset" /> and (<paramref name="offset" /> +
        ///     <paramref name="count" /> - 1) replaced by the bytes read from the current source.
        /// </param>
        /// <param name="offset">
        ///     The zero-based byte offset in the <paramref name="buffer" /> at which to begin storing the data
        ///     read from the current stream.
        /// </param>
        /// <param name="count">The maximum number of bytes to read from the current source.</param>
        /// <returns>The total number of bytes read into the buffer.</returns>
        public override int Read(byte[] buffer, int offset, int count)
        {
            lock (LockObj)
            {
                int read = 0;
                while (read < count)
                {
                    MediaObject mediaObject = Resampler.MediaObject;
                    if (mediaObject.IsReadyForInput(0))
                    {
                        var bytesToRead = (int)OutputToInput(count - read);
                        _readBuffer = _readBuffer.CheckBuffer(bytesToRead);
                        int bytesRead = base.Read(_readBuffer, 0, bytesToRead);
                        if (bytesRead <= 0)
                        {
                            break;
                        }

                        if (_disposed)
                        {
                            break;
                        }

                        if (InputBuffer.MaxLength < bytesRead)
                        {
                            InputBuffer.Dispose();
                            InputBuffer = new MediaBuffer(bytesRead);
                        }
                        InputBuffer.Write(_readBuffer, 0, bytesRead);

                        mediaObject.ProcessInput(0, InputBuffer);

                        OutputBuffer.Reset();
                        do
                        {
                            var outputBuffer = (MediaBuffer)OutputBuffer.Buffer;
                            if (outputBuffer.MaxLength < count)
                            {
                                outputBuffer.Dispose();
                                OutputBuffer.Buffer = new MediaBuffer(count);
                            }
                            OutputBuffer.Buffer.SetLength(0);

                            mediaObject.ProcessOutput(ProcessOutputFlags.None, new[] { OutputBuffer }, 1);

                            if (OutputBuffer.Length <= 0)
                            {
                                Debug.WriteLine("DmoResampler::Read: No data in output buffer.");
                                break;
                            }

                            OutputBuffer.Read(buffer, offset + read);
                            read += OutputBuffer.Length;
                        } while (/*_outputBuffer.DataAvailable*/ false); //todo: Implement DataAvailable
                    }
                    else
                    {
                        Debug.WriteLine("Case of not ready for input is not implemented yet."); //todo: .
                    }
                }

                return(read);
            }
        }
Exemple #24
0
        public IActionResult NewMediaObject(string blogid, string username, string password, MediaObject media)
        {
            string relative = BlogRepository.SaveMedia(blogid, media);

            return(new XmlRpcResult(new { url = $"{Request.Scheme}://{Request.Host}{relative}" }));
        }
Exemple #25
0
    object IMetaWeblog.NewMediaObject(string blogid, string username, string password, MediaObject media)
    {
        ValidateUser(username, password);

        string path = Blog.SaveFileToDisk(media.bits, Path.GetExtension(media.name));

        return new { url = path };
    }
Exemple #26
0
        public MediaObjectInfo NewMediaObject(string blogid, string username, string password, MediaObject mediaObject)
        {
            EnsureUser(username, password).Wait();

            var filenameonly = mediaObject.name.Substring(mediaObject.name.LastIndexOf('/') + 1);

            var url   = $"https://wilderminds.blob.core.windows.net/img/{filenameonly}";
            var creds = new StorageCredentials(_config["BlobStorage:Account"], _config["BlobStorage:Key"]);
            var blob  = new CloudBlockBlob(new Uri(url), creds);
            var bits  = Convert.FromBase64String(mediaObject.bits);

            blob.UploadFromByteArrayAsync(bits, 0, bits.Length).Wait();

            // Create the response
            MediaObjectInfo objectInfo = new MediaObjectInfo();

            objectInfo.url = url;

            return(objectInfo);
        }
        public IActionResult Update(UpdateMediaObjectViewModel updateMediaObjectViewModel)
        {
            if (ModelState.IsValid)
            {
                int i = 0;

                //strip double values
                //started
                List <bool> startedBools = StripAndConvertIntArrayToListBool(updateMediaObjectViewModel.StartedValues);
                //completed
                List <bool> completedBools = StripAndConvertIntArrayToListBool(updateMediaObjectViewModel.CompletedValues);

                foreach (int ID in updateMediaObjectViewModel.MediaIDs)
                {
                    //find media object in database
                    bool        countUpdate     = false;
                    string      userId          = Common.ExtensionMethods.getUserId(this.User);
                    MediaObject updateCandidate = context.MediaObjects.
                                                  Where(u => u.OwnerId == userId).
                                                  Single(m => m.ID == ID);

                    //check if Started value has changed, then add to UpdateCount
                    //compare existing value to new value
                    if (updateCandidate.Started != startedBools[i])
                    {
                        //then update
                        updateCandidate.Started = startedBools[i];
                        countUpdate             = true;
                    }
                    //check if Completed value has changed
                    if (updateCandidate.Completed != completedBools[i])
                    {
                        //then update
                        updateCandidate.Completed = completedBools[i];
                        countUpdate = true;
                    }
                    //check if Interest value has changed
                    if (updateCandidate.Interest != updateMediaObjectViewModel.Interest[i])
                    {
                        //check if value is in range
                        if (1 <= updateMediaObjectViewModel.Interest[i] & updateMediaObjectViewModel.Interest[i] <= 10)
                        {
                            //then update
                            updateCandidate.Interest = updateMediaObjectViewModel.Interest[i];
                            //check if new value is > existing value, if not don't count the update
                            if (updateMediaObjectViewModel.Interest[i] > updateCandidate.Interest)
                            {
                                countUpdate = true;
                            }
                        }
                    }
                    if (countUpdate)
                    {
                        updateCandidate.UpdateCount += 1;
                    }

                    i++;
                }
            }

            context.SaveChanges();

            //Then check for deleted Ids and pass any to the DeletePrompt route
            if (updateMediaObjectViewModel.DeletedIDs != null)
            {
                List <MediaObject> mediaToDelete = new List <MediaObject>();
                mediaToDelete = ArrayIdsToListMediaObjects(updateMediaObjectViewModel.DeletedIDs);
                return(View("DeletePrompt", mediaToDelete));
            }

            return(Redirect("/"));
        }
        public IActionResult NewMediaObject(string blogId, string userName, string password, MediaObject media)
        {
            return(CheckSecurity(userName, password, () =>
            {
                string relative = BlogRepository.SaveMedia(blogId, media);

                return new XmlRpcResult(new { url = $"{Request.Scheme}://{Request.Host}{relative}" });
            }));
        }
        public IActionResult WeightedSuggestion(int id)
        {
            string userId = Common.ExtensionMethods.getUserId(this.User);

            //query database for all undeleted, uncompleted results belonging to the user not yet suggested today.
            List <MediaObject> mediaObjects = context.MediaObjects.
                                              Include(s => s.MediaSubType).
                                              Where(u => u.OwnerId == userId).
                                              Where(d => d.Deleted == false).
                                              Where(c => c.Completed == false).
                                              Where(l => int.Parse(l.LastSuggested.ToString("yyyyMMdd")) < int.Parse(DateTime.Now.ToString("yyyyMMdd"))).
                                              ToList();
            List <MediaObject> weightedRandomMedia = new List <MediaObject>();

            if (id != 0)
            {
                mediaObjects = mediaObjects.Where(i => i.SubTypeID == id).ToList();
            }

            int  numSuggestion = 3;
            bool ignoreDoubles = true;

            //debug Suggestions
            if (testSuggestions == true)
            {
                ResetSuggestedCount(mediaObjects);
                //numSuggestion = numTest;
                //ignoreDoubles = false;
            }

            int numTests = 0;

            //loop for debugging
            for (int i = 0; i < numTest; i++)
            {
                //ensure the while loop does not continue needlessly when too few items in list
                if (mediaObjects.Count <= numSuggestion)
                {
                    foreach (MediaObject mediaObject in mediaObjects)
                    {
                        mediaObject.SuggestedCount += 1;
                        mediaObject.LastSuggested   = DateTime.Now;
                    }
                    context.SaveChanges();

                    SuggestionViewModel suggestionViewModelB = new SuggestionViewModel {
                        MediaObjects = mediaObjects
                    };

                    return(View(suggestionViewModelB));
                }
                else
                {
                    while (weightedRandomMedia.Count < numSuggestion)
                    {
                        Random      rand     = new Random();
                        int         index    = rand.Next(0, mediaObjects.Count);
                        MediaObject theMedia = mediaObjects[index];

                        //ignore doubles
                        if (weightedRandomMedia.Contains(theMedia) == false || ignoreDoubles == false)
                        {
                            int interestMax     = 10;
                            int updateThreshold = 3;  //caps influence of UpdateCount (measurement of engagement)

                            //compute probability range
                            int baseRange       = interestMax + updateThreshold;
                            int updateFactor    = theMedia.UpdateCount;
                            int suggestedFactor = theMedia.SuggestedCount / numSuggestion;

                            if (testSuggestions == true)
                            {
                                suggestedFactor = theMedia.SuggestedCount / 3;
                            }

                            //control for maximum suggestedFactor
                            if (suggestedFactor > interestMax)
                            {
                                suggestedFactor = interestMax;
                            }

                            //control for maximum updateFactor
                            if (updateFactor > updateThreshold)
                            {
                                updateFactor = updateThreshold;
                            }

                            int newRange = baseRange - updateFactor + suggestedFactor - theMedia.SelectedCount - theMedia.Interest;

                            //if newRange is <= 1, there is a 100% probability it will be chosen
                            if (newRange <= 1)
                            {
                                weightedRandomMedia.Add(theMedia);
                                theMedia.SuggestedCount += 1;
                                theMedia.LastSuggested   = DateTime.Now;
                            }
                            else
                            {
                                //run random with new range
                                Random prob   = new Random();
                                int    result = prob.Next(1, newRange + 1);

                                //if result == 1, then add it to list
                                if (result == 1)
                                {
                                    weightedRandomMedia.Add(theMedia);
                                    theMedia.SuggestedCount += 1;
                                    theMedia.LastSuggested   = DateTime.Now;
                                }
                            }
                        }
                    }
                }

                //check if debug
                if (testSuggestions == false)
                {
                    break;
                }
                else
                {
                    numTests           += 1;
                    weightedRandomMedia = new List <MediaObject>();
                }
            }

            context.SaveChanges();

            SuggestionViewModel suggestionViewModelA = new SuggestionViewModel {
                MediaObjects = weightedRandomMedia
            };

            return(View(suggestionViewModelA));
        }
Exemple #30
0
        public async Task <MediaObjectInfo> NewMediaObjectAsync(string blogid, string username, string password, MediaObject mediaObject)
        {
            MediaObjectInfo mediaInfo = new MediaObjectInfo();

            if (await IsValidMetaWeblogUserAsync(username, password))
            {
                string fileName = Path.GetFileName(mediaObject.name);

                string PathOnly = Path.Combine(
                    _environment.WebRootPath,
                    "blogs",
                    $"{blogid}",
                    Path.GetDirectoryName(mediaObject.name));

                if (!Directory.Exists(PathOnly))
                {
                    Directory.CreateDirectory(PathOnly);
                }

                string FilePath = Path.Combine(PathOnly, fileName);

                var fileBytes = Convert.FromBase64String(mediaObject.bits);

                if (fileBytes != null)
                {
                    using (MemoryStream ms = new MemoryStream(fileBytes))
                    {
                        Bitmap bitmap = new Bitmap(ms);

                        bitmap.Save(FilePath);
                    }
                }

                mediaInfo.url = $@"{GetBaseUrl()}/blogs/{blogid}/{Path.GetDirectoryName(mediaObject.name).Replace("\\", @"/")}/{fileName}";
            }
            else
            {
                throw new Exception("Bad user name or password");
            }

            return(mediaInfo);
        }
Exemple #31
0
        public async Task <MediaObjectInfo> NewMediaObjectAsync(string blogid, string username, string password, MediaObject mediaObject)
        {
            ValidateUser(username, password);
            byte[] bytes = Convert.FromBase64String(mediaObject.bits);
            string path  = await _blog.SaveFile(bytes, mediaObject.name);

            return(new MediaObjectInfo {
                url = path
            });
        }
        public Task <MediaObjectInfo> NewMediaObjectAsync(string blogid, string username, string password, MediaObject mediaObject)
        {
            return(Task.Run(() =>
            {
                ValidateUser(username, password);
                byte[] bytes = Convert.FromBase64String(mediaObject.bits);
                string path = _blog.SaveFile(bytes, mediaObject.name).GetAwaiter().GetResult();

                return new MediaObjectInfo {
                    url = path
                };
            }));
        }
Exemple #33
0
 public MediaObjectInfo NewMediaObject(string blogid, string username, string password, MediaObject mediaObject)
 {
     return(new MediaObjectInfo());
 }
 public object NewMediaObject(string blogid, string username, string password, MediaObject mediaObject)
 {
     throw new System.NotImplementedException();
 }