/// <summary> /// Downloads the series zip. /// </summary> /// <param name="seriesId">The series id.</param> /// <param name="seriesDataPath">The series data path.</param> /// <param name="lastTvDbUpdateTime">The last tv database update time.</param> /// <param name="preferredMetadataLanguage">The preferred metadata language.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task.</returns> internal async Task DownloadSeriesZip(string seriesId, string seriesDataPath, long?lastTvDbUpdateTime, string preferredMetadataLanguage, CancellationToken cancellationToken) { var url = string.Format(SeriesGetZip, TVUtils.TvdbApiKey, seriesId, preferredMetadataLanguage); using (var zipStream = await _httpClient.Get(new HttpRequestOptions { Url = url, ResourcePool = TvDbResourcePool, CancellationToken = cancellationToken }).ConfigureAwait(false)) { // Delete existing files DeleteXmlFiles(seriesDataPath); // Copy to memory stream because we need a seekable stream using (var ms = new MemoryStream()) { await zipStream.CopyToAsync(ms).ConfigureAwait(false); ms.Position = 0; _zipClient.ExtractAllFromZip(ms, seriesDataPath, true); } } // Sanitize all files, except for extracted episode files foreach (var file in Directory.EnumerateFiles(seriesDataPath, "*.xml", SearchOption.AllDirectories).ToList() .Where(i => !Path.GetFileName(i).StartsWith("episode-", StringComparison.OrdinalIgnoreCase))) { await SanitizeXmlFile(file).ConfigureAwait(false); } await ExtractEpisodes(seriesDataPath, Path.Combine(seriesDataPath, preferredMetadataLanguage + ".xml"), lastTvDbUpdateTime).ConfigureAwait(false); }
public async Task <int> CalculateEpisodeCount(string seriesId, string preferredMetadataLanguage, CancellationToken cancellationToken) { var fullPath = _serverApplicationPaths.PluginsPath + "\\\\Statistics"; _fileSystem.CreateDirectory(fullPath); var url = string.Format(SeriesGetZip, ApiKey, seriesId, NormalizeLanguage(preferredMetadataLanguage)); using (var zipStream = await _httpClient.Get(new HttpRequestOptions { Url = url, ResourcePool = TvDbResourcePool, CancellationToken = cancellationToken }).ConfigureAwait(false)) { DeleteXmlFiles(fullPath); using (var ms = new MemoryStream()) { await zipStream.CopyToAsync(ms).ConfigureAwait(false); ms.Position = 0; _zipClient.ExtractAllFromZip(ms, fullPath, true); } } var downloadLangaugeXmlFile = Path.Combine(fullPath, NormalizeLanguage(preferredMetadataLanguage) + ".xml"); var result = ExtractEpisodes(downloadLangaugeXmlFile); _fileSystem.DeleteDirectory(fullPath, true); return(result); }
private async Task <UpdateInfoData> Do(GetUpdateInfo request) { var r = new UpdateInfoData() { LoadedVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(), PendingLoadVersion = GetPendingLoadVersion(), }; try { var resp = await client.GetAsync("https://api.github.com/repos/JavScraper/Emby.Plugins.JavScraper/releases/latest"); if (resp.StatusCode == System.Net.HttpStatusCode.OK) { var data = jsonSerializer.DeserializeFromStream <Rootobject>(await resp.Content.ReadAsStreamAsync()); r.UpdateMessage = data.body; foreach (var v in data.assets.Where(o => o.name.IndexOf("JavScraper", StringComparison.OrdinalIgnoreCase) >= 0 && o.name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))) { var m = regexVersion.Match(v.name); if (m.Success) { r.LatestVersion = m.ToString(); r.LatestUrl = v.browser_download_url; break; } } } else { r.ErrorMessage = "获取新版下失败。"; return(r); } } catch (Exception ex) { r.ErrorMessage = ex.Message; return(r); } //r.PendingLoadVersion = "1.0.0"; if (request.update == true && r.HasNewVersion) { try { var ms = await client.GetStreamAsync(r.LatestUrl); zipClient.ExtractAllFromZip(ms, appPaths.PluginsPath, true); r.PendingLoadVersion = GetPendingLoadVersion(); } catch (Exception ex) { r.ErrorMessage = $"更新失败:{ex.Message}"; } } return(r); }
private async Task PerformPackageInstallation(IProgress <double> progress, string target, PackageVersionInfo package, CancellationToken cancellationToken) { var extension = Path.GetExtension(package.targetFilename); var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase); if (!isArchive) { _logger.LogError("Only zip packages are supported. {Filename} is not a zip archive.", package.targetFilename); return; } if (target == null) { target = Path.Combine(_appPaths.PluginsPath, Path.GetFileNameWithoutExtension(package.targetFilename)); } // Download to temporary file so that, if interrupted, it won't destroy the existing installation var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions { Url = package.sourceUrl, CancellationToken = cancellationToken, Progress = progress }).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // TODO: Validate with a checksum, *properly* // Success - move it to the real target try { using (var stream = File.OpenRead(tempFile)) { _zipClient.ExtractAllFromZip(stream, target, true); } } catch (IOException ex) { _logger.LogError(ex, "Error attempting to extract {TempFile} to {TargetFile}", tempFile, target); throw; } try { _fileSystem.DeleteFile(tempFile); } catch (IOException ex) { // Don't fail because of this _logger.LogError(ex, "Error deleting temp file {TempFile}", tempFile); } }
public async Task Execute(CancellationToken cancellationToken, IProgress <double> progress) { await Task.Yield(); progress?.Report(0); try { var response = await _httpClient.GetResponse(new HttpRequestOptions { Url = "https://api.github.com/repos/xjasonlyu/jellyfin-plugin-avdc/releases/latest", CancellationToken = cancellationToken, EnableDefaultUserAgent = true }); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception($"api status code: {response.StatusCode}"); } var apiResult = _jsonSerializer.DeserializeFromStream <ApiResult>(response.Content); var currentVersion = ParseVersion(CurrentVersion); var remoteVersion = ParseVersion(apiResult.Tag_Name); if (currentVersion.CompareTo(remoteVersion) < 0) { _logger.Info("[AVDC] New version found: {0}", remoteVersion); var url = apiResult.Assets .Where(asset => asset.Name.StartsWith("Emby") && asset.Name.EndsWith(".zip")).ToArray() .FirstOrDefault() ?.Browser_Download_Url; if (string.IsNullOrEmpty(url)) { throw new Exception("download url is empty"); } var zipResp = await _httpClient.GetResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, EnableDefaultUserAgent = true, Progress = progress }); _zipClient.ExtractAllFromZip(zipResp.Content, _applicationPaths.PluginsPath, true); _logger.Info("[AVDC] Update is complete"); } else { _logger.Info("[AVDC] No need to update"); } } catch (Exception e) { _logger.Error("[AVDC] Update failed: {0}", e.Message); } progress?.Report(100); }
private async Task PerformPackageInstallation(IProgress <double> progress, string target, PackageVersionInfo package, CancellationToken cancellationToken) { // TODO: Remove the `string target` argument as it is not used any longer var extension = Path.GetExtension(package.targetFilename); var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase); if (!isArchive) { _logger.LogError("Only zip packages are supported. {Filename} is not a zip archive.", package.targetFilename); return; } // Always override the passed-in target (which is a file) and figure it out again target = Path.Combine(_appPaths.PluginsPath, package.name); _logger.LogDebug("Installing plugin to {Filename}.", target); // Download to temporary file so that, if interrupted, it won't destroy the existing installation _logger.LogDebug("Downloading ZIP."); var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions { Url = package.sourceUrl, CancellationToken = cancellationToken, Progress = progress }).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // TODO: Validate with a checksum, *properly* // Check if the target directory already exists, and remove it if so if (Directory.Exists(target)) { _logger.LogDebug("Deleting existing plugin at {Filename}.", target); Directory.Delete(target, true); } // Success - move it to the real target try { _logger.LogDebug("Extracting ZIP {TempFile} to {Filename}.", tempFile, target); using (var stream = File.OpenRead(tempFile)) { _zipClient.ExtractAllFromZip(stream, target, true); } } catch (IOException ex) { _logger.LogError(ex, "Error attempting to extract {TempFile} to {TargetFile}", tempFile, target); throw; } try { _logger.LogDebug("Deleting temporary file {Filename}.", tempFile); _fileSystem.DeleteFile(tempFile); } catch (IOException ex) { // Don't fail because of this _logger.LogError(ex, "Error deleting temp file {TempFile}", tempFile); } }