Ejemplo n.º 1
0
        public void TestRelationshipFilter()
        {
            Guid itemId           = new Guid("11111111-aaaa-aaaa-aaaa-111111111111");
            Guid itemType         = new Guid("22222222-bbbb-bbbb-bbbb-222222222222");
            Guid relationshipType = new Guid("33333333-cccc-cccc-cccc-333333333333");

            MediaItemQuery query1 = new MediaItemQuery(new Guid[] { MediaAspect.ASPECT_ID }, new RelationshipFilter(itemType, relationshipType, itemId));

            TextWriter writer     = new StringWriter();
            XmlWriter  serialiser = new XmlTextWriter(writer);

            query1.Serialize(serialiser);

            //Console.WriteLine("XML: {0}", writer.ToString());

            XmlReader      reader = XmlReader.Create(new StringReader(writer.ToString()));
            MediaItemQuery query2 = MediaItemQuery.Deserialize(reader);

            Assert.IsTrue(query2.Filter is RelationshipFilter, "Query filter type");
            RelationshipFilter filter = (RelationshipFilter)query2.Filter;

            Assert.AreEqual(filter.LinkedMediaItemId, itemId, "Filter item linked ID");
            Assert.AreEqual(filter.Role, itemType, "Filter item type");
            Assert.AreEqual(filter.LinkedRole, relationshipType, "Filter item linked role");
        }
 // Used for mock services
 internal XboxSocialUserGroup(XboxLiveUser localUser, SocialUserGroupType groupType = SocialUserGroupType.Filter, PresenceFilter presence = PresenceFilter.Unknown, RelationshipFilter relationship = RelationshipFilter.Friends, Dictionary <string, XboxSocialUser> users = null, List <string> trackedUsers = null)
 {
     LocalUser                 = localUser;
     SocialUserGroupType       = groupType;
     PresenceFilterOfGroup     = presence;
     RelationshipFilterOfGroup = relationship;
     m_users        = users == null ? new Dictionary <string, XboxSocialUser>() : users;
     m_trackedUsers = trackedUsers == null ? new List <string>() : trackedUsers;
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Builds a subquery that returns the ids of the media items returned by the <paramref name="filter"/>.
        /// </summary>
        /// <param name="filter">Relationship filter instance to create the sub query for.</param>
        /// <param name="subqueryFilter">Additional filter to apply to all subqueries.</param>
        /// <param name="miaManagement">MIA_Management instance to generate attribute column names.</param>
        /// <param name="bvNamespace">Namespace used to build bind var names.</param>
        /// <param name="resultParts">Statement parts for the filter.</param>
        /// <param name="resultBindVars">Bind variables for the filter.</param>
        public static void BuildRelationshipSubquery(AbstractRelationshipFilter filter, IFilter subqueryFilter, MIA_Management miaManagement,
                                                     BindVarNamespace bvNamespace, IList <object> resultParts, IList <BindVar> resultBindVars)
        {
            //Simple relationship filter with linked id
            BindVar            linkedIdVar        = null;
            RelationshipFilter relationshipFilter = filter as RelationshipFilter;

            if (relationshipFilter != null && relationshipFilter.LinkedMediaItemId != Guid.Empty)
            {
                linkedIdVar = new BindVar(bvNamespace.CreateNewBindVarName("V"), relationshipFilter.LinkedMediaItemId, typeof(Guid));
                resultBindVars.Add(linkedIdVar);
            }

            //Role
            BindVar roleVar = null;

            if (filter.Role != Guid.Empty)
            {
                roleVar = new BindVar(bvNamespace.CreateNewBindVarName("V"), filter.Role, typeof(Guid));
                resultBindVars.Add(roleVar);
            }

            //Linked role
            BindVar linkedRoleVar = null;

            if (filter.LinkedRole != Guid.Empty)
            {
                linkedRoleVar = new BindVar(bvNamespace.CreateNewBindVarName("V"), filter.LinkedRole, typeof(Guid));
                resultBindVars.Add(linkedRoleVar);
            }

            //Complex relationship filter with linked filter
            string                     sqlStatement = null;
            IList <BindVar>            bindVars     = null;
            FilteredRelationshipFilter filteredRelationshipFilter = filter as FilteredRelationshipFilter;

            if (filteredRelationshipFilter != null && filteredRelationshipFilter.Filter != null)
            {
                //Build a sub query for the linked filter
                string idAlias = null;
                ICollection <QueryAttribute> requiredAttributes = new List <QueryAttribute>();
                SubQueryBuilder filterBuilder = new SubQueryBuilder(miaManagement, requiredAttributes,
                                                                    new List <MediaItemAspectMetadata>(), filteredRelationshipFilter.Filter, subqueryFilter, bvNamespace.BindVarCounter);
                filterBuilder.GenerateSqlStatement(out idAlias, out sqlStatement, out bindVars);
                sqlStatement = " SELECT TS." + idAlias + " FROM (" + sqlStatement + ") TS";

                bvNamespace.BindVarCounter += bindVars.Count;
                CollectionUtils.AddAll(resultBindVars, bindVars);
            }

            //Relationships are only stored for one party in the relationship so we need to union the query with a query
            //that reverses the relationship to ensure that all relationships are selected
            BuildRelationshipSubqueryPart(roleVar, linkedRoleVar, linkedIdVar, sqlStatement, false, miaManagement, resultParts);
            resultParts.Add(" UNION ");
            BuildRelationshipSubqueryPart(roleVar, linkedRoleVar, linkedIdVar, sqlStatement, true, miaManagement, resultParts);
        }
        public override ICollection <FilterValue> GetAvailableValues(IEnumerable <Guid> necessaryMIATypeIds, IFilter selectAttributeFilter, IFilter filter)
        {
            IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory;

            if (cd == null)
            {
                throw new NotConnectedException("The MediaLibrary is not connected");
            }

            Guid?           userProfile = null;
            IUserManagement userProfileDataManagement = ServiceRegistration.Get <IUserManagement>();

            if (userProfileDataManagement != null && userProfileDataManagement.IsValidUser)
            {
                userProfile = userProfileDataManagement.CurrentUser.ProfileId;
            }

            IEnumerable <Guid> mias    = _necessaryMIATypeIds ?? necessaryMIATypeIds;
            IEnumerable <Guid> optMias = _optionalMIATypeIds != null?_optionalMIATypeIds.Except(mias) : null;

            IFilter queryFilter;

            if (filter != null)
            {
                queryFilter = new FilteredRelationshipFilter(_role, filter);
            }
            else
            {
                queryFilter = new RelationshipFilter(_role, _linkedRole, Guid.Empty);
            }
            MediaItemQuery query = new MediaItemQuery(mias, optMias, queryFilter);

            if (_sortInformation != null)
            {
                query.SortInformation = new List <SortInformation> {
                    _sortInformation
                }
            }
            ;
            IList <MediaItem>   items  = cd.Search(query, true, userProfile, ShowVirtualSetting.ShowVirtualMedia(necessaryMIATypeIds));
            IList <FilterValue> result = new List <FilterValue>(items.Count);

            foreach (MediaItem item in items)
            {
                string name;
                MediaItemAspect.TryGetAttribute(item.Aspects, MediaAspect.ATTR_TITLE, out name);
                result.Add(new FilterValue(name,
                                           new RelationshipFilter(_linkedRole, _role, item.MediaItemId),
                                           null,
                                           item,
                                           this));
            }
            return(result);
        }
Ejemplo n.º 5
0
        public override bool IsEnemy(Mobile m, RelationshipFilter filter)
        {
            if (!Core.UOAI && !Core.UOAR)
            {
                if (m.Player && m.FindItemOnLayer(Layer.Helm) is OrcishKinMask)
                {
                    return(false);
                }
            }

            return(base.IsEnemy(m, filter));
        }
Ejemplo n.º 6
0
 private static Task <IList <MediaItem> > SearchByGroupAsync(Guid?userId, Guid itemRole, Guid groupRole, Guid groupId, ISet <Guid> necessaryMIATypes, ISet <Guid> optionalMIATypes, IFilter filter = null, uint?limit = null, uint?offset = null, IList <ISortInformation> sort = null)
 {
     if (filter != null)
     {
         filter = BooleanCombinationFilter.CombineFilters(BooleanOperator.And, filter, new RelationshipFilter(itemRole, groupRole, groupId));
     }
     else
     {
         filter = new RelationshipFilter(itemRole, groupRole, groupId);
     }
     return(SearchAsync(userId, necessaryMIATypes, optionalMIATypes, filter, limit, offset, sort));
 }
Ejemplo n.º 7
0
        public override bool IsEnemy(Mobile m, RelationshipFilter filter)
        {
            if (!Core.UOAI && !Core.UOAR)
            {
                // Ai uses HUE value and not the BodyMod as there is no sitting graphic
                if ((m.BodyMod == 183 || m.BodyMod == 184) || m.HueMod == 0)
                {
                    return(false);
                }
            }

            return(base.IsEnemy(m, filter));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Determines if the user should be included based on their relationship.
        /// </summary>
        /// <param name="user">The user whose relationship should be checked.</param>
        /// <param name="relationshipFilter">The relationship filter to check against.</param>
        /// <returns>True if the user should be included, false otherwise.</returns>
        private bool CheckRelationshipFilter(XboxSocialUser user, RelationshipFilter relationshipFilter)
        {
            switch (relationshipFilter)
            {
            case RelationshipFilter.Friends:
                return(user.IsFollowedByCaller);

            case RelationshipFilter.Favorite:
                return(user.IsFavorite);

            default:
                throw new ArgumentOutOfRangeException("relationshipFilter", relationshipFilter, "Unexpected relationship filter value.");
            }
        }
Ejemplo n.º 9
0
        public override bool IsEnemy(Mobile m, RelationshipFilter filter)
        {
            PlayerMobile player = m as PlayerMobile;

            if (player != null && Map == Map.Trammel && X >= 5199 && X <= 5271 && Y >= 1812 && Y <= 1865)             // Schmendrick's cave
            {
                QuestSystem qs = player.Quest;

                if (qs is UzeraanTurmoilQuest && qs.IsObjectiveInProgress(typeof(FindSchmendrickObjective)))
                {
                    return(false);
                }
            }

            return(base.IsEnemy(m, filter));
        }
Ejemplo n.º 10
0
        public override bool IsEnemy(Mobile m, RelationshipFilter filter)
        {
            Faction ourFaction   = m_Faction;
            Faction theirFaction = Faction.Find(m);

            if (theirFaction == null && m is BaseFactionGuard)
            {
                theirFaction = ((BaseFactionGuard)m).Faction;
            }

            if (ourFaction != null && theirFaction != null && ourFaction != theirFaction)
            {
                ReactionType reactionType = Orders.GetReaction(theirFaction).Type;

                if (reactionType == ReactionType.Attack)
                {
                    return(true);
                }

                if (theirFaction != null)
                {
                    List <AggressorInfo> list = m.Aggressed;

                    for (int i = 0; i < list.Count; ++i)
                    {
                        AggressorInfo ai = list[i] as AggressorInfo;

                        if (ai == null)
                        {
                            continue;
                        }

                        if (ai.Defender is BaseFactionGuard)
                        {
                            BaseFactionGuard bf = (BaseFactionGuard)ai.Defender;

                            if (bf.Faction == ourFaction)
                            {
                                return(true);
                            }
                        }
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 11
0
        public void TestRelationshipQueryBuilder()
        {
            // Use the real RelationshipFilter because CompiledFilter is hard coded to look for it
            MockCore.AddMediaItemAspectStorage(RelationshipAspect.Metadata);

            SingleTestMIA mia1 = TestBackendUtils.CreateSingleMIA("Meta1", Cardinality.Inline, true, true);
            SingleTestMIA mia2 = TestBackendUtils.CreateSingleMIA("Meta2", Cardinality.Inline, true, true);

            ICollection <MediaItemAspectMetadata> requiredMIATypes = new List <MediaItemAspectMetadata>();

            requiredMIATypes.Add(mia1.Metadata);
            requiredMIATypes.Add(mia2.Metadata);

            Guid    movieId   = new Guid("aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa");
            Guid    movieType = new Guid("bbbbbbbb-2222-2222-2222-bbbbbbbbbbbb");
            Guid    actorType = new Guid("cccccccc-3333-3333-3333-cccccccccccc");
            IFilter filter    = new RelationshipFilter(actorType, movieType, movieId);

            MIAQueryBuilder builder = new MIAQueryBuilder(MockCore.Management, new List <QueryAttribute>(), null, requiredMIATypes, new List <MediaItemAspectMetadata>(), filter, null, null);

            string mediaItemIdAlias = null;
            IDictionary <MediaItemAspectMetadata, string> miamAliases      = null;
            IDictionary <QueryAttribute, string>          attributeAliases = null;
            string          statementStr = null;
            IList <BindVar> bindVars     = null;

            builder.GenerateSqlStatement(out mediaItemIdAlias, out miamAliases, out attributeAliases, out statementStr, out bindVars);
            Console.WriteLine("mediaItemIdAlias: {0}", mediaItemIdAlias);
            Console.WriteLine("miamAliases: [{0}]", string.Join(",", miamAliases));
            Console.WriteLine("attributeAliases: [{0}]", string.Join(",", attributeAliases));
            Console.WriteLine("statementStr: {0}", statementStr);
            Console.WriteLine("bindVars: [{0}]", string.Join(",", bindVars));

            Assert.AreEqual("A0", mediaItemIdAlias, "Media item ID alias");
            Assert.AreEqual(CreateMIAMAliases(mia1.Metadata, "A1", mia2.Metadata, "A2"), miamAliases, "MIAM aliases");
            Assert.AreEqual(new Dictionary <QueryAttribute, string>(), attributeAliases, "Attribute aliases");
            Assert.AreEqual("SELECT T0.MEDIA_ITEM_ID A0, T0.MEDIA_ITEM_ID A1, T1.MEDIA_ITEM_ID A2 FROM M_META1 T0 INNER JOIN M_META2 T1 ON T1.MEDIA_ITEM_ID = T0.MEDIA_ITEM_ID " +
                            " WHERE T0.MEDIA_ITEM_ID IN(SELECT R1.MEDIA_ITEM_ID FROM M_RELATIONSHIP R1 WHERE R1.LINKEDID=@V0 AND R1.ROLE=@V1 AND R1.LINKEDROLE=@V2 " +
                            "UNION SELECT R1.LINKEDID FROM M_RELATIONSHIP R1 WHERE R1.MEDIA_ITEM_ID=@V0 AND R1.LINKEDROLE=@V1 AND R1.ROLE=@V2)", statementStr, "Statement");
            Assert.AreEqual(new List <BindVar>
            {
                new BindVar("V0", movieId, typeof(Guid)),
                new BindVar("V1", actorType, typeof(Guid)),
                new BindVar("V2", movieType, typeof(Guid))
            }, bindVars, "Bind vars");
        }
Ejemplo n.º 12
0
 public void DestroySocialGroup(XboxLiveUser user, PresenceFilter presenceFilter, RelationshipFilter relationshipFilter)
 {
     lock (m_socialManager)
     {
         foreach (XboxSocialUserGroup socialUserGroup in m_socialUserGroups)
         {
             if (socialUserGroup.LocalUser.XboxUserId == user.XboxUserId &&
                 socialUserGroup.PresenceFilterOfGroup == presenceFilter &&
                 socialUserGroup.RelationshipFilterOfGroup == relationshipFilter)
             {
                 m_socialUserGroups.Remove(socialUserGroup);
                 m_socialManager.DestroySocialUserGroup(socialUserGroup);
                 break;
             }
         }
     }
 }
        protected void UpdateFilter()
        {
            Guid?role              = Role;
            Guid?linkedRole        = LinkedRole;
            Guid?linkedMediaItemId = LinkedMediaItemId;

            IFilter filter = null;

            //If all properties are valid, create the RelationshipFilter
            if (role.HasValue && linkedMediaItemId.HasValue)
            {
                filter = new RelationshipFilter(role.Value, linkedRole.HasValue ? linkedRole.Value : Guid.Empty, linkedMediaItemId.Value);
            }

            //Setting a valid filter causes the underlying MediaItemQueryExtension to
            //perform the actual query or setting to null resets the target property to null
            Filter = filter;
        }
Ejemplo n.º 14
0
        public void TestRelationshipFilter()
        {
            // Use the real RelationshipFilter because CompiledFilter is hard coded to look for it
            MockCore.AddMediaItemAspectStorage(RelationshipAspect.Metadata);

            Guid    movieId   = new Guid("aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa");
            Guid    movieType = new Guid("bbbbbbbb-2222-2222-2222-bbbbbbbbbbbb");
            Guid    actorType = new Guid("cccccccc-3333-3333-3333-cccccccccccc");
            IFilter filter    = new RelationshipFilter(actorType, movieType, movieId);

            ICollection <MediaItemAspectMetadata> requiredMIATypes = new List <MediaItemAspectMetadata>();

            IList <object>          parts      = new List <object>();
            IList <BindVar>         bindVars   = new List <BindVar>();
            ICollection <TableJoin> tableJoins = new List <TableJoin>();

            MockCompiledFilter compiledFilter = new MockCompiledFilter();

            compiledFilter.test(MockCore.Management, filter, null, requiredMIATypes, "test", tableJoins, parts, bindVars);

            //Console.WriteLine("Parts [{0}]", string.Join(",", parts));
            //Console.WriteLine("Bind vars [{0}]", string.Join(",", bindVars));
            //Console.WriteLine("Table joins [{0}]", string.Join(",", tableJoins));

            Assert.AreEqual(new List <object> {
                "test", " IN(",
                "SELECT R1.", "MEDIA_ITEM_ID", " FROM ", "M_RELATIONSHIP", " R1", " WHERE", " R1.", "LINKEDID", "=@V0", " AND", " R1.", "ROLE", "=@V1", " AND", " R1.", "LINKEDROLE", "=@V2",
                " UNION ",
                "SELECT R1.", "LINKEDID", " FROM ", "M_RELATIONSHIP", " R1", " WHERE", " R1.", "MEDIA_ITEM_ID", "=@V0", " AND", " R1.", "LINKEDROLE", "=@V1", " AND", " R1.", "ROLE", "=@V2", ")"
            }, parts, "Parts");

            Assert.AreEqual(new List <BindVar>
            {
                new BindVar("V0", movieId, typeof(Guid)),
                new BindVar("V1", actorType, typeof(Guid)),
                new BindVar("V2", movieType, typeof(Guid))
            }, bindVars, "Bind vars");
            Assert.AreEqual(new List <TableJoin> {
            }, tableJoins, "Tables joins");
        }
Ejemplo n.º 15
0
        public override bool IsEnemy(Mobile m, RelationshipFilter filter)
        {
            if (m.Player)
            {
                return(false);
            }

            if (m is BaseCreature)
            {
                BaseCreature bc = (BaseCreature)m;
                if (bc.Controlled && bc.ControlMaster != null)
                {
                    return(IsEnemy(bc.ControlMaster, filter));
                }
                else if (bc.Summoned && bc.SummonMaster != null)
                {
                    return(IsEnemy(bc.SummonMaster, filter));
                }
            }

            return(m.Karma < 0);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Album && mediaType != FanArtMediaTypes.Audio)
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId) || mediaType == FanArtMediaTypes.Image)
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter        = null;
            IList <MediaItem> items         = null;
            List <Guid>       necessaryMias = new List <Guid>(NECESSARY_MIAS);

            if (mediaType == FanArtMediaTypes.Album)
            {
                filter = new RelationshipFilter(AudioAspect.ROLE_TRACK, AudioAlbumAspect.ROLE_ALBUM, mediaItemId);
            }
            else if (mediaType == FanArtMediaTypes.Audio)
            {
                //Might be a request for track cover which doesn't exist. Album cover is used instead.
                filter = new MediaItemIdFilter(mediaItemId);
            }
            else
            {
                return(false);
            }

            MediaItemQuery mediaQuery = new MediaItemQuery(necessaryMias, filter);

            mediaQuery.Limit = 1;
            items            = mediaLibrary.Search(mediaQuery, false, null, false);
            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();
            var fanArtPaths       = new List <ResourcePath>();
            var files             = new List <IResourceLocator>();

            // File based access
            try
            {
                var    mediaItemPath          = mediaIteamLocator.NativeResourcePath;
                var    mediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../");
                string album = null;
                if (MediaItemAspect.TryGetAttribute(mediaItem.Aspects, AudioAspect.ATTR_ALBUM, out album) && LocalFanartHelper.IsDiscFolder(album, mediaItemDirectoryPath.FileName))
                {
                    //Probably a CD folder so try next parent
                    mediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../../");
                }
                var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();
                var mediaItemExtension = ResourcePathHelper.GetExtension(mediaItemPath.ToString());

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Cover || fanArtType == FanArtTypes.Thumbnail)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "poster" || potentialFanArtFileNameWithoutExtension == "folder" ||
                                                                              potentialFanArtFileNameWithoutExtension == "cover"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.DiscArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "discart" || potentialFanArtFileNameWithoutExtension == "disc"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.DiscArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "cdart"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.FanArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "backdrop" || potentialFanArtFileNameWithoutExtension == "fanart"
                                                                              select potentialFanArtFile);

                            if (directoryFsra.ResourceExists("ExtraFanArt/"))
                            {
                                using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                    fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                            }
                        }

                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalAlbumFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
Ejemplo n.º 17
0
		public virtual bool IsFriend( Mobile m, RelationshipFilter filter )
		{
			//Pix: If we're a non-controlled summon, nothing is our friend
			if( m_bSummoned && !m_bControled )
				return false;

			// Adam: is this a waring faction? (NPC)
			if ((filter & RelationshipFilter.CheckOpposition) > 0)
				if (IsOpposition(m))
					return false;

			// Adam: If you are an ememy, you are not a friend (PC)
			if (IOBSystem.IsEnemy(this,m) == true)
				return false;

			// Adam: different teams are always waring (NPC)
			if (IsTeamOpposition(m) == true)
				return false;

			// Adam: Is this an IOB kinship? (PC)
			if (IOBSystem.IsFriend(this, m) == true)
				return true;

			BaseCreature c = m as BaseCreature;
			if (c != null)
			{
				//if both are tamed pets dont attack each other
				if(m_bControled && c.m_bControled)
					return true;

				// same team?
				if ( m_iTeam == c.m_iTeam)
					return true;
			}

			// if it's a player, it's not a friend
			if ((filter & RelationshipFilter.IgnorePCHate) == 0)
				if ( !(m is BaseCreature) )
					return false;

			// not recognized as a friend
			return false;
		}
        public XboxSocialUserGroup CreateSocialUserGroupFromFilters(XboxLiveUser user, PresenceFilter presenceFilter, RelationshipFilter relationshipFilter)
        {
            var group = new XboxSocialUserGroup(user, presenceFilter, relationshipFilter, XboxLiveAppConfiguration.Instance.TitleId);

            var users = Enumerable.Range(0, 5)
                        .Select(id =>
            {
                var groupUser = CreateUser();

                switch (presenceFilter)
                {
                case PresenceFilter.AllOnline:
                case PresenceFilter.TitleOnline:
                    InitUserForOnlinePresence(ref groupUser);
                    break;

                case PresenceFilter.AllOffline:
                case PresenceFilter.TitleOffline:
                    InitUserForOfflinePresence(ref groupUser);
                    break;

                case PresenceFilter.AllTitle:
                case PresenceFilter.All:
                    if (id % 2 == 0)
                    {
                        InitUserForOnlinePresence(ref groupUser);
                    }
                    else
                    {
                        InitUserForOfflinePresence(ref groupUser);
                    }
                    break;
                }

                switch (relationshipFilter)
                {
                case RelationshipFilter.Friends:
                    groupUser.IsFollowedByCaller = true;
                    break;

                case RelationshipFilter.Favorite:
                    groupUser.IsFollowedByCaller = true;
                    groupUser.IsFavorite         = true;
                    break;
                }

                return(groupUser);
            }).ToDictionary(u => u.XboxUserId);

            group.InitializeGroup(users.Values);
            group.UpdateView(users, new List <SocialEvent>());
            this.events.Add(new SocialEvent(SocialEventType.SocialUserGroupLoaded, user, null, group));

            return(group);
        }
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.SeriesSeason && mediaType != FanArtMediaTypes.Episode)
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId) || mediaType == FanArtMediaTypes.Image)
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter filter = null;

            if (mediaType == FanArtMediaTypes.SeriesSeason)
            {
                filter = new RelationshipFilter(EpisodeAspect.ROLE_EPISODE, SeasonAspect.ROLE_SEASON, mediaItemId);
            }
            else if (mediaType == FanArtMediaTypes.Episode)
            {
                filter = new MediaItemIdFilter(mediaItemId);
            }
            MediaItemQuery episodeQuery = new MediaItemQuery(NECESSARY_MIAS, filter);

            episodeQuery.Limit = 1;
            IList <MediaItem> items = mediaLibrary.Search(episodeQuery, false, null, false);

            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();
            var fanArtPaths       = new List <ResourcePath>();
            var files             = new List <IResourceLocator>();

            // File based access
            try
            {
                var mediaItemPath                     = mediaIteamLocator.NativeResourcePath;
                var mediaItemDirectoryPath            = ResourcePathHelper.Combine(mediaItemPath, "../");
                var mediaItemParentDirectoryPath      = ResourcePathHelper.Combine(mediaItemPath, "../../");
                var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();
                var mediaItemExtension                = ResourcePathHelper.GetExtension(mediaItemPath.ToString());

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        if (fanArtType == FanArtTypes.Thumbnail)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "thumb"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.Poster)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "poster" || potentialFanArtFileNameWithoutExtension == "folder"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.Logo)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "logo"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.ClearArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "clearart"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.Banner)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "banner"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.FanArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "backdrop" || potentialFanArtFileNameWithoutExtension == "fanart"
                                                                              select potentialFanArtFile);

                            if (directoryFsra.ResourceExists("ExtraFanArt/"))
                            {
                                using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                    fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                            }
                        }

                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemParentDirectoryPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        int?season = null;
                        MediaItemAspect.TryGetAttribute(mediaItem.Aspects, EpisodeAspect.ATTR_SEASON, out season);

                        if (season.HasValue)
                        {
                            List <string> prefixes = new List <string>();
                            prefixes.Add(string.Format("season{0:00}-", season.Value));
                            if (season.Value == 0)
                            {
                                prefixes.Add("season-specials-");
                            }
                            else
                            {
                                prefixes.Add("season-all-");
                            }
                            prefixes.Add(""); //For finding series fallback

                            foreach (string prefix in prefixes)
                            {
                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.Thumbnail)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "thumb"
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.Poster)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "poster"
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.Logo)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "logo"
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.ClearArt)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "clearart"
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.Banner)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "banner"
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.FanArt)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "fanart"
                                                                                      select potentialFanArtFile);
                                }

                                files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalSeasonFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
Ejemplo n.º 20
0
		public virtual bool IsEnemy(Mobile m, RelationshipFilter filter)
		{
			//Pix: If we're a non-controlled summon, everything is an enemy
			if( m_bSummoned && !m_bControled )
				return true;

			// Adam: is this a waring faction? (NPC)
			if ((filter & RelationshipFilter.CheckOpposition) > 0)
				if (IsOpposition(m))
					return true;

			// Adam: Is this an IOB kinship? (PC)
			if (IOBSystem.IsEnemy(this,m) == true)
				return true;

			// Adam: different teams are always waring (NPC)
			if (IsTeamOpposition(m) == true)
				return true;

			// Adam: If you are a friend, you are not an enemy (PC)
			if (IOBSystem.IsFriend(this,m) == true)
				return false;

			if (m is BaseGuard)
				return false;

			// don't hate PCs just because they are PCs
			if ((filter & RelationshipFilter.IgnorePCHate) == 0)
				if (!(m is BaseCreature))
					return true;

			// don't hate summoned ot controlled NPCs just because
			if ((filter & RelationshipFilter.Faction) == 0)
				if (m is BaseCreature)
				{
					BaseCreature c = (BaseCreature)m;
					return (((m_bSummoned || m_bControled) != (c.m_bSummoned || c.m_bControled))); //anything else attack whatever			
				}

			// doesn't seem to be an enemy
			return false; 
		}
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.MovieCollection)
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId) || mediaType == FanArtMediaTypes.Image)
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter     = new RelationshipFilter(MovieAspect.ROLE_MOVIE, MovieCollectionAspect.ROLE_MOVIE_COLLECTION, mediaItemId);
            MediaItemQuery    movieQuery = new MediaItemQuery(NECESSARY_MIAS, filter);
            IList <MediaItem> items      = mediaLibrary.Search(movieQuery, false, null, false);

            if (items == null || items.Count == 0)
            {
                return(false);
            }

            var files = new List <IResourceLocator>();

            foreach (MediaItem mediaItem in items)
            {
                // Virtual resources won't have any local fanart
                if (mediaItem.IsVirtual)
                {
                    continue;
                }
                var mediaIteamLocator = mediaItem.GetResourceLocator();
                var fanArtPaths       = new List <ResourcePath>();

                // File based access
                try
                {
                    var mediaItemPath                     = mediaIteamLocator.NativeResourcePath;
                    var mediaItemDirectoryPath            = ResourcePathHelper.Combine(mediaItemPath, "../");
                    var mediaItemCollectionDirectoryPath  = ResourcePathHelper.Combine(mediaItemPath, "../../");
                    var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();

                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                            if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "movieset-poster"
                                                                                  select potentialFanArtFile);
                            }

                            if (fanArtType == FanArtTypes.Banner)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "movieset-banner"
                                                                                  select potentialFanArtFile);
                            }

                            if (fanArtType == FanArtTypes.FanArt)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "movieset-fanart"
                                                                                  select potentialFanArtFile);
                            }

                            files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                        }
                    }

                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemCollectionDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                            if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "poster" || potentialFanArtFileNameWithoutExtension == "folder" || potentialFanArtFileNameWithoutExtension == "movieset-poster" ||
                                                                                  potentialFanArtFileNameWithoutExtension.EndsWith("-poster")
                                                                                  select potentialFanArtFile);
                            }

                            if (fanArtType == FanArtTypes.Banner)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "banner" || potentialFanArtFileNameWithoutExtension == "movieset-banner" || potentialFanArtFileNameWithoutExtension.EndsWith("-banner")
                                                                                  select potentialFanArtFile);
                            }

                            if (fanArtType == FanArtTypes.FanArt)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "backdrop" || potentialFanArtFileNameWithoutExtension == "fanart" || potentialFanArtFileNameWithoutExtension == "movieset-fanart" ||
                                                                                  potentialFanArtFileNameWithoutExtension.EndsWith("-fanart")
                                                                                  select potentialFanArtFile);

                                if (directoryFsra.ResourceExists("ExtraFanArt/"))
                                {
                                    using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                        fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                                }
                            }

                            files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                        }
                    }
                }
                catch (Exception ex)
                {
#if DEBUG
                    ServiceRegistration.Get <ILogger>().Warn("LocalMovieCollectionFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
                }

                if (files.Count > 0)
                {
                    break;
                }
            }
            if (files.Count == 0)
            {
                foreach (MediaItem mediaItem in items)
                {
                    // Virtual resources won't have any local fanart
                    if (mediaItem.IsVirtual)
                    {
                        continue;
                    }
                    var mediaIteamLocator = mediaItem.GetResourceLocator();
                    var fanArtPaths       = new List <ResourcePath>();

                    // File based access
                    try
                    {
                        var mediaItemPath                     = mediaIteamLocator.NativeResourcePath;
                        var mediaItemDirectoryPath            = ResourcePathHelper.Combine(mediaItemPath, "../");
                        var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();

                        using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                        {
                            var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                            if (directoryFsra != null)
                            {
                                var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                                if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == "poster" || potentialFanArtFileNameWithoutExtension == "folder" || potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-poster")
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtType == FanArtTypes.Banner)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == "banner" || potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-banner")
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtType == FanArtTypes.FanArt)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == "backdrop" || potentialFanArtFileNameWithoutExtension == "fanart" || potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-fanart")
                                                                                      select potentialFanArtFile);

                                    if (directoryFsra.ResourceExists("ExtraFanArt/"))
                                    {
                                        using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                            fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                                    }
                                }

                                files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        ServiceRegistration.Get <ILogger>().Warn("LocalMovieCollectionFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
                    }

                    if (files.Count > 0)
                    {
                        break;
                    }
                }
            }
            result = files;
            return(files.Count > 0);
        }
Ejemplo n.º 22
0
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <FanArtImage> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Album && mediaType != FanArtMediaTypes.Audio)
            {
                return(false);
            }

            if (!Guid.TryParse(name, out mediaItemId))
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter filter = null;

            if (mediaType == FanArtMediaTypes.Album)
            {
                filter = new RelationshipFilter(AudioAspect.ROLE_TRACK, AudioAlbumAspect.ROLE_ALBUM, mediaItemId);
            }
            else if (mediaType == FanArtMediaTypes.Audio)
            {
                filter = new MediaItemIdFilter(mediaItemId);
            }
            MediaItemQuery mediaQuery = new MediaItemQuery(NECESSARY_MIAS, filter);

            mediaQuery.Limit = 1;
            IList <MediaItem> items = mediaLibrary.Search(mediaQuery, false, null, true);

            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var    resourceLocator       = mediaItem.GetResourceLocator();
            string fileSystemPath        = string.Empty;
            IList <PictureType> patterns = new List <PictureType>();

            switch (fanArtType)
            {
            case FanArtTypes.Undefined:
            case FanArtTypes.Poster:
            case FanArtTypes.Cover:
            case FanArtTypes.Thumbnail:
                patterns.Add(PictureType.FrontCover);
                patterns.Add(PictureType.Other);
                break;

            default:
                return(false);
            }
            // File based access
            try
            {
                using (var accessor = resourceLocator?.CreateAccessor())
                {
                    ILocalFsResourceAccessor fsra = accessor as ILocalFsResourceAccessor;
                    if (fsra != null)
                    {
                        fileSystemPath = fsra.LocalFileSystemPath;
                        var ext = Path.GetExtension(fsra.LocalFileSystemPath);
                        if (!SUPPORTED_EXTENSIONS.Contains(ext))
                        {
                            return(false);
                        }

                        ByteVector.UseBrokenLatin1Behavior = true; // Otherwise we have problems retrieving non-latin1 chars
                        using (var tag = TagLib.File.Create(fsra.LocalFileSystemPath))
                        {
                            IPicture[] pics = tag.Tag.Pictures;
                            if (pics.Length > 0)
                            {
                                foreach (var pattern in patterns)
                                {
                                    var picTag = pics.FirstOrDefault(p => p.Type == pattern);
                                    if (picTag != null)
                                    {
                                        result = new List <FanArtImage> {
                                            new FanArtImage(name, picTag.Data.Data)
                                        };
                                        return(true);
                                    }
                                }
                                //If no matching images found, use first images for thumbnails
                                if (fanArtType == FanArtTypes.Thumbnail)
                                {
                                    result = new List <FanArtImage> {
                                        new FanArtImage(name, pics[0].Data.Data)
                                    };
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Warn("AudioTagProvider: Exception while reading tag of type '{0}' from '{1}'", ex, fanArtType, fileSystemPath);
            }
            return(false);
        }
Ejemplo n.º 23
0
    public void CreateSocialGroupFromFilters(XboxLiveUser user, PresenceFilter presenceFilter, RelationshipFilter relationshipFilter)
    {
        XboxSocialUserGroup socialUserGroup = m_socialManager.CreateSocialUserGroupFromFilters(user, presenceFilter, relationshipFilter);

        lock (m_socialManager)
        {
            m_socialUserGroups.Add(socialUserGroup);
        }
    }
Ejemplo n.º 24
0
        internal static IList <MediaItem> GetMediaItemsByGroup(IOwinContext context, Guid itemRole, Guid groupRole, Guid groupId, ISet <Guid> necessaryMIATypes, ISet <Guid> optionalMIATypes)
        {
            IFilter filter = new RelationshipFilter(itemRole, groupRole, groupId);

            return(Search(context, necessaryMIATypes, optionalMIATypes, filter));
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Creates a filter based XboxSocialUserGroup from a given set of filter parameters.
 /// </summary>
 /// <param name="localUser">The user who the group belongs to.</param>
 /// <param name="presenceFilter">Indicates the presence of users who should be included in the group.</param>
 /// <param name="relationshipFilter">Indicates the relationship to the local user of users who should be included in the group.</param>
 /// <param name="titleId">The title id to filter users to.</param>
 internal XboxSocialUserGroup(XboxLiveUser localUser, PresenceFilter presenceFilter, RelationshipFilter relationshipFilter, uint titleId)
     : this(localUser, SocialUserGroupType.Filter)
 {
     this.PresenceFilter     = presenceFilter;
     this.RelationshipFilter = relationshipFilter;
     this.TitleId            = titleId;
 }
Ejemplo n.º 26
0
        public XboxSocialUserGroup CreateSocialUserGroupFromFilters(XboxLiveUser user, PresenceFilter presenceFilter, RelationshipFilter relationshipFilter)
        {
            Dictionary <string, XboxSocialUser> users = Enumerable.Range(0, 5)
                                                        .Select(id =>
            {
                var groupUser = CreateUser();

                switch (presenceFilter)
                {
                case PresenceFilter.AllOnline:
                case PresenceFilter.TitleOnline:
                    InitUserForOnlinePresence(ref groupUser);
                    break;

                case PresenceFilter.AllOffline:
                case PresenceFilter.TitleOffline:
                    InitUserForOfflinePresence(ref groupUser);
                    break;

                case PresenceFilter.AllTitle:
                case PresenceFilter.All:
                    if (id % 2 == 0)
                    {
                        InitUserForOnlinePresence(ref groupUser);
                    }
                    else
                    {
                        InitUserForOfflinePresence(ref groupUser);
                    }
                    break;
                }

                switch (relationshipFilter)
                {
                case RelationshipFilter.Friends:
                    groupUser.IsFollowedByCaller = true;
                    break;

                case RelationshipFilter.Favorite:
                    groupUser.IsFollowedByCaller = true;
                    groupUser.IsFavorite         = true;
                    break;
                }

                return(groupUser);
            }).ToDictionary(u => u.XboxUserId);

            XboxSocialUserGroup group = new XboxSocialUserGroup(user, SocialUserGroupType.Filter, presenceFilter, relationshipFilter, users);

            mEvents.Add(new SocialEvent(SocialEventType.SocialUserGroupLoaded, user, null, group));

            return(group);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Series && mediaType != FanArtMediaTypes.SeriesSeason && mediaType != FanArtMediaTypes.Episode)
            {
                return(false);
            }

            if (!Guid.TryParse(name, out mediaItemId))
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter filter = null;

            if (mediaType == FanArtMediaTypes.Series)
            {
                filter = new RelationshipFilter(EpisodeAspect.ROLE_EPISODE, SeriesAspect.ROLE_SERIES, mediaItemId);
            }
            else if (mediaType == FanArtMediaTypes.SeriesSeason)
            {
                filter = new RelationshipFilter(EpisodeAspect.ROLE_EPISODE, SeasonAspect.ROLE_SEASON, mediaItemId);
            }
            else if (mediaType == FanArtMediaTypes.Episode)
            {
                filter = new MediaItemIdFilter(mediaItemId);
            }
            MediaItemQuery episodeQuery = new MediaItemQuery(NECESSARY_MIAS, filter);

            episodeQuery.Limit = 1;
            IList <MediaItem> items = mediaLibrary.Search(episodeQuery, false, null, false);

            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaItemLocator = mediaItem.GetResourceLocator();
            var fanArtPaths      = new List <ResourcePath>();

            // File based access
            try
            {
                var mediaItemPath = mediaItemLocator.NativeResourcePath;
                int seasonNo      = -1;
                MediaItemAspect.TryGetAttribute(mediaItem.Aspects, EpisodeAspect.ATTR_SEASON, out seasonNo);
                var  seasonFolderPath = ResourcePathHelper.Combine(mediaItemPath, "../");
                var  seriesFolderPath = GetSeriesFolderFromEpisodePath(mediaItemLocator.NativeSystemId, mediaItemPath, seasonNo);
                bool hasSeasonFolders = seasonFolderPath != seriesFolderPath;

                //Episode FanArt
                if (mediaType == FanArtMediaTypes.Episode)
                {
                    if (fanArtType == FanArtTypes.Undefined || fanArtType == FanArtTypes.Thumbnail)
                    {
                        AddEpisodeFanArt(fanArtPaths, fanArtType, mediaItemLocator.NativeSystemId, mediaItemPath);
                    }
                    else
                    {
                        AddSeriesFanArt(fanArtPaths, fanArtType, mediaItemLocator.NativeSystemId, seriesFolderPath);
                    }
                }

                //Season FanArt
                if (mediaType == FanArtMediaTypes.SeriesSeason)
                {
                    if (hasSeasonFolders)
                    {
                        AddSeriesFanArt(fanArtPaths, fanArtType, mediaItemLocator.NativeSystemId, seasonFolderPath);
                        AddSpecialSeasonFolderFanArt(fanArtPaths, fanArtType, mediaItemLocator.NativeSystemId, seasonFolderPath, seasonNo);
                    }
                    else
                    {
                        AddSpecialSeasonFolderFanArt(fanArtPaths, fanArtType, mediaItemLocator.NativeSystemId, seasonFolderPath, seasonNo);
                    }

                    if (hasSeasonFolders && fanArtPaths.Count == 0)
                    {
                        //Series fallback
                        AddSeriesFanArt(fanArtPaths, fanArtType, mediaItemLocator.NativeSystemId, seriesFolderPath);
                    }
                }

                //Series FanArt
                if (mediaType == FanArtMediaTypes.Series)
                {
                    AddSeriesFanArt(fanArtPaths, fanArtType, mediaItemLocator.NativeSystemId, seriesFolderPath);
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalSeriesFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaItemLocator);
#endif
            }
            result = fanArtPaths.Select(p => (IResourceLocator) new ResourceLocator(mediaItemLocator.NativeSystemId, p)).ToList();
            return(result.Count > 0);
        }
        public XboxSocialUserGroup CreateSocialUserGroupFromFilters(XboxLiveUser user, PresenceFilter presenceFilter, RelationshipFilter relationshipFilter, uint titleId)
        {
            var group = new XboxSocialUserGroup(user, presenceFilter, relationshipFilter, titleId);

            var users = Enumerable.Range(0, 5)
                        .Select(id =>
            {
                var groupUser = CreateUser(0);

                switch (presenceFilter)
                {
                case PresenceFilter.TitleOnline:
                    groupUser.PresenceState   = UserPresenceState.Online;
                    groupUser.PresenceDetails = new List <SocialManagerPresenceTitleRecord>
                    {
                        new SocialManagerPresenceTitleRecord
                        {
                            TitleId       = titleId,
                            IsTitleActive = false,
                        }
                    };
                    break;

                case PresenceFilter.TitleOffline:
                    groupUser.PresenceState = UserPresenceState.Offline;
                    groupUser.TitleHistory  = new TitleHistory
                    {
                        HasUserPlayed      = true,
                        LastTimeUserPlayed = DateTime.UtcNow.AddDays(-1),
                    };
                    break;

                case PresenceFilter.AllOnline:
                    groupUser.PresenceState = UserPresenceState.Online;
                    break;

                case PresenceFilter.AllOffline:
                    groupUser.PresenceState = UserPresenceState.Offline;
                    break;

                case PresenceFilter.AllTitle:
                    break;
                }

                switch (relationshipFilter)
                {
                case RelationshipFilter.Friends:
                    groupUser.IsFollowedByCaller = true;
                    break;

                case RelationshipFilter.Favorite:
                    groupUser.IsFollowedByCaller = true;
                    groupUser.IsFavorite         = true;
                    break;
                }

                return(groupUser);
            }).ToDictionary(u => u.XboxUserId);

            group.UpdateView(users, new List <SocialEvent>());

            return(group);
        }
Ejemplo n.º 29
0
        public XboxSocialUserGroup CreateSocialUserGroupFromFilters(XboxLiveUser user, PresenceFilter presenceFilter, RelationshipFilter relationshipFilter, uint titleId)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            SocialGraph userGraph;

            if (!this.userGraphs.TryGetValue(user, out userGraph))
            {
                throw new ArgumentException("You must add a local user before you can create a social group for them.", "user");
            }

            XboxSocialUserGroup group = new XboxSocialUserGroup(user, presenceFilter, relationshipFilter, XboxLiveAppConfiguration.Instance.TitleId);

            if (userGraph.IsInitialized)
            {
                group.InitializeGroup(userGraph.ActiveUsers);
            }

            this.AddUserGroup(user, group);

            this.eventQueue.Enqueue(new SocialEvent(SocialEventType.SocialUserGroupLoaded, user, null, group));

            return(group);
        }
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Series && mediaType != FanArtMediaTypes.Episode)
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId) || mediaType == FanArtMediaTypes.Image)
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter filter = null;

            if (mediaType == FanArtMediaTypes.Series)
            {
                filter = new RelationshipFilter(EpisodeAspect.ROLE_EPISODE, SeriesAspect.ROLE_SERIES, mediaItemId);
            }
            else if (mediaType == FanArtMediaTypes.Episode)
            {
                filter = new MediaItemIdFilter(mediaItemId);
            }
            MediaItemQuery episodeQuery = new MediaItemQuery(NECESSARY_MIAS, filter);

            episodeQuery.Limit = 1;
            IList <MediaItem> items = mediaLibrary.Search(episodeQuery, false, null, false);

            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem         = items.First();
            var       mediaIteamLocator = mediaItem.GetResourceLocator();

            // Virtual resources won't have any local fanart
            if (mediaIteamLocator.NativeResourcePath.BasePathSegment.ProviderId == VirtualResourceProvider.VIRTUAL_RESOURCE_PROVIDER_ID)
            {
                return(false);
            }
            var fanArtPaths = new List <ResourcePath>();
            var files       = new List <IResourceLocator>();

            // File based access
            try
            {
                var mediaItemPath                     = mediaIteamLocator.NativeResourcePath;
                var mediaItemDirectoryPath            = ResourcePathHelper.Combine(mediaItemPath, "../../");
                var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();
                var mediaItemExtension                = ResourcePathHelper.GetExtension(mediaItemPath.ToString());

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = GetPotentialFanArtFiles(directoryFsra);

                        if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "poster" || potentialFanArtFileNameWithoutExtension == "folder"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.Banner)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "banner"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.Logo)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "logo"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.ClearArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "clearart"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.FanArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "backdrop" || potentialFanArtFileNameWithoutExtension == "fanart"
                                                                              select potentialFanArtFile);

                            if (directoryFsra.ResourceExists("ExtraFanArt/"))
                            {
                                using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                    fanArtPaths.AddRange(GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                            }
                        }

                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalSeriesFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Actor || (fanArtType != FanArtTypes.Undefined && fanArtType != FanArtTypes.Thumbnail))
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId))
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter        = new RelationshipFilter(EpisodeAspect.ROLE_EPISODE, PersonAspect.ROLE_ACTOR, mediaItemId);
            IList <MediaItem> items         = null;
            List <Guid>       necessaryMias = new List <Guid>(NECESSARY_MIAS);
            MediaItemQuery    mediaQuery    = new MediaItemQuery(necessaryMias, filter);

            mediaQuery.Limit = 1;
            items            = mediaLibrary.Search(mediaQuery, false, null, false);
            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem         = items.First();
            var       mediaIteamLocator = mediaItem.GetResourceLocator();

            // Virtual resources won't have any local fanart
            if (mediaIteamLocator.NativeResourcePath.BasePathSegment.ProviderId == VirtualResourceProvider.VIRTUAL_RESOURCE_PROVIDER_ID)
            {
                return(false);
            }
            var fanArtPaths = new List <ResourcePath>();
            var files       = new List <IResourceLocator>();

            string actorName = null;
            SingleMediaItemAspect videoAspect;
            List <string>         actors = new List <string>();

            if (MediaItemAspect.TryGetAspect(mediaItem.Aspects, VideoAspect.Metadata, out videoAspect))
            {
                IEnumerable <object> actorObjects = videoAspect.GetCollectionAttribute <object>(VideoAspect.ATTR_ACTORS);
                if (actorObjects != null)
                {
                    actors.AddRange(actorObjects.Cast <string>());
                }
            }

            IList <MultipleMediaItemAspect> relationAspects;

            if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
            {
                foreach (MultipleMediaItemAspect relation in relationAspects)
                {
                    if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == PersonAspect.ROLE_ACTOR && (Guid?)relation[RelationshipAspect.ATTR_LINKED_ID] == mediaItemId)
                    {
                        int?index = (int?)relation[RelationshipAspect.ATTR_RELATIONSHIP_INDEX];
                        if (index.HasValue && actors.Count > index.Value && index.Value >= 0)
                        {
                            actorName = actors[index.Value];
                        }
                    }
                }
            }

            // File based access
            try
            {
                var mediaItemPath = mediaIteamLocator.NativeResourcePath;
                var seasonMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../");
                var seriesMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../../");

                if (!string.IsNullOrEmpty(actorName))
                {
                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, seriesMediaItemDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            //Get Artists thumbs
                            IFileSystemResourceAccessor actorMediaItemDirectory = directoryFsra.GetResource(".actors");
                            if (actorMediaItemDirectory != null)
                            {
                                var potentialArtistFanArtFiles = GetPotentialFanArtFiles(actorMediaItemDirectory);

                                foreach (ResourcePath thumbPath in
                                         from potentialFanArtFile in potentialArtistFanArtFiles
                                         let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString())
                                                                                       where potentialFanArtFileNameWithoutExtension.StartsWith(actorName.Replace(" ", "_"), StringComparison.InvariantCultureIgnoreCase)
                                                                                       select potentialFanArtFile)
                                {
                                    files.Add(new ResourceLocator(mediaIteamLocator.NativeSystemId, thumbPath));
                                }
                            }
                        }
                    }

                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, seasonMediaItemDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            //Get Artists thumbs
                            IFileSystemResourceAccessor actorMediaItemDirectory = directoryFsra.GetResource(".actors");
                            if (actorMediaItemDirectory != null)
                            {
                                var potentialArtistFanArtFiles = GetPotentialFanArtFiles(actorMediaItemDirectory);

                                foreach (ResourcePath thumbPath in
                                         from potentialFanArtFile in potentialArtistFanArtFiles
                                         let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                       where potentialFanArtFileNameWithoutExtension.StartsWith(actorName.Replace(" ", "_"))
                                                                                       select potentialFanArtFile)
                                {
                                    files.Add(new ResourceLocator(mediaIteamLocator.NativeSystemId, thumbPath));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalSeriesActorFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Artist && mediaType != FanArtMediaTypes.Album && mediaType != FanArtMediaTypes.Audio)
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId))
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter        = null;
            IList <MediaItem> items         = null;
            List <Guid>       necessaryMias = new List <Guid>(NECESSARY_MIAS);

            if (mediaType == FanArtMediaTypes.Artist)
            {
                necessaryMias.Add(AudioAspect.ASPECT_ID);
                necessaryMias.Add(RelationshipAspect.ASPECT_ID);
                filter = new RelationshipFilter(AudioAspect.ROLE_TRACK, PersonAspect.ROLE_ALBUMARTIST, mediaItemId);
            }
            else if (fanArtType == FanArtTypes.FanArt)
            {
                if (mediaType == FanArtMediaTypes.Album)
                {
                    //Might be a request for album FanArt which doesn't exist. Artist FanArt is used instead.
                    filter = new RelationshipFilter(AudioAspect.ROLE_TRACK, AudioAlbumAspect.ROLE_ALBUM, mediaItemId);
                }
                else if (mediaType == FanArtMediaTypes.Audio)
                {
                    //Might be a request for track FanArt which doesn't exist. Artist FanArt is used instead.
                    necessaryMias.Add(AudioAspect.ASPECT_ID);
                    filter = new MediaItemIdFilter(mediaItemId);
                }
            }
            else
            {
                return(false);
            }

            MediaItemQuery mediaQuery = new MediaItemQuery(necessaryMias, filter);

            mediaQuery.Limit = 1;
            items            = mediaLibrary.Search(mediaQuery, false, null, false);
            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();
            var fanArtPaths       = new List <ResourcePath>();
            var files             = new List <IResourceLocator>();

            string artistName    = null;
            var    mediaItemPath = mediaIteamLocator.NativeResourcePath;
            var    albumMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../");
            var    artistMediaItemPath         = ResourcePathHelper.Combine(mediaItemPath, "../../");
            string album = null;

            if (MediaItemAspect.TryGetAttribute(mediaItem.Aspects, AudioAspect.ATTR_ALBUM, out album) && LocalFanartHelper.IsDiscFolder(album, albumMediaItemDirectoryPath.FileName))
            {
                //Probably a CD folder so try next parent
                albumMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../../");
                artistMediaItemPath         = ResourcePathHelper.Combine(mediaItemPath, "../../../");
            }
            if (mediaType == FanArtMediaTypes.Artist)
            {
                SingleMediaItemAspect audioAspect;
                List <string>         artists = new List <string>();
                if (MediaItemAspect.TryGetAspect(mediaItem.Aspects, AudioAspect.Metadata, out audioAspect))
                {
                    IEnumerable <object> artistObjects = audioAspect.GetCollectionAttribute <object>(AudioAspect.ATTR_ALBUMARTISTS);
                    if (artistObjects != null)
                    {
                        artists.AddRange(artistObjects.Cast <string>());
                    }
                }

                IList <MultipleMediaItemAspect> relationAspects;
                if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
                {
                    foreach (MultipleMediaItemAspect relation in relationAspects)
                    {
                        if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == PersonAspect.ROLE_ALBUMARTIST && (Guid?)relation[RelationshipAspect.ATTR_LINKED_ID] == mediaItemId)
                        {
                            int?index = (int?)relation[RelationshipAspect.ATTR_RELATIONSHIP_INDEX];
                            if (index.HasValue && artists.Count > index.Value && index.Value >= 0)
                            {
                                artistName = artists[index.Value];
                            }
                            break;
                        }
                    }
                }
            }

            // File based access
            try
            {
                var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();
                var mediaItemExtension = ResourcePathHelper.GetExtension(mediaItemPath.ToString());

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, artistMediaItemPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        if (fanArtType == FanArtTypes.Undefined || fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.ARTIST_FILENAMES));
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.POSTER_FILENAMES));
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.THUMB_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.Banner)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BANNER_FILENAMES));
                        }


                        if (fanArtType == FanArtTypes.Logo)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.LOGO_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.ClearArt)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.CLEARART_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.FanArt)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES));

                            if (directoryFsra.ResourceExists("ExtraFanArt/"))
                            {
                                using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                    fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                            }
                        }

                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }

                if (!string.IsNullOrEmpty(artistName)) //Only one artist was found
                {
                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, albumMediaItemDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            //Get Artists thumbs
                            IFileSystemResourceAccessor alternateArtistMediaItemDirectory = directoryFsra.GetResource(".artists");
                            if (alternateArtistMediaItemDirectory != null)
                            {
                                var potentialArtistFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(alternateArtistMediaItemDirectory);

                                foreach (ResourcePath thumbPath in
                                         from potentialFanArtFile in potentialArtistFanArtFiles
                                         let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString())
                                                                                       where potentialFanArtFileNameWithoutExtension.StartsWith(artistName.Replace(" ", "_"), StringComparison.InvariantCultureIgnoreCase)
                                                                                       select potentialFanArtFile)
                                {
                                    files.Add(new ResourceLocator(mediaIteamLocator.NativeSystemId, thumbPath));
                                }
                            }
                        }
                    }

                    //Find central artist information folder
                    ResourcePath centralArtistFolderPath = LocalFanartHelper.GetCentralPersonFolder(artistMediaItemPath, CentralPersonFolderType.AudioArtists);
                    if (centralArtistFolderPath != null)
                    {
                        // First get the ResourcePath of the central directory
                        var artistFolderPath = ResourcePathHelper.Combine(centralArtistFolderPath, $"{LocalFanartHelper.GetSafePersonFolderName(artistName)}/");

                        // Then try to create an IFileSystemResourceAccessor for this directory
                        artistFolderPath.TryCreateLocalResourceAccessor(out var artistNfoDirectoryRa);
                        var directoryFsra = artistNfoDirectoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                            if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.ARTIST_FILENAMES));
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.POSTER_FILENAMES));
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.THUMB_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.Banner)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BANNER_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.Logo)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.LOGO_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.ClearArt)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.CLEARART_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.FanArt)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES));

                                if (directoryFsra.ResourceExists("ExtraFanArt/"))
                                {
                                    using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                        fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                                }
                            }

                            files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalArtistFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }