using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Crowdin.Plugin.Models; using Crowdin.Plugin.Models.Settings; using Plugin.Server_API.Helpers; namespace Crowdin.Plugin.Server_API.Helpers { using Serializable; using Serializable.SourceFile; using Services; public static class StorageHelper { /// Creates a storage from the file at and either creates a new /// source file in or updates the existing one with that name. /// When updating and is null, falls back to the globally /// selected update option. public static async Task UploadSourceFileAsync( string title, string fullName, string filePath, int directoryId, bool includeTranslationsInFile, CancellationToken cancellationToken, string updateOptionApiKey = null) { var storageService = new StorageApiService(); var sourceFilesService = new SourceFilesApiService(); StorageData storage = await storageService.CreateStorage(fullName, filePath, cancellationToken); List existingFiles = await sourceFilesService.ListSourceFiles(directoryId, cancellationToken); FileData existing = existingFiles.FirstOrDefault(data => data.name == fullName); var importOptions = new ImportOptionsData { importTranslations = includeTranslationsInFile, firstLineContainsHeader = true, scheme = CreateImportOptionsScheme() }; if (existing is null) { AddFileQueryData queryData = directoryId > 0 ? new AddFileToFolderQueryData(storage.id, fullName, title, importOptions, directoryId) : new AddFileQueryData(storage.id, fullName, title, importOptions); return await sourceFilesService.AddSourceFile(queryData, cancellationToken); } string updateOption = updateOptionApiKey ?? UpdateOptionsHelper.GetCurrentOptionApiKey(); return await sourceFilesService.UpdateSourceFile( existing.id, new UpdateFileQueryData(storage.id, importOptions, updateOption), cancellationToken); } public static Dictionary CreateImportOptionsScheme() { var outScheme = new Dictionary { ["identifier"] = 0, ["context"] = 1, ["sourcePhrase"] = 2, }; List languages = SettingsHelper.GetLanguageScheme(); foreach (LanguageItem language in languages) { outScheme.Add(language.langType, language.collumPos + 1); } return outScheme; } } }