Exemplo n.º 1
0
        public override string MediaFolderPath(MediaOptions mediaOptions)
        {
            string result;

            if (mediaOptions.UsePublicStorage == false)
            {
                result = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath;
            }
            else
            {
                result = Env.GetExternalStoragePublicDirectory(Env.DirectoryPictures).AbsolutePath;
            }

            if (string.IsNullOrWhiteSpace(mediaOptions.Directory) == false)
            {
                result = System.IO.Path.Combine(result, mediaOptions.Directory);
            }

            if (Directory.Exists(result).Equals(false))
            {
                Directory.CreateDirectory(result);
            }

            return(result);
        }
Exemplo n.º 2
0
        // Called when you create a new Media('blah') object in JS.
        public void create(string options)
        {
            try
            {
                MediaOptions mediaOptions;
                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize <string[]>(options);
                    mediaOptions     = new MediaOptions();
                    mediaOptions.Id  = optionsString[0];
                    mediaOptions.Src = optionsString[1];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Error parsing options into create method"));
                    return;
                }

                DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
            }
        }
Exemplo n.º 3
0
        private MediaStream GetImageStream(MediaStream stream, TransformationOptions options)
        {
            Assert.ArgumentNotNull((object)stream, nameof(stream));
            Assert.ArgumentNotNull((object)options, nameof(options));
            var mediaOptions = new MediaOptions()
            {
                AllowStretch      = options.AllowStretch,
                BackgroundColor   = options.BackgroundColor,
                IgnoreAspectRatio = options.IgnoreAspectRatio,
                Scale             = options.Scale,
                Width             = options.Size.Width,
                Height            = options.Size.Height,
                MaxWidth          = options.MaxSize.Width,
                MaxHeight         = options.MaxSize.Height
            };

            mediaOptions.CustomOptions["extension"] = "webp";
            var args = new OptimizerArgs(stream.Stream, mediaOptions);

            CorePipeline.Run("dianogaOptimizeWebP", args);

            if (args.IsOptimized)
            {
                return(new MediaStream(args.Stream, args.Extension, stream.MediaItem));
            }
            return(null);
        }
Exemplo n.º 4
0
        // Some Audio Notes:
        // In the Windows Phone Emulator, playback of video or audio content using the MediaElement control is not supported.
        // While playing, a MediaElement stops all other media playback on the phone.
        // Multiple MediaElement controls are NOT supported

        // Called when you create a new Media('blah.wav') object in JS.
        public void create(string options)
        {
            string callbackId = this.CurrentCommandCallbackId;

            try
            {
                MediaOptions mediaOptions;
                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize <string[]>(options);
                    mediaOptions     = new MediaOptions();
                    mediaOptions.Id  = optionsString[0];
                    mediaOptions.Src = optionsString[1];
                    callbackId       = mediaOptions.CallbackId = optionsString[2];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION,
                                                           "Error parsing options into create method"), callbackId);
                    return;
                }

                GetOrCreatePlayerById(mediaOptions.Id);
                DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message), callbackId);
            }
        }
Exemplo n.º 5
0
		/// <summary>
		/// Optimizes a media stream and returns the optimized result. The original stream is closed if processing is successful.
		/// </summary>
		public virtual MediaStream Process(MediaStream stream, MediaOptions options)
		{
			Assert.ArgumentNotNull(stream, "stream");

			if (!stream.AllowMemoryLoading)
			{
				Tracer.Error("Could not resize image as it was larger than the maximum size allowed for memory processing. Media item: {0}", stream.MediaItem.Path);
				return null;
			}

			var optimizer = CreateOptimizer(stream);

			if (optimizer == null) return null;

			var sw = new Stopwatch();
			sw.Start();

			var result = optimizer.Optimize(stream);

			sw.Stop();

			if (result.Success)
			{
				stream.Stream.Close();

				Log.Info("Dianoga: optimized {0}.{1} [{2}] (final size: {3} bytes) - saved {4} bytes / {5:p}. Optimized in {6}ms.".FormatWith(stream.MediaItem.MediaPath, stream.MediaItem.Extension, GetDimensions(options), result.SizeAfter, result.SizeBefore - result.SizeAfter, 1 - ((result.SizeAfter / (float)result.SizeBefore)), sw.ElapsedMilliseconds), this);

				return new MediaStream(result.CreateResultStream(), stream.Extension, stream.MediaItem);
			}

			Log.Warn("Dianoga: unable to optimize {0}.{1} because {2}".FormatWith(stream.MediaItem.MediaPath, stream.MediaItem.Extension, result.ErrorMessage), this);

			return null;
		}
		public override bool AddStream(Media media, MediaOptions options, MediaStream stream, out MediaStream cachedStream)
		{
			/* STOCK METHOD (Decompiled) */
			Assert.ArgumentNotNull(media, "media");
			Assert.ArgumentNotNull(options, "options");
			Assert.ArgumentNotNull(stream, "stream");

			cachedStream = null;

			if (!CanCache(media, options))
				return false;

			MediaCacheRecord cacheRecord = CreateCacheRecord(media, options, stream);

			if (cacheRecord == null) return false;

			cachedStream = cacheRecord.GetStream();

			if (cachedStream == null) return false;

			AddToActiveList(cacheRecord);
			/* END STOCK */

			// we store the site context because on the background thread: without the Sitecore context saved (on a worker thread), that disables the media cache
			var currentSite = Context.Site;

			cacheRecord.PersistAsync((() => OnAfterPersist(cacheRecord, currentSite)));

			return true;
		}
Exemplo n.º 7
0
        private async void OnPickPicturesClicked(object sender, EventArgs args)
        {
            try
            {
                var mediaOptions = new MediaOptions {
                    Directory = "Sample"
                };
                var pickPage = new PickPhotosPage(mediaOptions);
                pickPage.PhotosSelected += (s, e) =>
                {
                    _photos.Clear();
                    foreach (var pic in e)
                    {
                        _photos.Add(ImageSource.FromStream(pic.GetStream));
                    }
                };

                await Navigation.PushModalAsync(pickPage);
            }
            catch (MediaPermissionException ex)
            {
                await DisplayAlert("Permission Denied", ex.Message, "OK");
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(ex.StackTrace);
#endif
            }
        }
Exemplo n.º 8
0
        // Some Audio Notes:
        // In the Windows Phone Emulator, playback of video or audio content using the MediaElement control is not supported.
        // While playing, a MediaElement stops all other media playback on the phone.
        // Multiple MediaElement controls are NOT supported
        // Called when you create a new Media('blah.wav') object in JS.
        public void create(string options)
        {
            string callbackId = this.CurrentCommandCallbackId;
            try
            {
                MediaOptions mediaOptions;
                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize<string[]>(options);
                    mediaOptions = new MediaOptions();
                    mediaOptions.Id = optionsString[0];
                    mediaOptions.Src = optionsString[1];
                    callbackId = mediaOptions.CallbackId = optionsString[2];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION,
                                            "Error parsing options into create method"), callbackId);
                    return;
                }

                GetOrCreatePlayerById(mediaOptions.Id);
                DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);

            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message), callbackId);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Opens the video stream with the specified index in the media container.
        /// </summary>
        /// <param name="container">The media container.</param>
        /// <param name="options">The media options.</param>
        /// <param name="stream">The stream.</param>
        /// <returns>The opened <see cref="Decoder"/>.</returns>
        internal static Decoder OpenStream(InputContainer container, MediaOptions options, AVStream *stream)
        {
            var      format = container.Pointer;
            AVCodec *codec  = null;

            var index = ffmpeg.av_find_best_stream(format, stream->codec->codec_type, stream->index, -1, &codec, 0);

            index.IfError(ffmpeg.AVERROR_DECODER_NOT_FOUND, "Cannot find a codec for the specified stream.");
            if (index < 0)
            {
                return(null);
            }

            var codecContext = ffmpeg.avcodec_alloc_context3(codec);

            ffmpeg.avcodec_parameters_to_context(codecContext, stream->codecpar)
            .ThrowIfError("Cannot open the stream codec!");
            codecContext->pkt_timebase = stream->time_base;

            var dict = new FFDictionary(options.DecoderOptions, false).Pointer;

            ffmpeg.avcodec_open2(codecContext, codec, &dict)
            .ThrowIfError("Cannot open the stream codec!");

            return(new Decoder(codecContext, stream, container));
        }
Exemplo n.º 10
0
        // Some Audio Notes:
        // In the Windows Phone Emulator, playback of video or audio content using the MediaElement control is not supported.
        // While playing, a MediaElement stops all other media playback on the phone.
        // Multiple MediaElement controls are NOT supported
        // Called when you create a new Media('blah') object in JS.
        public void create(string options)
        {
            // Debug.WriteLine("Creating Audio :: " + options);
            try
            {
                MediaOptions mediaOptions;
                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize<string[]>(options);
                    mediaOptions = new MediaOptions();
                    mediaOptions.Id = optionsString[0];
                    mediaOptions.Src = optionsString[1];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Error parsing options into create method"));
                    return;
                }

                AudioPlayer audio = new AudioPlayer(this, mediaOptions.Id);
                Media.players.Add(mediaOptions.Id, audio);
                DispatchCommandResult(new PluginResult(PluginResult.Status.OK));

            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
            }
        }
Exemplo n.º 11
0
        // Some Audio Notes:
        // In the Windows Phone Emulator, playback of video or audio content using the MediaElement control is not supported.
        // While playing, a MediaElement stops all other media playback on the phone.
        // Multiple MediaElement controls are NOT supported

        // Called when you create a new Media('blah') object in JS.
        public void create(string options)
        {
            // Debug.WriteLine("Creating Audio :: " + options);
            try
            {
                MediaOptions mediaOptions;
                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize <string[]>(options);
                    mediaOptions     = new MediaOptions();
                    mediaOptions.Id  = optionsString[0];
                    mediaOptions.Src = optionsString[1];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Error parsing options into create method"));
                    return;
                }

                AudioPlayer audio = new AudioPlayer(this, mediaOptions.Id);
                Media.players.Add(mediaOptions.Id, audio);
                DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
            }
        }
Exemplo n.º 12
0
        private async void upsertAttachmentButton_Click(object sender, EventArgs e)
        {
            try
            {
                var docUri       = UriFactory.CreateDocumentUri(DatabaseName, CollectionName, docIdTextBox.Text);
                var mediaOptions = new MediaOptions()
                {
                    ContentType = mediaTypeTextBox.Text,
                    Slug        = attachmentIdTextBox.Text
                };
                var requestOptions = new RequestOptions()
                {
                    PartitionKey = new Microsoft.Azure.Documents.PartitionKey(tenantId.ToString())
                };
                using (var fileStream = new FileStream(filePathTextBox.Text, FileMode.Open, FileAccess.Read))
                {
                    var result2 = await client.UpsertAttachmentAsync(docUri, fileStream, mediaOptions, requestOptions);

                    MessageBox.Show(result2.StatusCode.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 13
0
        protected override async void OnNavigatedTo(NavigationEventArgs args)
        {
            var config = new ConductorConfig()
            {
                CoreDispatcher = this.Dispatcher,
                LocalVideo     = this.LocalVideo
            };

            await this.conductor.Initialize(config);

            var opts = new MediaOptions(
                new MediaOptions.Init()
            {
                LocalLoopback = true
            });

            this.conductor.SetMediaOptions(opts);

            var devices = await this.conductor.GetVideoDevices();

            this.MediaDeviceComboBox.ItemsSource   = devices;
            this.MediaDeviceComboBox.SelectedIndex = 0;

            this.CaptureFormatComboBox.ItemsSource =
                await this.conductor.GetCaptureProfiles(devices.First());

            this.CaptureFormatComboBox.SelectedIndex = 0;
        }
        public override Task <byte[]> ResizedStream(MediaFile file, MediaOptions mediaOptions)
        {
            var percent = 1.0f;

            switch (mediaOptions.PhotoSize)
            {
            case PhotoSize.Large:
                percent = 0.75f;
                break;

            case PhotoSize.Medium:
                percent = 0.5f;
                break;

            case PhotoSize.Small:
                percent = 0.25f;
                break;

            case PhotoSize.Custom:
                percent = (float)mediaOptions.CustomPhotoSize / 100f;
                break;
            }

            var image = new UIImage(file.Path);

            var result = Resize(image, percent, mediaOptions.CompressionQuality);

            return(Task.FromResult(result));
        }
Exemplo n.º 15
0
 private MarkdownPipeline GetPipelineWithBootstrap(MediaOptions options = null)
 {
     return(new MarkdownPipelineBuilder()
            .UseBootstrap()
            .UseMediaLinks(options)
            .Build());
 }
Exemplo n.º 16
0
        /// <summary>
        /// Opens the video stream with the specified index in the media container.
        /// </summary>
        /// <param name="container">The media container.</param>
        /// <param name="options">The media options.</param>
        /// <returns>The opened <see cref="Decoder{TFrame}"/>.</returns>
        internal static Decoder <VideoFrame> OpenVideo(InputContainer container, MediaOptions options)
        {
            var      format = container.Pointer;
            AVCodec *codec  = null;

            var index = ffmpeg.av_find_best_stream(format, AVMediaType.AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);

            index.IfError(ffmpeg.AVERROR_DECODER_NOT_FOUND, "Cannot find a codec for the video stream.");
            if (index < 0)
            {
                return(null);
            }

            var stream       = format->streams[index];
            var codecContext = ffmpeg.avcodec_alloc_context3(codec);

            ffmpeg.avcodec_parameters_to_context(codecContext, stream->codecpar)
            .ThrowIfError("Cannot open the video codec!");
            codecContext->pkt_timebase = stream->time_base;

            var dict = new FFDictionary(options.DecoderOptions, false).Pointer;

            ffmpeg.avcodec_open2(codecContext, codec, &dict)
            .ThrowIfError("Cannot open the video codec");

            return(new Decoder <VideoFrame>(codecContext, stream, container));
        }
        private static void ValidateTokenlessCommands(ImageCommandContext context, MediaOptions mediaOptions)
        {
            // The following commands are not supported without a tokenized query string.
            context.Commands.Remove(ResizeWebProcessor.Xy);
            context.Commands.Remove(ImageVersionProcessor.VersionCommand);
            context.Commands.Remove(BackgroundColorWebProcessor.Color);

            // Width and height must be part of the supported sizes array when tokenization is disabled.
            if (context.Commands.TryGetValue(ResizeWebProcessor.Width, out var widthString))
            {
                var width = context.Parser.ParseValue <int>(widthString, context.Culture);

                if (Array.BinarySearch <int>(mediaOptions.SupportedSizes, width) < 0)
                {
                    context.Commands.Remove(ResizeWebProcessor.Width);
                }
            }

            if (context.Commands.TryGetValue(ResizeWebProcessor.Height, out var heightString))
            {
                var height = context.Parser.ParseValue <int>(heightString, context.Culture);

                if (Array.BinarySearch <int>(mediaOptions.SupportedSizes, height) < 0)
                {
                    context.Commands.Remove(ResizeWebProcessor.Height);
                }
            }
        }
Exemplo n.º 18
0
        private void lblPlaylist_PreviewDrop(object sender, DragEventArgs e)
        {
            var fileNames = e.Data.GetData(DataFormats.FileDrop) as string[];

            foreach (var file in fileNames)
            {
                var extension = Path.GetExtension(file);
                if (!AppHelper.MediaExtensions.Any(ext => ext == extension))
                {
                    if (file.EndsWith(AppHelper.Options.PlaylistExtension))
                    {
                        LoadPlaylist(file);
                        return;
                    }
                    else
                    {
                        Snackbar.MessageQueue.Enqueue(InternalResources.NotSupportedMediaExtensionFormat.Format(extension));
                        continue;
                    }
                }

                var media = MediaOptions.Create(lbxPlaylist.Items.Count + 1, file, AppHelper.Options.DefaultVolume);
                _viewModel.Playlist.Medias.Add(media);
                btnSave.IsEnabled = true;

                var defaultMedia = BindPlaylist(_viewModel.Playlist);
                _viewModel.PlayerWrapper.Load(defaultMedia);
            }
        }
Exemplo n.º 19
0
        protected override async void OnNavigatedTo(NavigationEventArgs args)
        {
            var signaller = new WebsocketSignaller();

            this.ConnectToServerButton.Click += async(s, a) =>
            {
                this.NotConnected.Hide();
                await signaller.ConnectToServer(ServerConfig.AwsAddress);

                this.Connected.Show();
            };

            this.DisconnectFromServerButton.Click += (s, a) =>
            {
                this.Connected.Hide();
                signaller.DisconnectFromServer();
                this.NotConnected.Show();
            };

            var config = new ConductorConfig()
            {
                CoreDispatcher = this.Dispatcher,
                Signaller      = signaller
            };

            Logger.Log("Initializing WebRTC...");
            await this.conductor.Initialize(config);

            Logger.Log("Done.");

            var opts = new MediaOptions(
                new MediaOptions.Init()
            {
                SendVideo = true
            });

            this.conductor.SetMediaOptions(opts);

            this.conductor.UISignaller.ReceivedShutdown += async(s, a) =>
            {
                await this.conductor.Shutdown();
            };

            this.conductor.UISignaller.ReceivedPlain += (s, message) =>
            {
                Logger.Log(message);
            };

            var devices = await this.conductor.GetVideoDevices();

            this.MediaDeviceComboBox.ItemsSource   = devices;
            this.MediaDeviceComboBox.SelectedIndex = 0;

            this.CaptureFormatComboBox.ItemsSource =
                await this.conductor.GetCaptureProfiles(devices.First());

            this.CaptureFormatComboBox.SelectedIndex = 0;
        }
Exemplo n.º 20
0
            public ImageSaver(Image image, File file, MediaOptions mediaOptions, DeviceRotation rotation, EventHandler <MediaFile> callBack)
            {
                _image           = image ?? throw new ArgumentNullException("image");
                _file            = file ?? throw new ArgumentNullException("file");
                _mediaOptions    = mediaOptions ?? throw new ArgumentNullException("mediaOptions");
                _currentRotation = rotation;

                CallBack = callBack;
            }
Exemplo n.º 21
0
 public ImageResizeTagHelper(
     IMediaProfileService mediaProfileService,
     IOptions <MediaOptions> mediaOptions,
     IMediaTokenService mediaTokenService)
 {
     _mediaProfileService = mediaProfileService;
     _mediaOptions        = mediaOptions.Value;
     _mediaTokenService   = mediaTokenService;
 }
Exemplo n.º 22
0
        private static InputContainer MakeContainer(string url, MediaOptions options, AVFormatContextDelegate contextDelegate)
        {
            var context = MakeContext(url, options, contextDelegate);

            var container = new InputContainer(context, options.PacketBufferSizeLimit);

            container.OpenStreams(options);
            return(container);
        }
Exemplo n.º 23
0
        protected override async void OnNavigatedTo(NavigationEventArgs args)
        {
            signaller = new WebsocketSignaller();

            this.SetUpCallButton.Click += async(s, a) =>
            {
                this.NotConnected.Hide();
                await signaller.ConnectToServer("ws://drhololens-env.esncizasfm.us-east-2.elasticbeanstalk.com/");

                this.Connected.Show();
            };

            this.HangUpCallButton.Click += (s, a) =>
            {
                this.Connected.Hide();
                this.conductor.Shutdown();
                this.NotConnected.Show();
            };

            this.DisconnectFromServerButton.Click += (s, a) =>
            {
                Logger.Log("Disconnected from server");
                signaller.DisconnectFromServer();
            };

            var config = new ConductorConfig()
            {
                CoreDispatcher = this.Dispatcher,
                RemoteVideo    = this.RemoteVideo,
                Signaller      = signaller
            };

            Logger.Log("Initializing WebRTC...");
            await this.conductor.Initialize(config);

            Logger.Log("Done.");

            var opts = new MediaOptions(
                new MediaOptions.Init()
            {
                SendAudio    = true,
                ReceiveAudio = true
            });

            this.conductor.SetMediaOptions(opts);

            this.conductor.UISignaller.ReceivedShutdown += async(s, a) =>
            {
                await this.conductor.Shutdown();
            };

            this.conductor.UISignaller.ReceivedPlain += (s, message) =>
            {
                Logger.Log(message);
            };
        }
Exemplo n.º 24
0
        private void CreateDocumentAttachment(Document document, Stream messageStream)
        {
            var mediaOptions = new MediaOptions
            {
                ContentType = "application/pdf",
                Slug        = "something.pdf"
            };

            _client.CreateAttachmentAsync(document.SelfLink, messageStream, mediaOptions);
        }
Exemplo n.º 25
0
 /// <summary>
 /// Opens the streams in the file using the specified <see cref="MediaOptions"/>.
 /// </summary>
 /// <param name="options">The <see cref="MediaOptions"/> object.</param>
 private void OpenStreams(MediaOptions options)
 {
     // if (options.StreamsToLoad != MediaMode.Audio)
     Video = DecoderFactory.OpenVideo(this, options);
     if (Video != null)
     {
         GetPacketFromStream(Video.Info.Index); // Requests for the first packet.
         canReusePacket = true;
     }
 }
Exemplo n.º 26
0
        /// <summary>
        /// Optimizes a media stream and returns the optimized result. The original stream is closed if processing is successful.
        /// Returns null if processing was unsuccessful.
        /// </summary>
        public virtual MediaStream Process(MediaStream stream, MediaOptions options)
        {
            Assert.ArgumentNotNull(stream, nameof(stream));
            Assert.ArgumentNotNull(options, nameof(options));

            if (!stream.AllowMemoryLoading)
            {
                Log.Error($"Dianoga: Could not resize image as it was larger than the maximum size allowed for memory processing. Media item: {stream.MediaItem.Path}", this);
                return(null);
            }

            //Run optimizer based on extension
            var sw = new Stopwatch();

            sw.Start();

            var result = new ProcessorArgs(stream, options);

            try
            {
                CorePipeline.Run("dianogaOptimize", result);
            }
            catch (Exception exception)
            {
                Log.Error($"Dianoga: Unable to optimize {stream.MediaItem.MediaPath} due to a processing error! It will be unchanged.", exception, this);
                return(null);
            }
            sw.Stop();

            if (result.ResultStream != null && result.ResultStream.CanRead)
            {
                if (result.Message.Length > 0)
                {
                    Log.Info($"Dianoga: messages occurred while optimizing {stream.MediaItem.MediaPath}: {result.Message.Trim()}", this);
                }

                var extension = result.Extension ?? stream.Extension;
                if (result.IsOptimized)
                {
                    Log.Info($"Dianoga: optimized {stream.MediaItem.MediaPath}.{stream.MediaItem.Extension} [original size: {GetDimensions(options)} {result.Statistics.SizeBefore} bytes] [final size: {result.Statistics.SizeAfter} bytes] [saved {result.Statistics.BytesSaved} bytes / {result.Statistics.PercentageSaved:p}] [Optimized in {sw.ElapsedMilliseconds}ms] [Extension {extension}]", this);
                }

                return(new MediaStream(result.ResultStream, extension, stream.MediaItem));
            }

            if (!string.IsNullOrWhiteSpace(result.Message))
            {
                Log.Warn($"Dianoga: unable to optimize {stream.MediaItem.MediaPath}.{stream.MediaItem.Extension} because {result.Message.Trim()}", this);
            }

            // if no message exists that implies that nothing in the dianogaOptimize pipeline acted to optimize - e.g. it's a media type we don't know how to optimize, like PDF.

            return(null);
        }
Exemplo n.º 27
0
        async void myMenuItemAttachmentFromFile_Click(object sender, EventArgs eventArg)
        {
            var ofd = new OpenFileDialog();
            var dr  = ofd.ShowDialog();

            if (dr == DialogResult.OK)
            {
                var filename = ofd.FileName;
                //
                // todo: present the dialog for Slug name and Content type
                //
                Program.GetMain().SetLoadingState();

                try
                {
                    using (var stream = new FileStream(filename,
                                                       FileMode.Open, FileAccess.Read))
                    {
                        var mediaOptions = new MediaOptions()
                        {
                            ContentType = "application/octet-stream",
                            Slug        = Path.GetFileName(ofd.FileName)
                        };

                        ResourceResponse <Attachment> rr;

                        var document   = ((Document)Tag);
                        var collection = ((DocumentCollection)Parent.Tag);

                        var requestOptions = GetRequestOptions();
                        if (collection.PartitionKey != null && collection.PartitionKey.Paths.Count > 0)
                        {
                            requestOptions.PartitionKey = new PartitionKey(DocumentAnalyzer.ExtractPartitionKeyValue(document, collection.PartitionKey));
                        }

                        using (PerfStatus.Start("CreateAttachment"))
                        {
                            rr = await _client.CreateAttachmentAsync((Tag as Document).SelfLink + "/attachments",
                                                                     stream, mediaOptions, requestOptions);
                        }

                        var json = rr.Resource.ToString();

                        SetResultInBrowser(json, null, false, rr.ResponseHeaders);

                        Nodes.Add(new ResourceNode(_client, rr.Resource, ResourceType.Attachment));
                    }
                }
                catch (Exception e)
                {
                    SetResultInBrowser(null, e.ToString(), true);
                }
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        public void startPlayingAudio(string options)
        {
            try
            {
                MediaOptions mediaOptions;
                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize <string[]>(options);
                    mediaOptions     = new MediaOptions();
                    mediaOptions.Id  = optionsString[0];
                    mediaOptions.Src = optionsString[1];
                    if (optionsString.Length > 2 && optionsString[2] != null)
                    {
                        mediaOptions.Milliseconds = int.Parse(optionsString[2]);
                    }
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                    return;
                }

                AudioPlayer audio;

                if (!Media.players.ContainsKey(mediaOptions.Id))
                {
                    audio = new AudioPlayer(this, mediaOptions.Id);
                    Media.players[mediaOptions.Id] = audio;
                }
                else
                {
                    Debug.WriteLine("INFO: startPlayingAudio FOUND mediaPlayer for " + mediaOptions.Id);
                    audio = Media.players[mediaOptions.Id];
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        audio.startPlaying(mediaOptions.Src);
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
                    }
                    catch (Exception e)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
                    }
                });
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
            }
        }
Exemplo n.º 29
0
 public ManageMediaFolderAuthorizationHandler(IServiceProvider serviceProvider,
                                              AttachedMediaFieldFileService attachedMediaFieldFileService,
                                              IMediaFileStore fileStore,
                                              IOptions <MediaOptions> options,
                                              IUserAssetFolderNameProvider userAssetFolderNameProvider)
 {
     _serviceProvider = serviceProvider;
     _attachedMediaFieldFileService = attachedMediaFieldFileService;
     _fileStore    = fileStore;
     _mediaOptions = options.Value;
     _userAssetFolderNameProvider = userAssetFolderNameProvider;
 }
Exemplo n.º 30
0
        /// <summary>
        /// Seeks to a location
        /// </summary>
        public void seekToAudio(string options)
        {
            string callbackId = this.CurrentCommandCallbackId;

            try
            {
                MediaOptions mediaOptions;

                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize <string[]>(options);
                    mediaOptions    = new MediaOptions();
                    mediaOptions.Id = optionsString[0];
                    int msec = 0;
                    if (int.TryParse(optionsString[1], out msec))
                    {
                        mediaOptions.Milliseconds = msec;
                    }
                    callbackId = mediaOptions.CallbackId = optionsString[2];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId);
                    return;
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        if (Media.players.ContainsKey(mediaOptions.Id))
                        {
                            AudioPlayer audio = Media.players[mediaOptions.Id];
                            audio.seekToPlaying(mediaOptions.Milliseconds);
                        }
                        else
                        {
                            Debug.WriteLine("ERROR: seekToAudio could not find mediaPlayer for " + mediaOptions.Id);
                        }

                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
                    }
                    catch (Exception e)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message), callbackId);
                    }
                });
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message), callbackId);
            }
        }
Exemplo n.º 31
0
        private async void SourceConnectButton_Click(object sender, RoutedEventArgs e)
        {
            if (isProcessing)
            {
                return;
            }
            isProcessing = true;

            if (!isConnectedToSource)
            {
                Logger.Log("Starting connection to source...");
                var opts = new MediaOptions(
                    new MediaOptions.Init()
                {
                    ReceiveVideo = (bool)this.ReceiveVideoCheck.IsChecked,
                    ReceiveAudio = (bool)this.ReceiveAudioCheck.IsChecked,
                    SendAudio    = (bool)this.SendAudioCheck.IsChecked
                });
                this.conductor.SetMediaOptions(opts);
                await this.conductor.StartCall();

                Logger.Log("Connection started...");
                //signaller.DisconnectFromServer(); Because of async calls, this disconnects too early.
                this.SayHiButton.Hide();
            }
            else
            {
                Logger.Log("Disconnecting from source...");
                await this.conductor.Shutdown();

                Logger.Log("Connection ended...");
                this.SayHiButton.Show();
                this.ConnectedOptions.Hide();
                this.StartupSettings.Show();
            }
            isConnectedToSource = !isConnectedToSource;
            //this.SourceConnectButton.Content = (isConnectedToSource ? "Connect to Source" : "Disconnect from Source");
            // ^-- this doesn't work but the general logic is that the button should show "Disconnect" or "Connect" depending on its state

            // Temporary workaround: two buttons!
            if (isConnectedToSource)
            {
                this.SourceConnectButton.Hide();
                this.SourceDisconnectButton.Show();
            }
            else
            {
                this.SourceDisconnectButton.Hide();
                this.SourceConnectButton.Show();
            }

            isProcessing = false;
        }
Exemplo n.º 32
0
        public void Initialize(StreamInfo streamInfo, int maxItemsInQueue)
        {
            if (streamInfo == null)
            {
                throw new ArgumentNullException("streamInfo");
            }

            m_streamInfo = streamInfo;
            AddOptions(MediaOptions.ToList());
            m_queue       = new BlockingCollection <FrameData>(maxItemsInQueue);
            m_initilaized = true;
        }
        public PickPhotosPage(MediaOptions mediaOptions) : this()
        {
            _photos       = new List <MediaFile>();
            _mediaOptions = mediaOptions;

            var loadPhotos = new Action(async() =>
            {
                await LoadFromDirectoryAsync();
            });

            loadPhotos.Invoke();
        }
Exemplo n.º 34
0
        protected override async void OnNavigatedTo(NavigationEventArgs args)
        {
            var signaller = new WebsocketSignaller();

            dispatcher           = CoreWindow.GetForCurrentThread().Dispatcher;
            contSpeechRecognizer = new SpeechRecognizer();
            await contSpeechRecognizer.CompileConstraintsAsync();

            contSpeechRecognizer.HypothesisGenerated += ContSpeechRecognizer_HypothesisGenerated;
            contSpeechRecognizer.ContinuousRecognitionSession.ResultGenerated +=
                ContinuousRecognitionSession_ResultGenerated;


            contSpeechRecognizer.ContinuousRecognitionSession.Completed += ContinuousRecognitionSession_Completed;

            await contSpeechRecognizer.ContinuousRecognitionSession.StartAsync();


            this.ServerConnectButton.Click += async(s, a) =>
            {
                this.StartupSettings.Hide();
                await signaller.ConnectToServer(ServerConfig.AwsAddress);

                this.ConnectedOptions.Show();
            };

            var config = new ConductorConfig()
            {
                CoreDispatcher = this.Dispatcher,
                RemoteVideo    = this.RemoteVideo,
                Signaller      = signaller
            };

            await this.conductor.Initialize(config);

            var opts = new MediaOptions(
                new MediaOptions.Init()
            {
                ReceiveVideo = false
            });

            this.conductor.SetMediaOptions(opts);

            this.conductor.UISignaller.ReceivedShutdown += async(s, a) =>
            {
                await this.conductor.Shutdown();
            };

            this.conductor.UISignaller.ReceivedPlain += (s, message) =>
            {
                Logger.Log(message);
            };
        }
 protected override Tristate Modified(HttpContext context, Sitecore.Resources.Media.Media media, MediaOptions options)
 {
     string str1 = context.Request.Headers["If-None-Match"];
     if (!string.IsNullOrEmpty(str1) && str1 != media.MediaData.MediaId)
         return Tristate.True;
     string str2 = context.Request.Headers["If-Modified-Since"];
     if (!string.IsNullOrEmpty(str2))
     {
         DateTime result;
         if (DateTime.TryParse(str2.Split(';')[0].Replace(" UTC", " GMT"), out result))
             return MainUtil.GetTristate(!this.CompareDatesWithRounding(result, media.MediaData.Updated, new TimeSpan(0, 0, 1)));
         Log.Warn(string.Format("Can't parse header. The wrong value  - \"If-Modified-Since: {0}\" ", (object)str2), (object)typeof(MediaRequestHandler));
     }
     return Tristate.Undefined;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CustomMediaOptions"/> class.
 /// </summary>
 /// <param name="mediaOptions">The media options.</param>
 public CustomMediaOptions(MediaOptions mediaOptions)
 {
     this.AllowStretch = mediaOptions.AllowStretch;
     this.BackgroundColor = mediaOptions.BackgroundColor;
     this.Height = mediaOptions.Height;
     this.IgnoreAspectRatio = mediaOptions.IgnoreAspectRatio;
     this.MaxHeight = mediaOptions.MaxHeight;
     this.MaxWidth = mediaOptions.MaxWidth;
     this.Scale = mediaOptions.Scale;
     this.Thumbnail = mediaOptions.Thumbnail;
     this.UseMediaCache = this.UseMediaCache;
     this.Width = mediaOptions.Width;
     if (mediaOptions.CustomOptions.ContainsKey("cropregion"))
     {
         this.CropRegion = mediaOptions.CustomOptions.FirstOrDefault(p => p.Key == "cropregion").Value;
     }           
 }
Exemplo n.º 37
0
        /// <summary>
        /// Releases the audio player instance to save memory.
        /// </summary>  
        public void release(string options)
        {
            string callbackId = this.CurrentCommandCallbackId;
            try
            {
                MediaOptions mediaOptions = new MediaOptions();

                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize<string[]>(options);
                    mediaOptions.Id = optionsString[0];
                    callbackId = mediaOptions.CallbackId = optionsString[1];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId);
                    return;
                }

                if (!Media.players.ContainsKey(mediaOptions.Id))
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, false), callbackId);
                    return;
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        AudioPlayer audio = Media.players[mediaOptions.Id];
                        Media.players.Remove(mediaOptions.Id);
                        audio.Dispose();
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, true), mediaOptions.CallbackId);
                    }
                    catch (Exception e)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message), mediaOptions.CallbackId);
                    }
                });
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message), callbackId);
            }
        }
Exemplo n.º 38
0
		protected virtual string GetDimensions(MediaOptions options)
		{
			if (options.MaxHeight == 0 && options.MaxWidth == 0 && options.Height == 0 && options.Width == 0) return "original size";
			
			string result = string.Empty;

			if (options.Width > 0) result = options.Width + "w";
			else if (options.MaxWidth > 0) result = options.MaxWidth + "mw";

			if (result.Length > 0 && (options.Height > 0 || options.MaxHeight > 0))
			{
				result += " x ";
			}

			if (options.Height > 0) result += options.Height + "h";
			else if (options.MaxHeight > 0) result += options.MaxHeight + "mh";

			if (options.Thumbnail) result += " (thumb)";

			return result;
		}
Exemplo n.º 39
0
        /// <summary>
        /// Starts recording and save the specified file 
        /// </summary>
        public void startRecordingAudio(string options)
        {
            try
            {
                MediaOptions mediaOptions;

                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize<string[]>(options);
                    mediaOptions = new MediaOptions();
                    mediaOptions.Id = optionsString[0];
                    mediaOptions.Src = optionsString[1];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                    return;
                }

                if (mediaOptions != null)
                {

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        try
                        {
                            AudioPlayer audio;
                            if (!Media.players.ContainsKey(mediaOptions.Id))
                            {
                                audio = new AudioPlayer(this, mediaOptions.Id);
                                Media.players.Add(mediaOptions.Id, audio);
                            }
                            else
                            {
                                audio = Media.players[mediaOptions.Id];
                            }

                            if (audio != null)
                            {
                                audio.startRecording(mediaOptions.Src);
                                DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
                            }
                            else
                            {
                                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error accessing AudioPlayer for key " + mediaOptions.Id));
                            }


                        }
                        catch (Exception e)
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
                        }

                    });
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                }
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
            }
        }
        public void getDurationAudio(string options)
        {
            string callbackId = this.CurrentCommandCallbackId;
            try
            {
                MediaOptions mediaOptions;

                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize<string[]>(options);

                    mediaOptions = new MediaOptions();
                    mediaOptions.Id = optionsString[0];
                    mediaOptions.Src = optionsString[1];
                    callbackId = mediaOptions.CallbackId = optionsString[2];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId);
                    return;
                }

                AudioPlayer audio;
                if (Media.players.ContainsKey(mediaOptions.Id))
                {
                    audio = Media.players[mediaOptions.Id];
                }
                else
                {
                    Debug.WriteLine("ERROR: getDurationAudio could not find mediaPlayer for " + mediaOptions.Id);
                    audio = new AudioPlayer(this, mediaOptions.Id);
                    Media.players.Add(mediaOptions.Id, audio);
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, audio.getDuration(mediaOptions.Src)), callbackId);
                });
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message), callbackId);
            }
        }
        /// <summary>
        /// Seeks to a location
        /// </summary>
        public void seekToAudio(string options)
        {
            string callbackId = this.CurrentCommandCallbackId;
            try
            {
                MediaOptions mediaOptions;

                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize<string[]>(options);
                    mediaOptions = new MediaOptions();
                    mediaOptions.Id = optionsString[0];
                    int msec = 0;
                    if (int.TryParse(optionsString[2], out msec))
                    {
                        mediaOptions.Milliseconds = msec;
                    }
                    callbackId = mediaOptions.CallbackId = optionsString[3];

                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId);
                    return;
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        if (Media.players.ContainsKey(mediaOptions.Id))
                        {
                            AudioPlayer audio = Media.players[mediaOptions.Id];
                            audio.seekToPlaying(mediaOptions.Milliseconds);
                        }
                        else
                        {
                            Debug.WriteLine("ERROR: seekToAudio could not find mediaPlayer for " + mediaOptions.Id);
                        }

                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
                    }
                    catch (Exception e)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message), callbackId);
                    }
                });
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message), callbackId);
            }
        }
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        public void startPlayingAudio(string options)
        {
            string callbackId = this.CurrentCommandCallbackId;
            try
            {
                MediaOptions mediaOptions;
                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize<string[]>(options);
                    mediaOptions = new MediaOptions();
                    mediaOptions.Id = optionsString[0];
                    mediaOptions.Src = optionsString[1];
                    int msec = 0;
                    if (int.TryParse(optionsString[2], out msec))
                    {
                        mediaOptions.Milliseconds = msec;
                    }
                    callbackId = mediaOptions.CallbackId = optionsString[3];

                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId);
                    return;
                }

                AudioPlayer audio = GetOrCreatePlayerById(mediaOptions.Id);

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        audio.startPlaying(mediaOptions.Src);
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
                    }
                    catch (Exception e)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message), callbackId);
                    }
                });
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message), callbackId);
            }
        }
Exemplo n.º 43
0
        async void myMenuItemAttachmentFromFile_Click(object sender, EventArgs eventArg)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            DialogResult dr = ofd.ShowDialog();

            if (dr == DialogResult.OK)
            {
                string filename = ofd.FileName;
                // 
                // todo: present the dialog for Slug name and Content type
                // 
                Program.GetMain().SetLoadingState();

                try
                {

                    using (FileStream stream = new FileStream(filename,
                        FileMode.Open, FileAccess.Read))
                    {
                        MediaOptions options = new MediaOptions()
                        {
                            ContentType = "application/octet-stream",
                            Slug = Path.GetFileName(ofd.FileName)
                        };

                        ResourceResponse<Documents.Attachment> rr;
                        using (PerfStatus.Start("CreateAttachment"))
                        {
                             rr = await this.client.CreateAttachmentAsync((this.Tag as Documents.Document).GetLink(this.client) + "/attachments",
                                       stream, options);
                        }
                        string json = rr.Resource.ToString();

                        Program.GetMain().SetResultInBrowser(json, null, false, rr.ResponseHeaders);

                        this.Nodes.Add(new DocumentNode(this.client, rr.Resource, ResourceType.Attachment));
                    }
                }
                catch (Exception e)
                {
                    Program.GetMain().SetResultInBrowser(null, e.ToString(), true);
                }
            }
        }
Exemplo n.º 44
0
        /// <summary>
        /// Starts or resume playing audio file 
        /// </summary>
        public void startPlayingAudio(string options)
        {
            try
            {
                MediaOptions mediaOptions;
                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize<string[]>(options);
                    mediaOptions = new MediaOptions();
                    mediaOptions.Id = optionsString[0];
                    mediaOptions.Src = optionsString[1];
                    if (optionsString.Length > 2 && optionsString[2] != null)
                    {
                        mediaOptions.Milliseconds = int.Parse(optionsString[2]);
                    }

                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                    return;
                }

                AudioPlayer audio;

                if (!Media.players.ContainsKey(mediaOptions.Id))
                {
                    audio = new AudioPlayer(this, mediaOptions.Id);
                    Media.players.Add(mediaOptions.Id, audio);
                }
                else
                {
                    //Debug.WriteLine("INFO: startPlayingAudio FOUND mediaPlayer for " + mediaOptions.Id);
                    audio = Media.players[mediaOptions.Id];
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        audio.startPlaying(mediaOptions.Src);
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
                    }
                    catch (Exception e)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
                    }
                });
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
            }
        }
Exemplo n.º 45
0
        /// <summary>
        /// Seeks to a location
        /// </summary>
        public void seekToAudio(string options)
        {
            try
            {
                MediaOptions mediaOptions;

                try
                {
                    string[] optionsString = JSON.JsonHelper.Deserialize<string[]>(options);
                    mediaOptions = new MediaOptions();
                    mediaOptions.Id = optionsString[0];
                    if (optionsString.Length > 1 && optionsString[1] != null)
                    {
                        mediaOptions.Milliseconds = int.Parse(optionsString[1]);
                    }
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                    return;
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        if (Media.players.ContainsKey(mediaOptions.Id))
                        {
                            AudioPlayer audio = Media.players[mediaOptions.Id];
                            audio.seekToPlaying(mediaOptions.Milliseconds);
                        }
                        else
                        {
                            Debug.WriteLine("ERROR: seekToAudio could not find mediaPlayer for " + mediaOptions.Id);
                        }

                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
                    }
                    catch (Exception e)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
                    }
                });
            }
            catch (Exception e)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
            }
        }
Exemplo n.º 46
0
        async void myMenuItemAttachmentFromFile_Click(object sender, EventArgs eventArg)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            DialogResult dr = ofd.ShowDialog();

            if (dr == DialogResult.OK)
            {
                string filename = ofd.FileName;
                // 
                // todo: present the dialog for Slug name and Content type
                // 
                Program.GetMain().SetLoadingState();

                try
                {

                    using (FileStream stream = new FileStream(filename,
                        FileMode.Open, FileAccess.Read))
                    {
                        MediaOptions mediaOptions = new MediaOptions()
                        {
                            ContentType = "application/octet-stream",
                            Slug = Path.GetFileName(ofd.FileName)
                        };

                        ResourceResponse<Attachment> rr;
                        
                        Document document = ((Document)this.Tag);
                        DocumentCollection collection = ((DocumentCollection)this.Parent.Tag);

                        RequestOptions requestOptions = Program.GetMain().GetRequestOptions();
                        if (collection.PartitionKey != null && collection.PartitionKey.Paths.Count > 0)
                        {
                            requestOptions.PartitionKey = new PartitionKey(DocumentAnalyzer.ExtractPartitionKeyValue(document, collection.PartitionKey));
                        }

                        using (PerfStatus.Start("CreateAttachment"))
                        {
                            rr = await this.client.CreateAttachmentAsync((this.Tag as Document).SelfLink + "/attachments",
                                      stream, mediaOptions, requestOptions);
                        }

                        string json = rr.Resource.ToString();

                        Program.GetMain().SetResultInBrowser(json, null, false, rr.ResponseHeaders);

                        this.Nodes.Add(new ResourceNode(this.client, rr.Resource, ResourceType.Attachment));
                    }
                }
                catch (Exception e)
                {
                    Program.GetMain().SetResultInBrowser(null, e.ToString(), true);
                }
            }
        }