示例#1
0
 public Provider(LyricsReloaded lyricsReloaded, string name, ushort quality, IDictionary <string, Variable> variables, FilterCollection postFilters, ValidationCollection validations, IDictionary <String, String> headers, LyricsLoader loader, RateLimit rateLimit = null)
 {
     this.lyricsReloaded = lyricsReloaded;
     this.name           = name;
     this.quality        = quality;
     this.variables      = variables;
     this.postFilters    = postFilters;
     this.validations    = validations;
     this.headers        = headers;
     this.loader         = loader;
     this.rateLimit      = rateLimit;
 }
        /// <summary>
        /// Performs a scan in the directory that contains the music file for a
        /// matching lyrics file.
        /// </summary>
        /// <param name="SongInfo">An <see cref="ISongInfo"/> instance that holds informations about a song.</param>
        /// <returns>An <see cref="ILyricsReader"/> instance if the lyrics is found or null otherwise.</returns>
        private ILyricsReader ScanFileDirectory(ISongInfo SongInfo)
        {
            string Dir = Path.GetDirectoryName(SongInfo.Source);

            #region Error checking
            if (!Directory.Exists(Dir))
            {
                return(null);
            }
            #endregion

            //Try to find a lyrics file with the same name as in SongInfo.
            //Eg. if we have "test.mp3", try to find "test.lrc".
            foreach (var Ext in LyricsLoader.SupportedExtensions)
            {
                string Filename = Path.ChangeExtension(SongInfo.Source, Ext);

                if (File.Exists(Filename))
                {
                    return(LyricsLoader.LoadFile(Filename));
                }
            }

            //Scan all the lyrics files in the same folder.
            foreach (var File in LyricsLoader.FindAllLyricsFiles(Dir))
            {
                try {
                    ILyricsReader   reader   = LyricsLoader.LoadFile(File);
                    ILyricsMetadata metadata = reader as ILyricsMetadata;

                    if (metadata != null)
                    {
                        if (metadata.Title == SongInfo.Title && metadata.Artist == SongInfo.Artist)
                        {
                            return(reader);
                        }
                    }
                }
                catch {}
            }

            //If lyrics was not found, null is returned.
            return(null);
        }
示例#3
0
        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog()
            {
                Filter = "Dalszöveg fájlok|*.lrc;*.xml"
            };

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                this.LyricsReader = LyricsLoader.LoadFile(dlg.FileName);

                if (this.LyricsReader == null)
                {
                    MessageBox.Show("Úgy tűnik, ez a fájl nem dalszöveg-fájl.");
                }
                else
                {
                    lFilename.Text = new FileInfo(dlg.FileName).Name;
                }
            }
        }
        /// <summary>
        /// Finds a lyrics file asynchronously using the informations provided by an
        /// ISongInfo instance.
        /// </summary>
        /// <param name="SongInfo">An ISongInfo instance that holds informations about a song.</param>
        /// <returns>A Task for an ILyricsReader instance if the lyrics is found or null otherwise.</returns>
        public async Task <ILyricsReader> FindLyricsAsync(ISongInfo SongInfo)
        {
            #region Error checking
            if (SongInfo == null)
            {
                return(null);
            }
            #endregion

            using (WebClient Client = new WebClient()) {
                Client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                Client.Headers[HttpRequestHeader.UserAgent]   = $"{App.Name} (version {App.Version})";

                string Data = $"title={UrlEncode(SongInfo.Title)}&artist={UrlEncode(SongInfo.Artist)}";
                string Response;
                try {
                    Response = await Client.UploadStringTaskAsync(
                        "http://tomisoft.site90.net/lyrics/api.getlrc.php?get_lyrics=true",
                        Data
                        );
                }
                catch (WebException) {
                    return(null);
                }

                if (Response != "NOTFOUND")
                {
                    string Filename = Path.GetTempFileName();

                    if (await CreateFileAsync(Filename, Response))
                    {
                        return(LyricsLoader.LoadFile(Filename));
                    }
                }
            }

            return(null);
        }
示例#5
0
        /// <summary>
        /// Loads a configuration from any TextReader
        /// </summary>
        /// <param name="configReader">the reader</param>
        /// <exception cref="InvalidConfigurationException">if an error occurs during configuration loading</exception>
        public void loadProvider(TextReader configReader)
        {
            YamlStream yaml = new YamlStream();

            try
            {
                yaml.Load(configReader);
            }
            catch (Exception e)
            {
                throw new InvalidConfigurationException(e.Message, e);
            }

            YamlNode node;
            IDictionary <YamlNode, YamlNode> rootNodes = ((YamlMappingNode)yaml.Documents[0].RootNode).Children;

            string loaderName;

            node = (rootNodes.ContainsKey(Node.LOADER) ? rootNodes[Node.LOADER] : null);
            if (node is YamlScalarNode)
            {
                loaderName = ((YamlScalarNode)node).Value.Trim().ToLower();
            }
            else
            {
                loaderName = "static";
            }
            if (!loaderFactories.ContainsKey(loaderName))
            {
                throw new InvalidConfigurationException("Unknown provider type " + loaderName + ", skipping");
            }
            LyricsLoaderFactory loaderFactory = loaderFactories[loaderName];

            node = (rootNodes.ContainsKey(Node.NAME) ? rootNodes[Node.NAME] : null);
            if (!(node is YamlScalarNode))
            {
                throw new InvalidConfigurationException("No provider name given!");
            }
            string name = ((YamlScalarNode)node).Value.Trim();

            ushort quality = 50;

            node = (rootNodes.ContainsKey(Node.QUALITY) ? rootNodes[Node.QUALITY] : null);
            if (node is YamlScalarNode)
            {
                try
                {
                    quality = Convert.ToUInt16(((YamlScalarNode)node).Value.Trim());
                }
                catch (FormatException e)
                {
                    throw new InvalidConfigurationException("Invalid quality value given, only positive numbers >= 0 are allowed!", e);
                }
            }

            RateLimit rateLimit = null;

            node = (rootNodes.ContainsKey(Node.RATE_LIMIT) ? rootNodes[Node.RATE_LIMIT] : null);
            if (node is YamlScalarNode)
            {
                rateLimit = RateLimit.parse(((YamlScalarNode)node).Value.Trim());
            }

            node = (rootNodes.ContainsKey(Node.VARIABLES) ? rootNodes[Node.VARIABLES] : null);
            Dictionary <string, Variable> variables = new Dictionary <string, Variable>();

            if (node is YamlMappingNode)
            {
                foreach (KeyValuePair <YamlNode, YamlNode> preparationEntry in ((YamlMappingNode)node).Children)
                {
                    node = preparationEntry.Key;
                    if (node is YamlScalarNode)
                    {
                        string variableName = ((YamlScalarNode)node).Value.ToLower();

                        if (variables.ContainsKey(variableName))
                        {
                            throw InvalidConfigurationException.fromFormat("{0}: Variable already defined!", variableName);
                        }

                        node = preparationEntry.Value;
                        // variable value without filters
                        if (node is YamlScalarNode)
                        {
                            string typeString = ((YamlScalarNode)node).Value.ToLower();
                            try
                            {
                                Variable.Type variableType = VARIABLE_TYPES[typeString];
                                variables.Add(variableName, new Variable(variableName, variableType));
                            }
                            catch
                            {
                                throw InvalidConfigurationException.fromFormat("{0}: Unknown variable type {1}!", variableName, typeString);
                            }
                        }
                        // value with filters expected
                        else if (node is YamlMappingNode)
                        {
                            YamlMappingNode variableConfig = (YamlMappingNode)node;

                            node = variableConfig.Children[Node.Variables.TYPE];
                            if (!(node is YamlScalarNode))
                            {
                                throw InvalidConfigurationException.fromFormat("{0}: Invalid variable type!", variableName);
                            }

                            Variable.Type type;
                            string        typeString = ((YamlScalarNode)node).Value.ToLower();
                            try
                            {
                                type = VARIABLE_TYPES[typeString];
                            }
                            catch
                            {
                                throw InvalidConfigurationException.fromFormat("{0}: Unknown variable type {1}!", variableName, typeString);
                            }

                            FilterCollection filterCollection;

                            node = (variableConfig.Children.ContainsKey(Node.Variables.FILTERS) ? variableConfig.Children[Node.Variables.FILTERS] : null);
                            // variable reference
                            if (node is YamlScalarNode)
                            {
                                string referencedVar = ((YamlScalarNode)node).Value.ToLower();
                                try
                                {
                                    filterCollection = variables[referencedVar].getFilters();
                                }
                                catch
                                {
                                    throw InvalidConfigurationException.fromFormat("{0}: Unknown variable {1} referenced!", variableName, referencedVar);
                                }
                            }
                            // a list of filters
                            else if (node is YamlSequenceNode)
                            {
                                filterCollection = FilterCollection.parseList((YamlSequenceNode)node, filters);
                            }
                            else
                            {
                                throw new InvalidConfigurationException("Invalid filter option specified!");
                            }

                            variables.Add(variableName, new Variable(variableName, type, filterCollection));
                        }
                    }
                    else
                    {
                        throw new InvalidConfigurationException("Invalid configration, aborting the configuration.");
                    }
                }
            }

            foreach (KeyValuePair <string, Variable.Type> entry in VARIABLE_TYPES)
            {
                if (!variables.ContainsKey(entry.Key))
                {
                    variables.Add(entry.Key, new Variable(entry.Key, entry.Value));
                }
            }

            node = (rootNodes.ContainsKey(Node.POST_FILTERS) ? rootNodes[Node.POST_FILTERS] : null);
            FilterCollection postFilters;

            if (node is YamlSequenceNode)
            {
                postFilters = FilterCollection.parseList((YamlSequenceNode)node, filters);
            }
            else
            {
                postFilters = new FilterCollection();
            }

            node = (rootNodes.ContainsKey(Node.VALIDATIONS) ? rootNodes[Node.VALIDATIONS] : null);
            ValidationCollection validations;

            if (node is YamlSequenceNode)
            {
                validations = ValidationCollection.parseList((YamlSequenceNode)node, validators);
            }
            else
            {
                validations = new ValidationCollection();
            }

            IDictionary <String, String> headers = new Dictionary <String, String>();

            node = (rootNodes.ContainsKey(Node.HEADERS) ? rootNodes[Node.HEADERS] : null);
            if (node is YamlMappingNode)
            {
                foreach (KeyValuePair <YamlNode, YamlNode> entry in (YamlMappingNode)node)
                {
                    if (entry.Key is YamlScalarNode && entry.Value is YamlScalarNode)
                    {
                        headers.Add(((YamlScalarNode)entry.Key).Value.Trim(), ((YamlScalarNode)entry.Value).Value);
                    }
                }
            }

            YamlMappingNode configNode;

            node = (rootNodes.ContainsKey(Node.CONFIG) ? rootNodes[Node.CONFIG] : null);
            if (node is YamlMappingNode)
            {
                configNode = (YamlMappingNode)node;
            }
            else
            {
                configNode = new YamlMappingNode();
            }

            LyricsLoader loader = loaderFactory.newLoader(configNode);

            Provider provider = new Provider(lyricsReloaded, name, quality, variables, postFilters, validations, headers, loader, rateLimit);

            logger.info("Provider loaded: " + provider.getName());

            lock (providerLock)
            {
                if (providers.ContainsKey(provider.getName()))
                {
                    logger.info("The provider {0} does already exist and will be replaced.", provider.getName());
                    providers.Remove(provider.getName());
                }
                providers.Add(provider.getName(), provider);
            }
        }