protected int CompareMediaFiles(SubtitleInfo subtitle, int matchPct) { int maxPct = 0; var subtitleFileName = ResourcePath.GetFileNameWithoutExtension(subtitle.Name); foreach (var mediaFile in subtitle.MediaFiles) { int pct = 0; var mediaFileName = ResourcePath.GetFileNameWithoutExtension(mediaFile.NativeResourcePath.FileName); //Compare file names if (subtitleFileName.Equals(mediaFileName, StringComparison.InvariantCultureIgnoreCase)) { return(100); } //Compare tags pct = Math.Max(CompareTags(subtitleFileName, mediaFileName), pct); //Compare letter pairs pct = Math.Max(CompareLetterPairs(subtitleFileName, mediaFileName), pct); maxPct = Math.Max(maxPct, pct); } return(maxPct + matchPct); }
private void BuildSubtitleInfos(Period period) { // Prevent simultaneous access to GetSubtitleInfo() / subtitleInfos.Clear() // lock (subtitleInfos) { subtitleInfos.Clear(); var textAdaptationSets = period.Sets.Where(o => o.Type.Value == MediaType.Text).ToList(); foreach (var textAdaptationSet in textAdaptationSets) { var lang = textAdaptationSet.Lang; var mimeType = textAdaptationSet.Type; foreach (var representation in textAdaptationSet.Representations) { var mediaSegments = representation.Segments.MediaSegments().ToList(); if (!mediaSegments.Any()) { continue; } var segment = mediaSegments.First(); var streamDescription = new SubtitleInfo { Id = subtitleInfos.Count, Language = lang, Path = segment.Url.ToString(), MimeType = mimeType?.Key }; subtitleInfos.Add(streamDescription); } } } }
List <SubtitleInfo> LoadSubs() { string filePath = Path.Combine(Application.streamingAssetsPath, FILENAME); if (File.Exists(filePath)) { string dataAsJson = File.ReadAllText(filePath); string[] subsarray = dataAsJson.Split('|'); subtitles = new List <SubtitleInfo>(); foreach (string sub in subsarray) { SubtitleInfo subtitleInfo = JsonUtility.FromJson <SubtitleInfo>(sub); subtitles.Add(subtitleInfo); } return(subtitles); } else { Debug.LogError("Fail to load subs"); return(null); } }
private void GenerateAviSynthScript(Size resizeTo) { SubtitleInfo sub = _jobInfo.SubtitleStreams.FirstOrDefault(item => item.HardSubIntoVideo); string subFile = string.Empty; bool keepOnlyForced = false; if (sub != null) { subFile = sub.TempFile; keepOnlyForced = sub.KeepOnlyForcedCaptions; } _jobInfo.AviSynthScript = AviSynthGenerator.Generate(_jobInfo.VideoStream, false, 0f, resizeTo, _jobInfo.EncodingProfile.StereoType, _jobInfo.StereoVideoStream, false, subFile, keepOnlyForced, AppSettings.Use64BitEncoders && AppSettings.UseFfmpegScaling); if (!string.IsNullOrEmpty(AviSynthGenerator.StereoConfigFile)) { _jobInfo.AviSynthStereoConfig = AviSynthGenerator.StereoConfigFile; } }
protected override List <SubtitleInfo> DoGetSubtitles(VideoInfo vi) { List <SubtitleInfo> retVal = new List <SubtitleInfo>(); SearchResult res = _wsdl.searchSubtitles(_sessionToken, vi.moviehash, (long)vi.moviebytesize, vi.sublanguageid, vi.imdbid); if (res.data != null && res.data.Length > 0) { foreach (SubtitleData sd in res.data) { SubtitleInfo si = new SubtitleInfo(); si.IDSubtitleFile = sd.subID.ToString(); si.SubFileName = sd.subName; si.MovieName = sd.movieName; si.SubHash = sd.subHash; si.LanguageName = OPMedia.Core.Language.ThreeLetterISOLanguageNameToEnglishName(sd.subLang); si.MovieHash = vi.moviehash; si.SubDownloadLink = sd.subDownloadLink; si.SubFormat = sd.subFormat; retVal.Add(si); } } return(retVal); }
void SubtitleScale() { if (m_pSubtitle.Count <= 0) { return; } float fTime = m_fStartOffset + m_pAudio.time; SubtitleInfo pInfo = m_pSubtitle.Peek(); float fStartOffset = fTime - pInfo.m_fStartTime; float fEndOffset = fTime - pInfo.m_fEndTime; if (fStartOffset >= 0.2f && fEndOffset <= 0.75f) { m_pSubtitleText.text = pInfo.m_pSubtitle; } else if (fEndOffset > 0.75f) { m_pSubtitleText.text = null; m_pSubtitle.Dequeue(); } else { m_pSubtitleText.text = null; } }
public CuesMap LoadSubtitles(SubtitleInfo subtitleInfo) { var stream = LoadSubtitle(subtitleInfo.Path); var parser = CreateSubtitleParser(subtitleInfo); return(FillCuesMap(parser, stream, subtitleInfo.Encoding)); }
protected override async Task<List<SubtitleInfo>> SearchMovieSubtitlesAsync(SubtitleInfo subtitleSearch, List<string> languages) { var langs = languages.Select(s => new CultureInfo(s).ThreeLetterISOLanguageName); List<SubtitleDownloaderResult> results = new List<SubtitleDownloaderResult>(); if (!string.IsNullOrEmpty(subtitleSearch.ImdbId)) results = await _subtitleDownloaderHandler.SearchMovieSubtitlesByImdbIdAsync(subtitleSearch.ImdbId, langs.ToArray()); if (results.Count == 0) results = await _subtitleDownloaderHandler.SearchMovieSubtitlesByTitleAndYearAsync(subtitleSearch.MediaTitle, subtitleSearch.Year, langs.ToArray()); if (results.Count == 0) results = await _subtitleDownloaderHandler.SearchMovieSubtitlesByTitleAndYearAsync(CleanMovieTitle(subtitleSearch.MediaTitle), subtitleSearch.Year, langs.ToArray()); return results.Select(s => new SubtitleInfo { DisplayName = Path.GetFileNameWithoutExtension(s.FileName), Name = s.FileName, ImdbId = subtitleSearch.ImdbId, Language = GetCultureInfoName(s.LanguageCode), MediaFiles = subtitleSearch.MediaFiles, MediaTitle = subtitleSearch.MediaTitle, MovieDbId = subtitleSearch.MovieDbId, SubtitleId = s.Id, Year = subtitleSearch.Year, DataProviders = new List<string>() { _providerName } }).ToList(); }
// Load subtitles directly from a TextAsset public static void loadFromXML(TextAsset file) { XmlDocument root = new XmlDocument(); root.LoadXml(file.text); // Styles Dictionary <string, SubtitleStyle> styles = new Dictionary <string, SubtitleStyle>(); foreach (XmlNode node in root.SelectNodes("subtitles/styles/style")) { string key = node.Attributes.GetNamedItem("id").Value; float red = float.Parse(node.Attributes.GetNamedItem("red").Value, System.Globalization.CultureInfo.InvariantCulture.NumberFormat); float green = float.Parse(node.Attributes.GetNamedItem("green").Value, System.Globalization.CultureInfo.InvariantCulture.NumberFormat); float blue = float.Parse(node.Attributes.GetNamedItem("blue").Value, System.Globalization.CultureInfo.InvariantCulture.NumberFormat); SubtitleStyle style = new SubtitleStyle(new Color(red, green, blue), (node.Attributes.GetNamedItem("italic").Value == "1")); styles[key] = style; } // Texts foreach (XmlNode node in root.SelectNodes("subtitles/texts/subtitle")) { string key = node.Attributes.GetNamedItem("id").Value; string message = node.InnerText; message = message.Replace("\n", ""); message = message.Replace("\r", ""); message = message.Replace("\t", ""); float duration = float.Parse(node.Attributes.GetNamedItem("duration").Value, System.Globalization.CultureInfo.InvariantCulture.NumberFormat); string style = node.Attributes.GetNamedItem("style").Value; SubtitleInfo info = new SubtitleInfo(message, duration, Color.white, true); if (styles.ContainsKey(style)) { info.color = styles[style].color; info.italic = styles[style].italic; } subtitlesDatabase[key] = info; } }
private void OnVideoFound(object sender, EventArgs args) { var videoFile = (args as VideoFoundEventArgs).VideoFile; try { using (FileStream videoStream = File.OpenRead(videoFile.FullName)) { SubtitleStream subtitleStream = DownloadSubtitle(videoStream); if (subtitleStream != null) { using (var subFileStream = subtitleStream.Stream) { SubtitleInfo subtitleFile = subtitleStream.WriteToFile(new FileInfo(Path.ChangeExtension(videoFile.FullName, subtitleStream.Format.Extension))); if (subtitleFile != null) { SubtitleDownloaded(SubtitleDownloaded.Target, new SubtitleDownloadedEventArgs(videoFile, subtitleFile)); } } } } } catch (Exception) { // File not ready (e.g.: still being downloaded/copied/etc) } CurrentJobs.Remove(videoFile.FullName); }
private string GenerateAviSynthFile() { int targetHeight; float sourceFPS = (float)Math.Round(_jobInfo.VideoStream.FPS, 3); float targetFPS = 0f; bool changeFPS = false; int targetWidth = _jobInfo.VideoStream.AspectRatio >= 1.4f ? 1024 : 720; if (_jobInfo.Input == InputType.InputDvd) { _jobInfo.VideoStream.Width = (int)Math.Round(_jobInfo.VideoStream.Height * _jobInfo.VideoStream.AspectRatio, 0); } if (_jobInfo.EncodingProfile.OutFormat == OutputType.OutputDvd) { if (_jobInfo.EncodingProfile.SystemType == 0) { targetHeight = 576; if (Math.Abs(sourceFPS - 25f) > 0) { changeFPS = true; } targetFPS = 25f; } else { targetHeight = 480; if (Math.Abs(sourceFPS - 29.970f) > 0 && Math.Abs(sourceFPS - 23.976f) > 0) { changeFPS = true; } targetFPS = (float)Math.Round(30000f / 1001f, 3); } } else { targetWidth = _jobInfo.EncodingProfile.TargetWidth; targetHeight = (int)Math.Floor(targetWidth / _jobInfo.VideoStream.AspectRatio); } Size resizeTo = new Size(targetWidth, targetHeight); SubtitleInfo sub = _jobInfo.SubtitleStreams.FirstOrDefault(item => item.HardSubIntoVideo); string subFile = string.Empty; bool keepOnlyForced = false; if (sub != null) { subFile = sub.TempFile; keepOnlyForced = sub.KeepOnlyForcedCaptions; } return(AviSynthGenerator.Generate(_jobInfo.VideoStream, changeFPS, targetFPS, resizeTo, StereoEncoding.None, new StereoVideoInfo(), true, subFile, keepOnlyForced, false)); }
public virtual async Task <bool> DownloadSubtitleAsync(SubtitleInfo info, bool overwriteExsting) { if (await InitAsync().ConfigureAwait(false)) { return(await _wrapper.DownloadSubtitleMatchesAsync(info, overwriteExsting)); } return(false); }
private static void GetSubOrVideoStep(EncodeInfo job) { if (job.VideoStream != null) { switch (job.CompletedStep) { case EncodingStep.Demux: case EncodingStep.EncodeAudio: case EncodingStep.EncodeVideo: case EncodingStep.DemuxSubtitle: SubtitleInfo sub = job.SubtitleStreams.FirstOrDefault(subInfo => subInfo.NeedConversion); int demuxSubtitleIndex = job.SubtitleStreams.FindIndex(info => info.RawStream == false); if (job.VideoProfile.Type != ProfileType.Copy && !job.VideoStream.Encoded) { job.NextStep = EncodingStep.IndexVideo; } else if (demuxSubtitleIndex > -1) { job.NextStep = EncodingStep.DemuxSubtitle; job.StreamId = demuxSubtitleIndex; } else if (((AppSettings.JavaInstalled && AppSettings.BDSup2SubInstalled) || job.EncodingProfile.OutFormat == OutputType.OutputMp4) && sub != null) { job.NextStep = EncodingStep.ProcessSubtitle; job.StreamId = job.SubtitleStreams.IndexOf(sub); } else if (job.EncodingProfile.OutFormat == OutputType.OutputDvd) { job.NextStep = EncodingStep.PreMuxResult; } else { job.NextStep = EncodingStep.MuxResult; } break; case EncodingStep.ProcessSubtitle: if (job.EncodingProfile.OutFormat == OutputType.OutputDvd) { job.NextStep = EncodingStep.PreMuxResult; } else { job.NextStep = EncodingStep.MuxResult; } break; } } else { job.NextStep = job.EncodingProfile.OutFormat == OutputType.OutputDvd ? EncodingStep.PreMuxResult : EncodingStep.MuxResult; } }
public async Task <bool> DownloadSubtitleAsync(SubtitleInfo subtitleInfo, bool overwriteExisting, string category = null) { bool success = false; foreach (ISubtitleMatcher matcher in SUBTITLE_MATCHERS.Where(m => category == null || m.Key == category).SelectMany(m => m.Value).Where(m => m.Enabled)) { success |= await matcher.DownloadSubtitleAsync(subtitleInfo, overwriteExisting).ConfigureAwait(false); } return(success); }
protected override void RankSeriesEpisodeSubtitleMatch(SubtitleInfo subtitleSearch, List <string> languages) { subtitleSearch.MatchPercentage = 100; int languageRank = languages?.IndexOf(subtitleSearch.Language) ?? -1; if (languageRank >= 0) { subtitleSearch.LanguageMatchRank = languageRank; } }
protected virtual IFilter GetSubtitlesFilter(SubtitleInfo subtitleInfo) { return(new Filter("subtitles") { Options = new Option[] { Option.FromValue($"\"{subtitleInfo.FileName}\""), new Option("si", subtitleInfo.RelativeIndex.ToString()) } }); }
async void LoadSubtitle(SubtitleInfo subtitleInfo) { //자막 파일의 인코딩 타입 추출하여 설정 var file = await subtitleInfo.GetStorageFile(true); LoadSubtitle(file, (subtitleLanguageList) => { //리스트를 전달 MessengerInstance.Send <Message>(new Message("SubtitlesLoaded", subtitleLanguageList), TransportControlViewModel.NAME); }); }
public void Resolve_SrtSubtitleInfo_ReturnsSrtFormat() { var subtitleFormatResolver = new SubtitleFormatResolver(); var subtitleInfo = new SubtitleInfo() { Path = "subtitles.srt" }; var format = subtitleFormatResolver.Resolve(subtitleInfo); Assert.That(format, Is.EqualTo(SubtitleFormat.Subrip)); }
/// <summary> /// Search for matches of Movie. This method tries to find the any matching Movies in following order: /// - Exact match using PreferredLanguage /// - Exact match using DefaultLanguage /// - If movies name contains " - ", it splits on this and tries to runs again using the first part (combined titles) /// </summary> /// <param name="movieSearch">Movie search parameters</param> /// <param name="language">Language, if <c>null</c> it takes the <see cref="PreferredLanguage"/></param> /// <returns>A list of all matching movies found.</returns> public async Task <List <SubtitleInfo> > SearchMovieSubtitleMatchesAsync(SubtitleInfo subtitleSearch, List <string> languages) { List <SubtitleInfo> subtitles = await SearchMovieSubtitlesAsync(subtitleSearch, languages).ConfigureAwait(false); if (subtitles?.Count > 0) { subtitles.ForEach(s => RankMovieSubtitleMatch(s, languages)); return(MergeMultiPartSubtitles(subtitles)); } return(null); }
private string GenerateCommandLine() { var sb = new StringBuilder(); _sub = _currentTask.SubtitleStreams[_currentTask.StreamId]; _inputFile = _currentTask.VideoStream.TempFile; _outputFile = FileSystemHelper.CreateTempFile(_appConfig.TempPath, _inputFile, $"+{_sub.LangCode}.mpg"); sb.Append($"-s {_currentTask.StreamId:0} \"{_sub.TempFile}\""); return(sb.ToString()); }
private void OnEnable() { if (msgs == null) { msgs = new List <SubtitleInfo>(); string[] lines = File.ReadAllLines(AssetDatabase.GetAssetPath(target)); foreach (var line in lines) { SubtitleInfo msg = new SubtitleInfo(); msg.InitByFormat(line); msgs.Add(msg); } } }
/// <summary> /// Ranks movie subtitle matches. /// </summary> /// <param name="subtitleSearch">Subtitle search result</param> protected virtual void RankMovieSubtitleMatch(SubtitleInfo subtitleSearch, List <string> languages) { int matchPct = 0; var match = _regexTitleYear.Match(CleanMovieTitle(subtitleSearch.Name)); if (match.Success && (match.Groups["title"].Value.Equals(subtitleSearch.MediaTitle, StringComparison.InvariantCultureIgnoreCase) || match.Groups["title"].Value.StartsWith(subtitleSearch.MediaTitle, StringComparison.InvariantCultureIgnoreCase))) { if (subtitleSearch.Year.HasValue && int.TryParse(match.Groups["year"].Value, out int subYear) && subYear == subtitleSearch.Year.Value) { matchPct = BASE_YEAR_MATCH_PCT; } else if (!subtitleSearch.Year.HasValue || string.IsNullOrEmpty(match.Groups["year"].Value)) { matchPct = BASE_MATCH_PCT; } } match = _regexMultiPartVideo.Match(subtitleSearch.Name); if (match.Success) { if (!string.IsNullOrEmpty(match.Groups["disc"].Value) && subtitleSearch.MediaFiles.Count > 1) { matchPct += MULTIFILE_MATCH_PCT; } else if (!string.IsNullOrEmpty(match.Groups["disc"].Value) && subtitleSearch.MediaFiles.Count == 1) { return; } } else if (subtitleSearch.MediaFiles.Count == 1) { matchPct += MULTIFILE_MATCH_PCT; } else if (subtitleSearch.MediaFiles.Count > 1) { return; } matchPct = CompareMediaFiles(subtitleSearch, matchPct); subtitleSearch.MatchPercentage = Math.Min(matchPct, 100); int languageRank = languages?.IndexOf(subtitleSearch.Language) ?? -1; if (languageRank >= 0) { subtitleSearch.LanguageMatchRank = languageRank; } }
/// <summary> /// Downloads the specified subtitle. /// </summary> /// <param name="subtitle">Subtitle to download.</param> public async Task <bool> DownloadSubtitleMatchesAsync(SubtitleInfo subtitle, bool overwriteExisting) { string[] subIds = new string[] { subtitle.SubtitleId }; if (subtitle.SubtitleId.Contains(";")) { subIds = subtitle.SubtitleId.Split(';'); } string[] subFileNames = new string[] { subtitle.Name }; if (subtitle.Name.Contains(";")) { subFileNames = subtitle.Name.Split(';'); } IDictionary <BaseSubtitleMatch <TId>, byte[]> subtitles = new Dictionary <BaseSubtitleMatch <TId>, byte[]>(); for (int i = 0; i < subIds.Length; i++) { var clone = subtitle.Clone(); clone.SubtitleId = subIds[i]; if (subFileNames.Length > i) { clone.Name = subFileNames[i]; } else { clone.Name = subFileNames[0]; } var subs = await DownloadSubtitleAsync(clone); if (!(subs?.Count > 0)) { return(false); } foreach (var sub in subs) { subtitles.Add(sub.Key, sub.Value); } } if (await SaveSubtitleAsync(subtitle, subtitles, overwriteExisting)) { return(true); } return(false); }
public async Task <bool> DownloadMetadataAsync(Guid mediaItemId, IDictionary <Guid, IList <MediaItemAspect> > aspectData) { try { if (aspectData.ContainsKey(TempSubtitleAspect.ASPECT_ID) && aspectData.ContainsKey(ProviderResourceAspect.ASPECT_ID)) { SubtitleInfo info = new SubtitleInfo(); info.FromMetadata(aspectData); return(await OnlineMatcherService.Instance.DownloadSubtitleAsync(info, true).ConfigureAwait(false)); } } catch (Exception e) { ServiceRegistration.Get <ILogger>().Info("SubtitleMetadataExtractor: Exception downloading subtitle (Text: '{0}')", e.Message); } return(false); }
/// <summary> /// Main processing function, called by BackgroundWorker thread /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void DoProcess(object sender, DoWorkEventArgs e) { _bw = (BackgroundWorker)sender; _bw.ReportProgress(-10, _status); _bw.ReportProgress(0, _status); SubtitleInfo sub = _jobInfo.SubtitleStreams[_jobInfo.StreamId]; string inFile = sub.TempFile; string outFile = Path.ChangeExtension(inFile, "converted.srt"); _bw.ReportProgress(0, _readingstatus); TextSubtitle textSub = null; switch (sub.Format) { case "SSA": case "ASS": textSub = SSAReader.ReadFile(inFile); break; case "UTF-8": textSub = SRTReader.ReadFile(inFile); break; } if (textSub == null) { return; } _bw.ReportProgress(50, _writingstatus); if (SRTWriter.WriteFile(outFile, textSub)) { sub.Format = "UTF-8"; sub.NeedConversion = false; _jobInfo.TempFiles.Add(inFile); sub.TempFile = outFile; _jobInfo.ExitCode = 0; } _bw.ReportProgress(100); _jobInfo.CompletedStep = _jobInfo.NextStep; e.Result = _jobInfo; }
private string GenerateCommandLine() { var sb = new StringBuilder(); sb.Append(DefaultParams); _subtitle = _currentTask.SubtitleStreams[_currentTask.StreamId]; _inputFile = _subtitle.TempFile; var ext = StreamFormat.GetFormatExtension(_subtitle.Format, "", true); string formattedExt = $"raw.{ext}"; _outputFile = FileSystemHelper.CreateTempFile(_appConfig.TempPath, _inputFile, formattedExt); sb.Append($"tracks \"{_inputFile}\" 0:\"{_outputFile}\" "); return(sb.ToString()); }
public Dictionary <string, SubtitleInfo> GetSubtitles() { Dictionary <string, SubtitleInfo> @return = new Dictionary <string, SubtitleInfo>(); foreach (ulong key in TrackedFiles[0x71]) { STUSubtitleContainer subtitleContainer = GetInstance <STUSubtitleContainer>(key); if (subtitleContainer == null) { continue; } @return[GetFileName(key)] = new SubtitleInfo(key, GetSubtitlesInternal(subtitleContainer)); } return(@return); }
protected virtual async Task <bool> SaveSubtitleAsync(SubtitleInfo subtitle, IDictionary <BaseSubtitleMatch <TId>, byte[]> downloads, bool overwriteExisting) { var mediaFile = subtitle.MediaFiles.First(); var namingTemplate = ResourcePath.GetFileNameWithoutExtension(mediaFile.NativeResourcePath.FileName); var templatePartMatch = _regexMultiPartVideo.Match(namingTemplate); foreach (var subtitleMatch in downloads.Keys) { var subPartMatch = _regexMultiPartVideo.Match(subtitleMatch.ItemName); string subName = namingTemplate; if (subPartMatch.Success && templatePartMatch.Success) { if (!int.TryParse(templatePartMatch.Groups["disc"].Value, out var _) || !int.TryParse(subPartMatch.Groups["disc"].Value, out var partNum)) { continue; } subName = _regexMultiPartVideo.Replace(namingTemplate, "${1}${2}${4}" + partNum + "${3}"); } string lang = new CultureInfo(subtitleMatch.Language).EnglishName; var dir = ResourcePathHelper.GetDirectoryName(mediaFile.NativeResourcePath.Serialize()); var sub = $"{subName}.{lang}{Path.GetExtension(subtitleMatch.ItemName)}"; ResourcePath subtitlePath = ResourcePath.Deserialize(dir); //File based access var resLoc = new ResourceLocator(mediaFile.NativeSystemId, subtitlePath); using (IResourceAccessor mediaItemAccessor = resLoc.CreateAccessor()) using (LocalFsResourceAccessorHelper rah = new LocalFsResourceAccessorHelper(mediaItemAccessor)) using (rah.LocalFsResourceAccessor.EnsureLocalFileSystemAccess()) { using (var stream = rah.LocalFsResourceAccessor.CreateOpenWrite(sub, overwriteExisting)) { var bytes = downloads[subtitleMatch]; if (stream != null) { await stream.WriteAsync(bytes, 0, bytes.Length); } } } } return(true); }
private ISubtitleParser CreateSubtitleParser(SubtitleInfo subtitleInfo) { var resolver = new SubtitleFormatResolver(); var format = resolver.Resolve(subtitleInfo); if (format == SubtitleFormat.Invalid) { throw new ArgumentException("Unsupported subtitle format"); } var factory = new SubtitleParserFactory(); var parser = factory.CreateParser(format); if (parser == null) { throw new ArgumentException("Unsupported subtitle format"); } return(parser); }
protected override string DoDownloadSubtitle(string fileName, SubtitleInfo si) { OPMedia.Runtime.ProTONE.NuSoap.SubtitleDownload sd = new OPMedia.Runtime.ProTONE.NuSoap.SubtitleDownload(); int x = 0; int.TryParse(si.IDSubtitleFile, out x); sd.cod_subtitle_file = x; sd.movie_hash = si.MovieHash; string destPath = Path.ChangeExtension(fileName, si.SubFormat); SubtitleArchive[] archives = _wsdl.downloadSubtitles(new OPMedia.Runtime.ProTONE.NuSoap.SubtitleDownload[] { sd }); if (archives != null && archives.Length > 0) { byte[] decodedBytes = Convert.FromBase64String(archives[0].data); using (MemoryStream compressedSubtitle = new MemoryStream(decodedBytes)) { using (InflaterInputStream str = new InflaterInputStream(compressedSubtitle)) { using (FileStream outputSubtitle = new FileStream(destPath, FileMode.Create, FileAccess.Write, FileShare.Read)) { byte[] buffer = new byte[65536]; int read = 0; do { read = str.Read(buffer, 0, buffer.Length); if (read > 0) { outputSubtitle.Write(buffer, 0, read); } }while (read > 0); } } } return(destPath); } return(string.Empty); }
public SubtitleBasicInfo[] Search(string title, SearchFilter[] filter, out string error) { try { error = null; string response = WebClient.DownloadString(string.Format("http://www.yoursubs.org/ajax-search-all.php?query={0}", HttpUtility.UrlEncode(title))); if (string.IsNullOrEmpty(response)) return null; int startIndexSuggestions = response.IndexOf("suggestions:["); int startIndexData = response.IndexOf("data:["); int endIndexSuggestions = response.IndexOf("]", startIndexSuggestions); int endIndexData = response.LastIndexOf("]"); int lengthSuggestions = endIndexSuggestions - (startIndexSuggestions + 13); int lengthData = endIndexData - (startIndexData + 6); string suggestions = response.Substring(startIndexSuggestions + 13, lengthSuggestions); string ids = response.Substring(startIndexData + 6, lengthData); RegExps.Suggestion regExpSuggestion = new RegExps.Suggestion(); RegExps.Id regExpId = new RegExps.Id(); RegExps.Seasons regExpSeasons = new RegExps.Seasons(); MatchCollection matchesSuggestions = regExpSuggestion.Matches(suggestions); MatchCollection matchesIds = regExpId.Matches(ids); int matchesCount = matchesIds.Count; // No results if (matchesCount == 0) return null; // Check the user-specified episode and/or season filter string seasonNumber; string episodeNumber; seasonNumber = GetFilterScalar(filter, typeof(SearchFilterSeason)); episodeNumber = GetFilterScalar(filter, typeof(SearchFilterEpisode)); string dataMovies = ""; string dataSeries = ""; string suggestion, id; string url = ""; for (int i = 0; i < matchesCount; i++) { suggestion = matchesSuggestions[i].Groups["suggestion"].Value; id = matchesIds[i].Groups["id"].Value; if (!string.IsNullOrEmpty(seasonNumber) && !string.IsNullOrEmpty(episodeNumber)) url = string.Format("http://www.yoursubs.org/title/{0}/Season{1}/AllLanguages/Episode{2}", id, seasonNumber, episodeNumber); else if (!string.IsNullOrEmpty(seasonNumber)) url = string.Format("http://www.yoursubs.org/title/{0}/Season{1}", id, seasonNumber); else url = string.Format("http://www.yoursubs.org/title/{0}", id); response = WebClient.DownloadString(url); if (suggestion.IndexOf("movie") != -1) { dataMovies += response; } else { // If episode and/or season is specified we only search subtitles for this season and/or episode, // else we search subtitles for all the available seasons (could be slow). if ((!string.IsNullOrEmpty(seasonNumber) && !string.IsNullOrEmpty(episodeNumber)) || !string.IsNullOrEmpty(seasonNumber)) { dataSeries += response; } else { MatchCollection seasons = regExpSeasons.Matches(response); string seasonUrl; foreach (Match season in seasons) { if (season.Groups["seasonUrl"] == null || !season.Groups["seasonUrl"].Success) continue; seasonUrl = season.Groups["seasonUrl"].Value.Trim(); response = WebClient.DownloadString(string.Format("http://www.yoursubs.org/title/{0}/{1}/AllLanguages", id, seasonUrl)); if (string.IsNullOrEmpty(response)) continue; dataSeries += response; } } } } var lstResult = new List<SubtitleBasicInfo>(); RegExps.Movies regExpMovies = new RegExps.Movies(); RegExps.Series regExpSeries = new RegExps.Series(); MatchCollection matchesMovies = regExpMovies.Matches(dataMovies); MatchCollection matchesSeries = regExpSeries.Matches(dataSeries); // First we loop over the movies foreach (Match match in matchesMovies) { if (match.Groups["id"] == null || !match.Groups["id"].Success || match.Groups["title"] == null || !match.Groups["title"].Success) continue; string subId = match.Groups["id"].Value; string subTitle = match.Groups["title"].Value.Trim(); string subPublisher = match.Groups["publisher"].Value.Trim(); string subLanguage = match.Groups["language"].Value.Trim(); Int16 subYear = ParseYear(subTitle, filter); var si = new SubtitleInfo(); si.Id = subId; si.Title = subTitle; si.Release = subTitle; si.Publisher = subPublisher; si.Language = LanguageAbbreviationToLanguage(subLanguage); if (subYear != -1) { si.Year = subYear; } if (DoesMatchFilter(si, filter)) { lstResult.Add(si); if (MaxResultsReached(filter, lstResult.Count)) { break; } } } // And then the series foreach (Match match in matchesSeries) { if (match.Groups["id"] == null || !match.Groups["id"].Success || match.Groups["title"] == null || !match.Groups["title"].Success) continue; string subId = match.Groups["id"].Value; string subTitle = match.Groups["title"].Value.Trim(); string subPublisher = match.Groups["publisher"].Value.Trim(); string subLanguage = match.Groups["language"].Value.Trim(); Int16 subSeason = Int16.Parse(match.Groups["season"].Value.Trim()); Int16 subEpisode = Int16.Parse(match.Groups["episode"].Value.Trim()); var sbi = new SubtitleInfo(); sbi.Id = subId; sbi.Title = subTitle; sbi.Release = subTitle; sbi.Publisher = subPublisher; sbi.Language = LanguageAbbreviationToLanguage(subLanguage); sbi.Season = subSeason; sbi.Episode = subEpisode; if (DoesMatchFilter(sbi, filter)) { lstResult.Add(sbi); if (MaxResultsReached(filter, lstResult.Count)) { break; } } } return lstResult.ToArray(); } catch (Exception ex) { error = string.Format("Error searching subtitles: {0}", ex.Message); return null; } }