diff --git a/.github/workflows/basic.yml b/.github/workflows/basic.yml index 917ece6..fe599a1 100644 --- a/.github/workflows/basic.yml +++ b/.github/workflows/basic.yml @@ -17,17 +17,14 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: temurin - java-version: 8 + java-version: 17 cache: 'gradle' - - name: Setup Gradle - uses: gradle/gradle-build-action@v2 - - name: Execute Gradle run: ./gradlew build buildPlugin verifyPlugin diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index d42facb..b338835 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -8,17 +8,14 @@ jobs: package: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: temurin - java-version: 8 + java-version: 17 cache: 'gradle' - - name: Setup Gradle - uses: gradle/gradle-build-action@v2 - - name: Execute Gradle run: ./gradlew build buildPlugin verifyPlugin diff --git a/README.md b/README.md index e084d34..65d33e7 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,13 @@ files.1.excluded-target-languages=uk # For a specific filegroup, high priority files.2.excluded-target-languages=fr # For a specific filegroup, high priority ``` +To specify cleanup mode or update strings flags for Strings-based projects use `cleanup-mode` and `update-strings`: + +```ini +files.1.cleanup-mode=true +files.1.update-strings=true +``` + ### Translations Upload Options The below properties can be used to configure the import options to the uploaded translations diff --git a/build.gradle b/build.gradle index f67e62f..9f091b7 100644 --- a/build.gradle +++ b/build.gradle @@ -1,13 +1,13 @@ plugins { id 'java' - id 'org.jetbrains.intellij' version '0.6.5' + id 'org.jetbrains.intellij' version '1.17.0' id 'jacoco' } group 'com.crowdin.crowdin-idea' version '1.6.3' -sourceCompatibility = 1.8 +sourceCompatibility = '17' repositories { mavenCentral() @@ -16,52 +16,59 @@ repositories { dependencies { - compile 'org.projectlombok:lombok:1.18.10' - annotationProcessor 'org.projectlombok:lombok:1.18.10' + implementation 'net.lingala.zip4j:zip4j:2.11.3' + implementation 'com.github.crowdin:crowdin-api-client-java:1.14.0' + implementation 'commons-io:commons-io:2.15.1' - testCompile group: 'junit', name: 'junit', version: '4.13.1' - compile group: 'net.lingala.zip4j', name: 'zip4j', version: '2.11.3' - compile 'com.github.crowdin:crowdin-api-client-java:1.12.0' - implementation 'org.apache.commons:commons-lang3:3.12.0' -// compile group: 'commons-io', name: 'commons-io', version: '2.6' //to run '2017.1.6' idea - - testCompile('org.junit.jupiter:junit-jupiter:5.5.2') - testCompile('org.hamcrest:hamcrest:2.2') - testCompile('org.mockito:mockito-core:2.1.0') + testImplementation 'junit:junit:4.13.1' + testImplementation 'org.junit.jupiter:junit-jupiter:5.5.2' + testImplementation 'org.hamcrest:hamcrest:2.2' + testImplementation 'org.mockito:mockito-core:2.1.0' } test { useJUnitPlatform() } -// See https://github.com/JetBrains/gradle-intellij-plugin/ intellij { -// version '2017.1.6' //current since-version //requires additional libraries - version '2019.2.3' -// version '2020.3.1' //current last version //requires 11 JDK to execute 'runIde' - plugins 'git4idea' - updateSinceUntilBuild false + version = '2022.3.3' + plugins = ['Git4Idea'] + updateSinceUntilBuild = false } patchPluginXml { - changeNotes """ + changeNotes = """ - Bugfixes""" } wrapper { - gradleVersion = '5.2.1' + gradleVersion = '8.5' } jacoco { - toolVersion = "0.8.5" - reportsDir = file("$buildDir/reports") + toolVersion = '0.8.10' + reportsDirectory = layout.buildDirectory.dir('reports') +} + +//https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin-faq.html#jacoco-reports-0-coverage +test { + jacoco { + includeNoLocationClasses = true + excludes = ["jdk.internal.*"] + } } jacocoTestReport { + classDirectories.setFrom(instrumentCode) + reports { - xml.enabled true - csv.enabled false - xml.destination file("${buildDir}/coverage.xml") + xml.required = true + csv.required = false + xml.outputLocation = layout.buildDirectory.file('coverage.xml') } - getExecutionData().setFrom("$buildDir/jacoco/test.exec") + getExecutionData().setFrom(layout.buildDirectory.file('jacoco/test.exec')) +} + +jacocoTestCoverageVerification { + classDirectories.setFrom(instrumentCode) } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 87b738c..d64cd49 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 414baf4..1af9e09 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ -#Mon May 04 14:47:45 EEST 2020 -distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-all.zip distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index af6708f..1aa94a4 100755 --- a/gradlew +++ b/gradlew @@ -1,78 +1,127 @@ -#!/usr/bin/env sh +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -81,92 +130,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" fi +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 6d57edc..93e3f59 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,4 +1,20 @@ -@if "%DEBUG%" == "" @echo off +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -9,19 +25,23 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -35,7 +55,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -45,38 +65,26 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/src/main/java/com/crowdin/Constants.java b/src/main/java/com/crowdin/Constants.java index 329385a..77028a5 100644 --- a/src/main/java/com/crowdin/Constants.java +++ b/src/main/java/com/crowdin/Constants.java @@ -27,6 +27,8 @@ public final class Constants { public static final String PROPERTY_FILES_TRANSLATIONS_PATTERN = "files.%stranslation"; public static final Pattern PROPERTY_FILES_TRANSLATIONS_REGEX = Pattern.compile("^files\\.(|\\d+\\.)translation$"); public static final String PROPERTY_FILES_EXCLUDED_TARGET_LANGUAGES_PATTERN = "files.%sexcluded-target-languages"; + public static final String PROPERTY_FILES_CLEANUP_MODE_PATTERN = "files.%scleanup-mode"; + public static final String PROPERTY_FILES_UPDATE_STRINGS_PATTERN = "files.%supdate-strings"; public static final String PROPERTY_FILES_LABELS_PATTERN = "files.%slabels"; public static final String PROPERTY_AUTO_UPLOAD = "auto-upload"; public static final String PROPERTY_DISABLE_BRANCHES = "disable-branches"; @@ -47,4 +49,18 @@ public final class Constants { public static final String PROPERTY_AUTO_APPROVE_IMPORTED = "auto-approve-imported"; public static final String PROPERTY_TRANSLATE_HIDDEN = "translate-hidden"; + + public static final String PROGRESS_TOOLBAR_ID = "Crowdin.TranslationProgressToolbar"; + + public static final String TOOLWINDOW_ID = "Crowdin"; + public static final String UPLOAD_TOOLBAR_ID = "Crowdin.UploadToolbar"; + public static final String DOWNLOAD_TOOLBAR_ID = "Crowdin.DownloadToolbar"; + + public static final String PROGRESS_REFRESH_ACTION = "Crowdin.RefreshTranslationProgressAction"; + public static final String UPLOAD_REFRESH_ACTION = "Crowdin.RefreshUploadAction"; + public static final String DOWNLOAD_REFRESH_ACTION = "Crowdin.RefreshDownloadAction"; + public static final String DOWNLOAD_TRANSLATIONS_ACTION = "Crowdin.DownloadTranslations"; + public static final String DOWNLOAD_SOURCES_ACTION = "Crowdin.DownloadSources"; + + public static final String PROGRESS_GROUP_FILES_BY_FILE_ACTION = "Crowdin.GroupByFiles"; } diff --git a/src/main/java/com/crowdin/action/ActionContext.java b/src/main/java/com/crowdin/action/ActionContext.java new file mode 100644 index 0000000..3c9830d --- /dev/null +++ b/src/main/java/com/crowdin/action/ActionContext.java @@ -0,0 +1,26 @@ +package com.crowdin.action; + +import com.crowdin.client.Crowdin; +import com.crowdin.client.CrowdinProperties; +import com.crowdin.client.sourcefiles.model.Branch; +import com.crowdin.service.CrowdinProjectCacheProvider; +import com.intellij.openapi.vfs.VirtualFile; + +public class ActionContext { + + public final String branchName; + public final Branch branch; + public final VirtualFile root; + public final CrowdinProperties properties; + public final Crowdin crowdin; + public final CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache; + + public ActionContext(String branchName, Branch branch, VirtualFile root, CrowdinProperties properties, Crowdin crowdin, CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache) { + this.branchName = branchName; + this.branch = branch; + this.root = root; + this.properties = properties; + this.crowdin = crowdin; + this.crowdinProjectCache = crowdinProjectCache; + } +} diff --git a/src/main/java/com/crowdin/action/BackgroundAction.java b/src/main/java/com/crowdin/action/BackgroundAction.java index 848edcd..631997a 100644 --- a/src/main/java/com/crowdin/action/BackgroundAction.java +++ b/src/main/java/com/crowdin/action/BackgroundAction.java @@ -1,27 +1,103 @@ package com.crowdin.action; +import com.crowdin.client.Crowdin; +import com.crowdin.client.CrowdinProperties; +import com.crowdin.client.CrowdinPropertiesLoader; +import com.crowdin.client.sourcefiles.model.Branch; +import com.crowdin.logic.BranchLogic; +import com.crowdin.service.CrowdinProjectCacheProvider; +import com.crowdin.service.CrowdinSettings; +import com.crowdin.util.FileUtil; +import com.crowdin.util.NotificationUtil; +import com.crowdin.util.StringUtils; +import com.crowdin.util.UIUtil; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; -import lombok.NonNull; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import javax.swing.*; +import java.util.Optional; + +import static com.crowdin.Constants.MESSAGES_BUNDLE; public abstract class BackgroundAction extends AnAction { - public BackgroundAction() { } + public BackgroundAction() { + } public BackgroundAction(String text, String description, Icon icon) { super(text, description, icon); } - protected abstract void performInBackground(@NonNull AnActionEvent e, @NonNull ProgressIndicator indicator); + protected abstract void performInBackground(@NotNull AnActionEvent e, @NotNull ProgressIndicator indicator); protected abstract String loadingText(AnActionEvent e); + protected Optional prepare( + Project project, + ProgressIndicator indicator, + boolean checkForManagerAccess, + boolean createBranchIfNotExists, + boolean realodCrowdinCache, + String question, + String okBtn + ) { + VirtualFile root = FileUtil.getProjectBaseDir(project); + + CrowdinSettings crowdinSettings = project.getService(CrowdinSettings.class); + + if (!StringUtils.isEmpty(question) && !StringUtils.isEmpty(okBtn)) { + boolean confirmation = UIUtil.confirmDialog(project, crowdinSettings, MESSAGES_BUNDLE.getString(question), okBtn); + if (!confirmation) { + return Optional.empty(); + } + if (indicator != null) { + indicator.checkCanceled(); + } + } + + CrowdinProperties properties; + try { + properties = CrowdinPropertiesLoader.load(project); + } catch (Exception e) { + NotificationUtil.showErrorMessage(project, e.getMessage()); + return Optional.empty(); + } + NotificationUtil.setLogDebugLevel(properties.isDebug()); + NotificationUtil.logDebugMessage(project, MESSAGES_BUNDLE.getString("messages.debug.started_action")); + + Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); + + BranchLogic branchLogic = new BranchLogic(crowdin, project, properties); + String branchName = branchLogic.acquireBranchName(); + if (indicator != null) { + indicator.checkCanceled(); + } + + CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache = + project.getService(CrowdinProjectCacheProvider.class).getInstance(crowdin, branchName, realodCrowdinCache); + + if (checkForManagerAccess) { + if (!crowdinProjectCache.isManagerAccess()) { + NotificationUtil.showErrorMessage(project, "You need to have manager access to perform this action"); + return Optional.empty(); + } + } + + Branch branch = branchLogic.getBranch(crowdinProjectCache, createBranchIfNotExists); + + if (indicator != null) { + indicator.checkCanceled(); + } + + return Optional.of(new ActionContext(branchName, branch, root, properties, crowdin, crowdinProjectCache)); + } + @Override public void actionPerformed(@NotNull AnActionEvent e) { ProgressManager.getInstance().run(new Task.Backgroundable(e.getProject(), "Crowdin") { @@ -31,6 +107,5 @@ public void run(@NotNull ProgressIndicator indicator) { performInBackground(e, indicator); } }); - } } diff --git a/src/main/java/com/crowdin/action/DownloadAction.java b/src/main/java/com/crowdin/action/DownloadAction.java index 3080be5..5fe79e4 100644 --- a/src/main/java/com/crowdin/action/DownloadAction.java +++ b/src/main/java/com/crowdin/action/DownloadAction.java @@ -1,71 +1,128 @@ package com.crowdin.action; -import com.crowdin.client.Crowdin; -import com.crowdin.client.CrowdinProjectCacheProvider; -import com.crowdin.client.CrowdinProperties; -import com.crowdin.client.CrowdinPropertiesLoader; -import com.crowdin.client.sourcefiles.model.Branch; -import com.crowdin.logic.BranchLogic; -import com.crowdin.logic.CrowdinSettings; +import com.crowdin.client.bundles.model.Bundle; +import com.crowdin.logic.DownloadBundleLogic; import com.crowdin.logic.DownloadTranslationsLogic; -import com.crowdin.util.*; +import com.crowdin.service.ProjectService; +import com.crowdin.ui.panel.CrowdinPanelWindowFactory; +import com.crowdin.ui.panel.download.DownloadWindow; +import com.crowdin.util.FileUtil; +import com.crowdin.util.NotificationUtil; import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; import static com.crowdin.Constants.MESSAGES_BUNDLE; +import static com.crowdin.Constants.TOOLWINDOW_ID; public class DownloadAction extends BackgroundAction { + private boolean enabled = false; + private boolean visible = false; + private String text = ""; + + private final AtomicBoolean isInProgress = new AtomicBoolean(false); + @Override - public void performInBackground(AnActionEvent anActionEvent, ProgressIndicator indicator) { + public void update(@NotNull AnActionEvent e) { + if (e.getPlace().equals(TOOLWINDOW_ID)) { + this.enabled = e.getPresentation().isEnabled(); + this.visible = e.getPresentation().isVisible(); + this.text = e.getPresentation().getText(); + } + e.getPresentation().setEnabled(!isInProgress.get() && enabled); + e.getPresentation().setVisible(visible); + e.getPresentation().setText(text); + } + + @Override + public void performInBackground(AnActionEvent anActionEvent, @NotNull ProgressIndicator indicator) { Project project = anActionEvent.getProject(); - try { - VirtualFile root = FileUtil.getProjectBaseDir(project); - CrowdinSettings crowdinSettings = ServiceManager.getService(project, CrowdinSettings.class); + if (project == null) { + return; + } - boolean confirmation = UIUtil.confirmDialog(project, crowdinSettings, MESSAGES_BUNDLE.getString("messages.confirm.download"), "Download"); - if (!confirmation) { - return; - } - indicator.checkCanceled(); + isInProgress.set(true); + try { + Optional context = super.prepare( + project, + indicator, + true, + false, + true, + "messages.confirm.download", + "Download" + ); - CrowdinProperties properties; - try { - properties = CrowdinPropertiesLoader.load(project); - } catch (Exception e) { - NotificationUtil.showErrorMessage(project, e.getMessage()); + if (context.isEmpty()) { return; } - NotificationUtil.setLogDebugLevel(properties.isDebug()); - NotificationUtil.logDebugMessage(project, MESSAGES_BUNDLE.getString("messages.debug.started_action")); - Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); + if (context.get().crowdinProjectCache.isStringsBased()) { + if (context.get().branch == null) { + NotificationUtil.showErrorMessage(project, "Branch is missing"); + return; + } + + DownloadWindow window = project.getService(ProjectService.class).getDownloadWindow(); + if (window == null) { + return; + } - BranchLogic branchLogic = new BranchLogic(crowdin, project, properties); - String branchName = branchLogic.acquireBranchName(true); - indicator.checkCanceled(); + Bundle bundle = window.getSelectedBundle(); + + if (bundle == null) { + NotificationUtil.showErrorMessage(project, "Bundle not selected"); + return; + } + + (new DownloadBundleLogic(project, context.get().crowdin, context.get().root, bundle)).process(); + return; + } - CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache = - CrowdinProjectCacheProvider.getInstance(crowdin, branchName, true); + List selectedFiles = Optional + .ofNullable(project.getService(ProjectService.class).getDownloadWindow()) + .map(DownloadWindow::getSelectedFiles) + .orElse(Collections.emptyList()) + .stream() + .map(str -> Paths.get(context.get().root.getPath(), str)) + .toList(); - if (!crowdinProjectCache.isManagerAccess()) { - NotificationUtil.showErrorMessage(project, "You need to have manager access to perform this action"); + if (!selectedFiles.isEmpty()) { + for (Path file : selectedFiles) { + try { + VirtualFile virtualFile = FileUtil.findVFileByPath(file); + DownloadTranslationFromContextAction.performDownload(this, context.get(), virtualFile); + } catch (Exception e) { + NotificationUtil.logErrorMessage(project, e); + NotificationUtil.showWarningMessage(project, e.getMessage()); + } + } return; } - Branch branch = branchLogic.getBranch(crowdinProjectCache, false); - (new DownloadTranslationsLogic(project, crowdin, properties, root, crowdinProjectCache, branch)).process(); + (new DownloadTranslationsLogic(project, context.get().crowdin, context.get().properties, context.get().root, context.get().crowdinProjectCache, context.get().branch)).process(); } catch (ProcessCanceledException e) { throw e; } catch (Exception e) { NotificationUtil.logErrorMessage(project, e); NotificationUtil.showErrorMessage(project, e.getMessage()); + } finally { + isInProgress.set(false); + ApplicationManager.getApplication().invokeAndWait(() -> CrowdinPanelWindowFactory.reloadPanels(project, false)); } } diff --git a/src/main/java/com/crowdin/action/DownloadSourceFromContextAction.java b/src/main/java/com/crowdin/action/DownloadSourceFromContextAction.java index 73f2f80..221bcbd 100644 --- a/src/main/java/com/crowdin/action/DownloadSourceFromContextAction.java +++ b/src/main/java/com/crowdin/action/DownloadSourceFromContextAction.java @@ -1,82 +1,71 @@ package com.crowdin.action; -import com.crowdin.client.Crowdin; -import com.crowdin.client.CrowdinProjectCacheProvider; -import com.crowdin.client.CrowdinProperties; -import com.crowdin.client.CrowdinPropertiesLoader; -import com.crowdin.client.sourcefiles.model.Branch; -import com.crowdin.logic.BranchLogic; import com.crowdin.logic.ContextLogic; -import com.crowdin.logic.CrowdinSettings; +import com.crowdin.ui.panel.CrowdinPanelWindowFactory; import com.crowdin.util.FileUtil; import com.crowdin.util.NotificationUtil; -import com.crowdin.util.UIUtil; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; -import lombok.NonNull; +import org.jetbrains.annotations.NotNull; import java.net.URL; import java.util.Objects; +import java.util.Optional; import static com.crowdin.Constants.MESSAGES_BUNDLE; public class DownloadSourceFromContextAction extends BackgroundAction { + @Override - protected void performInBackground(@NonNull AnActionEvent anActionEvent, @NonNull ProgressIndicator indicator) { + protected void performInBackground(@NotNull AnActionEvent anActionEvent, @NotNull ProgressIndicator indicator) { final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(anActionEvent.getDataContext()); if (file == null) { return; } - Project project = anActionEvent.getProject(); - try { - VirtualFile root = FileUtil.getProjectBaseDir(project); - CrowdinSettings crowdinSettings = ServiceManager.getService(project, CrowdinSettings.class); + Project project = anActionEvent.getProject(); + if (project == null) { + return; + } - boolean confirmation = UIUtil.confirmDialog(project, crowdinSettings, MESSAGES_BUNDLE.getString("messages.confirm.download"), "Download"); - if (!confirmation) { - return; - } - indicator.checkCanceled(); + try { + Optional context = super.prepare( + project, + indicator, + false, + false, + true, + "messages.confirm.download_sources", + "Download" + ); - CrowdinProperties properties; - try { - properties = CrowdinPropertiesLoader.load(project); - } catch (Exception e) { - NotificationUtil.showErrorMessage(project, e.getMessage()); + if (context.isEmpty()) { return; } - NotificationUtil.setLogDebugLevel(properties.isDebug()); - NotificationUtil.logDebugMessage(project, MESSAGES_BUNDLE.getString("messages.debug.started_action")); - - Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); - BranchLogic branchLogic = new BranchLogic(crowdin, project, properties); - String branchName = branchLogic.acquireBranchName(true); - indicator.checkCanceled(); - - CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache = - CrowdinProjectCacheProvider.getInstance(crowdin, branchName, true); - - Branch branch = branchLogic.getBranch(crowdinProjectCache, false); - - Long sourceId = ContextLogic.findSourceIdFromSourceFile(properties, crowdinProjectCache.getFileInfos(branch), file, root); - URL url = crowdin.downloadFile(sourceId); - FileUtil.downloadFile(this, file, url); + performDownload(this, file, context.get()); NotificationUtil.showInformationMessage(project, MESSAGES_BUNDLE.getString("messages.success.download_source")); } catch (ProcessCanceledException e) { throw e; } catch (Exception e) { NotificationUtil.logErrorMessage(project, e); NotificationUtil.showErrorMessage(project, e.getMessage()); + } finally { + ApplicationManager.getApplication().invokeAndWait(() -> CrowdinPanelWindowFactory.reloadPanels(project, false)); } } + public static void performDownload(Object requestor, VirtualFile file, ActionContext context) { + Long sourceId = ContextLogic.findSourceIdFromSourceFile(context.properties, context.crowdinProjectCache.getFileInfos(context.branch), file, context.root); + URL url = context.crowdin.downloadFile(sourceId); + FileUtil.downloadFile(requestor, file, url); + } + @Override public void update(AnActionEvent e) { Project project = e.getProject(); @@ -86,11 +75,17 @@ public void update(AnActionEvent e) { final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext()); boolean isSourceFile = false; try { - CrowdinProperties properties = CrowdinPropertiesLoader.load(project); - isSourceFile = properties.getFiles() - .stream() - .flatMap(fb -> FileUtil.getSourceFilesRec(FileUtil.getProjectBaseDir(project), fb.getSource()).stream()) - .anyMatch(f -> Objects.equals(file, f)); + Optional context = super.prepare(project, null, false, false, false, null, null); + + if (context.isEmpty()) { + return; + } + + //hide for SB + isSourceFile = !context.get().crowdinProjectCache.isStringsBased() && context.get().properties.getFiles() + .stream() + .flatMap(fb -> FileUtil.getSourceFilesRec(FileUtil.getProjectBaseDir(project), fb.getSource()).stream()) + .anyMatch(f -> Objects.equals(file, f)); } catch (Exception exception) { // do nothing } finally { diff --git a/src/main/java/com/crowdin/action/DownloadSourcesAction.java b/src/main/java/com/crowdin/action/DownloadSourcesAction.java index a22c0cb..f65b7be 100644 --- a/src/main/java/com/crowdin/action/DownloadSourcesAction.java +++ b/src/main/java/com/crowdin/action/DownloadSourcesAction.java @@ -1,110 +1,140 @@ package com.crowdin.action; import com.crowdin.client.Crowdin; -import com.crowdin.client.CrowdinProjectCacheProvider; -import com.crowdin.client.CrowdinProperties; -import com.crowdin.client.CrowdinPropertiesLoader; import com.crowdin.client.FileBean; -import com.crowdin.client.sourcefiles.model.Branch; import com.crowdin.client.sourcefiles.model.FileInfo; -import com.crowdin.logic.BranchLogic; -import com.crowdin.logic.CrowdinSettings; +import com.crowdin.service.ProjectService; +import com.crowdin.ui.panel.CrowdinPanelWindowFactory; +import com.crowdin.ui.panel.download.DownloadWindow; import com.crowdin.util.FileUtil; import com.crowdin.util.NotificationUtil; -import com.crowdin.util.UIUtil; import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; -import lombok.NonNull; +import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.InputStream; import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import static com.crowdin.Constants.MESSAGES_BUNDLE; +import static com.crowdin.Constants.TOOLWINDOW_ID; public class DownloadSourcesAction extends BackgroundAction { + private boolean enabled = false; + private boolean visible = false; + private String text = ""; + + private final AtomicBoolean isInProgress = new AtomicBoolean(false); + + @Override + public void update(@NotNull AnActionEvent e) { + if (e.getPlace().equals(TOOLWINDOW_ID)) { + this.enabled = e.getPresentation().isEnabled(); + this.visible = e.getPresentation().isVisible(); + this.text = e.getPresentation().getText(); + } + e.getPresentation().setEnabled(!isInProgress.get() && enabled); + e.getPresentation().setVisible(visible); + e.getPresentation().setText(text); + } + @Override protected String loadingText(AnActionEvent e) { return MESSAGES_BUNDLE.getString("labels.loading_text_download_sources"); } @Override - protected void performInBackground(@NonNull AnActionEvent anActionEvent, @NonNull ProgressIndicator indicator) { + protected void performInBackground(@NotNull AnActionEvent anActionEvent, @NotNull ProgressIndicator indicator) { Project project = anActionEvent.getProject(); - try { - VirtualFile root = FileUtil.getProjectBaseDir(project); - - CrowdinSettings crowdinSettings = ServiceManager.getService(project, CrowdinSettings.class); + if (project == null) { + return; + } - boolean confirmation = UIUtil.confirmDialog(project, crowdinSettings, MESSAGES_BUNDLE.getString("messages.confirm.download"), "Download"); - if (!confirmation) { + isInProgress.set(true); + try { + Optional context = super.prepare( + project, + indicator, + false, + false, + true, + "messages.confirm.download_sources", + "Download" + ); + + if (context.isEmpty()) { return; } - indicator.checkCanceled(); - CrowdinProperties properties; - try { - properties = CrowdinPropertiesLoader.load(project); - } catch (Exception e) { - NotificationUtil.showErrorMessage(project, e.getMessage()); + List selectedFiles = Optional + .ofNullable(project.getService(ProjectService.class).getDownloadWindow()) + .map(DownloadWindow::getSelectedFiles) + .orElse(Collections.emptyList()) + .stream() + .map(str -> Paths.get(context.get().root.getPath(), str)) + .toList(); + + if (!selectedFiles.isEmpty()) { + for (Path file : selectedFiles) { + try { + VirtualFile virtualFile = FileUtil.findVFileByPath(file); + DownloadSourceFromContextAction.performDownload(this, virtualFile, context.get()); + NotificationUtil.logDebugMessage(project, String.format(MESSAGES_BUNDLE.getString("messages.debug.download_sources.file_downloaded"), file)); + } catch (Exception e) { + NotificationUtil.logErrorMessage(project, e); + NotificationUtil.showWarningMessage(project, e.getMessage()); + } + } return; } - NotificationUtil.setLogDebugLevel(properties.isDebug()); - NotificationUtil.logDebugMessage(project, MESSAGES_BUNDLE.getString("messages.debug.started_action")); - - Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); - - BranchLogic branchLogic = new BranchLogic(crowdin, project, properties); - String branchName = branchLogic.acquireBranchName(true); - indicator.checkCanceled(); - - CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache = - CrowdinProjectCacheProvider.getInstance(crowdin, branchName, true); - Branch branch = branchLogic.getBranch(crowdinProjectCache, false); - - Map filePaths = crowdinProjectCache.getFileInfos(branch); + Map filePaths = context.get().crowdinProjectCache.getFileInfos(context.get().branch); AtomicBoolean isAnyFileDownloaded = new AtomicBoolean(false); - for (FileBean fileBean : properties.getFiles()) { - Predicate sourcePredicate = FileUtil.filePathRegex(fileBean.getSource(), properties.isPreserveHierarchy()); - Map localSourceFiles = (properties.isPreserveHierarchy()) - ? Collections.emptyMap() - : FileUtil.getSourceFilesRec(root, fileBean.getSource()).stream() - .collect(Collectors.toMap(VirtualFile::getPath, Function.identity())); + for (FileBean fileBean : context.get().properties.getFiles()) { + Predicate sourcePredicate = FileUtil.filePathRegex(fileBean.getSource(), context.get().properties.isPreserveHierarchy()); + Map localSourceFiles = (context.get().properties.isPreserveHierarchy()) + ? Collections.emptyMap() + : FileUtil.getSourceFilesRec(context.get().root, fileBean.getSource()).stream() + .collect(Collectors.toMap(VirtualFile::getPath, Function.identity())); List foundSources = filePaths.keySet().stream() - .map(FileUtil::unixPath) - .filter(sourcePredicate) - .map(FileUtil::normalizePath) - .sorted() - .collect(Collectors.toList()); + .map(FileUtil::unixPath) + .filter(sourcePredicate) + .map(FileUtil::normalizePath) + .sorted() + .toList(); if (foundSources.isEmpty()) { NotificationUtil.showWarningMessage(project, String.format(MESSAGES_BUNDLE.getString("errors.no_sources_for_pattern"), fileBean.getSource())); return; } + for (String foundSourceFilePath : foundSources) { - if (properties.isPreserveHierarchy()) { + if (context.get().properties.isPreserveHierarchy()) { Long fileId = filePaths.get(foundSourceFilePath).getId(); - this.downloadFile(crowdin, fileId, root, foundSourceFilePath); + this.downloadFile(context.get().crowdin, fileId, context.get().root, foundSourceFilePath); isAnyFileDownloaded.set(true); } else { List fittingSources = localSourceFiles.keySet().stream() - .filter(localSourceFilePath -> localSourceFilePath.endsWith(foundSourceFilePath)) - .collect(Collectors.toList()); + .filter(localSourceFilePath -> localSourceFilePath.endsWith(foundSourceFilePath)) + .toList(); + if (fittingSources.isEmpty()) { NotificationUtil.showWarningMessage(project, String.format(MESSAGES_BUNDLE.getString("errors.file_no_representative"), foundSourceFilePath)); continue; @@ -112,9 +142,10 @@ protected void performInBackground(@NonNull AnActionEvent anActionEvent, @NonNul NotificationUtil.showWarningMessage(project, String.format(MESSAGES_BUNDLE.getString("errors.file_not_one_representative"), foundSourceFilePath)); continue; } + Long fileId = filePaths.get(foundSourceFilePath).getId(); VirtualFile file = localSourceFiles.get(fittingSources.get(0)); - this.downloadFile(crowdin, fileId, file); + this.downloadFile(context.get().crowdin, fileId, file); isAnyFileDownloaded.set(true); } NotificationUtil.logDebugMessage(project, String.format(MESSAGES_BUNDLE.getString("messages.debug.download_sources.file_downloaded"), foundSourceFilePath)); @@ -132,6 +163,9 @@ protected void performInBackground(@NonNull AnActionEvent anActionEvent, @NonNul } catch (Exception e) { NotificationUtil.logErrorMessage(project, e); NotificationUtil.showErrorMessage(project, e.getMessage()); + } finally { + isInProgress.set(false); + ApplicationManager.getApplication().invokeAndWait(() -> CrowdinPanelWindowFactory.reloadPanels(project, false)); } } diff --git a/src/main/java/com/crowdin/action/DownloadTranslationFromContextAction.java b/src/main/java/com/crowdin/action/DownloadTranslationFromContextAction.java index b3fbe9a..e84af3a 100644 --- a/src/main/java/com/crowdin/action/DownloadTranslationFromContextAction.java +++ b/src/main/java/com/crowdin/action/DownloadTranslationFromContextAction.java @@ -1,120 +1,98 @@ package com.crowdin.action; -import com.crowdin.client.Crowdin; -import com.crowdin.client.CrowdinProjectCacheProvider; -import com.crowdin.client.CrowdinProperties; -import com.crowdin.client.CrowdinPropertiesLoader; import com.crowdin.client.RequestBuilder; import com.crowdin.client.languages.model.Language; -import com.crowdin.client.sourcefiles.model.Branch; -import com.crowdin.logic.BranchLogic; import com.crowdin.logic.ContextLogic; -import com.crowdin.logic.CrowdinSettings; -import com.crowdin.util.ActionUtils; +import com.crowdin.ui.panel.CrowdinPanelWindowFactory; import com.crowdin.util.FileUtil; import com.crowdin.util.NotificationUtil; -import com.crowdin.util.UIUtil; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; -import lombok.NonNull; -import org.apache.commons.lang3.tuple.Pair; +import org.jetbrains.annotations.NotNull; import java.net.URL; +import java.util.Map; +import java.util.Optional; import static com.crowdin.Constants.MESSAGES_BUNDLE; public class DownloadTranslationFromContextAction extends BackgroundAction { + @Override - protected void performInBackground(@NonNull AnActionEvent anActionEvent, @NonNull ProgressIndicator indicator) { + protected void performInBackground(@NotNull AnActionEvent anActionEvent, @NotNull ProgressIndicator indicator) { final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(anActionEvent.getDataContext()); + if (file == null) { return; } - Project project = anActionEvent.getProject(); - try { - VirtualFile root = FileUtil.getProjectBaseDir(project); - - CrowdinSettings crowdinSettings = ServiceManager.getService(project, CrowdinSettings.class); - - boolean confirmation = UIUtil.confirmDialog(project, crowdinSettings, MESSAGES_BUNDLE.getString("messages.confirm.download"), "Download"); - if (!confirmation) { - return; - } - indicator.checkCanceled(); - CrowdinProperties properties; - try { - properties = CrowdinPropertiesLoader.load(project); - } catch (Exception e) { - NotificationUtil.showErrorMessage(project, e.getMessage()); - return; - } - NotificationUtil.setLogDebugLevel(properties.isDebug()); - NotificationUtil.logDebugMessage(project, MESSAGES_BUNDLE.getString("messages.debug.started_action")); - - Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); + Project project = anActionEvent.getProject(); - BranchLogic branchLogic = new BranchLogic(crowdin, project, properties); - String branchName = branchLogic.acquireBranchName(true); - indicator.checkCanceled(); + if (project == null) { + return; + } - CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache = - CrowdinProjectCacheProvider.getInstance(crowdin, branchName, true); + try { - if (!crowdinProjectCache.isManagerAccess()) { - NotificationUtil.showErrorMessage(project, "You need to have manager access to perform this action"); + Optional context = super.prepare( + project, + indicator, + true, + false, + true, + "messages.confirm.download", + "Download" + ); + + if (context.isEmpty()) { return; } - Branch branch = branchLogic.getBranch(crowdinProjectCache, false); - - Pair source = ContextLogic.findSourceFileFromTranslationFile(file, properties, root, crowdinProjectCache) - .orElseThrow(() -> new RuntimeException(MESSAGES_BUNDLE.getString("errors.file_no_representative_context"))); - - Long sourceId = ContextLogic.findSourceIdFromSourceFile(properties, crowdinProjectCache.getFileInfos(branch), source.getLeft(), root); - - URL url = crowdin.downloadFileTranslation(sourceId, RequestBuilder.buildProjectFileTranslation(source.getRight().getId())); - FileUtil.downloadFile(this, file, url); + performDownload(this, context.get(), file); } catch (ProcessCanceledException e) { throw e; } catch (Exception e) { NotificationUtil.logErrorMessage(project, e); NotificationUtil.showErrorMessage(project, e.getMessage()); + } finally { + ApplicationManager.getApplication().invokeAndWait(() -> CrowdinPanelWindowFactory.reloadPanels(project, false)); } } + public static void performDownload(Object requestor, ActionContext context, VirtualFile file) { + Map.Entry source = ContextLogic.findSourceFileFromTranslationFile(file, context.properties, context.root, context.crowdinProjectCache) + .orElseThrow(() -> new RuntimeException(MESSAGES_BUNDLE.getString("errors.file_no_representative_context"))); + + Long sourceId = ContextLogic.findSourceIdFromSourceFile(context.properties, context.crowdinProjectCache.getFileInfos(context.branch), source.getKey(), context.root); + + URL url = context.crowdin.downloadFileTranslation(sourceId, RequestBuilder.buildProjectFileTranslation(source.getValue().getId())); + FileUtil.downloadFile(requestor, file, url); + } + @Override public void update(AnActionEvent e) { Project project = e.getProject(); final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext()); boolean isTranslationFile = false; + try { if (file == null) { return; } - CrowdinProperties properties; - try { - properties = CrowdinPropertiesLoader.load(project); - } catch (Exception exception) { - return; - } - NotificationUtil.setLogDebugLevel(properties.isDebug()); - NotificationUtil.logDebugMessage(project, MESSAGES_BUNDLE.getString("messages.debug.started_action")); - VirtualFile root = FileUtil.getProjectBaseDir(project); - Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); + Optional context = super.prepare(project, null, false, false, false, null, null); - String branchName = ActionUtils.getBranchName(project, properties, false); - - CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache = - CrowdinProjectCacheProvider.getInstance(crowdin, branchName, false); + if (context.isEmpty()) { + return; + } - isTranslationFile = ContextLogic.findSourceFileFromTranslationFile(file, properties, root, crowdinProjectCache).isPresent(); + //hide for SB + isTranslationFile = !context.get().crowdinProjectCache.isStringsBased() && ContextLogic.findSourceFileFromTranslationFile(file, context.get().properties, context.get().root, context.get().crowdinProjectCache).isPresent(); } catch (Exception exception) { // do nothing } finally { diff --git a/src/main/java/com/crowdin/action/UploadAction.java b/src/main/java/com/crowdin/action/UploadAction.java index 2c9e7b4..249979a 100644 --- a/src/main/java/com/crowdin/action/UploadAction.java +++ b/src/main/java/com/crowdin/action/UploadAction.java @@ -1,22 +1,28 @@ package com.crowdin.action; -import com.crowdin.client.*; -import com.crowdin.client.sourcefiles.model.Branch; -import com.crowdin.logic.BranchLogic; -import com.crowdin.logic.CrowdinSettings; +import com.crowdin.client.FileBean; import com.crowdin.logic.SourceLogic; -import com.crowdin.util.*; +import com.crowdin.service.CrowdinProjectCacheProvider; +import com.crowdin.service.ProjectService; +import com.crowdin.ui.panel.CrowdinPanelWindowFactory; +import com.crowdin.ui.panel.upload.UploadWindow; +import com.crowdin.util.FileUtil; +import com.crowdin.util.NotificationUtil; import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.AbstractMap; +import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.function.Function; +import java.util.Optional; import java.util.stream.Collectors; import static com.crowdin.Constants.MESSAGES_BUNDLE; @@ -29,47 +35,60 @@ public class UploadAction extends BackgroundAction { @Override public void performInBackground(@NotNull final AnActionEvent anActionEvent, ProgressIndicator indicator) { Project project = anActionEvent.getProject(); + if (project == null) { + return; + } + try { - CrowdinSettings crowdinSettings = ServiceManager.getService(project, CrowdinSettings.class); + Optional context = this.prepare( + project, + indicator, + false, + true, + true, + "messages.confirm.upload_sources", + "Upload" + ); - boolean confirmation = UIUtil.confirmDialog(project, crowdinSettings, MESSAGES_BUNDLE.getString("messages.confirm.upload_sources"), "Upload"); - if (!confirmation) { + if (context.isEmpty()) { return; } - indicator.checkCanceled(); - - VirtualFile root = FileUtil.getProjectBaseDir(project); - CrowdinProperties properties = CrowdinPropertiesLoader.load(project); - Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); - - NotificationUtil.setLogDebugLevel(properties.isDebug()); - NotificationUtil.logDebugMessage(project, MESSAGES_BUNDLE.getString("messages.debug.started_action")); + List selectedFiles = Optional + .ofNullable(project.getService(ProjectService.class).getUploadWindow()) + .map(UploadWindow::getSelectedFiles) + .orElse(Collections.emptyList()) + .stream() + .map(str -> Paths.get(context.get().root.getPath(), str)) + .toList(); NotificationUtil.logDebugMessage(project, MESSAGES_BUNDLE.getString("messages.debug.upload_sources.list_of_patterns") - + properties.getFiles().stream() - .map(fileBean -> String.format(MESSAGES_BUNDLE.getString("messages.debug.upload_sources.list_of_patterns_item"), fileBean.getSource(), fileBean.getTranslation())) - .collect(Collectors.joining())); - - BranchLogic branchLogic = new BranchLogic(crowdin, project, properties); - String branchName = branchLogic.acquireBranchName(true); - - CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache = - CrowdinProjectCacheProvider.getInstance(crowdin, branchName, true); - indicator.checkCanceled(); + + context.get().properties.getFiles().stream() + .map(fileBean -> String.format(MESSAGES_BUNDLE.getString("messages.debug.upload_sources.list_of_patterns_item"), fileBean.getSource(), fileBean.getTranslation())) + .collect(Collectors.joining())); - Branch branch = branchLogic.getBranch(crowdinProjectCache, true); - indicator.checkCanceled(); + Map> sources = context.get().properties.getFiles() + .stream() + .map(fileBean -> new AbstractMap.SimpleEntry<>( + fileBean, + FileUtil.getSourceFilesRec(context.get().root, fileBean.getSource()) + .stream() + .filter(f -> selectedFiles.isEmpty() || selectedFiles.contains(Paths.get(f.getPath()))) + .toList() + ) + ) + .filter(e -> !e.getValue().isEmpty()) + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + SourceLogic.processSources(project, context.get().root, context.get().crowdin, context.get().crowdinProjectCache, context.get().branch, context.get().properties.isPreserveHierarchy(), sources); - Map> sources = properties.getFiles().stream() - .collect(Collectors.toMap(Function.identity(), fileBean -> FileUtil.getSourceFilesRec(root, fileBean.getSource()))); - SourceLogic.processSources(project, root, crowdin, crowdinProjectCache, branch, properties.isPreserveHierarchy(), sources); - CrowdinProjectCacheProvider.outdateBranch(branchName); + project.getService(CrowdinProjectCacheProvider.class).outdateBranch(context.get().branchName); } catch (ProcessCanceledException e) { throw e; } catch (Exception e) { NotificationUtil.logErrorMessage(project, e); NotificationUtil.showErrorMessage(project, e.getMessage()); + } finally { + ApplicationManager.getApplication().invokeAndWait(() -> CrowdinPanelWindowFactory.reloadPanels(project, true)); } } diff --git a/src/main/java/com/crowdin/action/UploadFromContextAction.java b/src/main/java/com/crowdin/action/UploadFromContextAction.java index 1f39c85..d23f49e 100644 --- a/src/main/java/com/crowdin/action/UploadFromContextAction.java +++ b/src/main/java/com/crowdin/action/UploadFromContextAction.java @@ -1,23 +1,27 @@ package com.crowdin.action; -import com.crowdin.client.*; -import com.crowdin.client.sourcefiles.model.Branch; -import com.crowdin.logic.BranchLogic; -import com.crowdin.logic.CrowdinSettings; +import com.crowdin.client.CrowdinProperties; +import com.crowdin.client.CrowdinPropertiesLoader; +import com.crowdin.client.FileBean; import com.crowdin.logic.SourceLogic; -import com.crowdin.util.*; +import com.crowdin.service.CrowdinProjectCacheProvider; +import com.crowdin.ui.panel.CrowdinPanelWindowFactory; +import com.crowdin.util.FileUtil; +import com.crowdin.util.NotificationUtil; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import static com.crowdin.Constants.MESSAGES_BUNDLE; @@ -26,52 +30,47 @@ */ public class UploadFromContextAction extends BackgroundAction { @Override - public void performInBackground(AnActionEvent anActionEvent, ProgressIndicator indicator) { + public void performInBackground(AnActionEvent anActionEvent, @NotNull ProgressIndicator indicator) { final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(anActionEvent.getDataContext()); Project project = anActionEvent.getProject(); - try { - CrowdinSettings crowdinSettings = ServiceManager.getService(project, CrowdinSettings.class); + if (project == null) { + return; + } - boolean confirmation = UIUtil.confirmDialog(project, crowdinSettings, MESSAGES_BUNDLE.getString("messages.confirm.upload_source_file"), "Upload"); - if (!confirmation) { + try { + Optional context = this.prepare( + project, + indicator, + false, + true, + true, + "messages.confirm.upload_source_file", + "Upload" + ); + + if (context.isEmpty()) { return; } - indicator.checkCanceled(); - - VirtualFile root = FileUtil.getProjectBaseDir(project); - - CrowdinProperties properties = CrowdinPropertiesLoader.load(project); - NotificationUtil.setLogDebugLevel(properties.isDebug()); - NotificationUtil.logDebugMessage(project, MESSAGES_BUNDLE.getString("messages.debug.started_action")); - Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); - BranchLogic branchLogic = new BranchLogic(crowdin, project, properties); - String branchName = branchLogic.acquireBranchName(true); - indicator.checkCanceled(); - - CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache = - CrowdinProjectCacheProvider.getInstance(crowdin, branchName, true); - - Branch branch = branchLogic.getBranch(crowdinProjectCache, true); - indicator.checkCanceled(); - - FileBean foundFileBean = properties.getFiles() - .stream() - .filter(fb -> FileUtil.getSourceFilesRec(root, fb.getSource()).contains(file)) - .findAny() - .orElseThrow(() -> new RuntimeException("Unexpected error: couldn't find suitable source pattern")); + FileBean foundFileBean = context.get().properties.getFiles() + .stream() + .filter(fb -> FileUtil.getSourceFilesRec(context.get().root, fb.getSource()).contains(file)) + .findAny() + .orElseThrow(() -> new RuntimeException("Unexpected error: couldn't find suitable source pattern")); indicator.checkCanceled(); Map> source = Collections.singletonMap(foundFileBean, Collections.singletonList(file)); - SourceLogic.processSources(project, root, crowdin, crowdinProjectCache, branch, properties.isPreserveHierarchy(), source); + SourceLogic.processSources(project, context.get().root, context.get().crowdin, context.get().crowdinProjectCache, context.get().branch, context.get().properties.isPreserveHierarchy(), source); - CrowdinProjectCacheProvider.outdateBranch(branchName); + project.getService(CrowdinProjectCacheProvider.class).outdateBranch(context.get().branchName); } catch (ProcessCanceledException e) { throw e; } catch (Exception e) { NotificationUtil.logErrorMessage(project, e); NotificationUtil.showErrorMessage(project, e.getMessage()); + } finally { + ApplicationManager.getApplication().invokeAndWait(() -> CrowdinPanelWindowFactory.reloadPanels(project, true)); } } @@ -84,9 +83,9 @@ public void update(AnActionEvent e) { CrowdinProperties properties; properties = CrowdinPropertiesLoader.load(project); isSourceFile = properties.getFiles() - .stream() - .flatMap(fb -> FileUtil.getSourceFilesRec(FileUtil.getProjectBaseDir(project), fb.getSource()).stream()) - .anyMatch(f -> Objects.equals(file, f)); + .stream() + .flatMap(fb -> FileUtil.getSourceFilesRec(FileUtil.getProjectBaseDir(project), fb.getSource()).stream()) + .anyMatch(f -> Objects.equals(file, f)); } catch (Exception exception) { // do nothing } finally { diff --git a/src/main/java/com/crowdin/action/UploadTranslationsAction.java b/src/main/java/com/crowdin/action/UploadTranslationsAction.java index 32ddb8f..6eccb64 100644 --- a/src/main/java/com/crowdin/action/UploadTranslationsAction.java +++ b/src/main/java/com/crowdin/action/UploadTranslationsAction.java @@ -1,110 +1,153 @@ package com.crowdin.action; -import com.crowdin.client.*; +import com.crowdin.client.FileBean; +import com.crowdin.client.RequestBuilder; import com.crowdin.client.languages.model.Language; -import com.crowdin.client.sourcefiles.model.Branch; import com.crowdin.client.sourcefiles.model.FileInfo; import com.crowdin.client.translations.model.UploadTranslationsRequest; -import com.crowdin.logic.BranchLogic; -import com.crowdin.logic.CrowdinSettings; -import com.crowdin.util.*; +import com.crowdin.client.translations.model.UploadTranslationsStringsRequest; +import com.crowdin.service.ProjectService; +import com.crowdin.ui.panel.CrowdinPanelWindowFactory; +import com.crowdin.ui.panel.upload.UploadWindow; +import com.crowdin.util.FileUtil; +import com.crowdin.util.NotificationUtil; +import com.crowdin.util.PlaceholderUtil; +import com.crowdin.util.StringUtils; import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; -import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Collections; +import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import static com.crowdin.Constants.MESSAGES_BUNDLE; +import static com.crowdin.util.Util.isFileFormatNotAllowed; public class UploadTranslationsAction extends BackgroundAction { @Override - public void performInBackground(@NotNull AnActionEvent e, ProgressIndicator indicator) { + public void performInBackground(@NotNull AnActionEvent e, @NotNull ProgressIndicator indicator) { Project project = e.getProject(); - VirtualFile root = FileUtil.getProjectBaseDir(project); + if (project == null) { + return; + } - CrowdinProperties properties; try { - CrowdinSettings crowdinSettings = ServiceManager.getService(project, CrowdinSettings.class); - - boolean confirmation = UIUtil.confirmDialog(project, crowdinSettings, MESSAGES_BUNDLE.getString("messages.confirm.upload_translations"), "Upload"); - if (!confirmation) { + Optional context = this.prepare( + project, + indicator, + true, + true, + true, + "messages.confirm.upload_translations", + "Upload" + ); + + if (context.isEmpty()) { return; } - indicator.checkCanceled(); - - properties = CrowdinPropertiesLoader.load(project); - NotificationUtil.setLogDebugLevel(properties.isDebug()); - NotificationUtil.logDebugMessage(project, MESSAGES_BUNDLE.getString("messages.debug.started_action")); - - Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); - indicator.checkCanceled(); - - BranchLogic branchLogic = new BranchLogic(crowdin, project, properties); - String branchName = branchLogic.acquireBranchName(true); - CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache = - CrowdinProjectCacheProvider.getInstance(crowdin, branchName, true); + List selectedFiles = Optional + .ofNullable(project.getService(ProjectService.class).getUploadWindow()) + .map(UploadWindow::getSelectedFiles) + .orElse(Collections.emptyList()) + .stream() + .map(str -> Paths.get(context.get().root.getPath(), str)) + .toList(); - if (!crowdinProjectCache.isManagerAccess()) { - NotificationUtil.showErrorMessage(project, "You need to have manager access to perform this action"); + if (context.get().crowdinProjectCache.isStringsBased() && context.get().branch == null) { + NotificationUtil.showErrorMessage(project, "Branch is missing"); return; } - Branch branch = branchLogic.getBranch(crowdinProjectCache, false); + Map filePaths = context.get().crowdinProjectCache.isStringsBased() + ? Collections.emptyMap() + : context.get().crowdinProjectCache.getFileInfos(context.get().branch); - Map filePaths = crowdinProjectCache.getFileInfos(branch); - - NotificationUtil.logDebugMessage(project, "Project files: " + filePaths.keySet()); + if (!context.get().crowdinProjectCache.isStringsBased()) { + NotificationUtil.logDebugMessage(project, "Project files: " + filePaths.keySet()); + } AtomicInteger uploadedFilesCounter = new AtomicInteger(0); - for (FileBean fileBean : properties.getFiles()) { - for (VirtualFile source : FileUtil.getSourceFilesRec(root, fileBean.getSource())) { + for (FileBean fileBean : context.get().properties.getFiles()) { + for (VirtualFile source : FileUtil.getSourceFilesRec(context.get().root, fileBean.getSource())) { VirtualFile pathToPattern = FileUtil.getBaseDir(source, fileBean.getSource()); - String sourceRelativePath = properties.isPreserveHierarchy() ? StringUtils.removeStart(source.getPath(), root.getPath()) : FileUtil.sepAtStart(source.getName()); + String sourceRelativePath = context.get().properties.isPreserveHierarchy() ? StringUtils.removeStart(source.getPath(), context.get().root.getPath()) : FileUtil.sepAtStart(source.getName()); Map translationPaths = - PlaceholderUtil.buildTranslationPatterns(sourceRelativePath, fileBean.getTranslation(), crowdinProjectCache.getProjectLanguages(), crowdinProjectCache.getLanguageMapping()); + PlaceholderUtil.buildTranslationPatterns(sourceRelativePath, fileBean.getTranslation(), context.get().crowdinProjectCache.getProjectLanguages(), context.get().crowdinProjectCache.getLanguageMapping()); FileInfo crowdinSource = filePaths.get(FileUtil.normalizePath(sourceRelativePath)); - if (crowdinSource == null) { - NotificationUtil.showWarningMessage(project, String.format(MESSAGES_BUNDLE.getString("errors.missing_source"), FileUtil.normalizePath((branchName != null ? branchName + "/" : "") + sourceRelativePath))); - return; + if (!context.get().crowdinProjectCache.isStringsBased() && crowdinSource == null) { + if (selectedFiles.isEmpty()) { + NotificationUtil.showWarningMessage(project, String.format(MESSAGES_BUNDLE.getString("errors.missing_source"), FileUtil.normalizePath((context.get().branchName != null ? context.get().branchName + "/" : "") + sourceRelativePath))); + return; + } else { + continue; + } } for (Map.Entry translationPath : translationPaths.entrySet()) { - java.io.File translationFile = Paths.get(pathToPattern.getPath(), translationPath.getValue()).toFile(); + Path translationFilePath = Paths.get(pathToPattern.getPath(), translationPath.getValue()); + java.io.File translationFile = translationFilePath.toFile(); + + if (!selectedFiles.isEmpty()) { + if (!selectedFiles.contains(translationFilePath)) { + continue; + } + } + if (!translationFile.exists()) { - NotificationUtil.showWarningMessage(project, String.format(MESSAGES_BUNDLE.getString("errors.missing_translation"), FileUtil.noSepAtStart(StringUtils.removeStart(translationFile.getPath(), root.getPath())))); + NotificationUtil.showWarningMessage(project, String.format(MESSAGES_BUNDLE.getString("errors.missing_translation"), FileUtil.noSepAtStart(StringUtils.removeStart(translationFile.getPath(), context.get().root.getPath())))); continue; } + Long storageId; try (InputStream translationFileStrem = new FileInputStream(translationFile)) { - storageId = crowdin.addStorage(translationFile.getName(), translationFileStrem); + storageId = context.get().crowdin.addStorage(translationFile.getName(), translationFileStrem); } catch (IOException exception) { throw new RuntimeException("Unhandled exception with File '" + translationFile + "'", exception); } - UploadTranslationsRequest request = RequestBuilder.uploadTranslation(crowdinSource.getId(), storageId, properties.isImportEqSuggestions(), properties.isAutoApproveImported(), properties.isTranslateHidden()); + try { - crowdin.uploadTranslation(translationPath.getKey().getId(), request); + + if (context.get().crowdinProjectCache.isStringsBased()) { + UploadTranslationsStringsRequest request = RequestBuilder.uploadStringsTranslation(context.get().branch.getId(), storageId, context.get().properties.isImportEqSuggestions(), context.get().properties.isAutoApproveImported(), context.get().properties.isTranslateHidden()); + context.get().crowdin.uploadStringsTranslation(translationPath.getKey().getId(), request); + } else { + UploadTranslationsRequest request = RequestBuilder.uploadTranslation(crowdinSource.getId(), storageId, context.get().properties.isImportEqSuggestions(), context.get().properties.isAutoApproveImported(), context.get().properties.isTranslateHidden()); + context.get().crowdin.uploadTranslation(translationPath.getKey().getId(), request); + } + uploadedFilesCounter.incrementAndGet(); } catch (Exception exception) { - NotificationUtil.logErrorMessage(project, exception); - NotificationUtil.showErrorMessage(project, "Couldn't upload translation file '" + translationFile + "': " + exception.getMessage()); + if (isFileFormatNotAllowed(exception)) { + String message = String.format( + "*.%s files are not allowed to upload in strings-based projects", + source.getExtension() + ); + NotificationUtil.showWarningMessage(project, message); + } else { + NotificationUtil.logErrorMessage(project, exception); + NotificationUtil.showErrorMessage(project, "Couldn't upload translation file '" + translationFile + "': " + exception.getMessage()); + } } } } } + if (uploadedFilesCounter.get() > 0) { NotificationUtil.showInformationMessage(project, String.format(MESSAGES_BUNDLE.getString("messages.success.upload_translations"), uploadedFilesCounter.get())); } else { @@ -115,6 +158,8 @@ public void performInBackground(@NotNull AnActionEvent e, ProgressIndicator indi } catch (Exception exception) { NotificationUtil.logErrorMessage(project, exception); NotificationUtil.showErrorMessage(project, exception.getMessage()); + } finally { + ApplicationManager.getApplication().invokeAndWait(() -> CrowdinPanelWindowFactory.reloadPanels(project, true)); } } diff --git a/src/main/java/com/crowdin/action/UploadTranslationsFromContextAction.java b/src/main/java/com/crowdin/action/UploadTranslationsFromContextAction.java index 554c214..bc06f6d 100644 --- a/src/main/java/com/crowdin/action/UploadTranslationsFromContextAction.java +++ b/src/main/java/com/crowdin/action/UploadTranslationsFromContextAction.java @@ -1,107 +1,131 @@ package com.crowdin.action; -import com.crowdin.client.*; +import com.crowdin.client.FileBean; +import com.crowdin.client.RequestBuilder; import com.crowdin.client.languages.model.Language; -import com.crowdin.client.sourcefiles.model.Branch; import com.crowdin.client.sourcefiles.model.File; import com.crowdin.client.translations.model.UploadTranslationsRequest; -import com.crowdin.logic.BranchLogic; +import com.crowdin.client.translations.model.UploadTranslationsStringsRequest; import com.crowdin.logic.ContextLogic; -import com.crowdin.logic.CrowdinSettings; -import com.crowdin.util.*; +import com.crowdin.ui.panel.CrowdinPanelWindowFactory; +import com.crowdin.util.FileUtil; +import com.crowdin.util.NotificationUtil; +import com.crowdin.util.PlaceholderUtil; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Collections; import java.util.Map; +import java.util.Optional; import static com.crowdin.Constants.MESSAGES_BUNDLE; +import static com.crowdin.util.Util.isFileFormatNotAllowed; /** * Created by ihor on 1/27/17. */ public class UploadTranslationsFromContextAction extends BackgroundAction { - @Override - public void performInBackground(AnActionEvent anActionEvent, ProgressIndicator indicator) { + public void performInBackground(AnActionEvent anActionEvent, @NotNull ProgressIndicator indicator) { final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(anActionEvent.getDataContext()); + if (file == null) { + return; + } + Project project = anActionEvent.getProject(); - try { - CrowdinSettings crowdinSettings = ServiceManager.getService(project, CrowdinSettings.class); + if (project == null) { + return; + } - boolean confirmation = UIUtil.confirmDialog(project, crowdinSettings, MESSAGES_BUNDLE.getString("messages.confirm.upload_translation_file"), "Upload"); - if (!confirmation) { + try { + Optional context = this.prepare( + project, + indicator, + true, + true, + true, + "messages.confirm.upload_translation_file", + "Upload" + ); + + if (context.isEmpty()) { return; } - indicator.checkCanceled(); - - VirtualFile root = FileUtil.getProjectBaseDir(project); - CrowdinProperties properties = CrowdinPropertiesLoader.load(project); - Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); - - BranchLogic branchLogic = new BranchLogic(crowdin, project, properties); - String branchName = branchLogic.acquireBranchName(true); - indicator.checkCanceled(); - - CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache = - CrowdinProjectCacheProvider.getInstance(crowdin, branchName, true); - if (!crowdinProjectCache.isManagerAccess()) { - NotificationUtil.showErrorMessage(project, "You need to have manager access to perform this action"); + if (context.get().crowdinProjectCache.isStringsBased() && context.get().branch == null) { + NotificationUtil.showErrorMessage(project, "Branch is missing"); return; } - Branch branch = branchLogic.getBranch(crowdinProjectCache, true); - - Map filePaths = crowdinProjectCache.getFiles(branch); + Map filePaths = context.get().crowdinProjectCache.isStringsBased() + ? Collections.emptyMap() + : context.get().crowdinProjectCache.getFiles(context.get().branch); indicator.checkCanceled(); - for (FileBean fileBean : properties.getFiles()) { - for (VirtualFile source : FileUtil.getSourceFilesRec(root, fileBean.getSource())) { + for (FileBean fileBean : context.get().properties.getFiles()) { + for (VirtualFile source : FileUtil.getSourceFilesRec(context.get().root, fileBean.getSource())) { VirtualFile pathToPattern = FileUtil.getBaseDir(source, fileBean.getSource()); - String relativePathToPattern = (properties.isPreserveHierarchy()) - ? java.io.File.separator + FileUtil.findRelativePath(root, pathToPattern) - : ""; - String patternPathToFile = (properties.isPreserveHierarchy()) - ? java.io.File.separator + FileUtil.findRelativePath(pathToPattern, source.getParent()) - : ""; + String relativePathToPattern = (context.get().properties.isPreserveHierarchy()) + ? java.io.File.separator + FileUtil.findRelativePath(context.get().root, pathToPattern) + : ""; + String patternPathToFile = (context.get().properties.isPreserveHierarchy()) + ? java.io.File.separator + FileUtil.findRelativePath(pathToPattern, source.getParent()) + : ""; File crowdinSource = filePaths.get(FileUtil.normalizePath(FileUtil.joinPaths(relativePathToPattern, patternPathToFile, source.getName()))); - if (crowdinSource == null) { - NotificationUtil.showWarningMessage(project, String.format(MESSAGES_BUNDLE.getString("errors.missing_source"), (branchName != null ? branchName : "") + FileUtil.sepAtStart(FileUtil.joinPaths(relativePathToPattern, patternPathToFile, source.getName())))); + if (!context.get().crowdinProjectCache.isStringsBased() && crowdinSource == null) { + NotificationUtil.showWarningMessage(project, String.format(MESSAGES_BUNDLE.getString("errors.missing_source"), (context.get().branchName != null ? context.get().branchName : "") + FileUtil.sepAtStart(FileUtil.joinPaths(relativePathToPattern, patternPathToFile, source.getName())))); return; } String basePattern = PlaceholderUtil.replaceFilePlaceholders(fileBean.getTranslation(), FileUtil.joinPaths(relativePathToPattern, patternPathToFile, source.getName())); - for (Language lang : crowdinProjectCache.getProjectLanguages()) { - String builtPattern = PlaceholderUtil.replaceLanguagePlaceholders(basePattern, lang, crowdinProjectCache.getLanguageMapping()); + for (Language lang : context.get().crowdinProjectCache.getProjectLanguages()) { + String builtPattern = PlaceholderUtil.replaceLanguagePlaceholders(basePattern, lang, context.get().crowdinProjectCache.getLanguageMapping()); Path translationFile = Paths.get(pathToPattern.getPath(), builtPattern); int compare = translationFile.compareTo(Paths.get(file.getPath())); if (compare == 0) { Long storageId; - try (InputStream translationFileStrem = new FileInputStream(translationFile.toFile())) { - storageId = crowdin.addStorage(translationFile.toFile().getName(), translationFileStrem); + try (InputStream translationFileStream = new FileInputStream(translationFile.toFile())) { + storageId = context.get().crowdin.addStorage(translationFile.toFile().getName(), translationFileStream); } catch (IOException exception) { throw new RuntimeException("Unhandled exception with File '" + translationFile + "'", exception); } - UploadTranslationsRequest request = RequestBuilder.uploadTranslation(crowdinSource.getId(), storageId, properties.isImportEqSuggestions(), properties.isAutoApproveImported(), properties.isTranslateHidden()); + try { - crowdin.uploadTranslation(lang.getId(), request); + + if (context.get().crowdinProjectCache.isStringsBased()) { + UploadTranslationsStringsRequest request = RequestBuilder.uploadStringsTranslation(context.get().branch.getId(), storageId, context.get().properties.isImportEqSuggestions(), context.get().properties.isAutoApproveImported(), context.get().properties.isTranslateHidden()); + context.get().crowdin.uploadStringsTranslation(lang.getId(), request); + } else { + UploadTranslationsRequest request = RequestBuilder.uploadTranslation(crowdinSource.getId(), storageId, context.get().properties.isImportEqSuggestions(), context.get().properties.isAutoApproveImported(), context.get().properties.isTranslateHidden()); + context.get().crowdin.uploadTranslation(lang.getId(), request); + } + NotificationUtil.showInformationMessage(project, - String.format(MESSAGES_BUNDLE.getString("messages.success.upload_translation"), - FileUtil.noSepAtStart(FileUtil.joinPaths(relativePathToPattern, builtPattern)))); + String.format(MESSAGES_BUNDLE.getString("messages.success.upload_translation"), + FileUtil.noSepAtStart(FileUtil.joinPaths(relativePathToPattern, builtPattern)))); } catch (Exception exception) { - NotificationUtil.showErrorMessage(project, "Couldn't upload translation file '" + translationFile + "': " + exception.getMessage()); + if (isFileFormatNotAllowed(exception)) { + String message = String.format( + "*.%s files are not allowed to upload in strings-based projects", + source.getExtension() + ); + NotificationUtil.showWarningMessage(project, message); + } else { + NotificationUtil.showErrorMessage(project, "Couldn't upload translation file '" + translationFile + "': " + exception.getMessage()); + } } } } @@ -111,6 +135,8 @@ public void performInBackground(AnActionEvent anActionEvent, ProgressIndicator i throw e; } catch (Exception e) { NotificationUtil.showErrorMessage(project, e.getMessage()); + } finally { + ApplicationManager.getApplication().invokeAndWait(() -> CrowdinPanelWindowFactory.reloadPanels(project, true)); } } @@ -123,24 +149,14 @@ public void update(AnActionEvent e) { if (file == null) { return; } - CrowdinProperties properties; - try { - properties = CrowdinPropertiesLoader.load(project); - } catch (Exception exception) { - return; - } - NotificationUtil.setLogDebugLevel(properties.isDebug()); - NotificationUtil.logDebugMessage(project, MESSAGES_BUNDLE.getString("messages.debug.started_action")); - - VirtualFile root = FileUtil.getProjectBaseDir(project); - Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); - String branchName = ActionUtils.getBranchName(project, properties, false); + Optional context = super.prepare(project, null, false, false, false, null, null); - CrowdinProjectCacheProvider.CrowdinProjectCache crowdinProjectCache = - CrowdinProjectCacheProvider.getInstance(crowdin, branchName, false); + if (context.isEmpty()) { + return; + } - isTranslationFile = ContextLogic.findSourceFileFromTranslationFile(file, properties, root, crowdinProjectCache).isPresent(); + isTranslationFile = ContextLogic.findSourceFileFromTranslationFile(file, context.get().properties, context.get().root, context.get().crowdinProjectCache).isPresent(); } catch (Exception exception) { // do nothing } finally { diff --git a/src/main/java/com/crowdin/activity/CrowdinStartupActivity.java b/src/main/java/com/crowdin/activity/CrowdinStartupActivity.java index 76cf33b..18313f9 100644 --- a/src/main/java/com/crowdin/activity/CrowdinStartupActivity.java +++ b/src/main/java/com/crowdin/activity/CrowdinStartupActivity.java @@ -1,11 +1,13 @@ package com.crowdin.activity; import com.crowdin.client.Crowdin; -import com.crowdin.client.CrowdinProjectCacheProvider; import com.crowdin.client.CrowdinProperties; import com.crowdin.client.CrowdinPropertiesLoader; import com.crowdin.event.FileChangeListener; -import com.crowdin.util.ActionUtils; +import com.crowdin.logic.BranchLogic; +import com.crowdin.service.CrowdinProjectCacheProvider; +import com.crowdin.service.ProjectService; +import com.crowdin.ui.panel.CrowdinPanelWindowFactory; import com.crowdin.util.NotificationUtil; import com.crowdin.util.PropertyUtil; import com.intellij.openapi.progress.ProgressIndicator; @@ -15,6 +17,8 @@ import com.intellij.openapi.startup.StartupActivity; import org.jetbrains.annotations.NotNull; +import java.util.EnumSet; + public class CrowdinStartupActivity implements StartupActivity { @Override @@ -29,21 +33,31 @@ public void runActivity(@NotNull Project project) { properties = CrowdinPropertiesLoader.load(project); Crowdin crowdin = new Crowdin(properties.getProjectId(), properties.getApiToken(), properties.getBaseUrl()); - String branchName = ActionUtils.getBranchName(project, properties, false); - - ProgressManager.getInstance().run(new Task.Backgroundable(project, "Crowdin") { - @Override - public void run(@NotNull ProgressIndicator indicator) { - try { - indicator.setText("Updating Crowdin cache"); - CrowdinProjectCacheProvider.getInstance(crowdin, branchName, true); - } catch (Exception e) { - NotificationUtil.showErrorMessage(project, e.getMessage()); - } - } - }); + this.reloadPlugin(project, crowdin, properties); } catch (Exception e) { NotificationUtil.showErrorMessage(project, e.getMessage()); } } + + private void reloadPlugin(Project project, Crowdin crowdin, CrowdinProperties properties) { + BranchLogic branchLogic = new BranchLogic(crowdin, project, properties); + String branchName = branchLogic.acquireBranchName(); + + ProgressManager.getInstance().run(new Task.Backgroundable(project, "Crowdin") { + @Override + public void run(@NotNull ProgressIndicator indicator) { + try { + indicator.setText("Updating Crowdin cache"); + project.getService(CrowdinProjectCacheProvider.class).getInstance(crowdin, branchName, true); + ProjectService service = project.getService(ProjectService.class); + EnumSet loadedComponents = service.addAndGetLoadedComponents(ProjectService.InitializationItem.STARTUP_ACTIVITY); + if (loadedComponents.contains(ProjectService.InitializationItem.UI_PANELS)) { + CrowdinPanelWindowFactory.reloadPanels(project, true); + } + } catch (Exception e) { + NotificationUtil.showErrorMessage(project, e.getMessage()); + } + } + }); + } } diff --git a/src/main/java/com/crowdin/client/BranchInfo.java b/src/main/java/com/crowdin/client/BranchInfo.java index 492335d..9850881 100644 --- a/src/main/java/com/crowdin/client/BranchInfo.java +++ b/src/main/java/com/crowdin/client/BranchInfo.java @@ -1,11 +1,20 @@ package com.crowdin.client; -import lombok.Data; - -@Data public class BranchInfo { private final String name; private final String title; + public BranchInfo(String name, String title) { + this.name = name; + this.title = title; + } + + public String getName() { + return name; + } + + public String getTitle() { + return title; + } } diff --git a/src/main/java/com/crowdin/client/Crowdin.java b/src/main/java/com/crowdin/client/Crowdin.java index 5a86319..f213e8b 100644 --- a/src/main/java/com/crowdin/client/Crowdin.java +++ b/src/main/java/com/crowdin/client/Crowdin.java @@ -1,18 +1,24 @@ package com.crowdin.client; +import com.crowdin.client.bundles.model.Bundle; +import com.crowdin.client.bundles.model.BundleExport; import com.crowdin.client.core.http.exceptions.HttpBadRequestException; import com.crowdin.client.core.http.exceptions.HttpException; import com.crowdin.client.core.model.*; import com.crowdin.client.labels.model.AddLabelRequest; import com.crowdin.client.labels.model.Label; import com.crowdin.client.languages.model.Language; +import com.crowdin.client.projectsgroups.model.Project; import com.crowdin.client.sourcefiles.model.*; import com.crowdin.client.sourcestrings.model.SourceString; +import com.crowdin.client.sourcestrings.model.UploadStringsProgress; +import com.crowdin.client.sourcestrings.model.UploadStringsRequest; import com.crowdin.client.translations.model.BuildProjectFileTranslationRequest; import com.crowdin.client.translations.model.BuildProjectTranslationRequest; import com.crowdin.client.translations.model.ProjectBuild; import com.crowdin.client.translations.model.UploadTranslationsRequest; -import com.crowdin.client.translationstatus.model.FileProgress; +import com.crowdin.client.translations.model.UploadTranslationsStringsRequest; +import com.crowdin.client.translationstatus.model.FileBranchProgress; import com.crowdin.client.translationstatus.model.LanguageProgress; import com.crowdin.util.RetryUtil; import com.crowdin.util.Util; @@ -36,69 +42,82 @@ public class Crowdin implements CrowdinClient { private final Long projectId; + private final String baseUrl; private final com.crowdin.client.Client client; public Crowdin(@NotNull Long projectId, @NotNull String apiToken, String baseUrl) { this.projectId = projectId; + this.baseUrl = baseUrl; Credentials credentials = new Credentials(apiToken, null, baseUrl); ClientConfig clientConfig = ClientConfig.builder() - .userAgent(Util.getUserAgent()) - .build(); + .userAgent(Util.getUserAgent()) + .build(); this.client = new Client(credentials, clientConfig); } + @Override + public Long getProjectId() { + return this.projectId; + } + @Override public Long addStorage(String fileName, InputStream content) { return executeRequest(() -> this.client.getStorageApi() - .addStorage(fileName, content) - .getData() - .getId()); + .addStorage(fileName, content) + .getData() + .getId()); } @Override public void updateSource(Long sourceId, UpdateFileRequest request) { executeRequest(() -> this.client.getSourceFilesApi() - .updateOrRestoreFile(this.projectId, sourceId, request)); + .updateOrRestoreFile(this.projectId, sourceId, request)); } @Override public URL downloadFile(Long fileId) { return url(executeRequest(() -> this.client.getSourceFilesApi() - .downloadFile(this.projectId, fileId) - .getData())); + .downloadFile(this.projectId, fileId) + .getData())); } @Override public void addSource(AddFileRequest request) { executeRequest(() -> this.client.getSourceFilesApi() - .addFile(this.projectId, request)); + .addFile(this.projectId, request)); } @Override public void editSource(Long fileId, List request) { executeRequest(() -> this.client.getSourceFilesApi() - .editFile(this.projectId, fileId, request)); + .editFile(this.projectId, fileId, request)); } @Override public void uploadTranslation(String languageId, UploadTranslationsRequest request) { executeRequest(() -> this.client.getTranslationsApi() - .uploadTranslations(this.projectId, languageId, request)); + .uploadTranslations(this.projectId, languageId, request)); + } + + @Override + public void uploadStringsTranslation(String languageId, UploadTranslationsStringsRequest request) { + executeRequest(() -> this.client.getTranslationsApi() + .uploadTranslationStringsBased(this.projectId, languageId, request)); } @Override public Directory addDirectory(AddDirectoryRequest request) { return executeRequest(() -> this.client.getSourceFilesApi() - .addDirectory(this.projectId, request) - .getData()); + .addDirectory(this.projectId, request) + .getData()); } @Override public com.crowdin.client.projectsgroups.model.Project getProject() { return executeRequest(() -> this.client.getProjectsGroupsApi() - .getProject(this.projectId) - .getData()); + .getProject(this.projectId) + .getData()); } @Override @@ -106,67 +125,103 @@ public List extractProjectLanguages(com.crowdin.client.projectsgroups. return crowdinProject.getTargetLanguages(); } + @Override + public UploadStringsProgress uploadStrings(UploadStringsRequest request) { + return executeRequest(() -> this.client.getSourceStringsApi() + .uploadStrings(this.projectId, request) + .getData()); + } + + @Override + public UploadStringsProgress checkUploadStringsStatus(String id) { + return executeRequest(() -> this.client.getSourceStringsApi() + .uploadStringsStatus(projectId, id) + .getData()); + } + @Override public ProjectBuild startBuildingTranslation(BuildProjectTranslationRequest request) { return executeRequest(() -> this.client.getTranslationsApi() - .buildProjectTranslation(this.projectId, request) - .getData()); + .buildProjectTranslation(this.projectId, request) + .getData()); } @Override public ProjectBuild checkBuildingStatus(Long buildId) { return executeRequest(() -> this.client.getTranslationsApi() - .checkBuildStatus(projectId, buildId) - .getData()); + .checkBuildStatus(projectId, buildId) + .getData()); } @Override public URL downloadProjectTranslations(Long buildId) { return url(executeRequest(() -> this.client.getTranslationsApi() - .downloadProjectTranslations(this.projectId, buildId) - .getData())); + .downloadProjectTranslations(this.projectId, buildId) + .getData())); + } + + + @Override + public BundleExport startBuildingBundle(Long bundleId) { + return executeRequest(() -> this.client.getBundlesApi() + .exportBundle(this.projectId, bundleId) + .getData()); + } + + @Override + public BundleExport checkBundleBuildingStatus(Long buildId, String exportId) { + return executeRequest(() -> this.client.getBundlesApi() + .checkBundleExportStatus(projectId, buildId, exportId) + .getData()); + } + + @Override + public URL downloadBundle(Long buildId, String exportId) { + return url(executeRequest(() -> this.client.getBundlesApi() + .downloadBundle(this.projectId, buildId, exportId) + .getData())); } @Override public URL downloadFileTranslation(Long fileId, BuildProjectFileTranslationRequest request) { return url(executeRequest(() -> client.getTranslationsApi() - .buildProjectFileTranslation(this.projectId, fileId, null, request) - .getData())); + .buildProjectFileTranslation(this.projectId, fileId, null, request) + .getData())); } @Override public List getSupportedLanguages() { return executeRequest(() -> client.getLanguagesApi().listSupportedLanguages(500, 0) - .getData() - .stream() - .map(ResponseObject::getData) - .collect(Collectors.toList())); + .getData() + .stream() + .map(ResponseObject::getData) + .collect(Collectors.toList())); } @Override public Map getDirectories(Long branchId) { return executeRequestFullList((limit, offset) -> this.client.getSourceFilesApi() - .listDirectories(this.projectId, branchId, null, null, true, limit, offset) - .getData() - ) - .stream() - .map(ResponseObject::getData) - .filter(dir -> Objects.equals(dir.getBranchId(), branchId)) - .collect(Collectors.toMap(Directory::getId, Function.identity())); + .listDirectories(this.projectId, branchId, null, null, true, limit, offset) + .getData() + ) + .stream() + .map(ResponseObject::getData) + .filter(dir -> Objects.equals(dir.getBranchId(), branchId)) + .collect(Collectors.toMap(Directory::getId, Function.identity())); } @Override public List getFiles(Long branchId) { return executeRequestFullList((limit, offset) -> this.client.getSourceFilesApi() - .listFiles(this.projectId, branchId, null, null, true, 500, 0) - .getData() - ) - .stream() - .map(ResponseObject::getData) - .filter(file -> Objects.equals(file.getBranchId(), branchId)) - .collect(Collectors.toList()); + .listFiles(this.projectId, branchId, null, null, true, 500, 0) + .getData() + ) + .stream() + .map(ResponseObject::getData) + .filter(file -> Objects.equals(file.getBranchId(), branchId)) + .collect(Collectors.toList()); } @Override @@ -183,7 +238,7 @@ public List getStrings() { null, limit, offset).getData() - ) + ) .stream() .map(ResponseObject::getData) .collect(Collectors.toList()); @@ -191,7 +246,7 @@ public List getStrings() { /** * @param request represents function that downloads list of models and has two args (limit, offset) - * @param represents model + * @param represents model * @return list of models accumulated from request function */ private List executeRequestFullList(BiFunction> request) { @@ -210,8 +265,8 @@ private List executeRequestFullList(BiFunction> public Branch addBranch(AddBranchRequest request) { try { return executeRequest(() -> this.client.getSourceFilesApi() - .addBranch(this.projectId, request) - .getData()); + .addBranch(this.projectId, request) + .getData()); } catch (Exception e) { if (e.getMessage() != null && e.getMessage().contains("regexNotMatch File name can't contain")) { throw new RuntimeException(MESSAGES_BUNDLE.getString("errors.branch_contains_forbidden_symbols")); @@ -233,50 +288,70 @@ public Optional getBranch(String name) { @Override public Map getBranches() { return executeRequestFullList((limit, offset) -> - this.client.getSourceFilesApi() - .listBranches(this.projectId, null, limit, offset) - .getData() + this.client.getSourceFilesApi() + .listBranches(this.projectId, null, limit, offset) + .getData() ) - .stream() - .map(ResponseObject::getData) - .collect(Collectors.toMap(Branch::getName, Function.identity())); + .stream() + .map(ResponseObject::getData) + .collect(Collectors.toMap(Branch::getName, Function.identity())); } @Override public List getProjectProgress() { return executeRequestFullList((limit, offset) -> this.client.getTranslationStatusApi() - .getProjectProgress(this.projectId, limit, offset, null) - .getData() - .stream() - .map(ResponseObject::getData) - .collect(Collectors.toList())); + .getProjectProgress(this.projectId, limit, offset, null) + .getData() + .stream() + .map(ResponseObject::getData) + .collect(Collectors.toList())); } @Override - public List getLanguageProgress(String languageId) { + public List getLanguageProgress(String languageId) { return executeRequestFullList((limit, offset) -> this.client.getTranslationStatusApi() - .getLanguageProgress(this.projectId, languageId, limit, offset) - .getData() - .stream() - .map(ResponseObject::getData) - .collect(Collectors.toList())); + .getLanguageProgress(this.projectId, languageId, limit, offset) + .getData() + .stream() + .map(ResponseObject::getData) + .collect(Collectors.toList())); } @Override public List