Skip to content

Commit

Permalink
Fix input text encoding issue
Browse files Browse the repository at this point in the history
Issue id: #1
 - Name: Fix input text encoding issue
 - Description: Cyrillic character encoding problem
 - URL: #1
 - Status: FIXED
  • Loading branch information
OPHoperHPO authored Nov 17, 2019
1 parent 31d3d53 commit 08d11e0
Showing 1 changed file with 27 additions and 10 deletions.
37 changes: 27 additions & 10 deletions translate.sh
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#! /bin/bash

### Console Google Translate
### Example usage:
### gttranslate <source_lng> <new_lng> <your text>
### This bash script is combine of this scripts https://gist.github.com/elFua/3342075 and https://gist.github.com/ayubmalik/149e2c7f28104f61cc1c862fe9834793
### Updated by Anodev https://github.com/OPHoperHPO/

USAGE="
Example usage: '$0 <source_lng> <new_lng> <your text>'
Usage: '$0 en ru text'
Expand All @@ -29,17 +29,34 @@ if [ "$#" == "0" ]; then
exit 1
fi

# Parse arguments to vars
FROM_LNG=$1
TO_LNG=$2

# Fixed text encoding issue. Issue URL: https://github.com/OPHoperHPO/GT-bash-client/issues/1
urlencode() {
# Code was copyied from https://gist.github.com/zhangkaiyulw/8793cd8641d270f1461a
local length="${#1}"
for (( i = 0; i < length; i++ )); do
local c="${1:i:1}"
case $c in
[a-zA-Z0-9.~_-]) printf "$c" ;;
*) printf "$c" | xxd -p -c1 |
while read x;
do printf "%%%s" "$(echo "$x" | tr "[:lower:]" "[:upper:]" )";
done
esac
done
}

shift 2
QUERY=$*
# Send text and language to google translate api
base_url="https://translate.googleapis.com/translate_a/single?client=gtx&sl=${FROM_LNG}&tl=${TO_LNG}&dt=t&q="
ua='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
qry=$( echo $@ | sed -E 's/\s{1,}/\+/g' )
full_url=${base_url}${qry}
response=$(curl -sA "${ua}" "${full_url}")
# Parse arguments to vars
qry=$( urlencode "$*" ) # Get query from arguments and encode it to URL encoding
# Define utility variables
ua='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36' # User Agent
url="https://translate.googleapis.com/translate_a/single?client=gtx&sl=${FROM_LNG}&tl=${TO_LNG}&dt=t&q=${qry}" # Google Translate url
# Send encoded text and language to google translate api
response=$(curl --tr-encoding -sA "${ua}" "${url}")
# Print only first translation from JSON
translated=`echo ${response} | sed 's/","/\n/g' | sed -E 's/\[|\]|"//g' | head -1`
echo $translated
translated=$(echo "${response}" | sed 's/","/\n/g' | sed -E 's/\[|\]|"//g' | head -1)
echo "$translated"

0 comments on commit 08d11e0

Please sign in to comment.