public Media[] GetCachedMedia()
    {
        if (Cache["allImages"] == null)
        {
            string[] userNames = Roles.GetUsersInRole("Triphulcas");
            RelationType type = RelationType.GetByAlias("userMedia");
            var _allImages = new List<Media>();

            foreach (string userName in userNames)
            {
                var member = Member.GetMemberByName(userName, false);
                if (member != null && member.Length > 0)
                {
                    var relations = Relation.GetRelations(member[0].Id, type);

                    if (relations != null && relations.Length > 0)
                    {
                        foreach (var relation in relations)
                        {
                            var media = new Media(relation.Child.Id);
                            _allImages.Add(media);
                        }
                    }
                }
            }

            //kludgy & clumsy fast approach for popup-viewer
            Cache["allImages"] = _allImages;
        }

        Random rnd = new Random();
        return (Cache["allImages"] as List<Media>).ToArray<Media>().OrderBy(x => rnd.Next()).ToArray();
        //return (Cache["allImages"] as List<Media>).ToArray();
        
    }
        public static void SetCategories(IRepository repository, Media sourceMedia, Media destinationMedia)
        {
            var destination = destinationMedia as ICategorized;
            var source = sourceMedia as ICategorized;

            if (destination == null || source == null)
            {
                return;
            }

            if (destination.Categories != null)
            {
                var categoriesToRemove = destination.Categories.ToList();
                categoriesToRemove.ForEach(repository.Delete);
            }

            if (source.Categories == null)
            {
                return;
            }

            source.Categories.ForEach(destination.AddCategory);
            if (destination.Categories != null)
            {
                destination.Categories.ForEach(e => e.SetEntity(destinationMedia));
            }
        }
 public void WhenANewMediaViewModelIsCreated_ThenTheClassStringIsSetProperly()
 {
     var media = new Media
                     {Size = (int) Media.ValidSizes.Fullsize, Alignment = (int) Media.ValidAllignments.Left};
     var model = new ShowMediaViewModel(media);
     Assert.That(model.ClassString, Is.EqualTo("img-fullsize img-align-left"));
 }
Exemple #4
0
        /// <summary>
        /// Deletes the media.
        /// </summary>
        /// <param name="media">The media.</param>
        public void DeleteMedia(Media media)
        {
            if (media.MediaTags != null)
            {
                foreach (var mediaTag in media.MediaTags)
                {
                    repository.Delete(mediaTag);
                }
            }

            if (media is MediaFile)
            {
                MediaFile file = (MediaFile)media;
                if (file.AccessRules != null)
                {
                    var rules = file.AccessRules.ToList();
                    rules.ForEach(file.RemoveRule);
                }
            }

            repository.Delete(media);

            var subItems = repository.AsQueryable<Media>().Where(m => !m.IsDeleted && m.Folder != null && m.Folder.Id == media.Id).ToList();
            foreach (var item in subItems)
            {
                DeleteMedia(item);
            }
        }
Exemple #5
0
        public static Media CreateFrom(RegionOptions regionOptions)
        {
            UserControl widget = null;
            Media Backing = new Media(regionOptions.Width,regionOptions.Height,regionOptions.Top,regionOptions.Left);
            switch (regionOptions.Name)
            {
                case "CarInfo": 
                    widget = new CarInfo();
                    break;
                case "BatteryInfo":
                    widget = new BatteryInfo();
                    break;
                case "LocationInfo":
                    widget = new Location();
                    break;
                case "PersonalInfo":
                    widget = new Profile();
                    break;
                default:
                    break;
            }

            widget.Width = regionOptions.Width;
            widget.Height = regionOptions.Height;
            //MediaGrid.Width = Width;
            //MediaGrid.Height = Height;

            widget.HorizontalAlignment = HorizontalAlignment.Center;
            widget.VerticalAlignment = VerticalAlignment.Center;
            widget.Margin = new Thickness(0, 0, 0, 0);
           Backing.MediaCanvas.Children.Add(widget);
           Backing.HasOnLoaded = true;
            return Backing;
        }
        public void MediaDownloadStarted(Media m)
        {
            notificationsFlowLayoutPanel.BeginInvoke((MethodInvoker)delegate
            {
                if( mediaBeingDownloaded[m] ==null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append(GetFacts.Resources.GFResources.GetString("DOWNLOADING_MEDIA_CAPTION")); // "Downloading media"
                    sb.AppendLine();
                    sb.Append("URI=");
                    sb.Append(m.Uri);
                    sb.AppendLine();
                    sb.Append("Type=");
                    sb.Append(m.Type);
                    sb.AppendLine();
                    sb.Append("Priority=");
                    sb.Append(m.Priority);
                    sb.AppendLine();
                    sb.Append("Guid=");
                    sb.Append(m.Guid);
                    sb.AppendLine();

                    PictureBox pictureBox = new PictureBox();
                    pictureBox.Size = new Size(70, 70);
                    pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
                    pictureBox.Image = GetFacts.Plugins.Properties.Resources.media_downloading;
                    pictureBox.Margin = new Padding(10);
                    notificationsFlowLayoutPanel.Controls.Add(pictureBox);
                    mediaDownloadToolTip.SetToolTip(pictureBox, sb.ToString());
                    mediaBeingDownloaded[m] = pictureBox;
                }
            });
        }
Exemple #7
0
 public string Fetch(Media m)
 {
     media = m;
     string fileName = Path.GetTempFileName();
     try
     {
         using (webClient = new WebClient())
         {
             webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);
             webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
             lock (_download_lock_)
             {
                 webClient.DownloadFileAsync(m.Uri, fileName);
                 Monitor.Wait(_download_lock_);
                 if (downloadSuccessful == false)
                 {
                     throw new OperationCanceledException();
                 }
             }
         }
         return fileName;
     }
     catch
     {
         File.Delete(fileName);
         throw;
     }
 }
 public override void OnRender(Media.DrawingContext dc)
 {
     if (_pts != null)
     {
         dc.DrawPolygon(Fill, Stroke, _pts);
     }
 }
 public MediaExport(Media media, TimeSpan startTC, TimeSpan duration, decimal audioVolume)
 {
     this.Media = media;
     this.StartTC = startTC;
     this.Duration = duration;
     this.AudioVolume = audioVolume;
 }
		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;
		}
        public IEnumerable<MediaDistributor> GetFromMongo()
        {
            var result = new List<MediaDistributor>();

            foreach (var distributor in this.distributors.FindAll())
            {
                var distributorSql = new MediaDistributor()
                {
                    Name = distributor.Name
                };

                foreach (var media in distributor.Medias)
                {
                    var mediaSql = new Media()
                    {
                        Name = media.Name,
                        PriceSubscriptionPerMonth = media.PriceSubscriptionPerMonth,
                        DepartmentId = 1,
                        Type = media.Type
                    };

                    distributorSql.Medias.Add(mediaSql);
                }

                result.Add(distributorSql);
            }

            return result;
        }
        public static void SetTags(IRepository repository, Media sourceMedia, Media destinationMedia)
        {
            var destination = destinationMedia;
            var source = sourceMedia;

            if (destination == null || source == null)
            {
                return;
            }

            if (destination.MediaTags != null)
            {
                var tagsToRemove = destination.MediaTags.ToList();
                tagsToRemove.ForEach(repository.Delete);
            }

            if (source.MediaTags == null)
            {
                return;
            }

            source.MediaTags.ForEach(destination.AddTag);
            if (destination.MediaTags != null)
            {
                foreach (var mediaTag in destination.MediaTags)
                {
                    mediaTag.Media = destinationMedia;
                }
            }
        }
Exemple #13
0
        public MediaFile(Media.MediaFile mediaFile)
            : this()
        {
            _mediaFile = mediaFile;

            txtAlias.Text = _mediaFile.Alias;
            lblFileType.Text = string.Format("Type: {0} / {1}", _mediaFile.ResourceFileType.ToString(), _mediaFile.FileType.ToString());
            lblFileName.Text = string.Format("File: {0}", _mediaFile.FileName.ToString());
            lblResourceId.Text = string.Format("Resource: {0}", (_mediaFile.ResourceIdentifier != null ? _mediaFile.ResourceIdentifier.ToString() : "<n/a>"));

            txtVolAll.Text = _mediaFile.VolumeAll.ToString();
            txtVolLeft.Text = _mediaFile.VolumeLeft.ToString();
            txtVolRight.Text = _mediaFile.VolumeRight.ToString();

            chkMuteAll.Checked = _mediaFile.MuteAll;
            chkMuteLeft.Checked = _mediaFile.MuteLeft;
            chkMuteRight.Checked = _mediaFile.MuteRight;

            txtBalance.Text = _mediaFile.Balance.ToString();
            trackBalance.Value = _mediaFile.Balance;

            txtTreble.Text = _mediaFile.VolumeTreble.ToString();
            txtBass.Text = _mediaFile.VolumeBass.ToString();

            chkLoop.Checked = _mediaFile.Looping;
        }
        public ActionResult Create(Media media,int id)
        {
            foreach (var file in media.Images)
            {

                if(file.ContentLength>0)
                {
                    var filename = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Images/"), filename);
                    file.SaveAs(path);
                    ViewBag.Path = path;
                }

                Media m = new Media()
                {

                    UpdatesID = id,
                    Images = media.Images,
                    Video = media.Video

                };

                db.Media.Add(m);
                db.SaveChanges();
                return RedirectToAction("Index", new { id = media.UpdatesID });

            }

            return View(media);
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    public void Run(AdWordsUser user) {
      // Get the MediaService.
      MediaService mediaService = (MediaService) user.GetService(
          AdWordsService.v201509.MediaService);

      try {
        // Create HTML5 media.
        byte[] html5Zip = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/9Y7qI2");
        // Create a media bundle containing the zip file with all the HTML5 components.
        Media[] mediaBundle = new Media[] {
        new MediaBundle() {
          data = html5Zip,
          type = MediaMediaType.MEDIA_BUNDLE
        }};

        // Upload HTML5 zip.
        mediaBundle = mediaService.upload(mediaBundle);

        // Display HTML5 zip.
        if (mediaBundle != null && mediaBundle.Length > 0) {
          Media newBundle = mediaBundle[0];
          Dictionary<MediaSize, Dimensions> dimensions =
              CreateMediaDimensionMap(newBundle.dimensions);
          Console.WriteLine("HTML5 media with id \"{0}\", dimensions \"{1}x{2}\", and MIME type " +
              "\"{3}\" was uploaded.", newBundle.mediaId, dimensions[MediaSize.FULL].width,
              dimensions[MediaSize.FULL].height, newBundle.mimeType
          );
        } else {
          Console.WriteLine("No HTML5 zip was uploaded.");
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to upload HTML5 zip file.", e);
      }
    }
 public ServerMedia GetServerMedia(Media media, bool searchExisting = true)
 {
     if (media == null)
         return null;
     ServerMedia fm = null;
     _files.Lock.EnterUpgradeableReadLock();
     try
     {
         fm = (ServerMedia)FindMedia(media);
         if (fm == null || !searchExisting)
         {
             _files.Lock.EnterWriteLock();
             try
             {
                 fm = (new ServerMedia()
                 {
                     _mediaName = media.MediaName,
                     _folder = string.Empty,
                     _fileName = (media is IngestMedia) ? (VideoFileTypes.Any(ext => ext == Path.GetExtension(media.FileName).ToLower()) ? Path.GetFileNameWithoutExtension(media.FileName) : media.FileName) + DefaultFileExtension(media.MediaType) : media.FileName,
                     MediaType = (media.MediaType == TMediaType.Unknown) ? (StillFileTypes.Any(ve => ve == Path.GetExtension(media.FullPath).ToLowerInvariant()) ? TMediaType.Still : TMediaType.Movie) : media.MediaType,
                     _mediaStatus = TMediaStatus.Required,
                     _tCStart = media.TCStart,
                     _tCPlay = media.TCPlay,
                     _duration = media.Duration,
                     _durationPlay = media.DurationPlay,
                     _videoFormat = media.VideoFormat,
                     _audioChannelMapping = media.AudioChannelMapping,
                     _audioVolume = media.AudioVolume,
                     _audioLevelIntegrated = media.AudioLevelIntegrated,
                     _audioLevelPeak = media.AudioLevelPeak,
                     KillDate = (media is PersistentMedia) ? (media as PersistentMedia).KillDate : ((media is IngestMedia && (media.Directory as IngestDirectory).MediaRetnentionDays > 0) ? DateTime.Today + TimeSpan.FromDays(((IngestDirectory)media.Directory).MediaRetnentionDays) : default(DateTime)),
                     DoNotArchive = (media is ServerMedia && (media as ServerMedia).DoNotArchive)
                                  || media is IngestMedia && ((media as IngestMedia).Directory as IngestDirectory).MediaDoNotArchive,
                     HasExtraLines = media is ServerMedia && (media as ServerMedia).HasExtraLines,
                     _mediaCategory = media.MediaCategory,
                     _parental = media.Parental,
                     idAux = (media is PersistentMedia) ? (media as PersistentMedia).idAux : string.Empty,
                     idFormat = (media is PersistentMedia) ? (media as PersistentMedia).idFormat : 0L,
                     idProgramme = (media is PersistentMedia) ? (media as PersistentMedia).idProgramme : 0L,
                     _mediaGuid = fm == null ? media.MediaGuid : Guid.NewGuid(), // in case file with the same GUID already exists and we need to get new one
                     OriginalMedia = media,
                     Directory = this,
                 });
             }
             finally
             {
                 _files.Lock.ExitWriteLock();
             }
             fm.PropertyChanged += MediaPropertyChanged;
         }
         else
             if (fm.MediaStatus == TMediaStatus.Deleted)
                 fm.MediaStatus = TMediaStatus.Required;
     }
     finally
     {
         _files.Lock.ExitUpgradeableReadLock();
     }
     return fm;
 }
Exemple #17
0
        static void Main(string[] args)
        {
            Media media1 = new Media("Kirja", "Olio-ohjelmointi");
            Media media2 = new Media("Lehti", "Mikrobitti");
            Levy levy1 = new Levy("CD", "Lost Society", 66);
            Levy levy2 = new Levy("DVD", "Hellraiser", 93);
            Laite laite1 = new Laite("Puhelin", "Luuri", "Samsung");
            Laite laite2 = new Laite("Kannettava", "Läppäri", "Asus");

            media1.printData();
            media2.printData();
            levy1.printData();
            levy2.printData();
            laite1.printData();
            laite2.printData();

            media2.Nimi = "Tekniikan Maailma";
            laite2.Tyyppi = "Tabletti";
            laite2.Nimi = "Tab2";
            laite2.Valmistaja = "Samsung";

            media2.printData();
            laite2.printData();

            Console.ReadLine();
        }
Exemple #18
0
        public Media WriteMedia(string fileName, int userId, string contentType, Stream inputStream, int contentLength)
        {
            var mediaToCreate = new Media(fileName, userId, contentType, inputStream, contentLength);

            try
            {
                Media media = _mediaRepository.GetMedia(userId, mediaToCreate.Year, mediaToCreate.Month,
                                                  mediaToCreate.Day,
                                                  mediaToCreate.LinkKey);
                if (media == null)
                {
                    mediaToCreate = _mediaRepository.WriteMedia(mediaToCreate);
                    return mediaToCreate;
                }
                throw new MBlogInsertItemException("Unable to add media. The media already exists in the database");
            }
            catch (MBlogInsertItemException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new MBlogException("Could not create media", e);
            }
        }
    public static void compressImage(Media sender)
    {
        //Get settings file
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(HttpContext.Current.Server.MapPath("~/config/WaffelAutoCompress.config"));
        var propertyAlias = xmlDoc.GetElementsByTagName("propertyalias")[0].InnerText;
        var mediaTypes = xmlDoc.GetElementsByTagName("mediatypes")[0].InnerText;
        bool allowedMediaType = mediaTypes.Split(',').Contains(sender.ContentType.Alias.ToString());

        //Check if settings allow current mediatype and if upload property has value
        if (allowedMediaType && sender.getProperty(propertyAlias).Value.ToString().Length != 0)
        {
            var triggerSize = xmlDoc.GetElementsByTagName("triggersize")[0].InnerText;
            var fileTypes = xmlDoc.GetElementsByTagName("filetypes")[0].InnerText;

            //Get uploaded file
            string targetFilePath = HttpContext.Current.Server.MapPath(sender.getProperty(propertyAlias).Value.ToString());
            var file = File.Open(targetFilePath, FileMode.Open, FileAccess.ReadWrite);
            string fileName = file.Name.ToString();
            var ext = fileName.Substring(fileName.LastIndexOf(".") + 1, fileName.Length - fileName.LastIndexOf(".") - 1).ToLower();

            int maxFileSize = System.Convert.ToInt32(triggerSize) * 1024; // if above image is downscaled
            bool allowedExt = fileTypes.Split(',').Contains(ext);

            //Check if file type is allowed and if size is above triggersize
            if (maxFileSize <= file.Length && allowedExt)
            {
                ImageDownscale(file, sender, ext);
            }
            else file.Dispose();
        }
    }
        public override Media CopyDataTo(Media media, bool copyCollections = true)
        {
            var copy = (MediaImage)base.CopyDataTo(media, copyCollections);

            copy.Caption = Caption;
            copy.ImageAlign = ImageAlign;
            copy.Width = Width;
            copy.Height = Height;
            copy.CropCoordX1 = CropCoordX1;
            copy.CropCoordY1 = CropCoordY1;
            copy.CropCoordX2 = CropCoordX2;
            copy.CropCoordY2 = CropCoordY2;
            copy.OriginalWidth = OriginalWidth;
            copy.OriginalHeight = OriginalHeight;
            copy.OriginalSize = OriginalSize;
            copy.OriginalUri = OriginalUri;
            copy.IsOriginalUploaded = IsOriginalUploaded;
            copy.PublicOriginallUrl = PublicOriginallUrl;
            copy.ThumbnailWidth = ThumbnailWidth;
            copy.ThumbnailHeight = ThumbnailHeight;
            copy.ThumbnailSize = ThumbnailSize;
            copy.ThumbnailUri = ThumbnailUri;
            copy.IsThumbnailUploaded = IsThumbnailUploaded;
            copy.PublicThumbnailUrl = PublicThumbnailUrl;

            return copy;
        }
Exemple #21
0
        protected void btnSubir_Click(object sender, EventArgs e)
        {
            string upload = System.IO.Path.GetFileName(FileUploadExaminar.PostedFile.FileName);
            string nameFileOrignal = upload;

            if (upload != "")
            {
            char[] seps = { '.' };
            String[] values = upload.Split(seps);

            if (values[1] == "jpg" || values[1] == "jpeg" || values[1] == "wmv")
            {
                path = path + "Clientes\\";
                media = new Media()
                {
                    nombre = txtContenido.Text,
                    ext = values[1],
                    creadoPor = "samuel",
                    modiificado = "samuel",
                    fileOriginal = nameFileOrignal.ToString()
                };

                    context.AddToMedia(media);
                    int resul = context.SaveChanges();

                    if (resul == 1)
                    {
                        Int32 id = media.id;

                        if ((FileUploadExaminar.PostedFile != null) && (FileUploadExaminar.PostedFile.ContentLength > 0))
                        {
                            upload = id + "." + values[1];
                            path = path + upload;
                            GridView1.DataBind();

                            try
                            {
                                FileUploadExaminar.PostedFile.SaveAs(path);
                                txtContenido.Text = "";
                            }
                            catch (Exception ex)
                            {
                                Response.Write("Error: " + ex.Message);
                            }
                        }
                        else
                        {
                            Response.Write("Seleccione un archivo que cargar.");
                        }
                    }

            }
            else
            {
                Response.Write("formato no permitido");
            }

            }
        }
 public MediaSearchEventArgs(Media media, MediaSegment segment, string mediaName, TimeSpan tCIn, TimeSpan duration)
 {
     Media = media;
     MediaSegment = segment;
     MediaName = mediaName;
     TCIn = tCIn;
     Duration = duration;
 }
Exemple #23
0
 /// <summary>
 /// Sets the offset of the specified <see cref="UIElement"/>
 /// </summary>
 /// <param name="element">The <see cref="UIElement"/> to set the offset of</param>
 /// <param name="offset">A <see cref="Media.Point"/> representing the <see cref="UIElement"/>'s offset</param>
 public static void SetOffset(UIElement element, Media.Point offset)
 {
     if (!element.DependencyProperties.ContainsKey(StackPanel.OffsetProperty))
     {
         throw new ArgumentException("The UIElement passed as 'element' argument is not the child of a StackPanel");
     }
     element.SetValue(StackPanel.OffsetProperty, offset);
 }
 public override void CloneMediaProperties(Media fromMedia)
 {
     base.CloneMediaProperties(fromMedia);
     if (fromMedia is ServerMedia)
     {
         HasExtraLines = (fromMedia as ServerMedia).HasExtraLines;
         DoNotArchive = (fromMedia as ServerMedia).DoNotArchive;
     }
 }
 //public override void MediaAdd(Media media)
 //{
 //    // do not add to _files
 //}
 public override bool DeleteMedia(Media media)
 {
     if (base.DeleteMedia(media))
     {
         MediaRemove(media);
         return true;
     }
     return false;
 }
Exemple #26
0
 public void GivenImageData_WhenICreateAnImage_ThenIGetValidDates()
 {
     DateTime today = DateTime.Now;
     var media = new Media("filename", "title", "caption", "description", "alternate", 1, "mime",
                           (int) Media.ValidAllignments.None, (int) Media.ValidSizes.Fullsize, new byte[] {});
     Assert.That(media.Year, Is.EqualTo(today.Year));
     Assert.That(media.Month, Is.EqualTo(today.Month));
     Assert.That(media.Day, Is.EqualTo(today.Day));
 }
Exemple #27
0
 public Model(
     Subscriptions.SubscriptionService subscriptionService,
     Media.MediaCacheService mediaCacheService,
     CommuterApplication application)
 {
     _subscriptionService = subscriptionService;
     _mediaCacheService = mediaCacheService;
     _application = application;
 }
Exemple #28
0
        /// <summary>Assigns all needed attributes to the tag</summary>
        /// <returns>This instance downcasted to base class</returns>
        public virtual IndexedTag attr(
            Charset charset = null,
            string href = null,
            LangCode hreflang = null,
            Target target = null,
            MimeType type = null,
            LinkType? rel = null,
            LinkType? rev = null,
            Media? media = null,
            string id = null,
            string @class = null,
            string style = null,
            string title = null,
            LangCode lang = null,
            string xmllang = null,
            Dir? dir = null,
            string onclick = null,
            string ondblclick = null,
            string onmousedown = null,
            string onmouseup = null,
            string onmouseover = null,
            string onmousemove = null,
            string onmouseout = null,
            string onkeypress = null,
            string onkeydown = null,
            string onkeyup = null
        )
        {
            Charset = charset;
            Href = href;
            HrefLang = hreflang;
            Target = target;
            Type = type;
            Rel = rel;
            Rev = rev;
            Media = media;
            Id = id;
            Class = @class;
            Style = style;
            Title = title;
            Lang = lang;
            XmlLang = xmllang;
            Dir = dir;
            OnClick = onclick;
            OnDblClick = ondblclick;
            OnMouseDown = onmousedown;
            OnMouseUp = onmouseup;
            OnMouseOver = onmouseover;
            OnMouseMove = onmousemove;
            OnMouseOut = onmouseout;
            OnKeyPress = onkeypress;
            OnKeyDown = onkeydown;
            OnKeyUp = onkeyup;

            return this;
        }
 public override void MediaRemove(Media media)
 {
     if (media is ServerMedia)
     {
         ((ServerMedia)media).MediaStatus = TMediaStatus.Deleted;
         ((ServerMedia)media).Verified = false;
         ((ServerMedia)media).Save();
     }
     base.MediaRemove(media);
 }
Exemple #30
0
        public override void OnRender(Media.DrawingContext dc)
        {
            /// Make room for cases when strokes are thick.
            int x = _renderWidth / 2 + Stroke.Thickness - 1;
            int y = _renderHeight / 2 + Stroke.Thickness - 1;
            int w = _renderWidth / 2 - (Stroke.Thickness - 1) * 2;
            int h = _renderHeight / 2 - (Stroke.Thickness - 1) * 2;

            dc.DrawEllipse(Fill, Stroke, x, y, w, h);
        }
Exemple #31
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["event_id"] != null)
            {
                fnsignUrl = _settings.site_url();


                Terminal t = _terminals.single(Convert.ToInt32(Session["event_id"]),
                                               Convert.ToInt32(Page.RouteData.Values["id"]));

                if (t.template_id > 0)
                {
                    // fill the content
                    Location l = _locations.single(Convert.ToInt32(t.location_id));

                    Template temp = _templates.single(Convert.ToInt32(t.template_id));

                    bgimage = temp.bgimage;
                    video   = bgimage;

                    if (temp.video)
                    {
                        video_bg.Visible = true;

                        bgimage = null;
                    }

                    template_id.Value = temp.id.ToString();

                    event_id.Value       = t.event_id.ToString();
                    location_sched.Value = l.sched_id;
                    terminal_id.Value    = Page.RouteData.Values["id"].ToString();

                    Session current = _sessions.current(Convert.ToInt32(Session["event_id"]), l.sched_id, _timewarp.display(t.event_id));

                    if (current.internal_id > 0)
                    {
                        // good we have a session now let's get the rest
                        Session next = _sessions.next(Convert.ToInt32(Session["event_id"]), l.sched_id, current.end);

                        session_title_val = current.name;
                        session_type      = current.event_type;
                        start_time        = current.start.ToShortTimeString();
                        next_session      = next.event_start + ": " + next.name;

                        Int32 title_length = session_title_val.Length;

                        if (title_length > 50)
                        {
                            session_title.Attributes.Add("class", "session-type-big");
                        }
                    }
                    else
                    {
                        session_title_val = "No Current Session";
                        session_type      = "Currently there is no session in this room";
                        start_time        = "No Session";

                        Session next = _sessions.next(Convert.ToInt32(Session["event_id"]), l.sched_id, DateTime.Now);

                        next_session = next.event_start + ": " + next.name;
                    }

                    // now get the first twitter item to be rotated
                    m = _media.random_by_event(Convert.ToInt32(Session["event_id"].ToString()));

                    twitpic = m.profilepic;

                    if (m.source != null)
                    {
                        twitimg = "<img src=\"" + m.source + "\" />";
                    }
                    else
                    {
                        twitimg = null;
                    }
                }
                else
                {
                    // display the waiting signal
                    Response.Redirect("/not-assigned/" + t.id);
                }
            }
            else
            {
                Response.Redirect("/details");
            }
        }
Exemple #32
0
        public async Task <IActionResult> PostMedia([FromForm] Media media)
        {
            var mediaId = await _mediaApi.PostMedia(media);

            return(Ok(mediaId));
        }
Exemple #33
0
        protected void Page_Init(object sender, EventArgs e)
        {
            long id;
            long parentId;

            long.TryParse(Request["historyVersion"], out historyVersion);
            long.TryParse(Request["mediaTypeId"], out mediaTypeId);

            if (long.TryParse(Request["selectedMediaId"], out id))
            {
                selectedMediaItem = MediasMapper.GetByID(id);
                SelectedMedia     = selectedMediaItem;

                if (selectedMediaItem != null)
                {
                    selectedItem = MediaDetailsMapper.GetByMedia(selectedMediaItem, CurrentLanguage);

                    if (historyVersion > 0)
                    {
                        selectedItem       = BaseMapper.GetObjectFromContext((MediaDetail)selectedItem);
                        historyVersionItem = BaseMapper.GetObjectFromContext((MediaDetail)MediaDetailsMapper.GetByMedia(selectedMediaItem, CurrentLanguage, historyVersion));
                    }

                    if ((selectedItem != null) && (historyVersionItem != null))
                    {
                        tmpSelectedItem = BaseMapper.GetObjectFromContext((MediaDetail)selectedItem);
                        selectedItem    = historyVersionItem;
                    }
                }
            }

            if (long.TryParse(Request["parentMediaId"], out parentId))
            {
                parentMediaItem = MediasMapper.GetByID(parentId);
            }

            if (selectedItem == null)
            {
                if (parentMediaItem != null)
                {
                    SelectedMedia = parentMediaItem;
                }

                /*if (parentMediaItem == null)
                 *  return;*/

                selectedItem = MediaDetailsMapper.CreateObject(mediaTypeId, selectedMediaItem, parentMediaItem);
            }

            Return canAccessReturnObj = BaseMapper.GenerateReturn();

            if (selectedItem.ID != 0)
            {
                canAccessReturnObj = MediaDetailsMapper.CanAccessMediaDetail(selectedItem, CurrentUser);
                if (canAccessReturnObj.IsError)
                {
                    DisplayErrorMessage("Cannot edit item", canAccessReturnObj.Error);

                    CanAccessItem = canAccessReturnObj;

                    return;
                }
                else
                {
                    KeyValuePair <IMediaDetail, User> checkedOutItem = IsCheckedOut(selectedItem);

                    if (checkedOutItem.Key == null)
                    {
                        CheckOut(selectedItem);
                    }
                    else
                    {
                        if (checkedOutItem.Value.ID != CurrentUser.ID)
                        {
                            Return returnObj = BaseMapper.GenerateReturn("Cannot edit item", "The item has been checked out by user: ( " + checkedOutItem.Value.UserName + " )");

                            CanAccessItem = returnObj;

                            DisplayErrorMessage("Error", returnObj.Error);

                            return;
                        }
                    }
                }
            }

            SelectedMediaDetail = selectedItem;
            SelectedMedia       = selectedMediaItem;

            if (selectedMediaItem == null)
            {
                SelectedMedia = parentMediaItem;
            }

            if (selectedItem.ID == 0)
            {
                Save.Text           = "Create";
                SaveAndPublish.Text = "Create And Publish";

                LoadLatestDraft.Visible = false;
                CreateDraft.Visible     = false;

                var mediaType = MediaTypesMapper.GetByID(selectedItem.MediaTypeID);

                if (mediaType == null)
                {
                    return;
                }

                selectedItem.MainLayout     = mediaType.MainLayout;
                selectedItem.SummaryLayout  = mediaType.SummaryLayout;
                selectedItem.FeaturedLayout = mediaType.FeaturedLayout;

                selectedItem.UseMediaTypeLayouts = mediaType.UseMediaTypeLayouts;

                var liveMediaDetail = selectedItem.Media?.GetLiveMediaDetail();

                if (liveMediaDetail != null)
                {
                    selectedItem.CopyFrom(liveMediaDetail);

                    var fieldsNotInMediaType = liveMediaDetail.Fields.Where(i => i.MediaTypeFieldID == null);

                    if (fieldsNotInMediaType != null)
                    {
                        foreach (var field in fieldsNotInMediaType)
                        {
                            var newField = new MediaDetailField();
                            newField.CopyFrom(field);

                            if (field.FieldAssociations.Count > 0)
                            {
                                newField.FieldValue = "";
                            }
                            else
                            {
                                newField.FieldValue = field.FieldValue;
                            }

                            newField.DateCreated      = DateTime.Now;
                            newField.DateLastModified = DateTime.Now;

                            selectedItem.Fields.Add(newField);
                        }
                    }

                    var fieldsThatCanBeCopied = liveMediaDetail.Fields.Where(i => !i.FieldAssociations.Any());

                    foreach (var field in fieldsThatCanBeCopied)
                    {
                        var foundField = selectedItem.Fields.FirstOrDefault(i => i.FieldCode == field.FieldCode);

                        if (foundField != null)
                        {
                            foundField.CopyFrom(field);
                        }
                    }
                }
            }
            else
            {
                Save.Text           = "Save Page";
                SaveAndPublish.Text = "Save And Publish";
            }

            if ((historyVersion > 0) && (historyVersionItem != null) && (!historyVersionItem.IsDraft))
            {
                //SavePanel.Visible = false;
            }
            else
            {
                var draftItems = selectedItem.History.Where(i => i.IsDraft);

                if (draftItems.Count() > 0)
                {
                    LoadLatestDraft.Visible = true;
                    CreateDraft.Visible     = false;
                }

                SaveAndPublish.Visible = true;
                SavePanel.Visible      = true;

                HistoryPanel.Visible = false;
            }

            if (historyVersion > 0)
            {
                SavePanel.Visible = true;

                if (!selectedItem.IsDraft)
                {
                    Save.Visible = false;
                }

                CreateDraft.Visible = false;
                PublishNow.Visible  = false;
                PublishLive.Visible = true;

                HistoryPanel.Visible      = true;
                HistoryVersionNumber.Text = historyVersion.ToString();
            }

            if (CurrentUser.IsInRole(RoleEnum.Developer))
            {
                EditMediaType.NavigateUrl = "~/Admin/Views/PageHandlers/MediaTypes/Detail.aspx?id=" + SelectedMediaDetail.MediaTypeID;
                EditMediaType.Visible     = true;
            }

            Panel.SetObject(SelectedMediaDetail);

            if (Request.QueryString["masterFilePath"] != null)
            {
                PreviewPanel.Visible             = false;
                RemovePreviewPanelScript.Visible = true;
            }
            else
            {
                PreviewPanel.Visible             = true;
                RemovePreviewPanelScript.Visible = false;
            }

            UpdateSectionTitles();
        }
            /// <summary>
            /// Insert new movies to database
            /// </summary>
            /// <returns></returns>
            public static async Task MoviesToDatabase()
            {
                await History.Create(History.Type.API, new History_API()
                {
                    api_action   = "Starting task -> Add movies to local Database",
                    api_datetime = DateTime.Now,
                    api_type     = "Task -> add movies to Db",
                });

                var list = new List <int>();

                //item1 = MovieData, item2 = Match
                foreach (var item in NewMovieEntry)
                {
                    try
                    {
                        //check if movie is already in database with this title and update values only for data not info!!
                        var Db_Movie = await Db.Movie_Data.Where(x => x.name == item.Item1.name).FirstOrDefaultAsync();

                        if (Db_Movie == null)
                        {
                            //get movieinfo from api
                            if (MoviesAPI.countAPICalls > 30)
                            {
                                await Task.Delay(5000); MoviesAPI.countAPICalls = 0;
                            }
                            //editMovieInfo, movie[0] is array from method GetMovieName
                            Movie_Info mInfo = await MoviesAPI.Get.Info(item.Item2, DatabaseMovieCount);

                            if (mInfo.id != null)
                            {
                                //tagline error in database has max length of 128 char in SQL
                                if (mInfo.tagline.Length > 128)
                                {
                                    mInfo.tagline = mInfo.tagline.Substring(0, 127);
                                }
                                item.Item1.Movie_Info = mInfo;

                                //set tick for movie length
                                item.Item1.Movie_Info.length = Media.Length(item.Item1);

                                try
                                {
                                    Db.Movie_Data.Add(item.Item1);
                                    await Db.SaveChangesAsync();

                                    //databaseMovieCount++;
                                    //temp.Add(mData);
                                    Movie_Data movie = Db.Movie_Data.Where(x => x.name == item.Item1.name).First();
                                    await History.Create(History.Type.API, new History_API()
                                    {
                                        api_action   = "Movie " + movie.Movie_Info.title + " was added to the database as id " + movie.Id + "!",
                                        api_datetime = DateTime.Now,
                                        api_type     = "Movie added to database",
                                    });

                                    list.Add(movie.Id);
                                }
                                catch (Exception ex)
                                {
                                    await History.Create(History.Type.API, new History_API()
                                    {
                                        api_action   = "Exception : Inserting movie to Database --> " + ex.Message,
                                        api_datetime = DateTime.Now,
                                        api_type     = "Exception thrown InsertMoviesToDb",
                                    });
                                }
                            }
                            else
                            {
                                await History.Create(History.Type.API, new History_API()
                                {
                                    api_action   = "Movie " + item.Item2.Groups["title"].ToString() + " was not added as there was a problem!",
                                    api_datetime = DateTime.Now,
                                    api_type     = "Error on movie addition",
                                });
                            }
                        }
                        else
                        {
                            //update movie info but only directory at which the movie is located
                            await History.Create(History.Type.API, new History_API()
                            {
                                api_action   = "Movie update -> Updating movie: " + Db_Movie.name + " directory!",
                                api_datetime = DateTime.Now,
                                api_type     = "Task -> update movie data / info in SQL...",
                            });

                            if (await Database.Movie.Update.Directory(Db_Movie, item.Item1))
                            {
                                await History.Create(History.Type.API, new History_API()
                                {
                                    api_action   = "Movie update -> Succesfully updated movie: " + Db_Movie.name + " directory!",
                                    api_datetime = DateTime.Now,
                                    api_type     = "Task -> Success",
                                });
                            }
                            else
                            {
                                await History.Create(History.Type.API, new History_API()
                                {
                                    api_action   = "Movie update -> Failed to update movie: " + Db_Movie.name + " directory!",
                                    api_datetime = DateTime.Now,
                                    api_type     = "Task -> Failed",
                                });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        await History.Create(History.Type.API, new History_API()
                        {
                            api_action   = "Error -> An error occured : " + ex.Message,
                            api_datetime = DateTime.Now,
                            api_type     = "Error occured on InsertMoviesToDb",
                        });
                    }
                }
                await History.Create(History.Type.API, new History_API()
                {
                    api_action   = "End of import of movies.",
                    api_datetime = DateTime.Now,
                    api_type     = "Status -> InsertMoviesToDb",
                });

                History_API hapi;

                if (list.Count == NewMovieEntry.Count)
                {
                    hapi = new History_API()
                    {
                        api_type     = "Movie to Db status",
                        api_datetime = DateTime.Now,
                        api_action   = "Info -> All movies added (" + list.Count + " - ADDED)",
                    };
                }
                else if (list.Count < NewMovieEntry.Count)
                {
                    hapi = new History_API()
                    {
                        api_type     = "Movie to Db status",
                        api_datetime = DateTime.Now,
                        api_action   = "Error -> Less movies added than found on local storage! Movies added " + list.Count,
                    };
                }
                else
                {
                    hapi = new History_API()
                    {
                        api_type     = "Movie to Db status",
                        api_datetime = DateTime.Now,
                        api_action   = "Error -> Something went wrong with importing data to Db! Movies added " + list.Count,
                    };
                }
                if (hapi != null)
                {
                    await History.Create(History.Type.API, hapi);
                }
            }
Exemple #35
0
 public bool SetMedia(Media models)
 {
     throw new NotImplementedException();
 }
Exemple #36
0
 protected virtual void ClearNavigationProperties()
 {
     Media.Clear();
 }
        /// <summary>
        /// Handles the PreviewKeyDown event of the MainWindow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
        private async void OnWindowKeyDown(object sender, KeyEventArgs e)
        {
            // Console.WriteLine($"KEY: {e.Key}, SRC: {e.OriginalSource?.GetType().Name}");
            if (e.OriginalSource is TextBox)
            {
                return;
            }

            // Keep the key focus on the main window
            FocusManager.SetIsFocusScope(this, true);
            FocusManager.SetFocusedElement(this, this);

            if (e.Key == Key.G)
            {
                // Example of toggling subtitle color
                if (Subtitles.GetForeground(Media) == Brushes.LightYellow)
                {
                    Subtitles.SetForeground(Media, Brushes.Yellow);
                }
                else
                {
                    Subtitles.SetForeground(Media, Brushes.LightYellow);
                }

                return;
            }

            // Pause
            if (TogglePlayPauseKeys.Contains(e.Key) && Media.IsPlaying)
            {
                await App.Current.Commands.PauseCommand.ExecuteAsync();

                return;
            }

            // Play
            if (TogglePlayPauseKeys.Contains(e.Key) && Media.IsPlaying == false)
            {
                await App.Current.Commands.PlayCommand.ExecuteAsync();

                return;
            }

            // Seek to left
            if (e.Key == Key.Left)
            {
                if (Media.IsPlaying)
                {
                    await Media.Pause();
                }
                Media.Position -= TimeSpan.FromMilliseconds(
                    Media.FrameStepDuration.TotalMilliseconds * (Media.SpeedRatio >= 1 ? Media.SpeedRatio : 1));

                return;
            }

            // Seek to right
            if (e.Key == Key.Right)
            {
                if (Media.IsPlaying)
                {
                    await Media.Pause();
                }
                Media.Position += TimeSpan.FromMilliseconds(
                    Media.FrameStepDuration.TotalMilliseconds * (Media.SpeedRatio >= 1 ? Media.SpeedRatio : 1));

                return;
            }

            // Volume Up
            if (e.Key == Key.Add || e.Key == Key.VolumeUp)
            {
                Media.Volume += 0.05;
                return;
            }

            // Volume Down
            if (e.Key == Key.Subtract || e.Key == Key.VolumeDown)
            {
                Media.Volume -= 0.05;
                return;
            }

            // Mute/Unmute
            if (e.Key == Key.M || e.Key == Key.VolumeMute)
            {
                Media.IsMuted = !Media.IsMuted;
                return;
            }

            // Increase speed
            if (e.Key == Key.Up)
            {
                Media.SpeedRatio += 0.05;
                return;
            }

            // Decrease speed
            if (e.Key == Key.Down)
            {
                Media.SpeedRatio -= 0.05;
                return;
            }

            // Reset changes
            if (e.Key == Key.R)
            {
                Media.SpeedRatio = 1.0;
                Media.Volume     = 1.0;
                Media.Balance    = 0;
                Media.IsMuted    = false;
                ViewModel.Controller.MediaElementZoom = 1.0;
                return;
            }

            // Exit fullscreen
            if (e.Key == Key.Escape && WindowStyle == WindowStyle.None)
            {
                await App.Current.Commands.ToggleFullscreenCommand.ExecuteAsync();

                return;
            }
        }
Exemple #38
0
        private static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            //先行処理
            DX.SetOutApplicationLogValidFlag(DX.FALSE);

            //メインウィンドウ起動準備
            wnd       = new MainWindow();
            Media.GGS = GuruGuruSmf.Ggs4Dll.GetInstance();
            Media.GGS.OpenDevice(GuruGuruSmf.Device.DirectMusic, wnd.Handle);

            //実際には描画しないコントロールをセットした状態でDXライブラリを初期化しないと色々不具合が起きる
            //	1. 描画先を変更したときに2回目だけ反映されない(ただし、DXライブラリ側によって解決済み)
            //	2. 最初にセットしたコントロールのサイズが変わると、描画結果が元のサイズから拡大縮小されたものになってしまう
            Media.Init(wnd.pnlDefaultDrawTarget.Handle);

            wnd.SplashCloseFlag = true;

            //コマンドライン引数にプロジェクトファイルが指定されている場合はそれを開く
            ProjectManager project = null;

            if (args.Length > 0 && File.Exists(args[0]))
            {
                var pPath = Path.GetDirectoryName(Path.GetDirectoryName(args[0]));
                project = new ProjectManager(wnd, pPath);
                project = ProjectManager.LoadProjectFile(project);
            }
            else
            {
                //前に開いたプロジェクトを開く?
                if (string.IsNullOrEmpty(Settings.Default.Last_ProjectPath) == false &&
                    ProjectManager.CheckProjectInfo(Settings.Default.Last_ProjectPath))
                {
                    if (MessageBox.Show("前回開いたプロジェクトを開きますか?", Resources.AppName, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification) == DialogResult.Yes)
                    {
                        project = new ProjectManager(wnd, Settings.Default.Last_ProjectPath);
                        project = ProjectManager.LoadProjectFile(project);
                    }
                }
            }
            if (project == null)
            {
                //プロジェクトオープンできず
                Application.Exit();
            }
            wnd.Project = project;

            //内部ログを初期化
            var errorLogBuffer = new StringBuilder();

            //ハンドルされない例外が発生したときの処理: 再開可能
            Application.ThreadException += (sender, e) => {
                //内部ログへスタックトレースと例外メッセージを書き込む
                addErrorLog(errorLogBuffer, e.Exception);

                MessageBox.Show("予期せぬエラーが発生しました。\r\nこのエラーが何度も発生するときは、プログラム終了後に出力されるログを作者までご送付下さい。", Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            };

            //ハンドルされない例外が発生したときの処理: 再開不可
            AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
                //内部ログへスタックトレースと例外メッセージを書き込む
                errorLogBuffer.Append("\r\n" + DateTime.Now.ToString(Common.DateFormat) + "\r\n");

                var ex = (e.ExceptionObject as Exception);
                if (ex != null)
                {
                    addErrorLog(errorLogBuffer, ex);
                }
                else
                {
                    errorLogBuffer.Append("(原因不明のエラーが発生しました)\r\n\r\n");
                    errorLogBuffer.Append("---------------------------------------------------------\r\n");
                }

                MessageBox.Show("予期せぬエラーが発生したため、" + Resources.AppName + "を終了します。\r\nこのエラーが何度も発生するときは、プログラム終了後に出力されるログを作者までご送付下さい。", Resources.AppName, MessageBoxButtons.OK, e.IsTerminating ? MessageBoxIcon.Error : MessageBoxIcon.Warning);
            };

            //メインウィンドウ立ち上げ
            Application.Run(wnd);

            if (errorLogBuffer.Length == 0)
            {
                //ログがないときはそのまま終了
                return;
            }

            //ログが出力されているときは書き出す
            try {
                File.WriteAllText(
                    Application.StartupPath + "\\" + DateTime.Now.ToString("yy-MM-dd HH-mm-ss") + " - " + Environment.UserName + ".log",
                    errorLogBuffer.ToString(),
                    Common.SJIS
                    );
            } catch (Exception e) {
                MessageBox.Show("ログの書き出しに失敗しました。\r\n\r\n" + e.Message, Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private string formatMedia(string html)
        {
            // Local media path
            string localMediaPath = IOHelper.ResolveUrl(SystemDirectories.Media);

            // Find all media images
            string pattern = String.Format("<img [^>]*src=\"(?<mediaString>{0}[^\"]*)\" [^>]*>", SystemDirectories.Media);

            MatchCollection tags =
                Regex.Matches(html, pattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

            foreach (Match tag in tags)
            {
                if (tag.Groups.Count > 0)
                {
                    // Replace /> to ensure we're in old-school html mode
                    string tempTag = "<img";
                    string orgSrc  = tag.Groups["mediaString"].Value;

                    // gather all attributes
                    // TODO: This should be replaced with a general helper method - but for now we'll wanna leave umbraco.dll alone for this patch
                    Hashtable       ht = new Hashtable();
                    MatchCollection m  =
                        Regex.Matches(tag.Value.Replace(">", " >"),
                                      "(?<attributeName>\\S*)=\"(?<attributeValue>[^\"]*)\"|(?<attributeName>\\S*)=(?<attributeValue>[^\"|\\s]*)\\s",
                                      RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
                    foreach (Match attributeSet in m)
                    {
                        if (attributeSet.Groups["attributeName"].Value.ToString().ToLower() != "src")
                        {
                            ht.Add(attributeSet.Groups["attributeName"].Value.ToString(),
                                   attributeSet.Groups["attributeValue"].Value.ToString());
                        }
                    }

                    // build the element
                    // Build image tag
                    IDictionaryEnumerator ide = ht.GetEnumerator();
                    while (ide.MoveNext())
                    {
                        tempTag += " " + ide.Key.ToString() + "=\"" + ide.Value.ToString() + "\"";
                    }

                    // Find the original filename, by removing the might added width and height
                    orgSrc =
                        IOHelper.ResolveUrl(orgSrc.Replace(
                                                "_" + helper.FindAttribute(ht, "width") + "x" + helper.FindAttribute(ht, "height"), "").
                                            Replace("%20", " "));

                    // Check for either id or guid from media
                    string mediaId = getIdFromSource(orgSrc, localMediaPath);

                    Media imageMedia = null;

                    try
                    {
                        int      mId = int.Parse(mediaId);
                        Property p   = new Property(mId);
                        imageMedia = new Media(Content.GetContentFromVersion(p.VersionId).Id);
                    }
                    catch
                    {
                        try
                        {
                            imageMedia = new Media(Content.GetContentFromVersion(new Guid(mediaId)).Id);
                        }
                        catch
                        {
                        }
                    }

                    // Check with the database if any media matches this url
                    if (imageMedia != null)
                    {
                        try
                        {
                            // Check extention
                            if (imageMedia.getProperty("umbracoExtension").Value.ToString() != orgSrc.Substring(orgSrc.LastIndexOf(".") + 1, orgSrc.Length - orgSrc.LastIndexOf(".") - 1))
                            {
                                orgSrc = orgSrc.Substring(0, orgSrc.LastIndexOf(".") + 1) +
                                         imageMedia.getProperty("umbracoExtension").Value.ToString();
                            }

                            // Format the tag
                            tempTag = tempTag + " rel=\"" +
                                      imageMedia.getProperty("umbracoWidth").Value.ToString() + "," +
                                      imageMedia.getProperty("umbracoHeight").Value.ToString() + "\" src=\"" + orgSrc +
                                      "\"";
                            tempTag += "/>";

                            // Replace the tag
                            html = html.Replace(tag.Value, tempTag);
                        }
                        catch (Exception ee)
                        {
                            Log.Add(LogTypes.Error, User.GetUser(0), -1,
                                    "Error reading size data from media: " + imageMedia.Id.ToString() + ", " +
                                    ee.ToString());
                        }
                    }
                    else
                    {
                        Log.Add(LogTypes.Error, User.GetUser(0), -1,
                                "Error reading size data from media (not found): " + orgSrc);
                    }
                }
            }
            return(html);
        }
Exemple #40
0
 public bool UpdateMedia(Media oldMedia, Media newMedia, List <Person> people, List <CustomAttributes> customAttributes)
 {
     return(API.updateMediaInDatabase(oldMedia, newMedia, people, customAttributes));
 }
Exemple #41
0
 public int DeleteMedia(Media media)
 {
     return(API.removeMediaFromDatabase(media));
 }
Exemple #42
0
 public bool AddMedia(Media media, List <Person> people, List <CustomAttributes> customAttributes)
 {
     return(API.addMediaToDatabase(media, people, customAttributes));
 }
Exemple #43
0
 internal override Boolean IsValid(RenderDevice device)
 {
     return(Media.Validate(device));
 }
Exemple #44
0
        public async Task <Media> SaveMediaAsync(Stream mediaBinaryStream, string fileName, string mimeType = null)
        {
            var bytes = new byte[mediaBinaryStream.Length];

            using (mediaBinaryStream)
            {
                mediaBinaryStream.Read(bytes, 0, bytes.Length);
            }
            var hsMd5 = Md5Helper.Encrypt(bytes);
            var media = await _mediaRepository.Query(c => c.Md5 == hsMd5).FirstOrDefaultAsync();

            if (media != null)
            {
                return(media);
            }

            var result = await Task.Run(() =>
            {
                return(Upload(bytes, hsMd5, fileName));
            });

            if (result?.Data == null)
            {
                return(null);
            }
            var cusDomain = await _appSettingService.Get <StorageSmOptions>();

            var url = result.Data.Url;

            if (!string.IsNullOrWhiteSpace(cusDomain?.CustomDomain))
            {
                url = $"{cusDomain.CustomDomain.Trim('/')}/{result.Data.Path.Trim('/')}";
            }
            media = new Media()
            {
                MediaType = MediaType.File,
                FileName  = result.Data.Filename,
                FileSize  = result.Data.Size,
                Hash      = result.Data.Hash,
                Url       = url,
                Path      = result.Data.Path,
                Host      = StorageSmKeys.Host,
                Md5       = hsMd5
            };
            if (!string.IsNullOrWhiteSpace(mimeType))
            {
                mimeType = mimeType.Trim().ToLower();
                if (mimeType.StartsWith("video"))
                {
                    media.MediaType = MediaType.Video;
                }
                else if (mimeType.StartsWith("image"))
                {
                    media.MediaType = MediaType.Image;
                }
                else
                {
                    media.MediaType = MediaType.File;
                }
            }
            _mediaRepository.Add(media);
            await _mediaRepository.SaveChangesAsync();

            return(media);
        }
Exemple #45
0
        //private void ChangeLinksForAllMediaDetails(string oldAbsoluteUrl, string newAbsoluteUrl)
        //{
        //    if (string.IsNullOrEmpty(oldAbsoluteUrl) || oldAbsoluteUrl == newAbsoluteUrl)
        //        return;

        //    var oldTemplateVarUrl = ParserHelper.ParseData(oldAbsoluteUrl, this.TemplateVars, true);
        //    var newTemplateVarUrl = ParserHelper.ParseData(newAbsoluteUrl, this.TemplateVars, true);

        //    var foundItems = MediaDetailsMapper.GetDataModel().MediaDetails.Where(i => i.MainContent.Contains(oldTemplateVarUrl) || i.ShortDescription.Contains(oldTemplateVarUrl));

        //    if (foundItems.Any())
        //    {
        //        foreach (var item in foundItems)
        //        {
        //            item.ShortDescription = item.ShortDescription.Replace(oldTemplateVarUrl, newTemplateVarUrl);
        //            item.MainContent = item.MainContent.Replace(oldTemplateVarUrl, newTemplateVarUrl);
        //        }

        //        var numberOfItemsEffected = MediaDetailsMapper.GetDataModel().SaveChanges();
        //    }
        //}

        protected void Save_OnClick(object sender, EventArgs e)
        {
            if (CanAccessItem != null && CanAccessItem.IsError)
            {
                DisplayErrorMessage("Error saving item", CanAccessItem.Error);
                return;
            }

            if (!CurrentUser.HasPermission(PermissionsEnum.Publish))
            {
                DisplayErrorMessage("Error saving item", ErrorHelper.CreateError(new Exception("You do not have the appropriate permissions to save items")));
                return;
            }

            string commandArgument = ((LinkButton)sender).CommandArgument;

            bool isDraft = false;

            if (commandArgument == "CreateDraft")
            {
                isDraft = true;
            }

            IMediaDetail history = CreateHistory(isDraft);

            Return returnObj = BaseMapper.GenerateReturn();

            if ((history != null) && (history.IsDraft))
            {
                history.CopyFrom(selectedItem);
                UpdateObjectFromFields(history);
                history.IsDraft = isDraft;

                returnObj = SaveHistory(history);

                if (returnObj.IsError)
                {
                    DisplayErrorMessage("Error Saving Item", returnObj.Error);
                }
                else
                {
                    DisplaySuccessMessage("Successfully Saved Item as Draft");

                    UpdateFieldsFromObject();
                }

                RedirectToAdminUrl(selectedItem, history.HistoryVersionNumber);

                return;
            }

            var tmpSelectedItem = BaseMapper.GetObjectFromContext((MediaDetail)selectedItem);

            if (tmpSelectedItem != null)
            {
                selectedItem = tmpSelectedItem;
            }

            if (parentMediaItem != null)
            {
                parentMediaItem = BaseMapper.GetObjectFromContext(parentMediaItem);
            }
            else
            {
                parentMediaItem = selectedItem?.Media?.ParentMedia;
            }

            if (selectedItem == null)
            {
                selectedItem = MediaDetailsMapper.CreateObject(mediaTypeId, selectedMediaItem, parentMediaItem);
            }

            var oldLinkTitle       = selectedItem.LinkTitle;
            var oldVirtualPath     = selectedItem.VirtualPath;
            var canRender          = selectedItem.CanRender;
            var oldAbsoluteUrl     = selectedItem.AbsoluteUrl;
            var oldPostPublishDate = selectedItem.PublishDate;

            UpdateObjectFromFields(selectedItem);

            var validate = selectedItem.Validate();

            if (validate.IsError)
            {
                DisplayErrorMessage("Error saving item", validate.Error);
                return;
            }

            if ((oldPostPublishDate != selectedItem.PublishDate) && !CurrentUser.HasPermission(PermissionsEnum.Publish))
            {
                DisplayErrorMessage("Error saving item", ErrorHelper.CreateError(new Exception("You do not have the appropriate permissions to publish items")));
                return;
            }

            if (selectedItem.ID == 0)
            {
                selectedItem.CreatedByUserID = CurrentUser.ID;

                if ((parentMediaItem != null) && (selectedItem.Media.ID == 0))
                {
                    selectedItem.Media.OrderIndex = parentMediaItem.ChildMedias.Count(i => i.ID != 0);
                }


                returnObj = MediaDetailsMapper.Insert(selectedItem);

                if (!returnObj.IsError)
                {
                    ContextHelper.Clear(ContextType.Cache);
                    FileCacheHelper.ClearAllCache();
                }
                else
                {
                    DisplayErrorMessage("Error", returnObj.Error);
                }
            }
            else
            {
                if (!isDraft)
                {
                    if (history != null)
                    {
                        returnObj = SaveHistory(history);
                    }

                    //selectedItem.Media.ReorderChildren();

                    if (!returnObj.IsError)
                    {
                        returnObj = MediaDetailsMapper.Update(selectedItem);
                    }
                }
            }

            if (returnObj.IsError)
            {
                DisplayErrorMessage("Error Saving Item", returnObj.Error);
            }
            else
            {
                if (history != null)
                {
                    selectedItem.History.Add((MediaDetail)history);
                    Return historyReturnObj = MediaDetailsMapper.Update(selectedItem);
                }

                selectedItem.RemoveFromCache();
                FileCacheHelper.DeleteGenerateNavCache();

                if (oldVirtualPath != selectedItem.VirtualPath || canRender != selectedItem.CanRender || oldLinkTitle != selectedItem.LinkTitle)
                {
                    ContextHelper.Clear(ContextType.Cache);
                    //FileCacheHelper.ClearCacheDir("generatenav");

                    //FileCacheHelper.ClearAllCache();

                    selectedItem.ClearAutoCalculatedVirtualPathCache();

                    if (commandArgument == "SaveAndPublish")
                    {
                        PublishNow_OnClick(sender, e);
                        //RedirectToMediaDetail(mediaTypeEnum, selectedItem.MediaID, selectedItem.Media.ParentMediaID);
                    }
                    else
                    {
                        RedirectToAdminUrl(selectedItem.MediaTypeID, selectedItem.MediaID, selectedItem.Media.ParentMediaID);
                    }

                    //ChangeLinksForAllMediaDetails(oldAbsoluteUrl, selectedItem.AbsoluteUrl);
                }

                DisplaySuccessMessage("Successfully Saved Item");

                ExecuteRawJS("ReloadPreviewPanel()");

                if (!selectedItem.IsHistory)
                {
                    SelectedMediaDetail = selectedItem;
                    SelectedMedia       = MediasMapper.GetByID(selectedItem.MediaID);
                }

                if (((Request["selectedMediaId"] == null) || (Request["selectedMediaId"].ToString() == "0")) && (commandArgument != "SaveAndPublish"))
                {
                    RedirectToAdminUrl(selectedItem.MediaTypeID, selectedItem.MediaID, selectedItem.Media.ParentMediaID);
                }
                else
                {
                    if (commandArgument == "SaveAndPublish")
                    {
                        PublishNow_OnClick(sender, e);
                        //RedirectToMediaDetail(mediaTypeEnum, selectedItem.MediaID, selectedItem.Media.ParentMediaID);
                    }

                    UpdateFieldsFromObject();

                    /*else
                     *  Response.Redirect(Request.Url.AbsoluteUri);*/

                    //UpdateFieldsFromObject();
                    //RedirectToMediaDetail(mediaTypeEnum, selectedItem.MediaID, selectedItem.Media.ParentMediaID);
                }
            }
        }
Exemple #46
0
        public void Play(string Path)
        {
            Media media = new Media(libvlc, Path);

            mediaplayer.Play(media);
        }
Exemple #47
0
 public static bool CanPlay(Media media)
 {
     return(media is Music && (media as Music).MusicFiles.Count() == 1);
 }
Exemple #48
0
 public int Edit(Media media)
 {
     context.Media.Update(media);
     return(context.SaveChanges());
 }
Exemple #49
0
 public PlayableMusicFile(Media media)
     : base()
 {
     this.music = media as Music;
     this.path  = music.MusicFiles.First();
 }
Exemple #50
0
 public int Add(Media media)
 {
     context.Media.Add(media);
     return(context.SaveChanges());
 }
Exemple #51
0
 public bool EditMedia(Media modelEdit)
 {
     throw new NotImplementedException();
 }
Exemple #52
0
        public static bool ReadMediaInfo(string fileNameFull, bool forceRefresh, ref MediaInfoResult info)
        {
            try
            {
                if (!forceRefresh)
                {
                    // if we have populated the full info, we have already read the data
                    if (!string.IsNullOrEmpty(info.FullInfo))
                    {
                        return(false);
                    }
                }
                Media m = PlexMediaInfo.MediaConvert.Convert(fileNameFull);
                if (m != null)
                {
                    string xml = XmlSerializeToString(m);
                    if (!string.IsNullOrEmpty(m.Width) && !string.IsNullOrEmpty(m.Height))
                    {
                        info.VideoResolution = m.Width + "x" + m.Height;
                    }
                    if (!string.IsNullOrEmpty(m.VideoCodec))
                    {
                        info.VideoCodec = m.VideoCodec;
                    }
                    if (!string.IsNullOrEmpty(m.AudioCodec))
                    {
                        info.AudioCodec = m.AudioCodec;
                    }
                    if (!string.IsNullOrEmpty(m.Duration))
                    {
                        info.Duration = int.Parse(m.Duration);
                    }
                    List <JMMContracts.PlexContracts.Stream> vparts = m.Parts[0].Streams.Where(a => a.StreamType == "1").ToList();
                    if (vparts.Count > 0)
                    {
                        if (!string.IsNullOrEmpty(vparts[0].Bitrate))
                        {
                            info.VideoBitrate = vparts[0].Bitrate;
                        }
                        if (!string.IsNullOrEmpty(vparts[0].BitDepth))
                        {
                            info.VideoBitDepth = vparts[0].BitDepth;
                        }
                        if (!string.IsNullOrEmpty(vparts[0].FrameRate))
                        {
                            info.VideoFrameRate = vparts[0].FrameRate;
                        }
                    }
                    List <JMMContracts.PlexContracts.Stream> aparts = m.Parts[0].Streams.Where(a => a.StreamType == "2").ToList();
                    if (aparts.Count > 0)
                    {
                        if (!string.IsNullOrEmpty(aparts[0].Bitrate))
                        {
                            info.AudioBitrate = aparts[0].Bitrate;
                        }
                    }
                    info.FullInfo = xml;
                }
                else
                {
                    logger.Error("ERROR getting media info:: {0}", fileNameFull);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error reading Media Info for: {0} --- {1}", fileNameFull, ex.ToString());
            }

            return(true);
        }
Exemple #53
0
        public bool RefreshMediaInfo()
        {
            try
            {
                logger.Trace("Getting media info for: {0}", FullServerPath ?? VideoLocal_Place_ID.ToString());
                Media m = null;
                List <Azure_Media> webmedias = AzureWebAPI.Get_Media(VideoLocal.ED2KHash);
                if (webmedias != null && webmedias.Count > 0 && webmedias.FirstOrDefault(a => a != null) != null)
                {
                    m = webmedias.FirstOrDefault(a => a != null).ToMedia();
                }
                if (m == null && FullServerPath != null)
                {
                    string name = (ImportFolder?.CloudID == null)
                        ? FullServerPath.Replace("/", "\\")
                        : ((IProvider)null).ReplaceSchemeHost(((IProvider)null).ConstructVideoLocalStream(0,
                                                                                                          VideoLocalID.ToString(), "file", false));
                    m = MediaConvert.Convert(name, GetFile()); //Mediainfo should have libcurl.dll for http
                    if (string.IsNullOrEmpty(m?.Duration))
                    {
                        m = null;
                    }
                    if (m != null)
                    {
                        AzureWebAPI.Send_Media(VideoLocal.ED2KHash, m);
                    }
                }


                if (m != null)
                {
                    SVR_VideoLocal info = VideoLocal;
                    FillVideoInfoFromMedia(info, m);

                    m.Id = VideoLocalID.ToString();
                    List <Stream> subs = SubtitleHelper.GetSubtitleStreams(this);
                    if (subs.Count > 0)
                    {
                        m.Parts[0].Streams.AddRange(subs);
                    }
                    foreach (Part p in m.Parts)
                    {
                        p.Id         = null;
                        p.Accessible = "1";
                        p.Exists     = "1";
                        bool vid = false;
                        bool aud = false;
                        bool txt = false;
                        foreach (Stream ss in p.Streams.ToArray())
                        {
                            if (ss.StreamType == "1" && !vid)
                            {
                                vid = true;
                            }
                            if (ss.StreamType == "2" && !aud)
                            {
                                aud         = true;
                                ss.Selected = "1";
                            }
                            if (ss.StreamType == "3" && !txt)
                            {
                                txt         = true;
                                ss.Selected = "1";
                            }
                        }
                    }
                    info.Media = m;
                    return(true);
                }
                logger.Error($"File {FullServerPath ?? VideoLocal_Place_ID.ToString()} does not exist, unable to read media information from it");
            }
            catch (Exception e)
            {
                logger.Error($"Unable to read the media information of file {FullServerPath ?? VideoLocal_Place_ID.ToString()} ERROR: {e}");
            }
            return(false);
        }
Exemple #54
0
 public void CollectContractMemory()
 {
     _media = null;
 }
Exemple #55
0
 private void RightSwap_MouseEnter(object sender, MouseEventArgs e)
 {
     Media.Pause();
 }
        private async void OnSourceChanged()
        {
            if (Instance == null || DesignMode.DesignModeEnabled)
            {
                return;
            }

            using (await SourceChangedMutex.LockAsync())
            {
                Stop();
                TransportControls?.Clear();

                var source = Source;
                if (source == null)
                {
                    await ClearMedia();

                    return;
                }

                FromType type;
                if (!Uri.TryCreate(source, UriKind.RelativeOrAbsolute, out Uri location) || location.IsAbsoluteUri && !location.IsFile)
                {
                    type = FromType.FromLocation;
                }
                else
                {
                    if (!location.IsAbsoluteUri)
                    {
                        source = Path.Combine(Package.Current.InstalledLocation.Path, source);
                    }
                    type = FromType.FromPath;
                }
                var media = new Media(Instance, source, type);
                media.addOption($":avcodec-hw={(HardwareAcceleration ? "d3d11va" : "none")}");
                media.addOption($":avcodec-threads={Convert.ToInt32(HardwareAcceleration)}");
                var options = Options;
                if (options != null)
                {
                    foreach (var option in options)
                    {
                        media.addOption($":{option.Key}={option.Value}");
                    }
                }
                Media = media;

                var mediaPlayer  = new MediaPlayer(media);
                var eventManager = mediaPlayer.eventManager();
                eventManager.OnBuffering += async p => await UpdateState(MediaElementState.Buffering);

                eventManager.OnOpening += async() => await UpdateState(MediaElementState.Opening);

                eventManager.OnPlaying += async() => await UpdateState(MediaElementState.Playing);

                eventManager.OnPaused += async() => await UpdateState(MediaElementState.Paused);

                eventManager.OnStopped += async() => await UpdateState(MediaElementState.Stopped);

                eventManager.OnEndReached       += async() => { await ClearMedia(); await UpdateState(MediaElementState.Closed); };
                eventManager.OnPositionChanged  += EventManager_OnPositionChanged;
                eventManager.OnVoutCountChanged += async p => await DispatcherRunAsync(async() => { await UpdateZoom(); });

                eventManager.OnTrackAdded   += EventManager_OnTrackAdded;
                eventManager.OnTrackDeleted += async(trackType, trackId) => await DispatcherRunAsync(() => TransportControls?.OnTrackDeleted(trackType, trackId));

                eventManager.OnLengthChanged += async length => await DispatcherRunAsync(() => TransportControls?.OnLengthChanged(length));

                eventManager.OnTimeChanged     += EventManager_OnTimeChanged;
                eventManager.OnSeekableChanged += async seekable => await DispatcherRunAsync(() => TransportControls?.OnSeekableChanged(seekable));

                MediaPlayer = mediaPlayer;

                SetAudioDevice();
                SetDeinterlaceMode();

                if (AutoPlay)
                {
                    Play();
                }
            }
        }
Exemple #57
0
        public void ProcessUploadRequest(HttpContext context, XmlTextWriter xmlTextWriter)
        {
            int parentNodeId;

            if (int.TryParse(context.Request["parentNodeId"], out parentNodeId) && context.Request.Files.Count > 0)
            {
                try
                {
                    // Check Path
                    if (!string.IsNullOrEmpty(context.Request["path"]))
                    {
                        var pathParts = context.Request["path"].Trim('/').Split('/');

                        var parentNode = new Media(parentNodeId);
                        foreach (var pathPart in pathParts)
                        {
                            if (!string.IsNullOrEmpty(pathPart))
                            {
                                parentNode = GetOrCreateFolder(parentNode, pathPart);
                            }
                        }
                        parentNodeId = parentNode.Id;
                    }

                    // Check whether to replace existing
                    bool replaceExisting = (context.Request["replaceExisting"] == "1");

                    // loop through uploaded files
                    for (var j = 0; j < context.Request.Files.Count; j++)
                    {
                        // get the current file
                        var uploadFile = context.Request.Files[j];

                        // if there was a file uploded
                        if (uploadFile.ContentLength > 0)
                        {
                            var postedMediaFile = new PostedMediaFile
                            {
                                FileName      = uploadFile.FileName,
                                ContentType   = uploadFile.ContentType,
                                ContentLength = uploadFile.ContentLength,
                                InputStream   = uploadFile.InputStream
                            };

                            // Get concrete MediaFactory
                            var factory = MediaFactory.GetMediaFactory(parentNodeId, postedMediaFile, AuthenticatedUser);

                            // Handle media Item
                            var media = factory.HandleMedia(parentNodeId, postedMediaFile, AuthenticatedUser, replaceExisting);
                        }
                    }

                    // log succes
                    Log.Add(LogTypes.New, parentNodeId, "Succes");
                }
                catch (Exception e)
                {
                    // log error
                    Log.Add(LogTypes.Error, parentNodeId, e.ToString());
                }
            }
            else
            {
                // log error
                Log.Add(LogTypes.Error, -1, "Parent node id is in incorrect format");
            }
        }
        public LoadIngamePlayerOrObserverUILogic(Widget widget, World world)
        {
            var ingameRoot = widget.Get("INGAME_ROOT");
            var worldRoot  = ingameRoot.Get("WORLD_ROOT");
            var menuRoot   = ingameRoot.Get("MENU_ROOT");
            var playerRoot = worldRoot.Get("PLAYER_ROOT");

            if (world.LocalPlayer == null)
            {
                Game.LoadWidget(world, "OBSERVER_WIDGETS", playerRoot, new WidgetArgs());
            }
            else
            {
                var playerWidgets = Game.LoadWidget(world, "PLAYER_WIDGETS", playerRoot, new WidgetArgs());
                var sidebarTicker = playerWidgets.Get <LogicTickerWidget>("SIDEBAR_TICKER");
                var objectives    = world.LocalPlayer.PlayerActor.Info.TraitInfoOrDefault <MissionObjectivesInfo>();

                sidebarTicker.OnTick = () =>
                {
                    // Switch to observer mode after win/loss
                    if (world.LocalPlayer.WinState != WinState.Undefined && !loadingObserverWidgets)
                    {
                        loadingObserverWidgets = true;
                        Game.RunAfterDelay(objectives != null ? objectives.GameOverDelay : 0, () =>
                        {
                            if (!Game.IsCurrentWorld(world))
                            {
                                return;
                            }

                            playerRoot.RemoveChildren();
                            Game.LoadWidget(world, "OBSERVER_WIDGETS", playerRoot, new WidgetArgs());
                        });
                    }
                };
            }

            Game.LoadWidget(world, "CHAT_PANEL", worldRoot, new WidgetArgs());

            world.GameOver += () =>
            {
                Ui.CloseWindow();
                menuRoot.RemoveChildren();

                if (world.LocalPlayer != null)
                {
                    var scriptContext = world.WorldActor.TraitOrDefault <LuaScript>();
                    var video         = world.LocalPlayer.WinState == WinState.Won ? world.Map.Videos.GameWon : world.Map.Videos.GameLost;

                    if (!string.IsNullOrEmpty(video) && !(scriptContext != null && scriptContext.FatalErrorOccurred))
                    {
                        Media.PlayFMVFullscreen(world, video, () => { });
                    }
                }

                var optionsButton = playerRoot.GetOrNull <MenuButtonWidget>("OPTIONS_BUTTON");
                if (optionsButton != null)
                {
                    optionsButton.OnClick();
                }
            };
        }
        protected override bool DoProcessRequest(HttpContext context, MediaRequest request, Media media)
        {
            if (context?.Request.QueryString?["extension"] == "webp" || (!Helpers.CdnEnabled && context.BrowserSupportsWebP()))
            {
                request.Options.CustomOptions["extension"] = "webp";
            }

            return(base.DoProcessRequest(context, request, media));
        }
Exemple #60
0
    IEnumerator makeWorldFromMarathonMap(Weland.Level Level)
    {
        string load = loadingText;

        //marathon maps have y +/- directions swapped so fix that
        for (int i = 0; i < Level.Endpoints.Count; i++)
        {
            Level.Endpoints[i] = new Point(Level.Endpoints[i].X, (short)(0 - Level.Endpoints[i].Y));
        }
        //now we can generate mapsegment objects from each map polygon
        for (int p = 0; p < Level.Polygons.Count; p++)
        {
            GameObject pol = Instantiate(polygon);
            pol.name = "Polygon" + p;
            pol.tag  = "polygon";
            MapSegment seg = pol.GetComponent <MapSegment>();
            segments.Add(seg);
            seg.height = new Vector3(0, (float)(Level.Polygons[p].CeilingHeight - Level.Polygons[p].FloorHeight) / 1024f, 0);
            if (Level.Polygons[p].Type == Weland.PolygonType.Platform)
            {
                foreach (Weland.Platform pl in Level.Platforms)
                {
                    if (pl.PolygonIndex == p)
                    {
                        seg.platform = new PlatformObject();
                        seg.platform.comesFromCeiling         = pl.ComesFromCeiling;
                        seg.platform.comesFromFloor           = pl.ComesFromFloor;
                        seg.platform.initiallyExtended        = pl.InitiallyExtended;
                        seg.platform.maximumHeight            = (float)pl.MaximumHeight / 1024f;
                        seg.platform.minimumHeight            = (float)pl.MinimumHeight / 1024f;
                        seg.platform.speed                    = (float)pl.Speed / 64f;
                        seg.platform.usesNativePolygonHeights = pl.UsesNativePolygonHeights;
                        seg.platform.door            = pl.IsDoor;
                        seg.platform.initiallyActive = pl.InitiallyActive;
                        seg.platform.parent          = seg;
                        seg.platform.activatesAdjacantPlatformsAtEachLevel      = pl.ActivatesAdjacantPlatformsAtEachLevel;
                        seg.platform.activatesAdjacentPlatformsWhenActivating   = pl.ActivatesAdjacentPlatformsWhenActivating;
                        seg.platform.activatesAdjacentPlatformsWhenDeactivating = pl.ActivatesAdjacentPlatformsWhenDeactivating;
                        seg.platform.activatesLight                = pl.ActivatesLight;
                        seg.platform.activatesOnlyOnce             = pl.ActivatesOnlyOnce;
                        seg.platform.cannotBeExternallyDeactivated = pl.CannotBeExternallyDeactivated;
                        seg.platform.causesDamage    = pl.CausesDamage;
                        seg.platform.contractsSlower = pl.ContractsSlower;
                        seg.platform.deactivatesAdjacentPlatformsWhenActivating   = pl.DeactivatesAdjacentPlatformsWhenActivating;
                        seg.platform.deactivatesAdjacentPlatformsWhenDeactivating = pl.DeactivatesAdjacentPlatformsWhenDeactivating;
                        seg.platform.deactivatesAtEachLevel    = pl.DeactivatesAtEachLevel;
                        seg.platform.deactivatesAtInitialLevel = pl.DeactivatesAtInitialLevel;
                        seg.platform.deactivatesLight          = pl.DeactivatesLight;
                        seg.platform.delay = pl.Delay / 30f;
                        seg.platform.delaysBeforeActivation = pl.DelaysBeforeActivation;
                        seg.platform.doesNotActivateParent  = pl.DoesNotActivateParent;
                        seg.platform.extendsFloorToCeiling  = pl.ExtendsFloorToCeiling;
                        seg.platform.isMonsterControllable  = pl.IsMonsterControllable;
                        seg.platform.isPlayerControllable   = pl.IsPlayerControllable;
                        seg.platform.locked = pl.IsLocked;
                        seg.platform.reversesDirectionWhenObstructed = pl.ReversesDirectionWhenObstructed;
                        seg.platform.secret = pl.IsSecret;
                        seg.platform.mapTag = pl.Tag;
                        seg.platform.usesNativePolygonHeights = pl.UsesNativePolygonHeights;
                    }
                }
            }


            if (Level.Polygons[p].MediaIndex >= 0)
            {
                seg.liquid = new Liquid();

                Media media = Level.Medias[Level.Polygons[p].MediaIndex];
                seg.liquid.currentSpeed      = (float)media.CurrentMagnitude / 1024f;
                seg.liquid.currentDirectioin = Quaternion.Euler(0, (float)media.Direction + 90, 0);
                seg.liquid.high       = (float)media.High / 1024f;
                seg.liquid.low        = (float)media.Low / 1024f;
                seg.liquid.mediaLight = lights[media.LightIndex];
                //?? where is the liquid data stored???
                // Material mat = new Material(Shader.Find("Custom/StandardClippableV2"));

                Weland.ShapeDescriptor tex = new Weland.ShapeDescriptor();

                switch (media.Type)
                {
                case MediaType.Water:
                    tex.Collection     = (byte)GlobalData.mediaCollections[0];
                    tex.Bitmap         = (byte)GlobalData.mediaBitmaps[0];
                    seg.liquid.surface = getTexture(tex);
                    seg.liquid.colour  = GlobalData.mediaColours[0];
                    seg.liquid.density = GlobalData.mediaDensities[0];
                    break;

                case MediaType.Lava:
                    tex.Collection     = (byte)GlobalData.mediaCollections[1];
                    tex.Bitmap         = (byte)GlobalData.mediaBitmaps[1];
                    seg.liquid.surface = getTexture(tex);
                    seg.liquid.colour  = GlobalData.mediaColours[1];
                    seg.liquid.density = GlobalData.mediaDensities[1];
                    break;

                case MediaType.Goo:
                    tex.Collection     = (byte)GlobalData.mediaCollections[2];
                    tex.Bitmap         = (byte)GlobalData.mediaBitmaps[2];
                    seg.liquid.surface = getTexture(tex);
                    seg.liquid.colour  = GlobalData.mediaColours[2];
                    seg.liquid.density = GlobalData.mediaDensities[2];
                    break;

                case MediaType.Sewage:
                    tex.Collection     = (byte)GlobalData.mediaCollections[3];
                    tex.Bitmap         = (byte)GlobalData.mediaBitmaps[3];
                    seg.liquid.surface = getTexture(tex);
                    seg.liquid.colour  = GlobalData.mediaColours[3];
                    seg.liquid.density = GlobalData.mediaDensities[3];
                    break;

                case MediaType.Jjaro:
                    tex.Collection     = (byte)GlobalData.mediaCollections[4];
                    tex.Bitmap         = (byte)GlobalData.mediaBitmaps[4];
                    seg.liquid.surface = getTexture(tex);
                    seg.liquid.colour  = GlobalData.mediaColours[4];
                    seg.liquid.density = GlobalData.mediaDensities[4];
                    break;

                default:
                    tex.Collection     = (byte)GlobalData.mediaCollections[0];
                    tex.Bitmap         = (byte)GlobalData.mediaBitmaps[0];
                    seg.liquid.surface = getTexture(tex);
                    seg.liquid.colour  = GlobalData.mediaColours[0];
                    seg.liquid.density = GlobalData.mediaDensities[0];
                    break;
                }

                seg.liquid.parent = seg;
            }

            switch (Level.Polygons[p].Type)
            {
            case Weland.PolygonType.AutomaticExit:
                seg.automaticExit = Level.Polygons[p].Permutation;
                break;

            case Weland.PolygonType.Base:
                seg.mapBase = Level.Polygons[p].Permutation;
                break;

            case Weland.PolygonType.DualMonsterTrigger:
                seg.dualMonsterTrigger = true;
                break;

            case Weland.PolygonType.Glue:
                seg.glue = true;
                break;

            case Weland.PolygonType.GlueTrigger:
                seg.glueTrigger = true;
                break;

            case Weland.PolygonType.Goal:
                seg.goal = true;
                break;

            case Weland.PolygonType.Hill:
                seg.hill = true;
                break;

            case Weland.PolygonType.InvisibleMonsterTrigger:
                seg.invisibleMonsterTrigger = true;
                break;

            case Weland.PolygonType.ItemImpassable:
                seg.itemImpassable = true;
                break;

            case Weland.PolygonType.ItemTrigger:
                seg.itemTrigger = true;
                break;

            case Weland.PolygonType.LightOffTrigger:
                seg.lightOffTrigger = Level.Polygons[p].Permutation;
                break;

            case Weland.PolygonType.LightOnTrigger:
                seg.lightOnTrigger = Level.Polygons[p].Permutation;
                break;

            case Weland.PolygonType.MajorOuch:
                seg.damage = 7;
                break;

            case Weland.PolygonType.MinorOuch:
                seg.damage = 3;
                break;

            case Weland.PolygonType.MonsterImpassable:
                seg.monsterImpassable = true;
                break;

            case Weland.PolygonType.MustBeExplored:
                seg.mustBeExplored = true;
                break;

            case Weland.PolygonType.PlatformOffTrigger:
                seg.platformOffTrigger = Level.Polygons[p].Permutation;
                break;

            case Weland.PolygonType.PlatformOnTrigger:
                seg.platformOnTrigger = Level.Polygons[p].Permutation;
                break;

            case Weland.PolygonType.Superglue:
                seg.superglue = true;
                break;

            case Weland.PolygonType.Teleporter:
                seg.teleporter = Level.Polygons[p].Permutation;
                break;

            case Weland.PolygonType.VisibleMonsterTrigger:
                seg.visibleMonsterTrigger = true;
                break;

            case Weland.PolygonType.ZoneBorder:
                seg.zoneBorder = true;
                break;
            }

            //get the map points that make up the polygon
            List <Vector3> points = new List <Vector3>();
            //find the top most point so we can sort them clockwise to make
            int zPt = 0;
            int xPt = 0;
            for (int ep = 0; ep < Level.Polygons[p].VertexCount; ep++)
            {
                int x = Level.Endpoints[Level.Polygons[p].EndpointIndexes[ep]].X;
                int z = Level.Endpoints[Level.Polygons[p].EndpointIndexes[ep]].Y;

                if (z > Level.Endpoints[Level.Polygons[p].EndpointIndexes[zPt]].Y ||
                    (z == Level.Endpoints[Level.Polygons[p].EndpointIndexes[zPt]].Y && x > Level.Endpoints[Level.Polygons[p].EndpointIndexes[zPt]].X))
                {
                    zPt = ep;
                }
                if (x < Level.Endpoints[Level.Polygons[p].EndpointIndexes[xPt]].X ||
                    (x == Level.Endpoints[Level.Polygons[p].EndpointIndexes[xPt]].X && z > Level.Endpoints[Level.Polygons[p].EndpointIndexes[xPt]].Y))
                {
                    xPt = ep;
                }
            }

            //add the lines and sides for the polygon
            List <Weland.Line> Line  = new List <Weland.Line>();
            List <Weland.Side> Sides = new List <Weland.Side>();
            int currentLine          = -1;
            for (int ln = 0; ln < Level.Polygons[p].VertexCount; ln++)
            {
                Line.Add(Level.Lines[Level.Polygons[p].LineIndexes[ln]]);
                if (Level.Polygons[p].SideIndexes[ln] >= 0)
                {
                    Sides.Add(Level.Sides[Level.Polygons[p].SideIndexes[ln]]);
                }
                //which lines are attached to the vertex
                int ep = -1;
                if (Line[Line.Count - 1].EndpointIndexes[0] == Level.Polygons[p].EndpointIndexes[zPt])
                {
                    ep = 0;
                }
                if (Line[Line.Count - 1].EndpointIndexes[1] == Level.Polygons[p].EndpointIndexes[zPt])
                {
                    ep = 1;
                }
                if (ep >= 0)
                {
                    if (currentLine < 0)
                    {
                        currentLine = ln;
                    }
                    else
                    {
                        int lep = 0;
                        if (Line[currentLine].EndpointIndexes[1] == Line[Line.Count - 1].EndpointIndexes[0] ||
                            Line[currentLine].EndpointIndexes[1] == Line[Line.Count - 1].EndpointIndexes[1])
                        {
                            lep = 1;
                        }
                        Point   point = Level.Endpoints[Line[currentLine].EndpointIndexes[lep]];
                        Vector2 a     = new Vector2(point.X, point.Y);

                        ep  = Line[Line.Count - 1].EndpointIndexes[Mathf.Abs(ep - 1)];
                        lep = Line[currentLine].EndpointIndexes[Mathf.Abs(lep - 1)];
                        //make sure we are going clockwise
                        Vector2 b = new Vector2(Level.Endpoints[lep].X, Level.Endpoints[lep].Y);
                        Vector2 c = new Vector2(Level.Endpoints[ep].X, Level.Endpoints[ep].Y);
                        if (Mathf.Atan2(b.y - a.y, b.x - a.x) < Mathf.Atan2(c.y - a.y, c.x - a.x))
                        {
                            currentLine = ln;
                        }
                    }
                }
            }

            int lastPt = -1;
            while (Line.Count > 0)
            {
                //get the correct point for each line
                int   pt = 0;
                int[] ei = { Line[currentLine].EndpointIndexes[0], Line[currentLine].EndpointIndexes[1] };
                if (lastPt == -1)
                {
                    if (Level.Endpoints[ei[1]].Y > Level.Endpoints[ei[0]].Y)
                    {
                        pt = 1;
                    }
                    if (Level.Endpoints[ei[1]].Y == Level.Endpoints[ei[0]].Y)
                    {
                        if (Level.Endpoints[ei[1]].X < Level.Endpoints[ei[0]].X)
                        {
                            pt = 1;
                        }
                    }
                }
                if (ei[1] == lastPt)
                {
                    pt = 1;
                }
                // map segment vertices must be in clockwise order
                points.Add(new Vector3(
                               (float)Level.Endpoints[ei[pt]].X / 1024f,
                               0,
                               (float)Level.Endpoints[ei[pt]].Y / 1024f)
                           );

                MapSegmentSide mss = new MapSegmentSide();
                mss.transparent = Line[currentLine].Transparent;
                mss.solid       = Line[currentLine].Solid;
                Side side = new Side();
                //get texture + lighting information for side
                if ((Line[currentLine].ClockwisePolygonSideIndex >= 0 && Line[currentLine].ClockwisePolygonOwner == p) ||
                    (Level.Polygons[p].Type == PolygonType.Platform && Line[currentLine].ClockwisePolygonSideIndex >= 0))
                {
                    side = Level.Sides[Line[currentLine].ClockwisePolygonSideIndex];
                }
                else if ((Line[currentLine].CounterclockwisePolygonSideIndex >= 0 && Line[currentLine].CounterclockwisePolygonOwner == p) ||
                         (Level.Polygons[p].Type == PolygonType.Platform && Line[currentLine].CounterclockwisePolygonSideIndex >= 0))
                {
                    side = Level.Sides[Line[currentLine].CounterclockwisePolygonSideIndex];
                }
                mss.upperMaterial = getTexture(side.Primary.Texture);
                mss.lowerMaterial = getTexture(side.Secondary.Texture);
                mss.middeMaterial = getTexture(side.Transparent.Texture);

                mss.upperOffset  = new Vector2((float)side.Primary.X / 1024f, (float)side.Primary.Y / 1024f);
                mss.middleOffset = new Vector2((float)side.Transparent.X / 1024f, (float)side.Transparent.Y / 1024f);
                mss.lowerOffset  = new Vector2((float)side.Secondary.X / 1024f, (float)side.Secondary.Y / 1024f);

                mss.upperLight  = lights[side.PrimaryLightsourceIndex];
                mss.lowerLight  = lights[side.SecondaryLightsourceIndex];
                mss.middleLight = lights[side.TransparentLightsourceIndex];


                if (mss.lowerMaterial == null)
                {
                    mss.lowerMaterial = mss.upperMaterial;
                    mss.lowerOffset   = mss.upperOffset;
                    mss.lowerLight    = mss.upperLight;
                }

                //get control panel information if needed
                if (side != null && (side.IsControlPanel || side.IsPlatformSwitch() || side.IsTagSwitch() || side.IsLightSwitch()))
                {
                    mss.controlPanel              = new ControlPanel();
                    mss.controlPanel.permutation  = side.ControlPanelPermutation;
                    mss.controlPanel.type         = side.ControlPanelType;
                    mss.controlPanel.controlPanel = side.IsControlPanel;
                    if (side.IsPlatformSwitch())
                    {
                        mss.controlPanel.platformSwitch = side.ControlPanelPermutation;
                    }
                    if (side.IsTagSwitch())
                    {
                        mss.controlPanel.tagSwitch = side.ControlPanelPermutation;
                    }
                    if (side.IsLightSwitch())
                    {
                        mss.controlPanel.lightSwitch = side.ControlPanelPermutation;
                    }
                    mss.controlPanel.inactiveMat = mss.upperMaterial;
                    for (int t = 0; t < materials.Count; t++)
                    {
                        if (materials[t] == mss.controlPanel.inactiveMat)
                        {
                            mss.controlPanel.activeMat = materials[t - 1];
                        }
                    }

                    switch (side.Flags)
                    {
                    // case SideFlags.None:
                    //  break;
                    case SideFlags.ControlPanelStatus:
                        mss.controlPanel.controlPanelStatus = 1;                                //?? what is this for?
                        break;

                    case SideFlags.Dirty:
                        mss.controlPanel.dirty = true;
                        break;

                    case SideFlags.IsDestructiveSwitch:
                        mss.controlPanel.destructiveSwitch = true;
                        break;

                    // case SideFlags.IsLightedSwitch:
                    //  mss.controlPanel.active = true;
                    //  break;
                    case SideFlags.IsRepairSwitch:
                        mss.controlPanel.repairSwitch = true;
                        break;

                    case SideFlags.IsControlPanel:
                        //mss.controlPanel.controlPanel = true;
                        break;

                    case SideFlags.SwitchCanBeDestroyed:
                        mss.controlPanel.canBeDestroyed = true;
                        break;

                    case SideFlags.SwitchCanOnlyBeHitByProjectiles:
                        mss.controlPanel.canOnlyBeHitByProjectiles = true;
                        break;
                    }
                }

                //connedtion information is used for occlusion culling
                seg.sides.Add(mss);
                if (Line[currentLine].ClockwisePolygonOwner == p)
                {
                    mss.connectionID = Line[currentLine].CounterclockwisePolygonOwner;
                }
                else
                {
                    mss.connectionID = Line[currentLine].ClockwisePolygonOwner;
                }
                pt     = Mathf.Abs(pt - 1);
                lastPt = ei[pt];

                //find next line that connects to the endpoint of this one to make the next side
                Line.RemoveAt(currentLine);
                for (int i = 0; i < Line.Count; i++)
                {
                    if (Line[i].EndpointIndexes[0] == ei[pt] || Line[i].EndpointIndexes[1] == ei[pt])
                    {
                        currentLine = i;
                    }
                }
            }

            //get floor and ceiling texture data
            seg.ceiling.upperMaterial = getTexture(Level.Polygons[p].CeilingTexture);
            seg.floor.upperMaterial   = getTexture(Level.Polygons[p].FloorTexture);

            seg.ceiling.upperOffset = new Vector2((float)Level.Polygons[p].CeilingOrigin.X / 1024f, (float)Level.Polygons[p].CeilingOrigin.Y / 1024f);
            seg.floor.upperOffset   = new Vector2((float)Level.Polygons[p].FloorOrigin.X / 1024f, (float)Level.Polygons[p].FloorOrigin.Y / 1024f);

            seg.ceiling.lightID = Level.Polygons[p].CeilingLight;
            seg.ceiling.light   = lights[Level.Polygons[p].CeilingLight];
            seg.floor.lightID   = Level.Polygons[p].FloorLight;
            seg.floor.light     = lights[Level.Polygons[p].FloorLight];
            seg.vertices        = points;
            seg.centerPoint     = new Vector3(0, (float)Level.Polygons[p].FloorHeight / 1024f, 0);
            seg.id = p;

            //convert points to be relative to the polygon average point
            seg.calculatePoints();

            if (p % 77 == 0)
            {
                loadingText = load + "\nGenerating Polygons " + p + "/" + Level.Polygons.Count;
                yield return(null);
            }
        }
        load = load + "\nGenerating Polygons " + Level.Polygons.Count + "/" + Level.Polygons.Count;

        //if a polygon is a platform we need to change its floor/ceiling heights to actually be
        //the volume that the platform would be moving up and down in if it were an actual
        //object - which it will be.
        int count = 0;

        foreach (Weland.Platform pl in Level.Platforms)
        {
            count++;
            segments[pl.PolygonIndex].recalculatePlatformVolume();
            if (count % 7 == 0)
            {
                loadingText = load + "\nRecalculate Platform Volumes " + count + "/" + Level.Platforms.Count;
                yield return(null);
            }
        }
        load  = load + "\nRecalculate Platform Volumes " + count + "/" + Level.Platforms.Count;
        count = 0;

        foreach (MapSegment s in segments)
        {
            count++;
            s.generateMeshes();
            if (count % 77 == 0)
            {
                loadingText = load + "\nGenerating Meshes " + count + "/" + segments.Count;
                yield return(null);
            }
        }
        load  = load + "\nGenerating Meshes " + count + "/" + segments.Count;
        count = 0;

        foreach (MapSegment s in segments)
        {
            count++;
            s.checkIfImpossible();
            if (count % 77 == 0)
            {
                loadingText = load + "\nFinding Impossible Space " + count + "/" + segments.Count;
                yield return(null);
            }
        }
        load  = load + "\nFinding Impossible Space " + count + "/" + segments.Count;
        count = 0;



        string mapHash = CalculateMD5(GlobalData.mapsFilePath);

        mapHash = Application.persistentDataPath + "/" + mapHash + "-" + mapNo + ".cache";
        if (!File.Exists(mapHash))
        {
            activePolygonList apl = new activePolygonList();
            apl.activePolygons = new List <bool[]>();
            for (int i = 0; i < segments.Count; i++)
            {
                count++;
                segments[i].calculateVisibility();

                apl.activePolygons.Add(segments[i].activePolygons);

                if (!GlobalData.skipOcclusion && count % 7 == 0)
                {
                    loadingText = load + "\nOcclusion Culling " + count + "/" + segments.Count;
                    yield return(null);
                }
            }
            BinaryFormatter bf = new BinaryFormatter();
            FileStream      fs = File.Open(mapHash, FileMode.Create);
            bf.Serialize(fs, apl);
            fs.Close();
        }
        else
        {
            FileStream        fs  = File.Open(mapHash, FileMode.Open);
            BinaryFormatter   bf  = new BinaryFormatter();
            activePolygonList apl = (activePolygonList)bf.Deserialize(fs);
            fs.Close();

            for (int i = 0; i < apl.activePolygons.Count; i++)
            {
                if (segments.Count > i)
                {
                    segments[i].activePolygons = apl.activePolygons[i];
                }
            }
        }
        load  = load + "\nOcclusion Culling " + count + "/" + segments.Count;
        count = 0;

        foreach (Weland.Platform pl in Level.Platforms)
        {
            count++;
            segments[pl.PolygonIndex].showHide(true);
            segments[pl.PolygonIndex].makePlatformObjects();
            if (count % 27 == 0)
            {
                loadingText = load + "\nMaking Platforms " + count + "/" + Level.Platforms.Count;
                yield return(null);
            }
        }

        foreach (Weland.Platform pl in Level.Platforms)
        {
            if (segments[pl.PolygonIndex].platform.initiallyActive)
            {
                segments[pl.PolygonIndex].platform.activate();
            }
        }
    }