Example #1
0
        public void Play(string filename)
        {
            if (InvokeRequired)
                Invoke(new PlayDelegate(Play), filename);
            else
            {
                _needsSize = _filename != filename;
                _filename = filename;
                _mMedia = _mFactory.CreateMedia<IMedia>(filename);
                _mMedia.Events.DurationChanged += EventsDurationChanged;
                _mMedia.Events.StateChanged += EventsStateChanged;
                _mMedia.Events.ParsedChanged += Events_ParsedChanged;
                _mPlayer.Open(_mMedia);
                _mMedia.Parse(true);

                _mPlayer.Play();

                string[] parts = filename.Split('\\');
                string fn = parts[parts.Length - 1];
                FilesFile ff =
                    ((MainForm) Owner).GetCameraWindow(ObjectID).FileList.FirstOrDefault(p => p.Filename.EndsWith(fn));
                if (ff!=null)
                    vNav.Render(ff);
            }
        }
Example #2
0
        public ImportInfo(IMedia media, IEntity entity)
        {
            if (media == null)
                throw new ArgumentNullException("media");

            this.media = media;
            this.entity = entity;
        }
 public void UploadToAzure(IMedia mediaItem)
 {
     if(!IsValidMediaItem(mediaItem))
         return;
     
     var files = GetMediaFilePaths(mediaItem);
     files.ForEach(UploadToAzure);
 }
Example #4
0
 public IMedia CloneWithoutMediaInfo(IMedia source)
 {
     return new Media
     {
         Name = source.Name,
         Data = source.Data
     };
 }
Example #5
0
        public void Organise(IMedia media, DirectoryInfoBase outputDirectory, OrganiserConversionOptions conversionOption, bool strictSeason)
        {
            // Create working directory.
            WorkingDirectory = _fileSystem.DirectoryInfo.FromDirectoryName(_fileSystem.Path.Combine(_fileSystem.Path.GetTempPath(), "WorkingArea"));

            // Create working directory if it does not exist.
            if(!WorkingDirectory.Exists)
            {
                WorkingDirectory.Create();
            }

            // Copy to working area.
            CopyMediaToWorkingArea(media);

            // Convert if required.
            if(conversionOption == OrganiserConversionOptions.Force)
            {
                Logger.Log("Organiser").StdOut.WriteLine("Conversion set to \"force\". Will convert. {0}", media.MediaFile.FullName);
                ConvertMedia(media);
            }
            else if(media.RequiresConversion)
            {
                if(conversionOption == OrganiserConversionOptions.Skip)
                {
                    Logger.Log("Organiser").StdOut.WriteLine("Media requires conversion. Conversion set to \"skip\", skipping conversion. {0}", media.MediaFile.FullName);
                }
                else
                {
                    Logger.Log("Organiser").StdOut.WriteLine("Media requires conversion. Will convert. {0}", media.MediaFile.FullName);
                    ConvertMedia(media);
                }
            }

            // Extract media details exhaustivly.
            ExtractExhaustiveMediaDetails(media, strictSeason);

            // Save media meta data.
            var saveResponse = SaveMediaMetaData(media);
            if(!saveResponse)
            {
                if(conversionOption == OrganiserConversionOptions.Skip)
                {
                    Logger.Log("Organiser").StdOut.WriteLine("Unable to save metadata. Conversion set to \"skip\", skipping conversion. {0}", media.MediaFile.FullName);
                }
                else
                {
                    Logger.Log("Organiser").StdOut.WriteLine("Unable to save metadata. Will convert. {0}", media.MediaFile.FullName);
                    ConvertMedia(media);
                    SaveMediaMetaData(media);
                }
            }

            // Rename media.
            RenameMediaToCleanFileName(media);

            // If output directory not provided, delete file. Otherwise move to output directory.
            MoveMediaToOutputDirectory(media, outputDirectory);
        }
Example #6
0
 public override ElectricStatus BreakDownTest(IMedia media, ElectricStatus elecStatus, WireStatus status, double voltage, out double current)
 {
     if (media.GetId() == _id)
     {
         switch (elecStatus)
         {
             case ElectricStatus.Resistence:
                 current = Defines.Clamp(voltage, 1e4);
                 return elecStatus;
             default:
                 break;
         }
     }
     else if (media.GetId() == MediaId.M_AIR)
     {
         voltage *= 0.01;
         switch (elecStatus)
         {
             case ElectricStatus.Resistence:
                 current = Defines.Clamp(voltage, 0.01);
                 if (Math.Abs(voltage) > 200)
                 {
                     return ElectricStatus.Ionization;
                 }
                 else
                 {
                     return elecStatus;
                 }
             case ElectricStatus.Ionization:
                 if (Math.Abs(voltage) > 500)
                 {
                     current = Defines.Clamp(voltage, 1e6);
                     return ElectricStatus.Conduction;
                 }
                 if (Math.Abs(voltage) > 200)
                 {
                     current = Defines.Clamp(voltage, 1e4);
                     return ElectricStatus.Ionization;
                 }
                 break;
             case ElectricStatus.Conduction:
                 if (Math.Abs(voltage) > 60)
                 {
                     current = Defines.Clamp(voltage, 1e6);
                     return ElectricStatus.Conduction;
                 }
                 else
                 {
                     current = Defines.Clamp(voltage, 1e6);
                     return ElectricStatus.Ionization;
                 }
             default:
                 break;
         }
     }
     return base.BreakDownTest(media, elecStatus, status, voltage, out current);
 }
        //Creates directories
        public virtual void Prepare(IMedia stream)
        {
            if (!System.IO.Directory.Exists(BaseDirectory + '/' + stream.Id))
            {
                System.IO.Directory.CreateDirectory(BaseDirectory + '/' + stream.Id);
            }

            //Create Toc file?
        }
Example #8
0
        public static bool SaveMediaFile(string path, IMedia media, XElement element)
        {
            LogHelper.Debug<FileHelper>("SaveMedia File {0} {1}", () => path, () => media.Name);

            string filename = string.Format("{0}.media", CleanFileName(media.Name));
            string fullpath = Path.Combine(string.Format("{0}{1}", _mappedMediaRoot, path), filename);

            return SaveContentBaseFile(fullpath, element); 

        }
        public void SetInfo(IMedia media)
        {
            int value;

            media.Path = _path;
            media.Filename = _mediaInfo.Get(0, 0, "FileName");
            media.Title = media.Filename;
            media.FileSize = (Int32.TryParse(_mediaInfo.Get(0, 0, "FileSize"), out value)) ? value : 0;
            media.Extension = _mediaInfo.Get(0, 0, "FileExtension");
        }
Example #10
0
        /// <summary>
        ///     Affichage du détail d'un média
        /// </summary>
        /// <param name="media"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        protected string afficheDetails(IMedia media, IFormatProvider format)
        {
            AbstractMediaDetailDisplay mycontrol = null;
            TextWriter txt = new StringWriter();
            HtmlTextWriter html = new HtmlTextWriter(txt);

            mycontrol = LoadControl(string.Format("~/Controls/Display/{0}WUC.ascx", media.GetType().Name)) as AbstractMediaDetailDisplay;
            mycontrol.afficheMedia(media);

            mycontrol.RenderControl(html);
            return txt.ToString();
        }
Example #11
0
        public void Export(string path, IMedia item, IMediaService _mediaService)
        {
            LogHelper.Info<MediaExporter>("Exporting {0}", () => FileHelper.CleanFileName(item.Name));
            SaveMedia(item, path);

            path = String.Format("{0}\\{1}", path, FileHelper.CleanFileName(item.Name));
            foreach (var childItem in _mediaService.GetChildren(item.Id))
            {
                Export(path, childItem, _mediaService);
            }


        }
Example #12
0
        bool CheckForRefresh(IMedia sender, CancellableEventArgs e)
        {
            // As of Umbraco 6.2.4 if you try to access e.Cancel for an event that isn't cancellable you'll get an exception
            if (sender.Name.Equals(PPC_2010.Data.Constants.RefreshIndicatorTitle, StringComparison.CurrentCultureIgnoreCase))
            {
                ServiceLocator.Instance.Locate<ISermonRepository>().RefreshSermons();
                if (e.CanCancel)
                    e.Cancel = true;
                return true;
            }

            return false;
        }
Example #13
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == true)
            {
                textBlock1.Text = ofd.FileName;
                m_media = m_factory.CreateMedia<IMediaFromFile>(ofd.FileName);
                m_media.Events.DurationChanged += new EventHandler<MediaDurationChange>(Events_DurationChanged);
                m_media.Events.StateChanged += new EventHandler<MediaStateChange>(Events_StateChanged);

                m_player.Open(m_media);
                m_media.Parse(true);
            }
        }
        //Stop recoding a stream
        public virtual void Stop(IMedia stream)
        {
            if (stream is RtpSource)
            {
                RtpTools.RtpDump.Program program;
                if (!Attached.TryGetValue(stream, out program)) return;

                program.Dispose();
                Attached.Remove(stream);

                (stream as RtpSource).RtpClient.RtpPacketReceieved -= RtpClientPacketReceieved;
                (stream as RtpSource).RtpClient.RtcpPacketReceieved -= RtpClientPacketReceieved;
            }
        }
        private IMultipartElement GenerateMultipartElement(IMedia media, string contentId, IMultipartRequestConfiguration configuration)
        {
            var additionalParameters = new Dictionary<string, string>();

            var element = new MultipartElement
            {
                Boundary = configuration.Boundary,
                ContentId = contentId,
                ContentDispositionType = "form-data",
                ContentType = "application/octet-stream",
                AdditionalParameters = additionalParameters,
                Data = configuration.EncodingAlgorithm.GetString(media.Data, 0, media.Data.Length),
            };

            return element;
        }
        private static void AfterMap(IMedia media, MediaItemDisplay display)
        {
            //map the tree node url
            if (HttpContext.Current != null)
            {
                var urlHelper = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));
                var url = urlHelper.GetUmbracoApiService<MediaTreeController>(controller => controller.GetTreeNode(display.Id.ToString(), null));
                display.TreeNodeUrl = url;
            }
            
            if (media.ContentType.IsContainer)
            {
                TabsAndPropertiesResolver.AddContainerView(display, "media");
            }

            TabsAndPropertiesResolver.MapGenericProperties(media, display);
        }
Example #17
0
        public void SaveMedia(IMedia media, string path)
        {
            XElement itemXml = ExportMedia(media);

            if (itemXml != null)
            {
                if (FileHelper.SaveMediaFile(path, media, itemXml))
                {
                    _count++;
                    SourceInfo.Add(media.Key, media.Name, media.ParentId);
                }
            }
            else
            {
                LogHelper.Info<MediaExporter>("Media xml came back as null");
            }
        }
        private string GetParentPath(IMediaService sender, IMedia mediaItem)
        {
            string result = string.Empty;
            IMedia current = mediaItem;
            IMedia parent = null;
            do
            {
                parent = sender.GetParent(current);
                if (parent != null)
                    result = "\\" + parent.Name + result;

                current = parent;

            } while (parent != null);

            return result.TrimStart('\\');
        }
        public virtual void Start(IMedia stream, RtpTools.FileFormat format = RtpTools.FileFormat.Binary)
        {
            if (stream is RtpSource)
            {
                RtpTools.RtpDump.Program program;
                if (Attached.TryGetValue(stream, out program)) return;

                Prepare(stream);

                program = new RtpTools.RtpDump.Program(); //.DumpWriter(BaseDirectory + '/' + stream.Id + '/' + DateTime.UtcNow.ToFileTime(), format, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0));

                Attached.Add(stream, program);

                (stream as RtpSource).RtpClient.RtpPacketReceieved += RtpClientPacketReceieved;
                (stream as RtpSource).RtpClient.RtcpPacketReceieved += RtpClientPacketReceieved;

            }
        }
Example #20
0
        /// <summary>
        /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
        /// that this Media should based on.
        /// </summary>
        /// <remarks>
        /// Note that using this method will simply return a new IMedia without any identity
        /// as it has not yet been persisted. It is intended as a shortcut to creating new media objects
        /// that does not invoke a save operation against the database.
        /// </remarks>
        /// <param name="name">Name of the Media object</param>
        /// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param>
        /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
        /// <param name="userId">Optional id of the user creating the media item</param>
        /// <returns><see cref="IMedia"/></returns>
        public IMedia CreateMedia(string name, IMedia parent, string mediaTypeAlias, int userId = 0)
        {
            var mediaType = FindMediaTypeByAlias(mediaTypeAlias);
            var media = new Models.Media(name, parent, mediaType);
            if (Creating.IsRaisedEventCancelled(new NewEventArgs<IMedia>(media, mediaTypeAlias, parent), this))
            {
                media.WasCancelled = true;
                return media;
            }

            media.CreatorId = userId;

            Created.RaiseEvent(new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parent), this);

            Audit.Add(AuditTypes.New, "", media.CreatorId, media.Id);

            return media;
        }
Example #21
0
        private void button3_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                m_media = m_factory.CreateMedia<IMedia>(textBox1.Text);
                m_media.Events.DurationChanged += new EventHandler<MediaDurationChange>(Events_DurationChanged);
                m_media.Events.StateChanged += new EventHandler<MediaStateChange>(Events_StateChanged);
                m_media.Events.ParsedChanged += new EventHandler<MediaParseChange>(Events_ParsedChanged);

                m_player.Open(m_media);
                m_media.Parse(true);

                m_player.Play();
            }
            else
            {
                errorProvider1.SetError(textBox1, "Please select media path first !");
            }
        }
        private IEntity GetEntity(IMedia media)
        {
            var name = media.Path.RemoveExtension();
            try
            {
                var url = new Uri(media.Path);
                if (url.IsFile)
                {
                    var fileInfo = new FileInfo(new Uri(media.Path).LocalPath);
                    name = fileInfo.Name.RemoveExtension();
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error getting entity name for path: " + media.Path, ex);
            }

            switch (media.Type.Supertype)
            {
                case MediaSupertype.Application:
                case MediaSupertype.Message:
                case MediaSupertype.Model:
                case MediaSupertype.Multipart:
                    return new Work(WorkType.Document, null, null, name, 0, 0);
                case MediaSupertype.Audio:
                    return new Work(WorkType.Track, null, null, name, 0, 0);
                case MediaSupertype.Image:
                    return new Work(WorkType.Image, null, null, name, 0, 0);
                case MediaSupertype.Text:
                    return new Work(WorkType.Text, null, null, name, 0, 0);
                case MediaSupertype.Video:
                    return new Work(WorkType.Video, null, null, name, 0, 0);
                default:
                    return null;
            }
        }
Example #23
0
 public void Insert(int index, IMedia item)
 {
     using (new MediaListLock(m_hMediaList))
      {
     LibVlcMethods.libvlc_media_list_insert_media(m_hMediaList, ((INativePointer)item).Pointer, index);
      }
 }
Example #24
0
 public void Add(IMedia item)
 {
     using (new MediaListLock(m_hMediaList))
      {
     LibVlcMethods.libvlc_media_list_add_media(m_hMediaList, ((INativePointer)item).Pointer);
      }
 }
Example #25
0
 public void CopyTo(IMedia[] array, int arrayIndex)
 {
     throw new NotImplementedException();
 }
Example #26
0
 // Umbraco.Code.MapAll
 private static void Map(IMedia source, ContentPropertyCollectionDto target, MapperContext context)
 {
     target.Properties = context.MapEnumerable <Property, ContentPropertyDto>(source.Properties);
 }
Example #27
0
 public int GetHashCode(IMedia obj)
 {
     return(((INativePointer)obj).Pointer.GetHashCode());
 }
Example #28
0
 public abstract Task <IMedia> PrepareMediaAsync(IMedia media, CancellationToken cancellationToken = default);
Example #29
0
        public static void Run()
        {
            DataTable GetData() => UsDataProcessor.GetData();

            var data = GetData();
            var coll = CvCollection.Create(data);


            Console.Title = "Getting data";


            System.Console.Title = $"[{DateTime.Now}] Sleeping 30 seconds";
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                System.Threading.Thread.Sleep(30000);
            }
            bool     pubbedAggr     = false;
            int      lastCTotal     = 0;
            int      lastDTotal     = 0;
            int      lastCtRowCount = 0;
            DateTime lastUpdated    = DateTime.Now;


            int      sleepMinutes       = Properties.Settings.Default.CheckTimeoutMinutes;
            DateTime lastTableDate      = DateTime.Now.AddMinutes(-sleepMinutes);
            int      sleep              = sleepMinutes * 60 * 1000;
            int      globalChartTimeout = Properties.Settings.Default.GlobalChartTimeout;

            while (true)
            {
restart:
                var start            = DateTime.Now;
                System.Console.Title = $"[{DateTime.Now}] Refreshing data";
                data = GetData();
                var temp = data.Clone();

                if (data.Rows.Count == 0)
                {
                    System.Console.Title = $"[{DateTime.Now}] Failed to retrieve data";
                    System.Threading.Thread.Sleep(sleep);
                    continue;
                }
                var newColl = CvCollection.Create(data);
                var dCount  = newColl.Stats.Sum(x => x.TotalDCount);
                var cCount  = newColl.Stats.Sum(x => x.TotalCount);
                Console.Title = $"[{DateTime.Now.ToLongTimeString()}] {cCount} - {dCount} [{lastUpdated.ToLongTimeString()}] ";
                var dRotwCount = newColl.Stats.Where(x => x.Loc != "China").Sum(x => x.TotalDCount);
                var cRotwCount = newColl.Stats.Where(x => x.Loc != "China").Sum(x => x.TotalCount);

                var newRotwCCount = newColl.Stats.Where(x => x.Loc != "China").Sum(x => x.DailyCount);
                var newRotwDCount = newColl.Stats.Where(x => x.Loc != "China").Sum(x => x.DailyDCount);

                var newCCount = newColl.Stats.Sum(x => x.DailyCount);
                var newDCount = newColl.Stats.Sum(x => x.DailyDCount);


                var changes = newColl.GetChanges(coll);
                if (changes.Count > 0)
                {
                    if (HasBadData(changes))
                    {
                        System.Threading.Thread.Sleep(30000);
                        goto restart;
                    }
                }

                int topLimit   = Properties.Settings.Default.TopLimit;
                var top        = newColl.Stats.OrderByDescending(x => x.TotalCount).Take(topLimit).Select(x => x.Loc);
                var topChanges = changes.Where(x => top.Contains(x.New.Loc));
                foreach (var change in topChanges)
                {
                    var changeText = change.ToString().Replace(", with reported today.", ".");;
                    if (changeText.Contains("for the first time"))
                    {
                        string bp = "";
                    }
                    var Processor = new TemplateProcessor(changeText);
                    var tagged    = Processor.GetProcessedText();
                    Console.WriteLine($"[{ DateTime.Now}] {tagged} ");
                    //var tParams = new Tweetinvi.Parameters.PublishTweetOptionalParameters()
                    //{
                    //    Medias = new List<IMedia>() { UpdateMedia }
                    //};
                    Tweet.PublishTweet(tagged);
                    System.Threading.Thread.Sleep(10000);
                    lastUpdated = DateTime.Now;
                }
                coll = newColl;
                if (!pubbedAggr || DateTime.Now.Subtract(lastTableDate).TotalMinutes >= globalChartTimeout && changes.Count > 0)
                {
                    if (bool.Parse(bool.FalseString))
                    {
                        data = GetData();
                    }

                    lastTableDate = DateTime.Now;
                    var formatted = $"US #CoronaVirus: To date a total of {dCount.ToString("N0")} total deaths and {cCount.ToString("N0")} total #covid19 cases have been confirmed in the United States.";
                    //if()
                    if (changes.Any(x => x.New.Loc == "China") && cRotwCount != lastCtRowCount)
                    {
                        formatted = $"#CoronaVirus Outside of China - {cRotwCount.ToString("N0")} cases and {dRotwCount.ToString("N0")} deaths.\n\nTo date a total of {dCount.ToString("N0")} deaths and {cCount.ToString("N0")} total #covid19 cases have been confirmed worldwide.\n\n#CoronaVirusOutbreak";
                    }

                    var Processor = new TemplateProcessor(formatted);
                    formatted = Processor.GetProcessedText();

                    data.Columns[0].ColumnName = $"Locations ({data.Rows.Count})";
                    Console.WriteLine($"[{ DateTime.Now}] {formatted} ");


                    var totalGlobalRow = data.NewRow();
                    totalGlobalRow[0] = "Total";

                    totalGlobalRow[1] = cCount;
                    totalGlobalRow[2] = newCCount;
                    totalGlobalRow[3] = dCount;
                    totalGlobalRow[4] = newDCount;
                    data.Rows.Add(totalGlobalRow);

                    var rows = data.Rows.Cast <DataRow>().ToList();



                    //data.AcceptChanges();
                    var    doc          = AsposeHelper.GetDataTableDocument(data);
                    var    fileNamePng  = $"covus-table-{DateTime.Now.ToFileTimeUtc()}.png";
                    var    fileNameDocx = $"covus-table-{DateTime.Now.ToFileTimeUtc()}.docx";
                    IMedia media        = null;
                    using (var ms = new System.IO.MemoryStream())
                    {
                        doc.Save(ms, Aspose.Words.SaveFormat.Png);
                        doc.Save(fileNamePng, Aspose.Words.SaveFormat.Png);
                        //doc.Save(fileNameDocx, Aspose.Words.SaveFormat.Docx);
                        media = Upload.UploadBinary(ms.ToArray());
                    }
                    var tParams = new Tweetinvi.Parameters.PublishTweetOptionalParameters()
                    {
                        Medias = new List <IMedia>()
                        {
                            media
                        }
                    };

                    Tweet.PublishTweet(formatted, tParams);
                    System.Threading.Thread.Sleep(10000);
                    pubbedAggr = true;
                }
                int diff = (int)DateTime.Now.Subtract(start).TotalMilliseconds;

                if (diff < sleep)
                {
                    var sleepTimeOut = sleep - diff;
                    System.Threading.Thread.Sleep(sleepTimeOut);
                }
                lastCTotal     = cCount;
                lastDTotal     = dCount;
                lastCtRowCount = cRotwCount;
            }
        }
Example #30
0
 /// <summary>
 /// Wait for Twitter to process the uploaded binary and returns a new media object containing all the available metadata.
 /// </summary>
 public static IMedia WaitForMediaProcessingToGetAllMetadata(IMedia media)
 {
     return(_uploadHelper.WaitForMediaProcessingToGetAllMetadata(media));
 }
 public MediaOnLayerEventArgs(IMedia media, VideoLayer layer)
 {
     Media = media;
     Layer = layer;
 }
Example #32
0
 /// <summary>
 /// Moves an IMedia object to a new location
 /// </summary>
 /// <param name="media">media to move</param>
 /// <param name="parentId">id of a new location</param>
 public void Move(IMedia media, int parentId)
 {
     _mediaService.Move(media, parentId);
 }
Example #33
0
 /// <summary>
 /// Get the status of the media. NOTE that this is only available if the `tweet_video` media category
 /// has been set. And the endpoint is available only after the
 /// UploadedMediaInfo.ProcessingInfo.CheckAfterInSeconds Timespan has completed.
 /// </summary>
 public static IUploadedMediaInfo GetMediaStatus(IMedia media, bool waitForStatusToBeAvailable = true)
 {
     return(UploadQueryExecutor.GetMediaStatus(media, waitForStatusToBeAvailable));
 }
Example #34
0
        private void WorkerThread()
        {
            bool file = false;

            try
            {
                if (File.Exists(_source))
                {
                    file = true;
                }
            }
            catch
            {
                // ignored
            }

            if (_mFactory == null)
            {
                var args = new List <string>
                {
                    "-I",
                    "dumy",
                    "--ignore-config",
                    "--no-osd",
                    "--disable-screensaver",
                    "--plugin-path=./plugins"
                };
                if (file)
                {
                    args.Add("--file-caching=3000");
                }
                try
                {
                    var l2 = args.ToList();
                    l2.AddRange(_arguments);

                    l2        = l2.Distinct().ToList();
                    _mFactory = new MediaPlayerFactory(l2.ToArray());
                }
                catch (Exception ex)
                {
                    MainForm.LogExceptionToFile(ex, "VLC Stream");
                    MainForm.LogMessageToFile("VLC arguments are: " + string.Join(",", args.ToArray()), "VLC Stream");
                    MainForm.LogMessageToFile("Using default VLC configuration.", "VLC Stream");
                    _mFactory = new MediaPlayerFactory(args.ToArray());
                }
                GC.KeepAlive(_mFactory);
            }

            _mMedia = file ? _mFactory.CreateMedia <IMediaFromFile>(_source) : _mFactory.CreateMedia <IMedia>(_source);

            _mMedia.Events.DurationChanged += EventsDurationChanged;
            _mMedia.Events.StateChanged    += EventsStateChanged;

            if (_mPlayer != null)
            {
                try
                {
                    _mPlayer?.Dispose();
                }
                catch
                {
                    // ignored
                }
                _mPlayer = null;
            }


            _mPlayer = _mFactory.CreatePlayer <IVideoPlayer>();
            _mPlayer.Events.TimeChanged += EventsTimeChanged;

            var fc = new Func <SoundFormat, SoundFormat>(SoundFormatCallback);

            _mPlayer.CustomAudioRenderer.SetFormatCallback(fc);
            var ac = new AudioCallbacks {
                SoundCallback = SoundCallback
            };

            _mPlayer.CustomAudioRenderer.SetCallbacks(ac);
            _mPlayer.CustomAudioRenderer.SetExceptionHandler(Handler);


            _mPlayer.CustomRenderer.SetCallback(FrameCallback);
            _mPlayer.CustomRenderer.SetExceptionHandler(Handler);
            GC.KeepAlive(_mPlayer);

            _needsSetup = true;
            _stopping   = false;
            _mPlayer.CustomRenderer.SetFormat(new BitmapFormat(FormatWidth, FormatHeight, ChromaType.RV24));
            _mPlayer.Open(_mMedia);
            _mMedia.Parse(true);

            _mPlayer.Delay = 0;

            _framesReceived = 0;
            Duration        = Time = 0;
            LastFrame       = DateTime.MinValue;


            //check if file source (isseekable in _mPlayer is not reliable)
            Seekable = false;
            try
            {
                var p = Path.GetFullPath(_mMedia.Input);
                Seekable = !string.IsNullOrEmpty(p);
            }
            catch (Exception)
            {
                Seekable = false;
            }
            _mPlayer.WindowHandle = IntPtr.Zero;

            _videoQueue = new ConcurrentQueue <Bitmap>();
            _audioQueue = new ConcurrentQueue <byte[]>();
            _eventing   = new Thread(EventManager)
            {
                Name = "vlc eventing", IsBackground = true
            };
            _eventing.Start();

            _mPlayer.Play();

            _stopEvent.WaitOne();

            if (_eventing != null && !_eventing.Join(0))
            {
                _eventing.Join();
            }

            if (!Seekable && !_stopRequested)
            {
                PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.DeviceLost));
                AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.DeviceLost));
            }
            else
            {
                PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser));
                AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser));
            }

            DisposePlayer();

            _stopEvent?.Close();
            _stopEvent = null;
        }
Example #35
0
 public override void RemoveMedia(IMedia media)
 {
 }
        /// <summary>
        /// Copies the contents of one media folder to another.
        /// </summary>
        /// <param name="media1Parent">The source folder.</param>
        /// <param name="media2Parent">The destination folder.</param>
        private void CopyMedia(IMedia media1Parent, IMedia media2Parent)
        {
            try
            {
                var copyFiles = _config.ReadBooleanSetting("copyMediaFiles");

                if (uMediaSyncHelper.mediaService.HasChildren(media1Parent.Id))
                {
                    foreach (IMedia item in uMediaSyncHelper.mediaService.GetChildren(media1Parent.Id))
                    {
                        IMedia mediaItem = null;
                        if (copyFiles)
                        {
                            mediaItem = uMediaSyncHelper.mediaService.CreateMedia(item.Name, media2Parent, item.ContentType.Alias, uMediaSyncHelper.userId);

                            if (item.HasProperty("umbracoFile") && !String.IsNullOrEmpty(item.GetValue("umbracoFile").ToString()))
                            {
                                string mediaFile = item.GetValue("umbracoFile").ToString();

                                // If the content is an image and doesnt start with /media, deserialize the json string to get the actual src path
                                if (item.ContentType.Alias == "Image" && !mediaFile.ToUpperInvariant().StartsWith("/MEDIA"))
                                {
                                    Image tempImage = JsonConvert.DeserializeObject <Image>(mediaFile);
                                    mediaFile = tempImage.src;
                                }

                                string newFile = HttpContext.Current.Server.MapPath(mediaFile);

                                if (File.Exists(newFile))
                                {
                                    string fName = mediaFile.Substring(mediaFile.LastIndexOf('/') + 1);

                                    FileStream fs = File.OpenRead(HttpContext.Current.Server.MapPath(mediaFile));

                                    // Check the file's extension just in case it is actually an image
                                    // If it is an image, reset the mediaItem with its content type set to "Image"
                                    if (item.ContentType.Alias == "File" && fName.EndsWith(".png") || fName.EndsWith(".jpg") || fName.EndsWith(".gif") || fName.EndsWith(".jpeg"))
                                    {
                                        mediaItem = uMediaSyncHelper.mediaService.CreateMedia(item.Name, media2Parent, "Image", uMediaSyncHelper.userId);
                                    }

                                    mediaItem.SetValue("umbracoFile", fName, fs);
                                }
                            }
                        }
                        else if (item.ContentType.Alias.ToUpperInvariant() == "FOLDER")
                        {
                            mediaItem = uMediaSyncHelper.mediaService.CreateMedia(item.Name, media2Parent, item.ContentType.Alias, uMediaSyncHelper.userId);
                        }

                        if (mediaItem != null)
                        {
                            // Hold the item name before saving the media
                            var originalName = item.Name;
                            uMediaSyncHelper.mediaService.Save(mediaItem, uMediaSyncHelper.userId);

                            // if after saving the names have changed, then the media already existed, so delete the duplicate
                            if (originalName != mediaItem.Name)
                            {
                                uMediaSyncHelper.mediaService.Delete(mediaItem);
                            }
                            // else continue as normal
                            else if (uMediaSyncHelper.mediaService.GetChildren(item.Id).Count() != 0)
                            {
                                CopyMedia(item, mediaItem);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToExceptionless().Submit();
                throw; // throw to the generic handler that writes to the Umbraco log
            }
        }
Example #37
0
        private static bool MediaIsValid(IMedia media)
        {
            if (media == null)
                return false;

            if (media.Type.Name == mediaFactory.DefaultType.Name)
                return false;

            return true;
        }
Example #38
0
        /// <summary>
        /// Creates a new media object.
        /// </summary>
        /// <param name="caller">The calling object.</param>
        /// <param name="rpu">A delegate of the type StatusMessageReportProgress.</param>
        /// <param name="type">The type.</param>
        /// <param name="path">The path.</param>
        /// <param name="isActive">if set to <c>true</c> [is active].</param>
        /// <param name="isDefault">if set to <c>true</c> [is default].</param>
        /// <param name="isExample">if set to <c>true</c> [is example].</param>
        /// <returns></returns>
        /// <remarks>Documented by Dev02, 2008-08-11</remarks>
        internal IMedia CreateNewMediaObject(object caller, StatusMessageReportProgress rpu, EMedia type, string path, bool isActive, bool isDefault, bool isExample)
        {
            IMedia media = null;
            Uri    uri;

            if (!this.HasPermission(PermissionTypes.CanModifyMedia))
            {
                throw new PermissionException();
            }

            if (path == null)
            {
                throw new ArgumentNullException("Null value not allowed for media file path!");
            }

            try
            {
                if (File.Exists(Path.Combine(Environment.CurrentDirectory, path)))                 //to allow relative paths
                {
                    path = Path.Combine(Environment.CurrentDirectory, path);
                }

                uri = new Uri(path);
            }
            catch (UriFormatException exception)
            {
                throw new FileNotFoundException("Uri format is invalid.", exception);
            }

            if (uri.Scheme == Uri.UriSchemeFile && uri.IsFile)             //we got a new file
            {
                if (File.Exists(path))
                {
                    int newid;
                    using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                        newid = mediaconnector.CreateMedia(stream, type, rpu, caller);

                    media = DbMedia.CreateDisconnectedCardMedia(newid, type, isDefault, isExample, parent);

                    Helper.UpdateMediaProperties(path, newid, mediaconnector);
                }
                else
                {
                    throw new FileNotFoundException("Media file could not be found.", path);
                }
            }
            else if (uri.Scheme == "http" && uri.IsLoopback)             //we got a http reference => file is already in db
            {
                if (DbMediaServer.DbMediaServer.Instance(parent).IsYours(uri))
                {
                    int mediaId = DbMediaServer.DbMediaServer.GetMediaID(uri.AbsolutePath);
                    media = DbMedia.CreateDisconnectedCardMedia(mediaId, type, isDefault, isExample, parent);
                    rpu(new StatusMessageEventArgs(StatusMessageType.CreateMediaProgress, 100, 100), caller);
                }
                else
                {
                    DbMediaServer.DbMediaServer server = DbMediaServer.DbMediaServer.Instance(uri);

                    int newid = mediaconnector.CreateMedia(GetMediaConnector(server.Parent).GetMediaStream(DbMediaServer.DbMediaServer.GetMediaID(uri.AbsolutePath)), type, rpu, caller);

                    media = DbMedia.CreateDisconnectedCardMedia(newid, type, isDefault, isExample, parent);

                    Helper.UpdateMediaProperties(path, newid, mediaconnector);
                }
            }

            return(media);
        }
 public AccountUpdateProfileBackgroundImageParameters(IMedia media)
 {
     MediaId = media.MediaId;
     IncludeEntities = true;
 }
Example #40
0
 public MediaPlayerMediaChanged(IMedia newMedia)
 {
     NewMedia = newMedia;
 }
Example #41
0
        private async Task GetMediaAsync(EventContext e, bool manga, params MediaFormat[] format)
        {
            IMedia media = null;

            ArgObject arg = e.Arguments.Join();

            int?mediaId = arg.AsInt();

            if (mediaId != null)
            {
                media = await anilistClient.GetMediaAsync(mediaId.Value);
            }
            else
            {
                string filter = "search: $p0, format_not_in: $p1";
                List <GraphQLParameter> parameters = new List <GraphQLParameter>
                {
                    new GraphQLParameter(arg.Argument),
                    new GraphQLParameter(format, "[MediaFormat]")
                };

                if (!e.Channel.IsNsfw)
                {
                    filter += ", isAdult: $p2";
                    parameters.Add(new GraphQLParameter(false, "Boolean"));
                }

                media = await anilistClient.GetMediaAsync(filter, parameters.ToArray());
            }

            if (media != null)
            {
                string description = media.Description;
                if (description.Length > 1024)
                {
                    description = new string(description.Take(1020).ToArray());
                    description = new string(description.Take(description.LastIndexOf(' ')).ToArray()) + "...";
                }

                EmbedBuilder embed = Utils.Embed.SetAuthor(media.DefaultTitle, "https://anilist.co/img/logo_al.png", media.Url)
                                     .SetDescription(media.NativeTitle);

                if (!manga)
                {
                    embed.AddInlineField("Status", media.Status ?? "Unknown")
                    .AddInlineField("Episodes", media.Episodes ?? 0);
                }
                else
                {
                    embed.AddInlineField("Volumes", media.Volumes ?? 0)
                    .AddInlineField("Chapters", media.Chapters ?? 0);
                }

                embed.AddInlineField("Rating", $"{media.Score ?? 0}/100")
                .AddInlineField("Genres", string.Join("\n", media.Genres) ?? "None")
                .AddInlineField("Description", description ?? "None")
                .SetColor(0, 170, 255)
                .SetThumbnail(media.CoverImage)
                .SetFooter("Powered by anilist.co", "")
                .ToEmbed().QueueToChannel(e.Channel);
            }
            else
            {
                e.ErrorEmbed("Anime not found!")
                .ToEmbed().QueueToChannel(e.Channel);
            }
        }
 public MediaService(IPermissionService permissionService)
 {
     media = CrossMedia.Current;
     this.permissionService = permissionService;
 }
Example #43
0
        /// <summary>
        /// Performs a permissions check for the user to check if it has access to the node based on
        /// start node and/or permissions for the node
        /// </summary>
        /// <param name="storage">The storage to add the content item to so it can be reused</param>
        /// <param name="user"></param>
        /// <param name="mediaService"></param>
        /// <param name="entityService"></param>
        /// <param name="nodeId">The content to lookup, if the contentItem is not specified</param>
        /// <param name="media">Specifies the already resolved content item to check against, setting this ignores the nodeId</param>
        /// <returns></returns>
        internal static bool CheckPermissions(IDictionary <string, object> storage, IUser user, IMediaService mediaService, IEntityService entityService, int nodeId, IMedia media = null)
        {
            if (storage == null)
            {
                throw new ArgumentNullException("storage");
            }
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (mediaService == null)
            {
                throw new ArgumentNullException("mediaService");
            }
            if (entityService == null)
            {
                throw new ArgumentNullException("entityService");
            }

            if (media == null && nodeId != Constants.System.Root && nodeId != Constants.System.RecycleBinMedia)
            {
                media = mediaService.GetById(nodeId);
                //put the content item into storage so it can be retrieved
                // in the controller (saves a lookup)
                storage[typeof(IMedia).ToString()] = media;
            }

            if (media == null && nodeId != Constants.System.Root && nodeId != Constants.System.RecycleBinMedia)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            var hasPathAccess = (nodeId == Constants.System.Root)
                ? user.HasMediaRootAccess(entityService)
                : (nodeId == Constants.System.RecycleBinMedia)
                    ? user.HasMediaBinAccess(entityService)
                    : user.HasPathAccess(media, entityService);

            return(hasPathAccess);
        }
 public DeferedReIndexForMedia(IMedia media, bool isPublished)
 {
     _media       = media;
     _isPublished = isPublished;
 }
Example #45
0
 public virtual void Open(IMedia media)
 {
     LibVlcMethods.libvlc_media_player_set_media(m_hMediaPlayer, ((INativePointer)media).Pointer);
 }
Example #46
0
 public virtual void Open(IMedia media)
 {
     LibVlcMethods.libvlc_media_player_set_media(m_hMediaPlayer, ((INativePointer)media).Pointer);
     // ((IReferenceCount)media).Release();
 }
Example #47
0
 public DeferedReIndexForMedia(ExamineComponent examineComponent, IMedia media, bool isPublished)
 {
     _examineComponent = examineComponent;
     _media            = media;
     _isPublished      = isPublished;
 }
 public void Project(IMedia target)
 {
     _modelModule.Value.ProjectModelToContent(this, target);
 }
        private static void AfterMap(IMedia media, MediaItemDisplay display, IDataTypeService dataTypeService, ILocalizedTextService localizedText, IContentTypeService contentTypeService, ILogger logger)
        {
            // Adapted from ContentModelMapper
            //map the IsChildOfListView (this is actually if it is a descendant of a list view!)
            var parent = media.Parent();

            display.IsChildOfListView = parent != null && (parent.ContentType.IsContainer || contentTypeService.HasContainerInPath(parent.Path));

            //map the tree node url
            if (HttpContext.Current != null)
            {
                var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                var url       = urlHelper.GetUmbracoApiService <MediaTreeController>(controller => controller.GetTreeNode(display.Id.ToString(), null));
                display.TreeNodeUrl = url;
            }

            if (media.ContentType.IsContainer)
            {
                TabsAndPropertiesResolver.AddListView(display, "media", dataTypeService, localizedText);
            }

            var genericProperties = new List <ContentPropertyDisplay>
            {
                new ContentPropertyDisplay
                {
                    Alias = string.Format("{0}doctype", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
                    Label = localizedText.Localize("content/mediatype"),
                    Value = localizedText.UmbracoDictionaryTranslate(display.ContentTypeName),
                    View  = PropertyEditorResolver.Current.GetByAlias(Constants.PropertyEditors.NoEditAlias).ValueEditor.View
                }
            };

            TabsAndPropertiesResolver.MapGenericProperties(media, display, localizedText, genericProperties, properties =>
            {
                if (HttpContext.Current != null && UmbracoContext.Current != null && UmbracoContext.Current.Security.CurrentUser != null &&
                    UmbracoContext.Current.Security.CurrentUser.AllowedSections.Any(x => x.Equals(Constants.Applications.Settings)))
                {
                    var mediaTypeLink = string.Format("#/settings/mediatypes/edit/{0}", media.ContentTypeId);

                    //Replace the doctype property
                    var docTypeProperty   = properties.First(x => x.Alias == string.Format("{0}doctype", Constants.PropertyEditors.InternalGenericPropertiesPrefix));
                    docTypeProperty.Value = new List <object>
                    {
                        new
                        {
                            linkText = media.ContentType.Name,
                            url      = mediaTypeLink,
                            target   = "_self",
                            icon     = "icon-item-arrangement"
                        }
                    };
                    docTypeProperty.View = "urllist";
                }

                // inject 'Link to media' as the first generic property
                var links = media.GetUrls(UmbracoConfig.For.UmbracoSettings().Content, logger);
                if (links.Any())
                {
                    var link = new ContentPropertyDisplay
                    {
                        Alias = string.Format("{0}urls", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
                        Label = localizedText.Localize("media/urls"),
                        Value = string.Join(",", links),
                        View  = "urllist"
                    };
                    properties.Insert(0, link);
                }
            });
        }
Example #50
0
        public static TimeSpan TcLastFrame(this IMedia media)
        {
            var frameRate = FrameRate(media);

            return(((media.TcStart + media.Duration).ToSmpteFrames(frameRate) - 1).SmpteFramesToTimeSpan(frameRate));
        }
Example #51
0
 public bool Contains(IMedia item)
 {
     return this.IndexOf(item) != -1;
 }
Example #52
0
        /// <summary>
        /// Updates the preview dictionary.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        /// <returns></returns>
        /// <remarks>Documented by Dev03, 2009-03-30</remarks>
        public static PreviewDictionary UpdatePreviewDictionary(PreviewDictionary dictionary)
        {
            using (XmlReader reader = XmlReader.Create(dictionary.Connection))
            {
                try
                {
                    ICard      card       = null;
                    IStatistic statistic  = null;
                    bool       imageFound = false;
                    while (reader.Read())
                    {
                        if (reader.IsEmptyElement || reader.NodeType == XmlNodeType.EndElement)
                        {
                            continue;
                        }
                        switch (reader.Name)
                        {
                        case "category":
                            int oldId, newId;
                            if (Int32.TryParse(reader.GetAttribute("id"), out newId) && (newId >= 0))
                            {
                                dictionary.Category = new Category(newId);
                            }
                            else if (Int32.TryParse(reader.ReadElementContentAsString(), out oldId) && (oldId >= 0))
                            {
                                dictionary.Category = new Category(oldId, false);
                            }
                            break;

                        case "author":
                            dictionary.Author = reader.ReadElementContentAsString().Trim();
                            break;

                        case "description":
                            dictionary.Description = reader.ReadElementContentAsString().Trim();
                            break;

                        case "sounddir":
                            dictionary.MediaDirectory = reader.ReadElementContentAsString().Trim();
                            break;

                        case "card":
                            card = dictionary.Cards.AddNew();
                            break;

                        case "answer":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                card.Answer.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
                            }
                            break;

                        case "question":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                card.Question.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
                            }
                            break;

                        case "answerexample":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                card.AnswerExample.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
                            }
                            break;

                        case "questionexample":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                card.QuestionExample.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
                            }
                            break;

                        case "questionimage":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                IMedia qmedia = card.CreateMedia(EMedia.Image, reader.ReadElementContentAsString(), true, false, false);
                                card.AddMedia(qmedia, Side.Question);
                                imageFound = true;
                            }
                            break;

                        case "answerimage":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                IMedia amedia = card.CreateMedia(EMedia.Image, reader.ReadElementContentAsString(), true, false, false);
                                card.AddMedia(amedia, Side.Question);
                            }
                            break;

                        case "stats":
                            statistic = new PreviewStatistic();
                            int sId;
                            if (Int32.TryParse(reader.GetAttribute("id"), out sId) && (sId >= 0))
                            {
                                (statistic as PreviewStatistic).Id = sId;
                            }
                            dictionary.Statistics.Add(statistic);
                            break;

                        case "start":
                            if (statistic != null)
                            {
                                statistic.StartTimestamp = XmlConvert.ToDateTime(reader.ReadElementContentAsString(), XmlDateTimeSerializationMode.RoundtripKind);
                            }
                            break;

                        case "end":
                            if (statistic != null)
                            {
                                statistic.EndTimestamp = XmlConvert.ToDateTime(reader.ReadElementContentAsString(), XmlDateTimeSerializationMode.RoundtripKind);
                            }
                            break;

                        case "right":
                            if (statistic != null)
                            {
                                statistic.Right = XmlConvert.ToInt32(reader.ReadElementContentAsString());
                            }
                            break;

                        case "wrong":
                            if (statistic != null)
                            {
                                statistic.Wrong = XmlConvert.ToInt32(reader.ReadElementContentAsString());
                            }
                            break;

                        default:
                            break;
                        }
                        //System.Threading.Thread.Sleep(5);
                    }
                }
                catch
                {
                    dictionary.Category = new Category(0);
                }
                dictionary.Id = 1;
                return(dictionary);
            }
        }
Example #53
0
 public int IndexOf(IMedia item)
 {
     using (new MediaListLock(m_hMediaList))
      {
     return LibVlcMethods.libvlc_media_list_index_of_item(m_hMediaList, ((INativePointer)item).Pointer);
      }
 }
 public void AddLogo(IMedia logo)
 {
     Logos.Add(logo);
 }
Example #55
0
        public bool Remove(IMedia item)
        {
            int index = this.IndexOf(item);
             if (index < 0)
             {
            return false;
             }

             this.RemoveAt(index);
             return true;
        }
 public void RemoveLogo(IMedia logo)
 {
     Logos.Remove(logo);
 }
Example #57
0
 public bool IsConverting(IMedia media)
 {
     return(media.GetValue <bool>(UmbracoAliases.Video.ConvertInProcessPropertyAlias));
 }
Example #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CameraService"/> class.
 /// </summary>
 /// <param name="dataStorageManager"></param>
 public CameraService(IDataStorageManager dataStorageManager)
 {
     media = CrossMedia.Current;
     media.Initialize();
     this.dataStorageManager = dataStorageManager;
 }
Example #59
0
        public QuestoesViewModel(int idAspecto)
        {
            GerenciadorFotos = DependencyService.Get <IGerenciadorFotos>();
            MyList           = new ObservableCollection <QuestionarioModelClass>();
            _idAspecto       = idAspecto;
            FillData(idAspecto);
            DesabilitarQuestoesAnulaveis(idQuestao, idResposta);
            RadionButtonCommandRespostaQuestao = new Command(async(model) =>
            {
                QuestionarioModelClass questaoSelecionada = (QuestionarioModelClass)model;
                var idQuestao       = Convert.ToInt32(questaoSelecionada.id);
                var respostaQuestao = Convert.ToInt32(questaoSelecionada.resposta);
                DesabilitarQuestoesAnulaveis(idQuestao, respostaQuestao);
            });
            ButtonClickCommandEnviarQuestionario = new Command(async(model) =>
            {
                Device.BeginInvokeOnMainThread(async() =>
                {
                    IList <QuestionarioModelClass> relacaoQuestoes = (IList <QuestionarioModelClass>)model;
                    using (UserDialogs.Instance.Loading("Sincronizando Questionário.", null, null, true, MaskType.Black))
                    {
                        await EnviarQuestionario(relacaoQuestoes, idAspecto);
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            UserDialogs.Instance.HideLoading();
                        });
                    }
                });
            });
            ButtonClickCommandFoto = new Command(async(model) =>
            {
                try
                {
                    MediaFile file;
                    IMedia media = CrossMedia.Current;
                    QuestionarioModelClass questoes = (QuestionarioModelClass)model;
                    MidiaQuestoes midiaQuestoes;
                    DatabaseHelper service = new DatabaseHelper();
                    var qtdMidia           = service.GetqtdMidia();
                    var qtdQuestoes        = service.QuantidadeMidiaQuestoes(questoes.id);
                    if (qtdQuestoes < qtdMidia.data)
                    {
                        await CrossMedia.Current.Initialize();
                        bool answer = await Application.Current.MainPage.DisplayAlert("", "Deseja Obter imagem através ", "Galeria", "Câmera");
                        if (answer)
                        {
                            //Procedimento para capturar foto da galeria
                            try
                            {
                                /*MediaFile _mediaFile;
                                 * if (!CrossMedia.Current.IsPickPhotoSupported)
                                 * {
                                 *  System.Diagnostics.Debug.WriteLine("Erro.");
                                 *  return;
                                 * }
                                 * file = await media.PickPhotoAsync();
                                 * if (file == null)
                                 * {
                                 *  await Application.Current.MainPage.DisplayAlert("", "Mídia não selecionada.", "OK");
                                 *  return;
                                 * }
                                 * else
                                 * {
                                 *  string caminho = file.Path;
                                 *  string filename = null;
                                 *  filename = Path.GetFileName(caminho);
                                 *  file.Dispose();
                                 *  midiaQuestoes = new MidiaQuestoes();
                                 *  midiaQuestoes.questaoVisitaId = questoes.id;
                                 *  midiaQuestoes.dataGravacao = DateTime.Now;
                                 *  midiaQuestoes.legenda = filename;
                                 *  midiaQuestoes.caminho = caminho;
                                 *  service.InsertMidiaQuestoes(midiaQuestoes);
                                 *
                                 * }*/
                                await GerenciadorFotos.MidiaAsync();
                                //ImageSource imagem = ImageSource.FromStream(() => imageStream);
                            }
                            catch (Exception ex)
                            {
                                await Application.Current.MainPage.DisplayAlert("", ex.Message, "OK");
                            }
                            //Fim Procedimento para capturar foto da galeria
                        }
                        else
                        {
                            //Procedimento para Tirar Foto para questão.
                            string _datahora;
                            var _data   = DateTime.Now;
                            var day     = _data.Day.ToString();
                            var month   = _data.Month.ToString();
                            var year    = _data.Year.ToString();
                            var hora    = _data.Hour.ToString();
                            var minuto  = _data.Minute.ToString();
                            var segundo = _data.Second.ToString();
                            _datahora   = day + "_" + month + "_" + year + "_" + hora + "_" + minuto + "_" + segundo;
                            if (!CrossMedia.Current.IsTakePhotoSupported || !CrossMedia.Current.IsCameraAvailable)
                            {
                                await Application.Current.MainPage.DisplayAlert("Ops", "Nenhuma câmera detectada.", "OK");

                                return;
                            }
                            try
                            {
                                file = await CrossMedia.Current.TakePhotoAsync(
                                    new StoreCameraMediaOptions
                                {
                                    PhotoSize          = PhotoSize.Small,
                                    CompressionQuality = 92,
                                    SaveToAlbum        = true,
                                    Name      = questoes.id.ToString() + "_" + _datahora,
                                    Directory = "Milenio"
                                });
                                string caminho = file.AlbumPath;

                                if (file == null)
                                {
                                    return;
                                }
                                else
                                {
                                    midiaQuestoes = new MidiaQuestoes();
                                    midiaQuestoes.questaoVisitaId = questoes.id;
                                    midiaQuestoes.dataGravacao    = DateTime.Now;
                                    midiaQuestoes.legenda         = questoes.id.ToString() + "_" + _datahora + ".jpg";
                                    midiaQuestoes.caminho         = caminho;
                                    service.InsertMidiaQuestoes(midiaQuestoes);
                                }
                            }
                            catch (Exception ex)
                            {
                                throw;
                            }

                            // Fim Procedimento para tirar Foto para questão
                        }
                    }
                    else
                    {
                        string msg = "Limite atingido de " + qtdMidia.data + " mídias por pergunta. ";
                        await Application.Current.MainPage.DisplayAlert("", msg, "OK");
                    }
                }
                catch (Exception ex)
                {
                    await Application.Current.MainPage.DisplayAlert("", "Mídia não selecionada.", "OK");
                }
            });
        }
Example #60
0
        protected override void DoBackgroundWork()
        {
            try
            {
                frameEncodeInterval = 1000 / this.cameraSpec.vlc_transcode_fps;
                w = this.cameraSpec.h264_video_width;
                h = this.cameraSpec.h264_video_height;
                if (w <= 0 || h <= 0)
                {
                    w = h = 0;
                }

                IVideoPlayer player = null;

                while (!Exit)
                {
                    try
                    {
                        frameNumber             = 0;
                        lastFrameEncoded        = 0;
                        nextFrameEncodeTime     = 0;
                        lastTimestampUpdateTime = -1;
                        frameTimer.Start();
                        IMediaPlayerFactory factory = new MediaPlayerFactory();
                        player = factory.CreatePlayer <IVideoPlayer>();
                        player.Events.TimeChanged += new EventHandler <Declarations.Events.MediaPlayerTimeChanged>(Events_TimeChanged);
                        int      b    = cameraSpec.vlc_transcode_buffer_time;
                        string[] args = new string[] { ":rtsp-caching=" + b, ":realrtsp-caching=" + b, ":network-caching=" + b, ":udp-caching=" + b, ":volume=0", cameraSpec.wanscamCompatibilityMode ? ":demux=h264" : "", cameraSpec.wanscamCompatibilityMode ? ":h264-fps=" + cameraSpec.wanscamFps : "" };
                        string   url  = cameraSpec.imageryUrl;
                        if (cameraSpec.wanscamCompatibilityMode)
                        {
                            url = "http://127.0.0.1:" + MJpegWrapper.cfg.webport + "/" + cameraSpec.id + ".wanscamstream";
                        }
                        IMedia media = factory.CreateMedia <IMedia>(url, args);
                        memRender = player.CustomRenderer2;
                        //memRender.SetExceptionHandler(ExHandler);
                        memRender.SetCallback(delegate(Bitmap frame)
                        {
                            // We won't consume the bitmap here.  For efficiency's sake under light load, we will only encode the bitmap as jpeg when it is requested by a client.
                            frameNumber++;
                            if (!player.Mute)
                            {
                                player.ToggleMute();
                            }
                            if (frameTimer.ElapsedMilliseconds >= nextFrameEncodeTime)
                            {
                                EventWaitHandle oldWaitHandle = newFrameWaitHandle;
                                newFrameWaitHandle            = new EventWaitHandle(false, EventResetMode.ManualReset);
                                oldWaitHandle.Set();
                            }
                            //long time = frameCounter.ElapsedMilliseconds;
                            //if (time >= nextFrameEncodeTime)
                            //{
                            //    lastFrame = ImageConverter.GetJpegBytes(frame);
                            //    nextFrameEncodeTime = time + frameEncodeInterval;
                            //}
                            //latestBitmap = new Bitmap(frame);  // frame.Clone() actually doesn't copy the data and exceptions get thrown
                        });
                        memRender.SetFormat(new BitmapFormat(w, h, ChromaType.RV24));
                        //memRender.SetFormatSetupCallback(formatSetupCallback);
                        player.Open(media);
                        player.Play();
                        if (w == 0)
                        {
                            // Need to auto-detect video size.
                            while (!Exit)
                            {
                                Thread.Sleep(50);
                                Size s = player.GetVideoSize(0);
                                if (s.Width > 0 && s.Height > 0)
                                {
                                    lock (MJpegWrapper.cfg)
                                    {
                                        w = this.cameraSpec.h264_video_width = (ushort)s.Width;
                                        h = this.cameraSpec.h264_video_height = (ushort)s.Height;
                                        MJpegWrapper.cfg.Save(Globals.ConfigFilePath);
                                    }
                                    throw new Exception("Restart");
                                }
                            }
                        }
                        else
                        {
                            while (!Exit)
                            {
                                Thread.Sleep(50);
                            }
                        }
                    }
                    catch (ThreadAbortException ex)
                    {
                        throw ex;
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message != "Restart")
                        {
                            Logger.Debug(ex);
                            int waitedTimes = 0;
                            while (!Exit && waitedTimes++ < 100)
                            {
                                Thread.Sleep(50);
                            }
                        }
                    }
                    finally
                    {
                        frameTimer.Stop();
                        frameTimer.Reset();
                        if (player != null)
                        {
                            player.Stop();
                        }
                        newFrameWaitHandle.Set();
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                Logger.Debug(ex);
            }
            newFrameWaitHandle.Set();
        }