diff --git a/app/build.gradle b/app/build.gradle index b706cf5e6..f7a919a33 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -43,6 +43,7 @@ dependencies { implementation 'org.jsoup:jsoup:1.10.3' implementation 'de.hdodenhof:circleimageview:2.2.0' implementation 'com.github.stom79:country-picker-android:1.2.0' + implementation 'com.github.stom79:mytransl:1.1' safetynetImplementation 'com.google.android.gms:play-services-safetynet:11.6.0' safetynetImplementation 'io.github.kobakei:ratethisapp:1.2.0' } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index 662a376e2..3d08ce374 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -84,6 +84,9 @@ import android.widget.Toast; import com.github.stom79.localepicker.CountryPicker; import com.github.stom79.localepicker.CountryPickerListener; +import com.github.stom79.mytransl.MyTransL; +import com.github.stom79.mytransl.client.HttpsConnectionException; +import com.github.stom79.mytransl.translate.Translate; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; @@ -127,7 +130,6 @@ import fr.gouv.etalab.mastodon.drawers.EmojisSearchAdapter; import fr.gouv.etalab.mastodon.interfaces.OnDownloadInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveEmojiInterface; import fr.gouv.etalab.mastodon.sqlite.CustomEmojiDAO; -import fr.gouv.etalab.mastodon.translation.Translate; import fr.gouv.etalab.mastodon.client.Entities.Version; import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader; import fr.gouv.etalab.mastodon.drawers.AccountsReplyAdapter; @@ -140,7 +142,6 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountsReplyInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAttachmentInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearcAccountshInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearchInterface; -import fr.gouv.etalab.mastodon.interfaces.OnTranslatedInterface; import fr.gouv.etalab.mastodon.jobs.ScheduledTootsSyncJob; import fr.gouv.etalab.mastodon.sqlite.AccountDAO; import fr.gouv.etalab.mastodon.sqlite.Sqlite; @@ -156,7 +157,7 @@ import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor; * Toot activity class */ -public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAccountshInterface, OnRetrieveAttachmentInterface, OnPostStatusActionInterface, OnRetrieveSearchInterface, OnRetrieveAccountsReplyInterface, OnTranslatedInterface, OnRetrieveEmojiInterface, OnDownloadInterface { +public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAccountshInterface, OnRetrieveAttachmentInterface, OnPostStatusActionInterface, OnRetrieveSearchInterface, OnRetrieveAccountsReplyInterface, OnRetrieveEmojiInterface, OnDownloadInterface { private String visibility; @@ -815,8 +816,83 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc startActivity(browserIntent); } }); - new Translate(getApplicationContext(), Helper.targetField.CW, locale, TootActivity.this).privacy(toot_cw_content.getText().toString()); - new Translate(getApplicationContext(), Helper.targetField.STATUS, locale, TootActivity.this).privacy(toot_content.getText().toString()); + MyTransL myTransL = MyTransL.getInstance(MyTransL.translatorEngine.YANDEX); + myTransL.setYandexAPIKey(Helper.YANDEX_KEY); + myTransL.setObfuscation(true); + myTransL.setTimeout(60); + myTransL.translate(toot_cw_content.getText().toString(), myTransL.getLocale(), new com.github.stom79.mytransl.client.Results() { + @Override + public void onSuccess(Translate translate) { + try { + if( translate.getTranslatedContent() == null) + return; + if( popup_trans != null ) { + ProgressBar trans_progress_cw = popup_trans.findViewById(R.id.trans_progress_cw); + ProgressBar trans_progress_toot = popup_trans.findViewById(R.id.trans_progress_toot); + if( trans_progress_cw != null) + trans_progress_cw.setVisibility(View.GONE); + LinearLayout trans_container = popup_trans.findViewById(R.id.trans_container); + if( trans_container != null ){ + TextView cw_trans = popup_trans.findViewById(R.id.cw_trans); + if( cw_trans != null) { + cw_trans.setVisibility(View.VISIBLE); + cw_trans.setText(translate.getTranslatedContent()); + } + }else { + Toast.makeText(getApplicationContext(), R.string.toast_error_translate, Toast.LENGTH_LONG).show(); + } + if(trans_progress_cw != null && trans_progress_toot != null && trans_progress_cw.getVisibility() == View.GONE && trans_progress_toot.getVisibility() == View.GONE ) + if( dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE) != null) + dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE).setEnabled(true); + } + } catch (IllegalArgumentException e) { + e.printStackTrace(); + Toast.makeText(getApplicationContext(), R.string.toast_error_translate, Toast.LENGTH_LONG).show(); + } + + } + + @Override + public void onFail(HttpsConnectionException e) { + + } + }); + myTransL.translate(toot_content.getText().toString(), myTransL.getLocale(), new com.github.stom79.mytransl.client.Results() { + @Override + public void onSuccess(Translate translate) { + try { + if( translate.getTranslatedContent() == null) + return; + if( popup_trans != null ) { + ProgressBar trans_progress_cw = popup_trans.findViewById(R.id.trans_progress_cw); + ProgressBar trans_progress_toot = popup_trans.findViewById(R.id.trans_progress_toot); + if( trans_progress_toot != null) + trans_progress_toot.setVisibility(View.GONE); + LinearLayout trans_container = popup_trans.findViewById(R.id.trans_container); + if( trans_container != null ){ + TextView toot_trans = popup_trans.findViewById(R.id.toot_trans); + if(toot_trans != null){ + toot_trans.setVisibility(View.VISIBLE); + toot_trans.setText(translate.getTranslatedContent()); + } + }else { + Toast.makeText(getApplicationContext(), R.string.toast_error_translate, Toast.LENGTH_LONG).show(); + } + if(trans_progress_cw != null && trans_progress_toot != null && trans_progress_cw.getVisibility() == View.GONE && trans_progress_toot.getVisibility() == View.GONE ) + if( dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE) != null) + dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE).setEnabled(true); + } + } catch (IllegalArgumentException e) { + e.printStackTrace(); + Toast.makeText(getApplicationContext(), R.string.toast_error_translate, Toast.LENGTH_LONG).show(); + } + } + + @Override + public void onFail(HttpsConnectionException e) { + + } + }); transAlert.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); @@ -1902,50 +1978,7 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc } } - @Override - public void onTranslatedTextview(Translate translate, Status status, String translatedResult, Boolean error) { - } - - @Override - public void onTranslated(Translate translate, Helper.targetField targetField, String translatedResult, Boolean error) { - try { - String aJsonString; - if( translatedResult != null && translatedResult.length() > 0) - aJsonString = translate.replace(translatedResult); - else - aJsonString = ""; - if( popup_trans != null ) { - ProgressBar trans_progress_cw = popup_trans.findViewById(R.id.trans_progress_cw); - ProgressBar trans_progress_toot = popup_trans.findViewById(R.id.trans_progress_toot); - if( targetField == Helper.targetField.STATUS && trans_progress_toot != null) - trans_progress_toot.setVisibility(View.GONE); - if( targetField == Helper.targetField.CW && trans_progress_cw != null) - trans_progress_cw.setVisibility(View.GONE); - LinearLayout trans_container = popup_trans.findViewById(R.id.trans_container); - if( trans_container != null && aJsonString != null){ - TextView toot_trans = popup_trans.findViewById(R.id.toot_trans); - TextView cw_trans = popup_trans.findViewById(R.id.cw_trans); - if( targetField == Helper.targetField.CW && cw_trans != null) { - cw_trans.setVisibility(View.VISIBLE); - cw_trans.setText(aJsonString); - }else if(targetField == Helper.targetField.STATUS && toot_trans != null){ - toot_trans.setVisibility(View.VISIBLE); - toot_trans.setText(aJsonString); - } - }else { - Toast.makeText(getApplicationContext(), R.string.toast_error_translate, Toast.LENGTH_LONG).show(); - } - if(trans_progress_cw != null && trans_progress_toot != null && trans_progress_cw.getVisibility() == View.GONE && trans_progress_toot.getVisibility() == View.GONE ) - if( dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE) != null) - dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE).setEnabled(true); - } - } catch (IllegalArgumentException e) { - e.printStackTrace(); - Toast.makeText(getApplicationContext(), R.string.toast_error_translate, Toast.LENGTH_LONG).show(); - } - - } } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/TranslateAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/TranslateAsyncTask.java deleted file mode 100644 index 12b0b2f77..000000000 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/TranslateAsyncTask.java +++ /dev/null @@ -1,95 +0,0 @@ -/* Copyright 2017 Thomas Schneider - * - * This file is a part of Mastalab - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 3 of the - * License, or (at your option) any later version. - * - * Mastalab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Mastalab; if not, - * see . */ -package fr.gouv.etalab.mastodon.asynctasks; - -import android.os.AsyncTask; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import fr.gouv.etalab.mastodon.client.HttpsConnection; -import fr.gouv.etalab.mastodon.helper.Helper; -import fr.gouv.etalab.mastodon.interfaces.OnTranslatedInterface; -import fr.gouv.etalab.mastodon.translation.Translate; - - -/** - * Created by Thomas on 29/04/2017. - * Makes actions for post calls - */ - -public class TranslateAsyncTask extends AsyncTask { - - private OnTranslatedInterface listener; - private static final String BASE_URL = "https://translate.yandex.net/api/v1.5/tr.json/translate?"; - private static final String YANDEX_KEY = "trnsl.1.1.20170703T074828Z.a95168c920f61b17.699437a40bbfbddc4cd57f345a75c83f0f30c420"; - private String text, toLanguage; - private Translate translate; - private Helper.targetField target; - - public enum typeInter{ - TRANSLATED, - TRANSLATEDTEXTVIEW - } - private typeInter type; - private String str_response; - private fr.gouv.etalab.mastodon.client.Entities.Status status; - - public TranslateAsyncTask(final Translate translate, Helper.targetField target, fr.gouv.etalab.mastodon.client.Entities.Status status, String text, String toLanguage, typeInter type, OnTranslatedInterface onTranslatedInterface){ - this.listener = onTranslatedInterface; - this.type = type; - this.text = text; - this.toLanguage = toLanguage; - this.translate = translate; - this.target = target; - this.status = status; - } - - @Override - protected Void doInBackground(Void... params) { - try { - str_response = new HttpsConnection().get(getAbsoluteUrl(text, toLanguage), 30, null, null ); - } catch (Exception e) { - if( type == typeInter.TRANSLATED) - listener.onTranslatedTextview(translate, status, null, true); - else if( type == typeInter.TRANSLATEDTEXTVIEW) - listener.onTranslated(translate, target, "", false); - - } - return null; - } - - @Override - protected void onPostExecute(Void result) { - if( type == typeInter.TRANSLATED) - listener.onTranslated(translate, target, str_response, false); - else if( type == typeInter.TRANSLATEDTEXTVIEW) - listener.onTranslatedTextview(translate, status, str_response, false); - } - - - private static String getAbsoluteUrl(String content, String toLanguage) { - String key = "key=" + YANDEX_KEY + "&"; - toLanguage = toLanguage.replace("null",""); - String lang = "lang=" + toLanguage + "&"; - String text; - try { - text = "text=" + URLEncoder.encode(content, "utf-8") + "&"; - } catch (UnsupportedEncodingException e) { - text = "text=" + content + "&"; - e.printStackTrace(); - } - String format = "format=html&"; - return BASE_URL + key + lang +format + text ; - } -} diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java index 68b6c4352..58dd04bc9 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java @@ -56,6 +56,10 @@ import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; +import com.github.stom79.mytransl.MyTransL; +import com.github.stom79.mytransl.client.HttpsConnectionException; +import com.github.stom79.mytransl.client.Results; +import com.github.stom79.mytransl.translate.Translate; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; @@ -88,7 +92,6 @@ import fr.gouv.etalab.mastodon.client.Entities.Emojis; import fr.gouv.etalab.mastodon.client.Entities.Error; import fr.gouv.etalab.mastodon.client.Entities.Status; import fr.gouv.etalab.mastodon.client.HttpsConnection; -import fr.gouv.etalab.mastodon.translation.Translate; import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader; import fr.gouv.etalab.mastodon.helper.CrossActions; import fr.gouv.etalab.mastodon.helper.Helper; @@ -96,7 +99,6 @@ import fr.gouv.etalab.mastodon.interfaces.OnPostActionInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveEmojiInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveFeedsInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveRepliesInterface; -import fr.gouv.etalab.mastodon.interfaces.OnTranslatedInterface; import static fr.gouv.etalab.mastodon.activities.MainActivity.currentLocale; import static fr.gouv.etalab.mastodon.helper.Helper.THEME_DARK; @@ -107,7 +109,7 @@ import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor; * Created by Thomas on 24/04/2017. * Adapter for Status */ -public class StatusListAdapter extends RecyclerView.Adapter implements OnPostActionInterface, OnTranslatedInterface, OnRetrieveFeedsInterface, OnRetrieveEmojiInterface, OnRetrieveRepliesInterface { +public class StatusListAdapter extends RecyclerView.Adapter implements OnPostActionInterface, OnRetrieveFeedsInterface, OnRetrieveEmojiInterface, OnRetrieveRepliesInterface { private Context context; private List statuses; @@ -975,12 +977,30 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct return false; } }); - + final MyTransL myTransL = MyTransL.getInstance(MyTransL.translatorEngine.YANDEX); + myTransL.setObfuscation(true); + myTransL.setYandexAPIKey(Helper.YANDEX_KEY); holder.status_translate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if( !status.isTranslated() ){ - new Translate(context, status,StatusListAdapter.this).privacy(status.getContent()); + myTransL.translate(status.getContent(), myTransL.getLocale(), new Results() { + @Override + public void onSuccess(Translate translate) { + if( translate.getTranslatedContent() != null) { + status.setTranslated(true); + status.setTranslationShown(true); + status.setContent_translated(translate.getTranslatedContent()); + statusListAdapter.notifyDataSetChanged(); + }else { + Toast.makeText(context, R.string.toast_error_translate, Toast.LENGTH_LONG).show(); + } + } + @Override + public void onFail(HttpsConnectionException e) { + Toast.makeText(context, R.string.toast_error_translate, Toast.LENGTH_LONG).show(); + } + }); }else { status.setTranslationShown(!status.isTranslationShown()); statusListAdapter.notifyDataSetChanged(); @@ -1452,36 +1472,4 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct public void onRetrieveSearchEmoji(List emojis) { } - - @Override - public void onTranslatedTextview(Translate translate, Status status, String translatedResult, Boolean error) { - if( error){ - Toast.makeText(context, R.string.toast_error_translate, Toast.LENGTH_LONG).show(); - }else { - try { - String aJsonString = translate.replace(translatedResult); - if( aJsonString != null) { - status.setTranslated(true); - status.setTranslationShown(true); - status.setContent_translated(aJsonString); - statusListAdapter.notifyDataSetChanged(); - } - } catch (IllegalArgumentException e) { - e.printStackTrace(); - Toast.makeText(context, R.string.toast_error_translate, Toast.LENGTH_LONG).show(); - } - } - } - - @Override - public void onTranslated(Translate translate, Helper.targetField targetField, String content, Boolean error) { - } - - - - - - - - } \ No newline at end of file diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java index c55ff3be7..17a653b28 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java @@ -167,6 +167,7 @@ public class Helper { //Thekinrar's API: https://instances.social/api/doc/ public static final String THEKINRAR_SECRET_TOKEN = "jGj9gW3z9ptyIpB8CMGhAlTlslcemMV6AgoiImfw3vPP98birAJTHOWiu5ZWfCkLvcaLsFZw9e3Pb7TIwkbIyrj3z6S7r2oE6uy6EFHvls3YtapP8QKNZ980p9RfzTb4"; + public static final String YANDEX_KEY = "trnsl.1.1.20170703T074828Z.a95168c920f61b17.699437a40bbfbddc4cd57f345a75c83f0f30c420"; //Some definitions public static final String CLIENT_NAME = "client_name"; diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnTranslatedInterface.java b/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnTranslatedInterface.java deleted file mode 100644 index b8cecfa38..000000000 --- a/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnTranslatedInterface.java +++ /dev/null @@ -1,29 +0,0 @@ -/* Copyright 2017 Thomas Schneider - * - * This file is a part of Mastalab - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 3 of the - * License, or (at your option) any later version. - * - * Mastalab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Mastalab; if not, - * see . */ -package fr.gouv.etalab.mastodon.interfaces; - -import fr.gouv.etalab.mastodon.client.Entities.Status; -import fr.gouv.etalab.mastodon.helper.Helper; -import fr.gouv.etalab.mastodon.translation.Translate; - -/** - * Created by Thomas on 03/07/2017. - * Yandex client API Handler - */ -public interface OnTranslatedInterface { - void onTranslatedTextview(Translate translate, Status status, String translatedResult, Boolean error); - void onTranslated(Translate translate, Helper.targetField targetField, String content, Boolean error); - -} diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/translation/Translate.java b/app/src/main/java/fr/gouv/etalab/mastodon/translation/Translate.java deleted file mode 100644 index 0bfe8d1c5..000000000 --- a/app/src/main/java/fr/gouv/etalab/mastodon/translation/Translate.java +++ /dev/null @@ -1,262 +0,0 @@ -/* Copyright 2017 Thomas Schneider - * - * This file is a part of Mastalab - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 3 of the - * License, or (at your option) any later version. - * - * Mastalab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Mastalab; if not, - * see . */ -package fr.gouv.etalab.mastodon.translation; - -import android.content.*; -import android.os.Build; -import android.text.Html; -import android.text.SpannableString; -import android.util.Patterns; -import android.widget.Toast; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.regex.Matcher; - -import fr.gouv.etalab.mastodon.R; -import fr.gouv.etalab.mastodon.client.Entities.Status; -import fr.gouv.etalab.mastodon.helper.Helper; -import fr.gouv.etalab.mastodon.interfaces.OnTranslatedInterface; - -import static fr.gouv.etalab.mastodon.activities.BaseMainActivity.currentLocale; - -/** - * Created by Thomas on 31/10/2017. - * Manages translations - */ - -public class Translate { - - private HashMap urlConversion; - private HashMap tagConversion; - private HashMap mentionConversionOtherInstance; - private HashMap mentionConversion; - private HashMap blacklistConversion; - - - private android.content.Context context; - private OnTranslatedInterface listener; - private Status status; - private String targetedLanguage; - private Helper.targetField targetField; - - public Translate(android.content.Context context, Status status, OnTranslatedInterface onTranslatedInterface){ - this.context = context; - this.listener = onTranslatedInterface; - this.status = status; - targetedLanguage = currentLocale; - this.targetField = Helper.targetField.SIMPLE; - } - - public Translate(android.content.Context context, Helper.targetField targetField, String targetedLanguage, OnTranslatedInterface onTranslatedInterface){ - this.context = context; - this.listener = onTranslatedInterface; - this.targetedLanguage = targetedLanguage; - this.targetField = targetField; - } - - - /*** - * Removes sensitive elements from translation, ie: links, tags, mentions, and blacklisted words starting with % - * @param content String - */ - public void privacy (String content){ - this.tagConversion = new HashMap<>(); - this.mentionConversion = new HashMap<>(); - this.urlConversion = new HashMap<>(); - this.blacklistConversion = new HashMap<>(); - this.mentionConversionOtherInstance = new HashMap<>(); - try { - SpannableString spannableString; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - spannableString = new SpannableString(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY)); - else - //noinspection deprecation - spannableString = new SpannableString(Html.fromHtml(content)); - String text = spannableString.toString(); - Matcher matcher; - - int i = 0; - //Same for mentions for other instances with __o0__, __o1__, etc. - matcher = Helper.mentionOtherInstancePattern.matcher(text); - while (matcher.find()){ - String key = "__o" + String.valueOf(i) + "__"; - String value = matcher.group(0); - this.mentionConversionOtherInstance.put(key, value); - if( value != null) { - this.mentionConversionOtherInstance.put(key, value); - text = text.replace(value, key); - } - i++; - } - i = 0; - //Same for mentions with __m0__, __m1__, etc. - matcher = Helper.mentionPattern.matcher(text); - while (matcher.find()){ - String key = "__m" + String.valueOf(i) + "__"; - String value = matcher.group(0); - this.mentionConversion.put(key, value); - if( value != null) { - this.mentionConversion.put(key, value); - text = text.replace(value, key); - } - i++; - } - //Extracts urls - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) - matcher = Patterns.WEB_URL.matcher(spannableString.toString()); - else - matcher = Helper.urlPattern.matcher(spannableString.toString()); - i = 0; - //replaces them by a kind of variable which shouldn't be translated ie: __u0__, __u1__, etc. - while (matcher.find()){ - String key = "__u" + String.valueOf(i) + "__"; - String value = matcher.group(0); - int end = matcher.end(); - if (spannableString.length() > end && spannableString.charAt(end) == '/') { - text = spannableString.toString().substring(0, end). - concat(spannableString.toString().substring(end+1, spannableString.length())); - } - if( value != null) { - this.urlConversion.put(key, value); - text = text.replace(value, key); - } - i++; - } - i = 0; - //Same for tags with __t0__, __t1__, etc. - matcher = Helper.hashtagPattern.matcher(text); - while (matcher.find()){ - String key = "__t" + String.valueOf(i) + "__"; - String value = matcher.group(0); - this.tagConversion.put(key, value); - if( value != null) { - this.tagConversion.put(key, value); - text = text.replace(value, key); - } - i++; - } - i = 0; - //Same for blacklisted words (ie: starting with %) with __b0__, __b1__, etc. - matcher = Helper.blacklistPattern.matcher(text); - while (matcher.find()){ - String key = "__b" + String.valueOf(i) + "__"; - String value = matcher.group(0); - this.blacklistConversion.put(key, value); - if( value != null) { - this.blacklistConversion.put(key, value); - text = text.replace(value, key); - } - i++; - } - if( status == null) { - new YandexQuery(this.listener).getYandexTranslation(this,targetField, content, this.targetedLanguage); - }else { - new YandexQuery(this.listener).getYandexTextview(this, this.status, content, this.targetedLanguage); - } - } catch (JSONException e) { - Toast.makeText(context, R.string.toast_error_translate, Toast.LENGTH_LONG).show(); - } - } - - /** - * Replaces sensitive elements once translated by their original values - * @param translatedResult String - * @return String "decrypted content" - */ - public String replace(String translatedResult){ - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); - int translator = sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX); - String aJsonString = null; - try { - aJsonString = yandexTranslateToText(translatedResult); - if( aJsonString == null) - return null; - - if( this.urlConversion != null) { - Iterator itU = this.urlConversion.entrySet().iterator(); - while (itU.hasNext()) { - Map.Entry pair = (Map.Entry) itU.next(); - aJsonString = aJsonString.replace(pair.getKey().toString(), pair.getValue().toString()); - itU.remove(); - } - } - if( this.tagConversion != null) { - Iterator itT = this.tagConversion.entrySet().iterator(); - while (itT.hasNext()) { - Map.Entry pair = (Map.Entry) itT.next(); - aJsonString = aJsonString.replace(pair.getKey().toString(), pair.getValue().toString()); - itT.remove(); - } - } - if( this.mentionConversionOtherInstance != null) { - Iterator itM = this.mentionConversionOtherInstance.entrySet().iterator(); - while (itM.hasNext()) { - Map.Entry pair = (Map.Entry) itM.next(); - aJsonString = aJsonString.replace(pair.getKey().toString(), pair.getValue().toString()); - itM.remove(); - } - } - if( this.mentionConversion != null) { - Iterator itM = this.mentionConversion.entrySet().iterator(); - while (itM.hasNext()) { - Map.Entry pair = (Map.Entry) itM.next(); - aJsonString = aJsonString.replace(pair.getKey().toString(), pair.getValue().toString()); - itM.remove(); - } - } - if( this.blacklistConversion != null) { - Iterator itB = this.blacklistConversion.entrySet().iterator(); - while (itB.hasNext()) { - Map.Entry pair = (Map.Entry) itB.next(); - aJsonString = aJsonString.replace(pair.getKey().toString(), pair.getValue().toString().substring(1)); - itB.remove(); - } - } - } catch (JSONException | UnsupportedEncodingException | IllegalArgumentException e) { - e.printStackTrace(); - Toast.makeText(context, R.string.toast_error_translate, Toast.LENGTH_LONG).show(); - } - return aJsonString; - } - - private String yandexTranslateToText(String text) throws JSONException, UnsupportedEncodingException{ - String aJsonString = null; - if( text !=null) { - JSONObject translationJson = new JSONObject(text); - JSONArray aJsonArray = translationJson.getJSONArray("text"); - aJsonString = aJsonArray.get(0).toString(); - - /* The one instance where I've seen this happen, - the special tag was originally a hashtag ("__t1__"), - that Yandex decided to change to a "__q1 - __". - */ - aJsonString = aJsonString.replaceAll("__q(\\d+) - __", "__t$1__"); - - // Noticed this in the very same toot - aJsonString = aJsonString.replace("&", "&"); - - aJsonString = URLDecoder.decode(aJsonString, "UTF-8"); - } - return aJsonString; - } -} diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/translation/YandexQuery.java b/app/src/main/java/fr/gouv/etalab/mastodon/translation/YandexQuery.java deleted file mode 100644 index 20962ec7a..000000000 --- a/app/src/main/java/fr/gouv/etalab/mastodon/translation/YandexQuery.java +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright 2017 Thomas Schneider - * - * This file is a part of Mastalab - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 3 of the - * License, or (at your option) any later version. - * - * Mastalab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Mastalab; if not, - * see . */ -package fr.gouv.etalab.mastodon.translation; - -import android.os.AsyncTask; -import org.json.JSONException; -import fr.gouv.etalab.mastodon.asynctasks.TranslateAsyncTask; -import fr.gouv.etalab.mastodon.client.Entities.Status; -import fr.gouv.etalab.mastodon.helper.Helper; -import fr.gouv.etalab.mastodon.interfaces.OnTranslatedInterface; - -/** - * Created by Thomas on 03/07/2017. - * Yandex client API - */ -class YandexQuery { - - private OnTranslatedInterface listener; - YandexQuery(OnTranslatedInterface listenner) { - this.listener = listenner; - } - - - void getYandexTextview(final Translate translate, final Status status, final String text, final String toLanguage) throws JSONException { - if( text != null && text.length() > 0) { - new TranslateAsyncTask(translate, null, status, text, toLanguage, TranslateAsyncTask.typeInter.TRANSLATEDTEXTVIEW, listener).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else { - listener.onTranslatedTextview(translate, status, "", false); - } - } - void getYandexTranslation(final Translate translate, final Helper.targetField target, final String content, final String toLanguage) throws JSONException { - if( content != null && content.length() > 0) { - new TranslateAsyncTask(translate, target, null, content, toLanguage, TranslateAsyncTask.typeInter.TRANSLATEDTEXTVIEW, listener).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ - listener.onTranslated(translate, target, "", false); - } - } -}