fedilab-Android-App/app/src/main/java/app/fedilab/android/helper/Helper.java

4981 lines
224 KiB
Java
Raw Normal View History

2017-05-05 16:36:04 +02:00
/* Copyright 2017 Thomas Schneider
*
2019-05-18 11:10:30 +02:00
* This file is a part of Fedilab
2017-05-05 16:36:04 +02:00
*
* 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.
*
2019-05-18 11:10:30 +02:00
* Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
2017-05-05 16:36:04 +02:00
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
2019-05-18 11:10:30 +02:00
* You should have received a copy of the GNU General Public License along with Fedilab; if not,
2017-05-05 16:36:04 +02:00
* see <http://www.gnu.org/licenses>. */
2019-05-18 11:10:30 +02:00
package app.fedilab.android.helper;
2017-05-05 16:36:04 +02:00
2017-11-25 11:01:34 +01:00
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
2018-11-04 10:01:16 +01:00
import android.app.FragmentManager;
2019-09-26 18:58:43 +02:00
import android.app.Notification;
2017-10-22 11:55:49 +02:00
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
2019-09-21 16:29:33 +02:00
import android.content.ContentUris;
2017-05-05 16:36:04 +02:00
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
2017-05-05 16:36:04 +02:00
import android.content.SharedPreferences;
2019-09-22 18:35:16 +02:00
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
2017-05-26 17:20:36 +02:00
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
2017-07-01 15:24:28 +02:00
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
2017-07-01 15:24:28 +02:00
import android.graphics.drawable.Drawable;
import android.media.AudioAttributes;
2019-10-20 12:02:46 +02:00
import android.media.MediaMetadataRetriever;
import android.media.RingtoneManager;
2017-05-05 16:36:04 +02:00
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
2017-05-05 16:36:04 +02:00
import android.os.Build;
2017-06-11 11:58:46 +02:00
import android.os.Bundle;
import android.os.CountDownTimer;
2017-05-05 16:36:04 +02:00
import android.os.Environment;
2019-09-21 16:29:33 +02:00
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
2019-09-06 17:55:14 +02:00
2019-06-11 19:38:26 +02:00
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
2019-08-22 19:57:51 +02:00
import androidx.appcompat.widget.SwitchCompat;
2019-06-11 19:38:26 +02:00
import androidx.browser.customtabs.CustomTabsIntent;
2019-08-02 14:44:59 +02:00
2019-06-11 19:38:26 +02:00
import com.google.android.material.navigation.NavigationView;
2019-09-06 17:55:14 +02:00
2019-06-11 19:38:26 +02:00
import androidx.exifinterface.media.ExifInterface;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.menu.ActionMenuItemView;
import androidx.appcompat.widget.ActionMenuView;
import androidx.appcompat.widget.Toolbar;
2019-09-06 17:55:14 +02:00
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
2019-02-23 14:39:51 +01:00
import android.text.TextUtils;
import android.text.style.ClickableSpan;
2018-11-14 18:12:59 +01:00
import android.text.style.URLSpan;
2017-05-26 17:20:36 +02:00
import android.util.DisplayMetrics;
2019-02-06 18:03:47 +01:00
import android.util.Log;
2017-07-31 19:29:14 +02:00
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
2017-07-01 15:24:28 +02:00
import android.view.SubMenu;
import android.view.View;
2018-11-03 12:06:44 +01:00
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
2017-05-05 16:36:04 +02:00
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
2017-11-02 14:06:59 +01:00
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
2019-08-22 19:57:51 +02:00
import android.widget.Spinner;
import android.widget.TextView;
2017-05-05 16:36:04 +02:00
import android.widget.Toast;
2017-12-02 11:02:25 +01:00
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
2017-12-25 12:06:35 +01:00
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
2017-12-02 11:02:25 +01:00
import com.bumptech.glide.request.RequestListener;
2017-12-25 12:06:35 +01:00
import com.bumptech.glide.request.RequestOptions;
2017-12-02 11:02:25 +01:00
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
2019-06-11 19:38:26 +02:00
import com.google.android.material.tabs.TabLayout;
2018-02-15 07:55:24 +01:00
import com.google.common.reflect.TypeToken;
2017-12-15 18:03:06 +01:00
import com.google.gson.Gson;
2019-09-21 10:45:17 +02:00
import com.iceteck.silicompressorr.SiliCompressor;
2019-01-08 18:11:40 +01:00
import com.jaredrummler.materialspinner.MaterialSpinner;
2018-11-04 16:00:44 +01:00
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu;
import com.oguzdev.circularfloatingactionmenu.library.SubActionButton;
import com.tonyodev.fetch2.Download;
import com.tonyodev.fetch2.Error;
import com.tonyodev.fetch2.Fetch;
import com.tonyodev.fetch2.FetchConfiguration;
import com.tonyodev.fetch2.FetchListener;
import com.tonyodev.fetch2.NetworkType;
import com.tonyodev.fetch2.Priority;
import com.tonyodev.fetch2.Request;
import com.tonyodev.fetch2core.DownloadBlock;
2017-05-20 19:40:46 +02:00
2019-06-12 08:05:36 +02:00
import net.gotev.uploadservice.UploadService;
2019-06-12 10:04:52 +02:00
import net.gotev.uploadservice.okhttp.OkHttpStack;
2019-06-12 08:05:36 +02:00
2017-12-14 07:26:37 +01:00
import org.conscrypt.Conscrypt;
import org.jetbrains.annotations.NotNull;
2017-12-14 07:26:37 +01:00
import java.io.BufferedReader;
2018-04-22 13:16:52 +02:00
import java.io.ByteArrayInputStream;
2017-07-17 15:22:59 +02:00
import java.io.ByteArrayOutputStream;
2017-05-05 16:36:04 +02:00
import java.io.File;
import java.io.FileInputStream;
2018-04-22 13:16:52 +02:00
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
2019-01-18 16:11:48 +01:00
import java.lang.ref.WeakReference;
2018-02-15 07:55:24 +01:00
import java.lang.reflect.Type;
2019-10-20 11:25:28 +02:00
import java.net.Authenticator;
2017-05-05 16:36:04 +02:00
import java.net.InetAddress;
2019-10-20 11:25:28 +02:00
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
2019-09-21 10:45:17 +02:00
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
2017-12-14 07:26:37 +01:00
import java.security.Security;
import java.text.DateFormat;
2017-05-05 16:36:04 +02:00
import java.text.ParseException;
import java.text.SimpleDateFormat;
2018-02-15 07:55:24 +01:00
import java.util.ArrayList;
2017-07-10 18:43:36 +02:00
import java.util.Calendar;
2019-07-24 17:48:24 +02:00
import java.util.Collections;
import java.util.Comparator;
2017-05-05 16:36:04 +02:00
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
2019-07-24 17:48:24 +02:00
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
2017-05-05 16:36:04 +02:00
import java.util.Locale;
import java.util.Map;
2019-04-21 09:12:10 +02:00
import java.util.Objects;
import java.util.Random;
2017-05-05 16:36:04 +02:00
import java.util.TimeZone;
2019-06-12 10:04:52 +02:00
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
2017-05-05 16:36:04 +02:00
2019-06-12 10:04:52 +02:00
import javax.net.ssl.SSLContext;
import app.fedilab.android.BuildConfig;
import app.fedilab.android.activities.MutedInstanceActivity;
import app.fedilab.android.asynctasks.PostActionAsyncTask;
2019-05-18 11:10:30 +02:00
import app.fedilab.android.client.API;
import app.fedilab.android.client.APIResponse;
2019-05-18 11:10:30 +02:00
import app.fedilab.android.client.Entities.Account;
import app.fedilab.android.client.Entities.Application;
import app.fedilab.android.client.Entities.Attachment;
import app.fedilab.android.client.Entities.Card;
import app.fedilab.android.client.Entities.Emojis;
import app.fedilab.android.client.Entities.Filters;
2019-08-28 14:43:10 +02:00
import app.fedilab.android.client.Entities.MainMenuItem;
2019-05-18 11:10:30 +02:00
import app.fedilab.android.client.Entities.Mention;
import app.fedilab.android.client.Entities.RemoteInstance;
import app.fedilab.android.client.Entities.Status;
import app.fedilab.android.client.Entities.Tag;
import app.fedilab.android.client.Entities.TagTimeline;
2019-06-12 10:04:52 +02:00
import app.fedilab.android.client.Tls12SocketFactory;
2019-10-19 15:51:07 +02:00
import app.fedilab.android.services.LiveNotificationDelayedService;
import app.fedilab.android.services.LiveNotificationService;
2019-08-28 14:43:10 +02:00
import app.fedilab.android.sqlite.MainMenuDAO;
2019-07-22 12:27:46 +02:00
import app.fedilab.android.sqlite.StatusCacheDAO;
import app.fedilab.android.sqlite.TimelineCacheDAO;
2019-10-14 18:54:04 +02:00
import app.fedilab.android.webview.CustomWebview;
2018-11-25 10:45:16 +01:00
import es.dmoral.toasty.Toasty;
2019-05-18 11:10:30 +02:00
import app.fedilab.android.R;
import app.fedilab.android.activities.BaseMainActivity;
import app.fedilab.android.activities.HashTagActivity;
import app.fedilab.android.activities.LoginActivity;
import app.fedilab.android.activities.MainActivity;
import app.fedilab.android.activities.MainApplication;
import app.fedilab.android.activities.ShowAccountActivity;
import app.fedilab.android.activities.WebviewActivity;
import app.fedilab.android.asynctasks.RemoveAccountAsyncTask;
import app.fedilab.android.asynctasks.RetrieveFeedsAsyncTask;
import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask;
import app.fedilab.android.sqlite.AccountDAO;
import app.fedilab.android.sqlite.Sqlite;
2019-06-12 08:05:36 +02:00
import info.guardianproject.netcipher.client.StrongBuilder;
import info.guardianproject.netcipher.client.StrongOkHttpClientBuilder;
2019-06-12 10:04:52 +02:00
import okhttp3.ConnectionSpec;
2019-06-12 08:05:36 +02:00
import okhttp3.OkHttpClient;
2019-06-12 10:04:52 +02:00
import okhttp3.TlsVersion;
2017-05-05 16:36:04 +02:00
import static android.content.Context.DOWNLOAD_SERVICE;
2019-08-18 17:17:47 +02:00
import static app.fedilab.android.activities.BaseMainActivity.mutedAccount;
2019-08-18 18:20:48 +02:00
import static app.fedilab.android.activities.BaseMainActivity.regex_home;
import static app.fedilab.android.activities.BaseMainActivity.regex_local;
import static app.fedilab.android.activities.BaseMainActivity.regex_public;
2019-08-31 15:14:20 +02:00
import static app.fedilab.android.helper.Helper.NotifType.MENTION;
2019-08-23 09:29:30 +02:00
import static app.fedilab.android.sqlite.StatusCacheDAO.ARCHIVE_CACHE;
import static app.fedilab.android.sqlite.StatusCacheDAO.BOOKMARK_CACHE;
2019-02-23 14:39:51 +01:00
import static com.koushikdutta.async.util.StreamUtility.copyStream;
2019-05-18 11:10:30 +02:00
import static app.fedilab.android.activities.BaseMainActivity.filters;
2017-05-05 16:36:04 +02:00
/**
* Created by Thomas on 23/04/2017.
* - Constants are defined here.
* - Reusable methods are implemented in this section
*/
2018-04-22 18:02:00 +02:00
@SuppressWarnings("WeakerAccess")
2017-05-05 16:36:04 +02:00
public class Helper {
2019-09-06 17:55:14 +02:00
public static final String TAG = "mastodon_etalab";
2019-02-06 14:29:55 +01:00
public static final String CLIENT_NAME_VALUE = "Fedilab";
2017-05-05 16:36:04 +02:00
public static final String OAUTH_SCOPES = "read write follow";
2019-06-19 11:04:44 +02:00
public static final String OAUTH_SCOPES_ADMIN = "read write follow admin:read admin:write admin";
2019-04-16 17:07:51 +02:00
public static final String OAUTH_SCOPES_PIXELFED = "write follow";
2019-01-02 19:39:40 +01:00
public static final String OAUTH_SCOPES_PEERTUBE = "user";
2017-05-05 16:36:04 +02:00
public static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
2019-01-02 19:39:40 +01:00
2017-05-05 16:36:04 +02:00
public static final String PREF_KEY_ID = "userID";
public static final String PREF_IS_MODERATOR = "is_moderator";
public static final String PREF_IS_ADMINISTRATOR = "is_administrator";
public static final String PREF_INSTANCE = "instance";
public static final String REDIRECT_CONTENT = "urn:ietf:wg:oauth:2.0:oob";
2017-05-26 17:20:36 +02:00
public static final String REDIRECT_CONTENT_WEB = "mastalab://backtomastalab";
2017-05-05 16:36:04 +02:00
public static final int EXTERNAL_STORAGE_REQUEST_CODE = 84;
public static final int REQ_CODE_SPEECH_INPUT = 132;
2017-05-05 16:36:04 +02:00
//Thekinrar's API: https://instances.social/api/doc/
public static final String THEKINRAR_SECRET_TOKEN = "jGj9gW3z9ptyIpB8CMGhAlTlslcemMV6AgoiImfw3vPP98birAJTHOWiu5ZWfCkLvcaLsFZw9e3Pb7TIwkbIyrj3z6S7r2oE6uy6EFHvls3YtapP8QKNZ980p9RfzTb4";
2017-11-29 15:06:30 +01:00
public static final String YANDEX_KEY = "trnsl.1.1.20170703T074828Z.a95168c920f61b17.699437a40bbfbddc4cd57f345a75c83f0f30c420";
2017-05-05 16:36:04 +02:00
//Some definitions
public static final String CLIENT_NAME = "client_name";
public static final String APP_PREFS = "app_prefs";
public static final String ID = "id";
public static final String CLIENT_ID = "client_id";
public static final String CLIENT_SECRET = "client_secret";
public static final String REDIRECT_URI = "redirect_uri";
public static final String REDIRECT_URIS = "redirect_uris";
public static final String RESPONSE_TYPE = "response_type";
public static final String SCOPE = "scope";
public static final String SCOPES = "scopes";
public static final String WEBSITE = "website";
2019-02-06 14:29:55 +01:00
public static final String WEBSITE_VALUE = "https://fedilab.app";
public static final String SHOW_BATTERY_SAVER_MESSAGE = "show_battery_saver_message";
2017-05-05 16:36:04 +02:00
public static final String LAST_NOTIFICATION_MAX_ID = "last_notification_max_id";
public static final String LAST_HOMETIMELINE_MAX_ID = "last_hometimeline_max_id";
2017-12-08 19:36:26 +01:00
public static final String BOOKMARK_ID = "bookmark_id";
2019-01-22 08:51:36 +01:00
public static final String BOOKMARK_DATE = "bookmark_date";
2019-05-09 19:03:02 +02:00
public static final String HOME_LAST_READ = "home_last_read";
2018-12-19 15:12:46 +01:00
public static final String LAST_READ_TOOT_ID = "last_read_toot_id";
2019-01-22 08:51:36 +01:00
public static final String LAST_READ_TOOT_DATE = "last_read_toot_date";
2017-12-08 19:36:26 +01:00
public static final String LAST_HOMETIMELINE_NOTIFICATION_MAX_ID = "last_hometimeline_notification_max_id";
2017-09-29 14:08:46 +02:00
public static final String SHOULD_CONTINUE_STREAMING = "should_continue_streaming";
2018-12-18 19:08:59 +01:00
public static final String SHOULD_CONTINUE_STREAMING_HOME = "should_continue_streaming_home";
2017-09-29 14:08:46 +02:00
public static final String SHOULD_CONTINUE_STREAMING_FEDERATED = "should_continue_streaming_federated";
2017-09-30 08:48:44 +02:00
public static final String SHOULD_CONTINUE_STREAMING_LOCAL = "should_continue_streaming_local";
public static final String SEARCH_KEYWORD = "search_keyword";
2018-09-01 15:59:16 +02:00
public static final String SEARCH_URL = "search_url";
public static final String CLIP_BOARD = "clipboard";
2018-08-20 19:00:20 +02:00
public static final String INSTANCE_NAME = "instance_name";
2018-09-10 19:21:42 +02:00
public static final String LAST_DATE_LIST_REFRESH = "last_date_list_refresh";
public static final String LAST_DATE_LIST_NAME_REFRESH = "last_date_list_name_refresh";
public static final String LAST_LIST = "last_list";
public static final String LAST_LIST_NAME = "last_list_name";
2018-09-19 10:13:28 +02:00
2017-05-05 16:36:04 +02:00
//Notifications
public static final int NOTIFICATION_INTENT = 1;
public static final int HOME_TIMELINE_INTENT = 2;
2018-12-16 15:11:58 +01:00
public static final int BACK_TO_SETTINGS = 3;
2017-07-26 18:31:26 +02:00
public static final int CHANGE_USER_INTENT = 4;
public static final int ADD_USER_INTENT = 5;
2018-02-17 15:42:09 +01:00
public static final int BACKUP_INTENT = 6;
public static final int SEARCH_TAG = 7;
2018-08-20 19:00:20 +02:00
public static final int SEARCH_INSTANCE = 8;
2018-09-01 15:59:16 +02:00
public static final int SEARCH_REMOTE = 9;
2019-01-12 17:36:24 +01:00
public static final int RELOAD_MYVIDEOS = 10;
public static final int REFRESH_TIMELINE = 11;
2019-08-25 17:21:34 +02:00
public static final int BACKUP_NOTIFICATION_INTENT = 12;
2019-08-28 14:43:10 +02:00
public static final int REDRAW_MENU = 13;
2017-05-05 16:36:04 +02:00
//Settings
2019-07-18 14:12:55 +02:00
public static final int TOOTS_PER_PAGE = 20;
public static final int ACCOUNTS_PER_PAGE = 20;
2019-07-13 15:05:46 +02:00
public static final int NOTIFICATIONS_PER_PAGE = 15;
2017-05-05 16:36:04 +02:00
public static final String SET_ATTACHMENT_ACTION = "set_attachment_action";
2019-08-31 16:41:29 +02:00
public static final String SET_TOOT_PER_PAGE = "set_toot_per_page";
2017-06-30 17:09:07 +02:00
public static final String SET_THEME = "set_theme";
2017-07-10 18:43:36 +02:00
public static final String SET_TIME_FROM = "set_time_from";
public static final String SET_TIME_TO = "set_time_to";
2017-07-15 14:59:09 +02:00
public static final String SET_AUTO_STORE = "set_auto_store";
public static final String SET_POPUP_PUSH = "set_popup_push_new";
public static final String SET_NSFW_TIMEOUT = "set_nsfw_timeout";
public static final String SET_MEDIA_URLS = "set_media_urls";
public static final String SET_TEXT_SIZE = "set_text_size";
public static final String SET_ICON_SIZE = "set_icon_size";
2017-08-25 15:53:04 +02:00
public static final String SET_TRANSLATOR = "set_translator";
public static final String SET_LED_COLOUR = "set_led_colour";
public static final String SET_SHOW_BOOSTS = "set_show_boost";
public static final String SET_SHOW_REPLIES = "set_show_replies";
2019-01-12 18:12:11 +01:00
public static final String SET_VIDEO_NSFW = "set_video_nsfw";
public static final String INSTANCE_VERSION = "instance_version";
2019-06-08 18:55:30 +02:00
public static final String NEWS_ACCOUNT_ID = "news_account_id";
public static final String SET_LIVE_NOTIFICATIONS = "set_live_notifications";
2019-09-11 16:02:56 +02:00
public static final String SET_DELAYED_NOTIFICATIONS = "set_delayed_notifications";
2017-12-10 08:33:26 +01:00
public static final String SET_DISABLE_GIF = "set_disable_gif";
2019-07-26 15:58:54 +02:00
public static final String SET_DISABLE_ANIMATED_EMOJI = "set_disable_animated_emoji";
public static final String SET_CAPITALIZE = "set_capitalize";
2019-07-20 17:44:44 +02:00
public static final String SET_WYSIWYG = "set_wysiwyg";
2019-09-25 15:44:52 +02:00
public static final String LOGO_LAUNCHER = "logo_launcher";
2019-09-20 18:32:10 +02:00
public static final String SET_PICTURE_COMPRESSED = "set_picture_compressed";
2019-09-21 10:45:17 +02:00
public static final String SET_VIDEO_COMPRESSED = "set_picture_compressed";
2019-05-13 18:15:45 +02:00
public static final String SET_FORWARD_TAGS_IN_REPLY = "set_forward_tags_in_reply";
public static final String SET_FULL_PREVIEW = "set_full_preview";
2018-05-12 09:41:47 +02:00
public static final String SET_COMPACT_MODE = "set_compact_mode";
2019-02-13 18:36:29 +01:00
public static final String SET_CONSOLE_MODE = "set_console_mode";
2018-05-12 11:11:17 +02:00
public static final String SET_SHARE_DETAILS = "set_share_details";
public static final String SET_CUSTOM_SHARING = "set_custom_sharing";
public static final String SET_CUSTOM_SHARING_URL = "set_custom_sharing_url";
2018-09-16 19:05:54 +02:00
public static final String SET_NOTIF_SOUND = "set_notif_sound";
2018-09-19 10:13:28 +02:00
public static final String SET_ENABLE_TIME_SLOT = "set_enable_time_slot";
2019-09-02 18:25:22 +02:00
public static final String SET_CLEAR_CACHE_EXIT = "set_clear_cache_exit";
2018-10-28 11:32:23 +01:00
public static final String SET_DISPLAY_EMOJI = "set_display_emoji";
2018-11-07 08:07:45 +01:00
public static final String SET_DISPLAY_CARD = "set_display_card";
2019-09-06 17:55:14 +02:00
public static final String SET_DISPLAY_VIDEO_PREVIEWS = "set_display_video_previews";
2018-12-15 10:59:43 +01:00
public static final String SET_DEFAULT_LOCALE_NEW = "set_default_locale_new";
public static final String SET_NOTIFICATION_ACTION = "set_notification_action";
2019-01-22 16:31:54 +01:00
public static final String SET_DISPLAY_CONTENT_AFTER_FM = "set_display_content_after_fm";
2019-09-06 17:55:14 +02:00
public static final String SET_FEATURED_TAGS = "set_featured_tags";
public static final String SET_SEND_CRASH_REPORTS = "set_send_crash_reports";
public static final String SET_FEATURED_TAG_ACTION = "set_featured_tag_action";
2019-03-19 02:04:09 +01:00
public static final String SET_HIDE_DELETE_BUTTON_ON_TAB = "set_hide_delete_notification_on_tab";
public static final String SET_RETRIEVE_METADATA_IF_URL_FROM_EXTERAL = "set_retrieve_metadata_share_from_extras";
2019-05-18 16:47:49 +02:00
public static final String SET_BLUR_SENSITIVE = "set_blur_sensitive";
public static final String SET_LONG_PRESS_MEDIA = "set_long_press_media";
2019-05-19 14:33:24 +02:00
public static final String SET_DISPLAY_TIMELINE_IN_LIST = "set_display_timeline_in_list";
2019-09-04 00:31:37 +02:00
public static final String SET_UNFOLLOW_VALIDATION = "set_unfollow_validation";
2019-05-24 15:13:28 +02:00
public static final String SET_ONION_SCHEME = "set_onion_scheme";
2019-05-25 18:58:31 +02:00
public static final String SET_REMEMBER_POSITION_HOME = "set_remember_position";
2019-06-22 12:18:51 +02:00
public static final String SET_DISPLAY_ADMIN_MENU = "set_display_admin_menu";
public static final String SET_DISPLAY_ADMIN_STATUSES = "set_display_admin_statuses";
public static final String SET_DISPLAY_FEDILAB_FEATURES_BUTTON = "set_display_fedilab_features_button";
2019-08-06 15:12:17 +02:00
public static final String SET_AUTO_BACKUP_STATUSES = "set_auto_backup_statuses";
public static final String SET_AUTO_BACKUP_NOTIFICATIONS = "set_auto_backup_notifications";
2019-06-22 12:18:51 +02:00
2019-07-04 10:17:53 +02:00
2017-05-05 16:36:04 +02:00
public static final int ATTACHMENT_ALWAYS = 1;
public static final int ATTACHMENT_WIFI = 2;
public static final int ATTACHMENT_ASK = 3;
2018-05-11 10:40:58 +02:00
2019-01-06 15:36:01 +01:00
public static final String SET_VIDEO_MODE = "set_video_mode";
public static final int VIDEO_MODE_TORRENT = 0;
public static final int VIDEO_MODE_WEBVIEW = 1;
public static final int VIDEO_MODE_DIRECT = 2;
2018-11-23 19:18:38 +01:00
2017-06-30 17:09:07 +02:00
public static final int THEME_LIGHT = 1;
public static final int THEME_DARK = 2;
2018-05-11 10:40:58 +02:00
public static final int THEME_BLACK = 3;
2017-05-05 16:36:04 +02:00
2019-09-11 16:30:29 +02:00
public static final int NOTIF_LIVE = 0;
2019-09-11 16:02:56 +02:00
public static final int NOTIF_DELAYED = 1;
2019-09-11 16:30:29 +02:00
public static final int NOTIF_NONE = 2;
2019-09-11 16:02:56 +02:00
public static final int LED_COLOUR = 0;
2017-08-25 15:53:04 +02:00
public static final int TRANS_YANDEX = 0;
2018-08-14 16:20:53 +02:00
public static final int TRANS_DEEPL = 1;
2017-08-25 15:53:04 +02:00
public static final int TRANS_NONE = 2;
public static final int ACTION_SILENT = 0;
public static final int ACTION_ACTIVE = 1;
public static final String SET_TRANS_FORCED = "set_trans_forced";
public static final String SET_NOTIFY = "set_notify";
2017-05-05 16:36:04 +02:00
public static final String SET_NOTIF_FOLLOW = "set_notif_follow";
public static final String SET_NOTIF_ADD = "set_notif_follow_add";
public static final String SET_NOTIF_MENTION = "set_notif_follow_mention";
public static final String SET_NOTIF_SHARE = "set_notif_follow_share";
public static final String SET_NOTIF_POLL = "set_notif_follow_poll";
public static final String SET_NOTIF_FOLLOW_FILTER = "set_notif_follow_filter";
public static final String SET_NOTIF_ADD_FILTER = "set_notif_follow_add_filter";
public static final String SET_NOTIF_MENTION_FILTER = "set_notif_follow_mention_filter";
public static final String SET_NOTIF_SHARE_FILTER = "set_notif_follow_share_filter";
public static final String SET_NOTIF_POLL_FILTER = "set_notif_follow_poll_filter";
public static final String SET_FILTER_REGEX_HOME = "set_filter_regex_home";
public static final String SET_FILTER_REGEX_LOCAL = "set_filter_regex_local";
public static final String SET_FILTER_REGEX_PUBLIC = "set_filter_regex_public";
public static final String SET_INVIDIOUS = "set_invidious";
2019-09-04 17:16:57 +02:00
public static final String SET_INVIDIOUS_HOST = "set_invidious_host";
public static final String DEFAULT_INVIDIOUS_HOST = "invidio.us";
2019-09-13 17:37:59 +02:00
public static final String SET_NITTER = "set_nitter";
public static final String SET_NITTER_HOST = "set_nitter_host";
public static final String DEFAULT_NITTER_HOST = "nitter.net";
2017-05-05 16:36:04 +02:00
public static final String SET_NOTIF_VALIDATION = "set_share_validation";
public static final String SET_NOTIF_VALIDATION_FAV = "set_share_validation_fav";
2017-05-05 16:36:04 +02:00
public static final String SET_WIFI_ONLY = "set_wifi_only";
public static final String SET_NOTIF_SILENT = "set_notif_silent";
2018-02-09 17:39:09 +01:00
public static final String SET_EXPAND_CW = "set_expand_cw";
2018-09-15 09:33:53 +02:00
public static final String SET_EXPAND_MEDIA = "set_expand_media";
2019-05-31 18:20:54 +02:00
public static final String SET_PHOTO_EDITOR = "set_photo_editor";
public static final String MAX_UPLOAD_IMG_RETRY_TIMES = "max_upload_img_retry_times";
public static final String SET_DISPLAY_FOLLOW_INSTANCE = "set_display_follow_instance";
public static final String SET_DISPLAY_NEW_BADGE = "set_display_new_badge";
2019-05-24 19:17:44 +02:00
public static final String SET_DISPLAY_BOT_ICON = "set_display_bot_icon";
2019-07-06 16:17:13 +02:00
public static final String SET_DISPLAY_CONFIRM = "set_display_confirm";
public static final String SET_QUICK_REPLY = "set_quick_reply";
public static final String SET_EMBEDDED_BROWSER = "set_embedded_browser";
2018-02-09 16:44:18 +01:00
public static final String SET_CUSTOM_TABS = "set_custom_tabs";
public static final String SET_JAVASCRIPT = "set_javascript";
public static final String SET_COOKIES = "set_cookies";
public static final String SET_FOLDER_RECORD = "set_folder_record";
public static final String SET_TOOT_VISIBILITY = "set_toot_visibility";
2018-10-10 08:33:36 +02:00
public static final String SET_DISPLAY_DIRECT = "set_display_direct";
2017-09-01 17:17:22 +02:00
public static final String SET_DISPLAY_LOCAL = "set_display_local";
public static final String SET_DISPLAY_GLOBAL = "set_display_global";
2018-12-05 12:04:49 +01:00
public static final String SET_DISPLAY_ART = "set_display_art";
2019-04-21 09:12:10 +02:00
public static final String SET_DISPLAY_PEERTUBE = "set_display_peertube";
2018-08-15 11:24:57 +02:00
public static final String SET_AUTOMATICALLY_SPLIT_TOOTS = "set_automatically_split_toots";
public static final String SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE = "set_automatically_split_toots_size";
2018-11-28 11:24:59 +01:00
public static final String SET_TRUNCATE_TOOTS_SIZE = "set_truncate_toots_size";
2018-12-15 18:27:54 +01:00
public static final String SET_ART_WITH_NSFW = "set_art_with_nsfw";
2019-02-14 10:06:18 +01:00
public static final String SET_SECURITY_PROVIDER = "set_security_provider";
2019-09-01 18:11:57 +02:00
public static final String SET_ALLOW_STREAM = "set_allow_stream";
2017-05-05 16:36:04 +02:00
//End points
public static final String EP_AUTHORIZE = "/oauth/authorize";
2018-01-19 18:20:31 +01:00
//Proxy
2018-01-19 18:59:30 +01:00
public static final String SET_PROXY_ENABLED = "set_proxy_enabled";
2018-01-20 09:46:28 +01:00
public static final String SET_PROXY_TYPE = "set_proxy_type";
2018-01-19 18:20:31 +01:00
public static final String SET_PROXY_HOST = "set_proxy_host";
public static final String SET_PROXY_PORT = "set_proxy_port";
public static final String SET_PROXY_LOGIN = "set_proxy_login";
public static final String SET_PROXY_PASSWORD = "set_proxy_password";
2017-08-29 16:22:57 +02:00
//Refresh job
public static final int MINUTES_BETWEEN_NOTIFICATIONS_REFRESH = 15;
2019-08-06 15:12:17 +02:00
public static final int MINUTES_BETWEEN_BACKUP = 60;
2017-08-29 16:22:57 +02:00
public static final int MINUTES_BETWEEN_HOME_TIMELINE = 30;
2018-08-15 11:24:57 +02:00
public static final int SPLIT_TOOT_SIZE = 500;
2017-05-05 16:36:04 +02:00
2017-11-01 13:27:40 +01:00
//Translate wait time
public static final String LAST_TRANSLATION_TIME = "last_translation_time";
2017-11-01 13:58:12 +01:00
public static final int SECONDES_BETWEEN_TRANSLATE = 30;
2017-05-05 16:36:04 +02:00
//Intent
public static final String INTENT_ACTION = "intent_action";
public static final String INTENT_TARGETED_ACCOUNT = "intent_targeted_account";
2018-02-17 16:09:06 +01:00
public static final String INTENT_BACKUP_FINISH = "intent_backup_finish";
2019-05-30 16:37:49 +02:00
public static final String INTENT_SEND_MODIFIED_IMAGE = "intent_send_modified_image";
2019-07-24 18:54:57 +02:00
public static final String INTENT_ADD_UPLOADED_MEDIA = "intent_add_uploaded_media";
2017-05-05 16:36:04 +02:00
//Receiver
2017-08-28 15:01:45 +02:00
public static final String RECEIVE_DATA = "receive_data";
2019-01-10 11:51:25 +01:00
public static final String RECEIVE_ACTION = "receive_action";
2018-12-19 10:54:26 +01:00
public static final String RECEIVE_HOME_DATA = "receive_home_data";
public static final String RECEIVE_FEDERATED_DATA = "receive_federated_data";
2017-09-30 08:48:44 +02:00
public static final String RECEIVE_LOCAL_DATA = "receive_local_data";
2019-07-03 17:28:17 +02:00
public static final String RECEIVE_HIDE_ITEM = "receive_hide_item";
2019-08-19 18:30:47 +02:00
public static final String RECEIVE_UPDATE_TOPBAR = "receive_update_topbar";
2017-05-20 19:40:46 +02:00
//User agent
//public static final String USER_AGENT = "Fedilab/"+ BuildConfig.VERSION_NAME + " Android/"+ Build.VERSION.RELEASE;
public static final String USER_AGENT = System.getProperty("http.agent");
2018-08-14 16:20:53 +02:00
public static final String SET_YANDEX_API_KEY = "set_yandex_api_key";
public static final String SET_DEEPL_API_KEY = "set_deepl_api_key";
2019-01-09 16:04:14 +01:00
public static final String VIDEO_ID = "video_id_update";
2017-05-31 15:11:54 +02:00
private static boolean menuAccountsOpened = false;
2017-09-15 19:15:23 +02:00
public static boolean canPin;
private static final Pattern SHORTNAME_PATTERN = Pattern.compile(":( |)([-+\\w]+):");
2017-08-21 17:32:09 +02:00
public static final Pattern urlPattern = Pattern.compile(
2017-07-31 19:29:14 +02:00
"(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,10}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
2018-11-24 17:38:40 +01:00
public static final Pattern hashtagPattern = Pattern.compile("(#[\\w_A-zÀ-ÿ]+)");
2019-07-24 10:05:15 +02:00
public static final Pattern groupPattern = Pattern.compile("(\\![\\w_]+(\\s|$))");
2018-08-14 18:27:21 +02:00
public static final Pattern twitterPattern = Pattern.compile("((@[\\w]+)@twitter\\.com)");
2019-09-18 09:14:27 +02:00
public static final Pattern youtubePattern = Pattern.compile("(www\\.|m\\.)?(youtube\\.com|youtu\\.be|youtube-nocookie\\.com)\\/(((?!(\"|'|<)).)*)");
public static final Pattern nitterPattern = Pattern.compile("(mobile\\.|www\\.)?twitter.com([\\w-/]+)");
2018-12-08 12:05:58 +01:00
private static final Pattern mentionPattern = Pattern.compile("(@[\\w_]+(\\s|$))");
private static final Pattern mentionLongPattern = Pattern.compile("(@[\\w_-]+@[a-z0-9.\\-]+[.][a-z]{2,10})");
2019-09-14 15:51:06 +02:00
private static final Pattern mentionSearchPattern = Pattern.compile("(@[\\w_-]+@[a-z0-9.\\-]+|@[\\w_-]+)");
2018-12-31 12:06:50 +01:00
public static final Pattern xmppPattern = Pattern.compile("xmpp\\:[-a-zA-Z0-9+$&@#\\/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#\\/%=~_|]");
2019-09-06 17:55:14 +02:00
2019-10-20 12:02:46 +02:00
//Default values
public final static int DEFAULT_VIDEO_WIDTH = 640;
public final static int DEFAULT_VIDEO_HEIGHT = 360;
public final static int DEFAULT_VIDEO_BITRATE = 450000;
//Event Type
2019-09-06 17:55:14 +02:00
public enum EventStreaming {
UPDATE,
NOTIFICATION,
DELETE,
NONE
}
2017-10-31 12:47:51 +01:00
2019-09-06 17:55:14 +02:00
public enum NotifType {
2018-09-16 18:03:24 +02:00
FOLLLOW,
MENTION,
BOOST,
FAV,
POLL,
2018-09-16 18:03:24 +02:00
BACKUP,
STORE,
TOOT
}
2017-10-31 12:47:51 +01:00
2019-04-17 16:25:42 +02:00
2019-09-11 16:02:56 +02:00
public static int liveNotifType(Context context){
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean live = sharedpreferences.getBoolean(Helper.SET_LIVE_NOTIFICATIONS, false );
boolean delayed = sharedpreferences.getBoolean(Helper.SET_DELAYED_NOTIFICATIONS, true );
if( delayed){
return Helper.NOTIF_DELAYED;
}else if( live ){
return Helper.NOTIF_LIVE;
}else {
return Helper.NOTIF_NONE;
}
}
/**
2017-06-19 19:20:20 +02:00
* Converts emojis in input to unicode
2019-09-06 17:55:14 +02:00
*
* @param input String
* @param removeIfUnsupported boolean
* @return String
*/
public static String shortnameToUnicode(String input, boolean removeIfUnsupported) {
Matcher matcher = SHORTNAME_PATTERN.matcher(input);
boolean supported = Build.VERSION.SDK_INT >= 16;
while (matcher.find()) {
String unicode = emoji.get(matcher.group(2));
if (unicode == null) {
continue;
}
if (supported) {
if (matcher.group(1).equals(" "))
input = input.replace(": " + matcher.group(2) + ":", unicode);
else
input = input.replace(":" + matcher.group(2) + ":", unicode);
} else if (removeIfUnsupported) {
if (matcher.group(1).equals(" "))
input = input.replace(": " + matcher.group(2) + ":", unicode);
else
input = input.replace(":" + matcher.group(2) + ":", "");
}
}
return input;
}
2019-09-06 17:55:14 +02:00
//Emoji manager
private static Map<String, String> emoji = new HashMap<>();
public static void fillMapEmoji(Context context) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(context.getAssets().open("emoji.csv")));
String line;
2019-09-06 17:55:14 +02:00
while ((line = br.readLine()) != null) {
String str[] = line.split(",");
String unicode = null;
2019-09-06 17:55:14 +02:00
if (str.length == 2)
unicode = new String(new int[]{Integer.parseInt(str[1].replace("0x", "").trim(), 16)}, 0, 1);
else if (str.length == 3)
unicode = new String(new int[]{Integer.parseInt(str[1].replace("0x", "").trim(), 16), Integer.parseInt(str[2].replace("0x", "").trim(), 16)}, 0, 2);
else if (str.length == 4)
unicode = new String(new int[]{Integer.parseInt(str[1].replace("0x", "").trim(), 16), Integer.parseInt(str[2].replace("0x", "").trim(), 16), Integer.parseInt(str[3].replace("0x", "").trim(), 16)}, 0, 3);
else if (str.length == 5)
unicode = new String(new int[]{Integer.parseInt(str[1].replace("0x", "").trim(), 16), Integer.parseInt(str[2].replace("0x", "").trim(), 16), Integer.parseInt(str[3].replace("0x", "").trim(), 16), Integer.parseInt(str[4].replace("0x", "").trim(), 16)}, 0, 4);
if (unicode != null)
emoji.put(str[0], unicode);
}
br.close();
2019-09-06 17:55:14 +02:00
} catch (IOException ignored) {
}
}
2017-05-05 16:36:04 +02:00
/***
* Check if the user is connected to Internet
* @return boolean
*/
2017-09-21 07:21:04 +02:00
public static boolean isConnectedToInternet(Context context, String instance) {
2017-05-05 16:36:04 +02:00
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2019-09-06 17:55:14 +02:00
if (cm == null)
2017-10-27 14:19:13 +02:00
return true;
2017-05-05 16:36:04 +02:00
NetworkInfo ni = cm.getActiveNetworkInfo();
2019-09-06 17:55:14 +02:00
if (ni != null && ni.isConnected()) {
2017-05-05 16:36:04 +02:00
try {
2017-09-21 07:21:04 +02:00
InetAddress ipAddr = InetAddress.getByName(instance);
2017-05-05 16:36:04 +02:00
return !ipAddr.toString().equals("");
} catch (Exception e) {
return false;
}
} else {
return false;
}
}
/**
* Returns boolean depending if the user is authenticated
2019-09-06 17:55:14 +02:00
*
2017-05-05 16:36:04 +02:00
* @param context Context
* @return boolean
*/
public static boolean isLoggedIn(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String prefKeyOauthTokenT = sharedpreferences.getString(PREF_KEY_OAUTH_TOKEN, null);
2019-09-06 17:55:14 +02:00
return (prefKeyOauthTokenT != null);
2017-05-05 16:36:04 +02:00
}
/**
* Log out the authenticated user by removing its token
2019-09-06 17:55:14 +02:00
*
2017-05-05 16:36:04 +02:00
* @param context Context
*/
public static void logout(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, null);
editor.putString(Helper.CLIENT_ID, null);
editor.putString(Helper.CLIENT_SECRET, null);
editor.putString(Helper.PREF_KEY_ID, null);
editor.putBoolean(Helper.PREF_IS_MODERATOR, false);
editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, false);
editor.putString(Helper.PREF_INSTANCE, null);
2017-05-05 16:36:04 +02:00
editor.putString(Helper.ID, null);
editor.apply();
}
2019-01-29 11:52:54 +01:00
/**
* Log out the authenticated user by removing its token
2019-09-06 17:55:14 +02:00
*
2019-02-06 18:03:47 +01:00
* @param activity Activity
2019-01-29 11:52:54 +01:00
*/
2019-01-29 14:18:55 +01:00
public static void logoutCurrentUser(Activity activity) {
SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
2019-01-29 11:52:54 +01:00
//Current user
2019-02-08 15:07:46 +01:00
2019-01-29 14:18:55 +01:00
SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
2019-02-08 15:07:46 +01:00
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(activity));
Account account = new AccountDAO(activity, db).getUniqAccount(userId, instance);
2019-09-06 17:55:14 +02:00
if (account != null) {
2019-02-23 14:39:51 +01:00
account.setToken("null");
new AccountDAO(activity, db).updateAccount(account);
}
2019-01-29 14:18:55 +01:00
Account newAccount = new AccountDAO(activity, db).getLastUsedAccount();
2019-01-29 11:52:54 +01:00
SharedPreferences.Editor editor = sharedpreferences.edit();
2019-09-06 17:55:14 +02:00
if (newAccount == null) {
2019-01-29 11:52:54 +01:00
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, null);
editor.putString(Helper.CLIENT_ID, null);
editor.putString(Helper.CLIENT_SECRET, null);
editor.putString(Helper.PREF_KEY_ID, null);
editor.putBoolean(Helper.PREF_IS_MODERATOR, false);
editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, false);
editor.putString(Helper.PREF_INSTANCE, null);
editor.putString(Helper.ID, null);
editor.apply();
2019-09-06 17:55:14 +02:00
} else {
2019-01-29 11:52:54 +01:00
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, newAccount.getToken());
editor.putString(Helper.PREF_KEY_ID, newAccount.getId());
editor.putString(Helper.PREF_INSTANCE, newAccount.getInstance().trim());
2019-04-22 13:16:35 +02:00
2019-01-29 11:52:54 +01:00
editor.putBoolean(Helper.PREF_IS_MODERATOR, newAccount.isModerator());
editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, newAccount.isAdmin());
editor.commit();
2019-01-29 14:18:55 +01:00
Intent changeAccount = new Intent(activity, MainActivity.class);
2019-01-29 11:52:54 +01:00
changeAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2019-01-29 14:18:55 +01:00
activity.startActivity(changeAccount);
2019-01-29 11:52:54 +01:00
}
}
2017-05-05 16:36:04 +02:00
/**
* Convert String date from Mastodon
2019-09-06 17:55:14 +02:00
*
2017-05-05 16:36:04 +02:00
* @param context Context
2019-09-06 17:55:14 +02:00
* @param date String
2017-05-05 16:36:04 +02:00
* @return Date
*/
2018-08-23 10:52:50 +02:00
public static Date mstStringToDate(Context context, String date) throws ParseException {
2019-02-14 11:29:22 +01:00
if (date == null)
2019-01-22 08:51:36 +01:00
return null;
2019-02-14 11:29:22 +01:00
2019-02-03 09:27:02 +01:00
String STRING_DATE_FORMAT;
2019-02-14 11:29:22 +01:00
Locale local = Locale.getDefault();
if (!date.contains("+")) {
2019-02-03 09:27:02 +01:00
STRING_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
2019-09-06 17:55:14 +02:00
} else { //GNU date format
2019-02-03 09:27:02 +01:00
STRING_DATE_FORMAT = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";
2019-02-14 11:29:22 +01:00
local = Locale.ENGLISH;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(STRING_DATE_FORMAT, local);
2017-05-05 16:36:04 +02:00
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("gmt"));
simpleDateFormat.setLenient(true);
2018-12-26 15:43:36 +01:00
try {
return simpleDateFormat.parse(date);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2019-02-03 09:27:02 +01:00
String newdate = date.split("\\+")[0].trim();
2019-02-14 11:29:22 +01:00
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", local);
2018-12-26 15:43:36 +01:00
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("gmt"));
simpleDateFormat.setLenient(true);
return simpleDateFormat.parse(newdate);
}
2017-05-05 16:36:04 +02:00
}
2019-02-07 19:47:53 +01:00
/**
* Convert String date from Mastodon
2019-09-06 17:55:14 +02:00
*
2019-02-07 19:47:53 +01:00
* @param context Context
2019-09-06 17:55:14 +02:00
* @param date String
2019-02-07 19:47:53 +01:00
* @return Date
*/
public static Date opencollectivetStringToDate(Context context, String date) throws ParseException {
Locale userLocale;
2019-09-06 17:55:14 +02:00
if (date == null)
2019-02-07 19:47:53 +01:00
return null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
userLocale = context.getResources().getConfiguration().getLocales().get(0);
} else {
//noinspection deprecation
userLocale = context.getResources().getConfiguration().locale;
}
String STRING_DATE_FORMAT;
STRING_DATE_FORMAT = "yyyy-MM-dd HH:mm";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(STRING_DATE_FORMAT, userLocale);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("gmt"));
simpleDateFormat.setLenient(true);
return simpleDateFormat.parse(date);
}
2017-05-05 16:36:04 +02:00
/**
* Convert a date in String -> format yyyy-MM-dd HH:mm:ss
2019-09-06 17:55:14 +02:00
*
2017-05-05 16:36:04 +02:00
* @param date Date
* @return String
*/
2018-04-28 16:54:06 +02:00
public static String dateToString(Date date) {
2019-09-06 17:55:14 +02:00
if (date == null)
2018-08-16 15:26:39 +02:00
return null;
2019-09-06 17:55:14 +02:00
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
2017-05-05 16:36:04 +02:00
return dateFormat.format(date);
}
2019-03-24 16:38:12 +01:00
/**
* Convert a date in String -> format yyyy-MM-dd HH:mm:ss
2019-09-06 17:55:14 +02:00
*
2019-03-24 16:38:12 +01:00
* @param date Date
* @return String
*/
public static String dateToStringPoll(Date date) {
2019-09-06 17:55:14 +02:00
if (date == null)
2019-03-24 16:38:12 +01:00
return null;
2019-09-06 17:55:14 +02:00
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
2019-03-24 16:38:12 +01:00
return dateFormat.format(date);
}
2019-09-28 18:49:38 +02:00
/**
* Convert a date in String
*
* @param date Date
* @return String
*/
public static String longDateToString(Date date) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.SHORT, Locale.getDefault());
return df.format(date);
}
2018-02-17 12:35:54 +01:00
/**
* Convert a date in String -> format yyyy-MM-dd HH:mm:ss
2019-09-06 17:55:14 +02:00
*
2018-02-17 12:35:54 +01:00
* @param date Date
* @return String
*/
public static String shortDateToString(Date date) {
SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
return df.format(date);
}
2018-01-06 17:13:18 +01:00
/**
* Convert a date in String -> format yyyy-MM-dd HH:mm:ss
2019-09-06 17:55:14 +02:00
*
2018-01-06 17:13:18 +01:00
* @param context Context
2019-09-06 17:55:14 +02:00
* @param date Date
2018-01-06 17:13:18 +01:00
* @return String
*/
public static String dateFileToString(Context context, Date date) {
Locale userLocale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
userLocale = context.getResources().getConfiguration().getLocales().get(0);
} else {
//noinspection deprecation
userLocale = context.getResources().getConfiguration().locale;
}
2019-09-06 17:55:14 +02:00
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", userLocale);
2018-01-06 17:13:18 +01:00
return dateFormat.format(date);
}
2017-05-05 16:36:04 +02:00
/**
* Convert String date from db to Date Object
2019-09-06 17:55:14 +02:00
*
2017-05-05 16:36:04 +02:00
* @param stringDate date to convert
* @return Date
*/
public static Date stringToDate(Context context, String stringDate) {
2019-09-06 17:55:14 +02:00
if (stringDate == null)
2017-05-05 16:36:04 +02:00
return null;
Locale userLocale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
userLocale = context.getResources().getConfiguration().getLocales().get(0);
} else {
//noinspection deprecation
userLocale = context.getResources().getConfiguration().locale;
}
2019-09-06 17:55:14 +02:00
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", userLocale);
2017-05-05 16:36:04 +02:00
Date date = null;
try {
date = dateFormat.parse(stringDate);
} catch (java.text.ParseException ignored) {
}
return date;
}
/**
* Converts a Date date into a date-time string (SHORT format for both)
2019-09-06 17:55:14 +02:00
*
2017-12-28 17:56:03 +01:00
* @param context Context
2019-09-06 17:55:14 +02:00
* @param date to be converted
* @return String
*/
2018-01-06 15:14:11 +01:00
public static String shortDateTime(Context context, Date date) {
Locale userLocale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
userLocale = context.getResources().getConfiguration().getLocales().get(0);
} else {
//noinspection deprecation
userLocale = context.getResources().getConfiguration().locale;
}
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, userLocale);
return df.format(date);
}
/**
* Makes the tvDate TextView field clickable, and displays the absolute date & time of a toot
2019-09-06 17:55:14 +02:00
* for 5 seconds.
*
* @param context Context
2019-09-06 17:55:14 +02:00
* @param tvDate TextView
* @param date Date
*/
public static void absoluteDateTimeReveal(final Context context, final TextView tvDate, final Date date) {
tvDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvDate.setText(Helper.dateDiffFull(date));
new CountDownTimer((5 * 1000), 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
tvDate.setText(Helper.dateDiff(context, date));
}
}.start();
}
});
}
2017-05-05 16:36:04 +02:00
/**
* Check if WIFI is opened
2019-09-06 17:55:14 +02:00
*
2017-05-05 16:36:04 +02:00
* @param context Context
* @return boolean
*/
public static boolean isOnWIFI(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2017-10-27 14:19:13 +02:00
assert connManager != null;
2017-05-05 16:36:04 +02:00
NetworkInfo activeNetwork = connManager.getActiveNetworkInfo();
return (activeNetwork != null && activeNetwork.getType() == ConnectivityManager.TYPE_WIFI);
}
2019-09-06 17:55:14 +02:00
public static String dateDiffFull(Date dateToot) {
2018-04-25 15:28:21 +02:00
SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, Locale.getDefault());
2018-11-26 18:06:04 +01:00
try {
return df.format(dateToot);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-11-26 18:06:04 +01:00
return "";
}
}
2017-05-05 16:36:04 +02:00
/***
* Returns a String depending of the date
* @param context Context
* @param dateToot Date
* @return String
*/
2019-09-06 17:55:14 +02:00
public static String dateDiff(Context context, Date dateToot) {
2017-05-05 16:36:04 +02:00
Date now = new Date();
long diff = now.getTime() - dateToot.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
long months = days / 30;
long years = days / 365;
2017-12-25 18:23:01 +01:00
String format = DateFormat.getDateInstance(DateFormat.SHORT).format(dateToot);
2019-09-06 17:55:14 +02:00
if (years > 0) {
2017-12-25 18:23:01 +01:00
return format;
2019-09-06 17:55:14 +02:00
} else if (months > 0 || days > 7) {
2018-01-08 18:43:59 +01:00
//Removes the year depending of the locale from DateFormat.SHORT format
SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
df.applyPattern(df.toPattern().replaceAll("[^\\p{Alpha}]*y+[^\\p{Alpha}]*", ""));
return df.format(dateToot);
2019-09-06 17:55:14 +02:00
} else if (days > 0)
2017-12-16 08:17:42 +01:00
return context.getString(R.string.date_day, days);
2019-09-06 17:55:14 +02:00
else if (hours > 0)
return context.getResources().getString(R.string.date_hours, (int) hours);
else if (minutes > 0)
return context.getResources().getString(R.string.date_minutes, (int) minutes);
else {
if (seconds < 0)
seconds = 0;
2017-12-22 17:28:50 +01:00
return context.getResources().getString(R.string.date_seconds, (int) seconds);
}
2017-05-05 16:36:04 +02:00
}
/***
* Toast message depending of the status code and the initial action
* @param context Context
* @param statusCode int the status code
* @param statusAction API.StatusAction the initial action
*/
2019-09-06 17:55:14 +02:00
public static void manageMessageStatusCode(Context context, int statusCode, API.StatusAction statusAction) {
2017-05-05 16:36:04 +02:00
String message = "";
2019-07-06 16:17:13 +02:00
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean display_confirm = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CONFIRM, true);
2019-09-06 17:55:14 +02:00
if (!display_confirm) {
2019-07-06 16:39:16 +02:00
return;
}
2019-09-06 17:55:14 +02:00
if (statusCode >= 200 && statusCode < 400) {
if (statusAction == API.StatusAction.BLOCK) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_block);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.UNBLOCK) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_unblock);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.REBLOG) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_reblog);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.UNREBLOG) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_unreblog);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.MUTE) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_mute);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.UNMUTE) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_unmute);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.MUTE_CONVERSATION) {
2019-06-06 18:16:43 +02:00
message = context.getString(R.string.toast_mute_conversation);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.UNMUTE_CONVERSATION) {
2019-06-06 18:16:43 +02:00
message = context.getString(R.string.toast_unmute_conversation);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.FOLLOW) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_follow);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.UNFOLLOW) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_unfollow);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.FAVOURITE) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_favourite);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.UNFAVOURITE) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_unfavourite);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.PIN) {
message = context.getString(R.string.toast_pin);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.UNPIN) {
message = context.getString(R.string.toast_unpin);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.REPORT) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_report);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.UNSTATUS) {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_unstatus);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.UNENDORSE) {
2018-09-04 19:27:26 +02:00
message = context.getString(R.string.toast_unendorse);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.ENDORSE) {
2018-09-04 19:27:26 +02:00
message = context.getString(R.string.toast_endorse);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.SHOW_BOOST) {
2018-09-04 19:27:26 +02:00
message = context.getString(R.string.toast_show_boost);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.HIDE_BOOST) {
2018-09-04 19:27:26 +02:00
message = context.getString(R.string.toast_hide_boost);
2019-09-06 17:55:14 +02:00
} else if (statusAction == API.StatusAction.BLOCK_DOMAIN) {
2018-09-26 19:18:54 +02:00
message = context.getString(R.string.toast_block_domain);
}
2018-09-04 19:27:26 +02:00
2019-09-06 17:55:14 +02:00
} else {
2017-05-05 16:36:04 +02:00
message = context.getString(R.string.toast_error);
}
2019-09-06 17:55:14 +02:00
if (!message.trim().equals(""))
2018-11-25 10:45:16 +01:00
Toasty.success(context, message, Toast.LENGTH_LONG).show();
2017-05-05 16:36:04 +02:00
}
/**
* Manage downloads with URLs
2019-09-06 17:55:14 +02:00
*
* @param context Context
2019-09-06 17:55:14 +02:00
* @param url String download url
*/
2019-09-06 17:55:14 +02:00
public static void manageDownloads(final Context context, final String url) {
2018-11-03 14:45:55 +01:00
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
int style;
if (theme == Helper.THEME_DARK) {
style = R.style.DialogDark;
2019-09-06 17:55:14 +02:00
} else if (theme == Helper.THEME_BLACK) {
2018-11-03 14:45:55 +01:00
style = R.style.DialogBlack;
2019-09-06 17:55:14 +02:00
} else {
2018-11-03 14:45:55 +01:00
style = R.style.Dialog;
}
final AlertDialog.Builder builder = new AlertDialog.Builder(context, style);
final DownloadManager.Request request;
try {
request = new DownloadManager.Request(Uri.parse(url.trim()));
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show();
return;
}
final String fileName = URLUtil.guessFileName(url, null, null);
builder.setMessage(context.getResources().getString(R.string.download_file, fileName));
builder.setCancelable(false)
.setPositiveButton(context.getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
request.allowScanningByMediaScanner();
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
2017-10-27 16:00:54 +02:00
assert dm != null;
dm.enqueue(request);
dialog.dismiss();
}
})
.setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
2019-09-06 17:55:14 +02:00
if (alert.getWindow() != null)
alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
alert.show();
2017-05-05 16:36:04 +02:00
}
2019-10-10 19:28:16 +02:00
/**
* Manage downloads with URLs
*
* @param context Context
* @param url String download url
*/
public static long manageDownloadsNoPopup(final Context context, final String url) {
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
final DownloadManager.Request request;
try {
request = new DownloadManager.Request(Uri.parse(url.trim()));
} catch (Exception e) {
Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show();
return -1;
}
final String fileName = URLUtil.guessFileName(url, null, null);
request.allowScanningByMediaScanner();
String myDir = sharedpreferences.getString(Helper.SET_FOLDER_RECORD, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
request.setDestinationInExternalPublicDir(myDir, fileName);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
assert dm != null;
return dm.enqueue(request);
}
2019-05-05 12:41:45 +02:00
public static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
2019-08-05 16:15:06 +02:00
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?");
}
/**
* Sends notification with intent
2019-09-06 17:55:14 +02:00
*
* @param context Context
2019-09-06 17:55:14 +02:00
* @param intent Intent associated to the notifcation
* @param icon Bitmap profile picture
* @param title String title of the notification
* @param message String message for the notification
*/
2019-09-06 17:55:14 +02:00
public static void notify_user(Context context, Account account, Intent intent, Bitmap icon, NotifType notifType, String title, String message) {
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
// prepare intent which is triggered if the user click on the notification
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
2019-08-31 18:07:19 +02:00
/*String val;
2019-08-05 16:15:06 +02:00
if( isNumeric(account.getId())){
val = account.getId();
}else{
int count = 0;
for (int i = 0; i < account.getId().length(); ++i) {
count += (int)account.getId().charAt(i);
}
val = String.valueOf(count);
2019-08-31 18:07:19 +02:00
}*/
2019-08-05 16:02:54 +02:00
2019-09-06 17:55:14 +02:00
int notificationId = (int) System.currentTimeMillis();
2019-08-01 18:15:11 +02:00
PendingIntent pIntent = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_ONE_SHOT);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_CLEAR_TOP);
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// build notification
2018-09-16 18:03:24 +02:00
String channelId;
String channelTitle;
2019-08-01 18:15:11 +02:00
2019-09-06 17:55:14 +02:00
switch (notifType) {
2018-09-16 18:03:24 +02:00
case BOOST:
2019-09-26 18:58:43 +02:00
channelId = "channel_boost" + account.getAcct() + "@" + account.getInstance();
2018-09-16 18:03:24 +02:00
channelTitle = context.getString(R.string.channel_notif_boost);
break;
case FAV:
2019-09-26 18:58:43 +02:00
channelId = "channel_fav";
2019-08-01 18:15:11 +02:00
channelTitle = context.getString(R.string.channel_notif_fav);
2018-09-16 18:03:24 +02:00
break;
case FOLLLOW:
2019-09-26 18:58:43 +02:00
channelId = "channel_follow";
2019-08-01 18:15:11 +02:00
channelTitle = context.getString(R.string.channel_notif_follow);
2018-09-16 18:03:24 +02:00
break;
case MENTION:
2019-09-26 18:58:43 +02:00
channelId = "channel_mention";
2019-08-01 18:15:11 +02:00
channelTitle = context.getString(R.string.channel_notif_mention);
2018-09-16 18:03:24 +02:00
break;
case POLL:
2019-09-26 18:58:43 +02:00
channelId = "channel_poll";
2019-08-01 18:15:11 +02:00
channelTitle = context.getString(R.string.channel_notif_poll);
break;
2018-09-16 18:03:24 +02:00
case BACKUP:
2019-09-26 18:58:43 +02:00
channelId = "channel_backup";
2019-08-01 18:15:11 +02:00
channelTitle = context.getString(R.string.channel_notif_backup);
2018-09-16 18:03:24 +02:00
break;
case STORE:
2019-09-26 18:58:43 +02:00
channelId = "channel_store";
2019-08-01 18:15:11 +02:00
channelTitle = context.getString(R.string.channel_notif_media);
2018-09-16 18:03:24 +02:00
break;
case TOOT:
2019-09-26 18:58:43 +02:00
channelId = "channel_toot";
2019-08-01 18:15:11 +02:00
channelTitle = context.getString(R.string.channel_notif_toot);
2018-09-16 18:03:24 +02:00
break;
default:
2019-09-26 18:58:43 +02:00
channelId = "channel_boost";
2019-08-01 18:15:11 +02:00
channelTitle = context.getString(R.string.channel_notif_boost);
2018-09-16 18:03:24 +02:00
}
2019-09-25 15:44:52 +02:00
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(getNotificationIcon(context)).setTicker(message)
.setWhen(System.currentTimeMillis())
2019-08-31 15:14:20 +02:00
.setAutoCancel(true);
if (notifType == MENTION) {
2019-09-06 17:55:14 +02:00
if (message.length() > 500) {
message = message.substring(0, 499) + "";
}
2019-08-31 15:14:20 +02:00
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
}
2019-09-06 17:55:14 +02:00
notificationBuilder.setGroup(account.getAcct() + "@" + account.getInstance())
.setContentIntent(pIntent)
.setContentText(message);
int ledColour = Color.BLUE;
switch (sharedpreferences.getInt(Helper.SET_LED_COLOUR, Helper.LED_COLOUR)) {
case 0: // BLUE
ledColour = Color.BLUE;
break;
case 1: // CYAN
ledColour = Color.CYAN;
break;
case 2: // MAGENTA
ledColour = Color.MAGENTA;
break;
case 3: // GREEN
ledColour = Color.GREEN;
break;
case 4: // RED
ledColour = Color.RED;
break;
case 5: // YELLOW
ledColour = Color.YELLOW;
break;
case 6: // WHITE
ledColour = Color.WHITE;
break;
}
2018-09-19 09:55:09 +02:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
2019-09-06 17:55:14 +02:00
if (sharedpreferences.getBoolean(Helper.SET_NOTIF_SILENT, false)) {
2018-09-19 09:55:09 +02:00
channel = new NotificationChannel(channelId, channelTitle, NotificationManager.IMPORTANCE_LOW);
channel.setSound(null, null);
2019-09-06 17:55:14 +02:00
channel.setVibrationPattern(new long[]{500, 500, 500});
2018-09-19 09:55:09 +02:00
channel.enableVibration(true);
channel.setLightColor(ledColour);
2019-09-06 17:55:14 +02:00
} else {
2019-10-02 17:23:55 +02:00
channel = new NotificationChannel(channelId, channelTitle, NotificationManager.IMPORTANCE_DEFAULT);
2019-09-06 17:55:14 +02:00
String soundUri = sharedpreferences.getString(Helper.SET_NOTIF_SOUND, ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.boop);
2018-09-19 09:55:09 +02:00
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
2018-09-19 09:55:09 +02:00
.build();
channel.setSound(Uri.parse(soundUri), audioAttributes);
}
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(channel);
2019-09-06 17:55:14 +02:00
} else {
if (sharedpreferences.getBoolean(Helper.SET_NOTIF_SILENT, false)) {
notificationBuilder.setVibrate(new long[]{500, 500, 500});
} else {
String soundUri = sharedpreferences.getString(Helper.SET_NOTIF_SOUND, ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.boop);
2018-09-19 09:55:09 +02:00
notificationBuilder.setSound(Uri.parse(soundUri));
}
notificationBuilder.setLights(ledColour, 500, 1000);
}
notificationBuilder.setContentTitle(title);
notificationBuilder.setLargeIcon(icon);
notificationManager.notify(notificationId, notificationBuilder.build());
2019-09-26 18:58:43 +02:00
2019-10-31 15:26:37 +01:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification summaryNotification =
new NotificationCompat.Builder(context, channelId)
.setContentTitle(account.getAcct() + "@" + account.getInstance())
.setContentText(channelTitle)
.setSmallIcon(getNotificationIcon(context))
.setGroup(account.getAcct() + "@" + account.getInstance())
.setGroupSummary(true)
.build();
notificationManager.notify(0, summaryNotification);
}
}
2017-05-26 17:20:36 +02:00
/**
* Manage downloads with URLs
2019-09-06 17:55:14 +02:00
*
* @param context Context
2019-09-06 17:55:14 +02:00
* @param url String download url
*/
2019-09-06 17:55:14 +02:00
public static void manageMoveFileDownload(final Context context, final String preview_url, final String url, Bitmap bitmap, File fileVideo, boolean isSharing) {
2019-01-26 11:59:37 +01:00
final String fileName = URLUtil.guessFileName(url, null, null);
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
2017-07-17 15:22:59 +02:00
String myDir = sharedpreferences.getString(Helper.SET_FOLDER_RECORD, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
2018-12-22 15:14:51 +01:00
String mime = getMimeType(url);
try {
File file;
2019-09-06 17:55:14 +02:00
if (bitmap != null) {
file = new File(myDir, fileName);
2017-07-26 18:31:26 +02:00
//noinspection ResultOfMethodCallIgnored
2017-07-17 15:22:59 +02:00
file.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
2019-09-06 17:55:14 +02:00
if (mime != null && (mime.contains("png") || mime.contains(".PNG")))
2018-12-22 15:14:51 +01:00
bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
else
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
2017-07-17 15:22:59 +02:00
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(file);
fos.write(bitmapdata);
fos.flush();
fos.close();
2019-09-06 17:55:14 +02:00
} else {
File fileVideoTargeded = new File(myDir, fileName);
copy(fileVideo, fileVideoTargeded);
file = fileVideoTargeded;
}
// prepare intent which is triggered if the
// notification is selected
final Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
Uri uri = Uri.parse("file://" + file.getAbsolutePath());
intent.setDataAndType(uri, getMimeType(url));
2019-09-06 17:55:14 +02:00
if (!isSharing)
2019-01-26 11:59:37 +01:00
Glide.with(context)
.asBitmap()
.load(preview_url)
2019-09-06 17:55:14 +02:00
.listener(new RequestListener<Bitmap>() {
2019-01-26 11:59:37 +01:00
@Override
public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
2019-08-01 17:41:59 +02:00
SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context));
Account account = new AccountDAO(context, db).getUniqAccount(userId, instance);
2019-08-01 18:15:11 +02:00
notify_user(context, account, intent, BitmapFactory.decodeResource(context.getResources(),
2019-09-25 13:55:03 +02:00
R.mipmap.ic_launcher_bubbles), NotifType.STORE, context.getString(R.string.save_over), context.getString(R.string.download_from, fileName));
2019-09-06 17:55:14 +02:00
Toasty.success(context, context.getString(R.string.toast_saved), Toast.LENGTH_LONG).show();
2019-01-26 11:59:37 +01:00
return false;
}
})
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
2019-08-01 17:41:59 +02:00
SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context));
Account account = new AccountDAO(context, db).getUniqAccount(userId, instance);
2019-09-06 17:55:14 +02:00
notify_user(context, account, intent, resource, NotifType.STORE, context.getString(R.string.save_over), context.getString(R.string.download_from, fileName));
Toasty.success(context, context.getString(R.string.toast_saved), Toast.LENGTH_LONG).show();
2019-01-26 11:59:37 +01:00
}
});
else {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
2019-09-06 17:55:14 +02:00
if (bitmap != null)
2019-01-26 11:59:37 +01:00
shareIntent.setType("image/*");
else
shareIntent.setType("video/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.putExtra(Intent.EXTRA_TEXT, R.string.share_with);
context.startActivity(shareIntent);
}
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
}
}
/**
* Copy a file by transferring bytes from in to out
2019-09-06 17:55:14 +02:00
*
* @param src File source file
* @param dst File targeted file
* @throws IOException Exception
*/
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
2017-10-27 16:00:54 +02:00
//noinspection TryFinallyCanBeTryWithResources
try {
OutputStream out = new FileOutputStream(dst);
2017-10-27 16:00:54 +02:00
//noinspection TryFinallyCanBeTryWithResources
try {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
} finally {
out.close();
}
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
} finally {
in.close();
}
}
/**
* Returns the instance of the authenticated user
2019-09-06 17:55:14 +02:00
*
* @param context Context
* @return String domain instance
*/
2019-09-06 17:55:14 +02:00
public static String getLiveInstance(Context context) {
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
2018-12-16 14:29:23 +01:00
return sharedpreferences.getString(Helper.PREF_INSTANCE, null);
}
2018-01-24 15:56:33 +01:00
public static String getLiveInstanceWithProtocol(Context context) {
2019-05-24 15:13:28 +02:00
return instanceWithProtocol(context, getLiveInstance(context));
2018-01-24 15:56:33 +01:00
}
2019-09-06 17:55:14 +02:00
public static String instanceWithProtocol(Context context, String instance) {
if (instance == null)
2018-01-24 15:56:33 +01:00
return null;
2019-09-06 17:55:14 +02:00
if (instance.endsWith(".onion")) {
2019-05-24 15:13:28 +02:00
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
2019-09-06 17:55:14 +02:00
String scheme = sharedpreferences.getString(SET_ONION_SCHEME + instance, "http");
2019-05-24 15:13:28 +02:00
return scheme + "://" + instance;
2019-09-06 17:55:14 +02:00
} else {
2018-01-24 15:56:33 +01:00
return "https://" + instance;
2019-05-24 15:13:28 +02:00
}
2018-01-24 15:56:33 +01:00
}
2017-05-26 17:20:36 +02:00
2017-12-28 17:25:36 +01:00
/**
* Converts dp to pixel
2019-09-06 17:55:14 +02:00
*
* @param dp float - the value in dp to convert
* @param context Context
* @return float - the converted value in pixel
*/
2019-09-06 17:55:14 +02:00
public static float convertDpToPixel(float dp, Context context) {
2017-05-26 17:20:36 +02:00
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
2019-09-06 17:55:14 +02:00
return dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
2017-05-26 17:20:36 +02:00
}
/**
* Toggle for the menu (ie: main menu or accounts menu)
2019-09-06 17:55:14 +02:00
*
* @param activity Activity
*/
2019-09-06 17:55:14 +02:00
public static void menuAccounts(final Activity activity) {
2017-10-27 14:19:13 +02:00
final NavigationView navigationView = activity.findViewById(R.id.nav_view);
SharedPreferences mSharedPreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String currrentUserId = mSharedPreferences.getString(Helper.PREF_KEY_ID, null);
2019-09-06 17:55:14 +02:00
final ImageView arrow = navigationView.getHeaderView(0).findViewById(R.id.owner_accounts);
if (currrentUserId == null)
return;
2017-07-01 15:24:28 +02:00
final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
2019-09-06 17:55:14 +02:00
if (theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK) {
changeDrawableColor(activity, R.drawable.ic_person_add, R.color.dark_text);
changeDrawableColor(activity, R.drawable.ic_person, R.color.dark_text);
changeDrawableColor(activity, R.drawable.ic_cancel, R.color.dark_text);
} else {
changeDrawableColor(activity, R.drawable.ic_person_add, R.color.black);
changeDrawableColor(activity, R.drawable.ic_person, R.color.black);
changeDrawableColor(activity, R.drawable.ic_cancel, R.color.black);
2017-07-01 15:24:28 +02:00
}
2019-09-06 17:55:14 +02:00
if (!menuAccountsOpened) {
arrow.setImageResource(R.drawable.ic_arrow_drop_up);
SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
final List<Account> accounts = new AccountDAO(activity, db).getAllAccount();
2017-08-22 09:02:40 +02:00
String lastInstance = "";
navigationView.getMenu().clear();
navigationView.inflateMenu(R.menu.menu_accounts);
Menu mainMenu = navigationView.getMenu();
SubMenu currentSubmenu = null;
2019-09-06 17:55:14 +02:00
if (accounts != null)
for (final Account account : accounts) {
2019-09-06 17:55:14 +02:00
if (!currrentUserId.equals(account.getId()) || !getLiveInstance(activity).equals(account.getInstance())) {
if (!lastInstance.trim().toUpperCase().equals(account.getInstance().trim().toUpperCase())) {
lastInstance = account.getInstance().toUpperCase();
currentSubmenu = mainMenu.addSubMenu(account.getInstance().toUpperCase());
}
2019-09-06 17:55:14 +02:00
if (currentSubmenu == null)
continue;
final MenuItem item = currentSubmenu.add("@" + account.getAcct());
item.setIcon(R.drawable.ic_person);
String url = account.getAvatar();
if (url.startsWith("/")) {
url = "https://" + account.getInstance() + account.getAvatar();
}
if (!url.equals("null"))
Glide.with(navigationView.getContext())
.asBitmap()
.load(url)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
item.setIcon(new BitmapDrawable(activity.getResources(), resource));
item.getIcon().setColorFilter(0xFFFFFFFF, PorterDuff.Mode.MULTIPLY);
}
2019-09-06 17:55:14 +02:00
});
else
Glide.with(navigationView.getContext())
.asBitmap()
.load(R.drawable.missing_peertube)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
item.setIcon(new BitmapDrawable(activity.getResources(), resource));
item.getIcon().setColorFilter(0xFFFFFFFF, PorterDuff.Mode.MULTIPLY);
}
2019-09-06 17:55:14 +02:00
});
item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (!activity.isFinishing()) {
menuAccountsOpened = false;
Toasty.info(activity.getApplicationContext(), activity.getString(R.string.toast_account_changed, "@" + account.getAcct() + "@" + account.getInstance()), Toast.LENGTH_LONG).show();
changeUser(activity, account.getId(), account.getInstance(), false);
arrow.setImageResource(R.drawable.ic_arrow_drop_down);
return true;
}
return false;
}
});
item.setActionView(R.layout.update_account);
ImageView deleteButton = item.getActionView().findViewById(R.id.account_remove_button);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
int style;
if (theme == Helper.THEME_DARK) {
style = R.style.DialogDark;
} else if (theme == Helper.THEME_BLACK) {
style = R.style.DialogBlack;
} else {
style = R.style.Dialog;
}
new AlertDialog.Builder(activity, style)
.setTitle(activity.getString(R.string.delete_account_title))
.setMessage(activity.getString(R.string.delete_account_message, "@" + account.getAcct() + "@" + account.getInstance()))
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new RemoveAccountAsyncTask(activity, account).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
item.setVisible(false);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
2019-09-06 17:55:14 +02:00
}
}
currentSubmenu = mainMenu.addSubMenu("");
2017-08-22 09:02:40 +02:00
MenuItem addItem = currentSubmenu.add(R.string.add_account);
addItem.setIcon(R.drawable.ic_person_add);
addItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(activity, LoginActivity.class);
intent.putExtra("addAccount", true);
activity.startActivity(intent);
return true;
}
});
2019-09-06 17:55:14 +02:00
} else {
2017-08-22 09:02:40 +02:00
navigationView.getMenu().clear();
navigationView.inflateMenu(R.menu.activity_main_drawer);
2019-08-28 14:43:10 +02:00
hideMenuItem(activity, navigationView.getMenu());
arrow.setImageResource(R.drawable.ic_arrow_drop_down);
switchLayout(activity);
}
menuAccountsOpened = !menuAccountsOpened;
}
2019-09-06 17:55:14 +02:00
public static void hideMenuItem(Activity activity, Menu menu) {
2019-09-06 17:55:14 +02:00
if (BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
2019-01-03 11:19:45 +01:00
MenuItem itemCom = menu.findItem(R.id.nav_main_com);
2019-09-06 17:55:14 +02:00
if (itemCom != null)
2019-01-03 11:19:45 +01:00
itemCom.setVisible(false);
MenuItem itemOpt = menu.findItem(R.id.nav_main_opt);
2019-09-06 17:55:14 +02:00
if (itemOpt != null)
2019-01-03 11:19:45 +01:00
itemOpt.setVisible(false);
2019-01-14 11:50:42 +01:00
MenuItem itemPFCom = menu.findItem(R.id.nav_pixelfed_comm);
2019-09-06 17:55:14 +02:00
if (itemPFCom != null)
2019-01-14 11:50:42 +01:00
itemPFCom.setVisible(false);
2019-01-03 11:19:45 +01:00
2019-09-06 17:55:14 +02:00
} else if (BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PIXELFED) {
2019-01-14 11:50:42 +01:00
MenuItem itemCom = menu.findItem(R.id.nav_main_com);
2019-09-06 17:55:14 +02:00
if (itemCom != null)
2019-01-14 11:50:42 +01:00
itemCom.setVisible(false);
/*MenuItem itemOpt = menu.findItem(R.id.nav_main_opt);
2019-09-06 17:55:14 +02:00
if (itemOpt != null)
itemOpt.setVisible(false);*/
2019-01-14 11:50:42 +01:00
MenuItem itemPCom = menu.findItem(R.id.nav_peertube_comm);
2019-09-06 17:55:14 +02:00
if (itemPCom != null)
2019-01-14 11:50:42 +01:00
itemPCom.setVisible(false);
2019-09-06 17:55:14 +02:00
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
2019-01-03 12:15:42 +01:00
MenuItem itemCom = menu.findItem(R.id.nav_peertube_comm);
2019-09-06 17:55:14 +02:00
if (itemCom != null)
2019-01-03 12:15:42 +01:00
itemCom.setVisible(false);
2019-01-14 11:50:42 +01:00
MenuItem itemPFCom = menu.findItem(R.id.nav_pixelfed_comm);
2019-09-06 17:55:14 +02:00
if (itemPFCom != null)
2019-01-14 11:50:42 +01:00
itemPFCom.setVisible(false);
2019-02-05 18:05:21 +01:00
2019-09-06 17:55:14 +02:00
if (BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
2019-02-05 18:05:21 +01:00
MenuItem nav_list = menu.findItem(R.id.nav_list);
2019-09-06 17:55:14 +02:00
if (nav_list != null)
2019-02-05 18:05:21 +01:00
nav_list.setVisible(false);
MenuItem nav_peertube = menu.findItem(R.id.nav_peertube);
2019-09-06 17:55:14 +02:00
if (nav_peertube != null)
2019-02-05 18:05:21 +01:00
nav_peertube.setVisible(false);
MenuItem nav_filters = menu.findItem(R.id.nav_filters);
2019-09-06 17:55:14 +02:00
if (nav_filters != null)
2019-02-05 18:05:21 +01:00
nav_filters.setVisible(false);
MenuItem nav_follow_request = menu.findItem(R.id.nav_follow_request);
2019-09-06 17:55:14 +02:00
if (nav_follow_request != null)
2019-02-05 18:05:21 +01:00
nav_follow_request.setVisible(false);
MenuItem nav_who_to_follow = menu.findItem(R.id.nav_who_to_follow);
2019-09-06 17:55:14 +02:00
if (nav_who_to_follow != null)
2019-02-05 18:05:21 +01:00
nav_who_to_follow.setVisible(false);
MenuItem nav_blocked = menu.findItem(R.id.nav_blocked);
2019-09-06 17:55:14 +02:00
if (nav_blocked != null)
2019-02-05 18:05:21 +01:00
nav_blocked.setVisible(false);
MenuItem nav_muted = menu.findItem(R.id.nav_muted);
2019-09-06 17:55:14 +02:00
if (nav_muted != null)
2019-02-05 18:05:21 +01:00
nav_muted.setVisible(false);
MenuItem nav_blocked_domains = menu.findItem(R.id.nav_blocked_domains);
2019-09-06 17:55:14 +02:00
if (nav_blocked_domains != null)
2019-02-05 18:05:21 +01:00
nav_blocked_domains.setVisible(false);
2019-09-06 17:55:14 +02:00
if (BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU) {
2019-07-24 10:05:15 +02:00
MenuItem nav_group = menu.findItem(R.id.nav_group);
2019-09-06 17:55:14 +02:00
if (nav_group != null)
2019-07-24 10:05:15 +02:00
nav_group.setVisible(true);
}
2019-02-05 18:05:21 +01:00
2019-09-06 17:55:14 +02:00
} else {
2019-08-28 14:43:10 +02:00
SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
MainMenuItem mainMenuItem = new MainMenuDAO(activity, db).getMainMenu();
2019-09-06 17:55:14 +02:00
if (mainMenuItem == null) {
2019-08-28 16:21:50 +02:00
mainMenuItem = new MainMenuItem();
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_list()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_list).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_archive()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_archive).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_archive_notifications()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_archive_notifications).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_blocked()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_blocked).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_blocked_domains()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_blocked_domains).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_filters()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_filters).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_how_to_follow()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_who_to_follow).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_howto()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_how_to).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_muted()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_muted).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_news()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_news).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_peertube()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_peertube).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-09-06 17:55:14 +02:00
if (!mainMenuItem.isNav_scheduled()) {
2019-08-28 16:21:50 +02:00
menu.findItem(R.id.nav_scheduled).setVisible(false);
2019-08-28 14:43:10 +02:00
}
2019-02-05 18:05:21 +01:00
}
2019-01-03 11:19:45 +01:00
}
if (!BuildConfig.DONATIONS) {
MenuItem openCollectiveItem = menu.findItem(R.id.nav_opencollective);
2019-09-06 17:55:14 +02:00
if (openCollectiveItem != null) {
openCollectiveItem.setVisible(false);
}
MenuItem partnerShipItem = menu.findItem(R.id.nav_partnership);
2019-09-06 17:55:14 +02:00
if (partnerShipItem != null) {
partnerShipItem.setVisible(false);
}
}
2019-01-03 11:19:45 +01:00
}
2019-08-28 14:43:10 +02:00
/**
* Changes the user in shared preferences
2019-09-06 17:55:14 +02:00
*
* @param activity Activity
2019-09-06 17:55:14 +02:00
* @param userID String - the new user id
*/
2019-06-05 14:35:42 +02:00
public static void changeUser(Activity activity, String userID, String instance, boolean notificationIntent) {
final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
2018-11-03 19:25:36 +01:00
final NavigationView navigationView = activity.findViewById(R.id.nav_view);
navigationView.getMenu().clear();
MainActivity.lastNotificationId = null;
MainActivity.lastHomeId = null;
navigationView.inflateMenu(R.menu.activity_main_drawer);
2019-08-28 14:43:10 +02:00
hideMenuItem(activity, navigationView.getMenu());
2019-01-03 11:19:45 +01:00
SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
2019-09-06 17:55:14 +02:00
Account account = new AccountDAO(activity, db).getUniqAccount(userID, instance);
2017-07-16 17:09:35 +02:00
//Can happen when an account has been deleted and there is a click on an old notification
2019-09-06 17:55:14 +02:00
if (account == null)
2017-07-16 17:09:35 +02:00
return;
2018-11-04 10:01:16 +01:00
String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);
2019-09-06 17:55:14 +02:00
if (!account.getToken().equals(token)) {
2018-11-04 10:01:16 +01:00
FragmentManager fm = activity.getFragmentManager();
2019-09-06 17:55:14 +02:00
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
2018-11-04 10:01:16 +01:00
fm.popBackStack();
}
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, account.getToken());
editor.putString(Helper.PREF_KEY_ID, account.getId());
editor.putString(Helper.PREF_INSTANCE, account.getInstance().trim());
editor.putBoolean(Helper.PREF_IS_MODERATOR, account.isModerator());
editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, account.isAdmin());
2018-11-24 18:56:12 +01:00
editor.commit();
2018-12-22 16:03:27 +01:00
Intent changeAccount = new Intent(activity, MainActivity.class);
changeAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2019-09-06 17:55:14 +02:00
if (notificationIntent)
2019-01-10 17:56:19 +01:00
changeAccount.putExtra(INTENT_ACTION, NOTIFICATION_INTENT);
2018-12-22 16:03:27 +01:00
activity.startActivity(changeAccount);
2019-09-25 15:44:52 +02:00
}
2018-12-22 16:03:27 +01:00
2018-11-03 19:25:36 +01:00
2019-09-25 15:44:52 +02:00
public static int getNotificationIcon(Context context){
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String logo = sharedpreferences.getString(Helper.LOGO_LAUNCHER, "bubbles");
switch (logo) {
case "bubbles":
return R.drawable.ic_plain_bubbles;
case "fediverse":
return R.drawable.ic_plain_fediverse;
case "hero":
return R.drawable.ic_plain_hero;
case "atom":
return R.drawable.ic_plain_atom;
case "braincrash":
return R.drawable.ic_plain_crash;
2019-10-09 09:45:06 +02:00
case "mastalab":
return R.drawable.ic_plain_mastalab;
2019-09-25 15:44:52 +02:00
default:
return R.drawable.ic_plain_bubbles;
}
}
2019-09-25 15:44:52 +02:00
public static int getMainLogo(Context context){
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String logo = sharedpreferences.getString(Helper.LOGO_LAUNCHER, "bubbles");
switch (logo) {
case "bubbles":
return R.drawable.fedilab_logo_bubbles;
case "fediverse":
return R.drawable.fedilab_logo_fediverse;
case "hero":
return R.drawable.fedilab_logo_hero;
case "atom":
return R.drawable.fedilab_logo_atom;
case "braincrash":
return R.drawable.fedilab_logo_crash;
2019-10-09 09:45:06 +02:00
case "mastalab":
return R.drawable.fedilab_logo_mastalab;
2019-09-25 15:44:52 +02:00
default:
return R.drawable.fedilab_logo_bubbles;
}
}
2017-10-27 14:19:13 +02:00
@SuppressWarnings("SameParameterValue")
2017-10-27 16:00:54 +02:00
private static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int roundPixelSize) {
2018-09-07 07:58:20 +02:00
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565);
2017-09-23 18:27:45 +02:00
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
2017-09-27 17:52:23 +02:00
canvas.drawRoundRect(rectF, (float) roundPixelSize, (float) roundPixelSize, paint);
2017-09-23 18:27:45 +02:00
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
2019-07-24 17:48:24 +02:00
public static <K, V> Map<K, V> sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator<Object>() {
@SuppressWarnings("unchecked")
public int compare(Object o2, Object o1) {
return ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()).compareTo(((Map.Entry<K, V>) (o2)).getValue());
}
});
Map<K, V> result = new LinkedHashMap<>();
2019-09-06 17:55:14 +02:00
for (Iterator<Map.Entry<K, V>> it = list.iterator(); it.hasNext(); ) {
2019-07-24 17:48:24 +02:00
Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
}
2017-09-23 14:14:15 +02:00
/**
* Load the profile picture at the place of hamburger icon
2019-09-06 17:55:14 +02:00
*
2017-09-23 14:14:15 +02:00
* @param activity Activity The current activity
2019-09-06 17:55:14 +02:00
* @param account Account for the profile picture
2017-09-23 14:14:15 +02:00
*/
2019-09-06 17:55:14 +02:00
public static void loadPictureIcon(final Activity activity, Account account, final ImageView imageView) {
loadGiF(activity, account.getAvatar(), imageView);
2017-09-23 14:14:15 +02:00
}
2019-09-06 17:55:14 +02:00
public static SpannableString makeMentionsClick(final Context context, List<Mention> mentions) {
String cw_mention = "";
2019-09-06 17:55:14 +02:00
if (mentions == null)
2019-03-24 19:49:17 +01:00
return new SpannableString(cw_mention);
2019-09-06 17:55:14 +02:00
for (Mention mention : mentions) {
cw_mention = String.format("@%s %s", mention.getUsername(), cw_mention);
}
SpannableString spannableString = new SpannableString(cw_mention);
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
for (final Mention mention : mentions) {
String targetedAccount = "@" + mention.getUsername();
if (spannableString.toString().contains(targetedAccount)) {
//Accounts can be mentioned several times so we have to loop
2019-09-06 17:55:14 +02:00
for (int startPosition = -1; (startPosition = spannableString.toString().indexOf(targetedAccount, startPosition + 1)) != -1; startPosition++) {
int endPosition = startPosition + targetedAccount.length();
spannableString.setSpan(new ClickableSpan() {
2019-09-06 17:55:14 +02:00
@Override
public void onClick(@NotNull View textView) {
Intent intent = new Intent(context, ShowAccountActivity.class);
Bundle b = new Bundle();
b.putString("accountId", mention.getId());
intent.putExtras(b);
context.startActivity(intent);
}
@Override
public void updateDrawState(@NotNull TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
if (theme == THEME_DARK)
ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot));
else if (theme == THEME_BLACK)
ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot));
else if (theme == THEME_LIGHT)
ds.setColor(ContextCompat.getColor(context, R.color.mastodonC4));
}
},
startPosition, endPosition,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
}
return spannableString;
}
/**
* Update the header with the new selected account
2019-09-06 17:55:14 +02:00
*
* @param activity Activity
* @param account Account - new account in use
* @param headerLayout View - the menu header
*/
2019-09-06 17:55:14 +02:00
public static void updateHeaderAccountInfo(Activity activity, final Account account, final View headerLayout) {
2017-10-27 14:19:13 +02:00
ImageView profilePicture = headerLayout.findViewById(R.id.profilePicture);
TextView username = headerLayout.findViewById(R.id.username);
TextView displayedName = headerLayout.findViewById(R.id.displayedName);
2018-11-04 16:00:44 +01:00
LinearLayout more_option_container = headerLayout.findViewById(R.id.more_option_container);
2018-12-22 16:43:16 +01:00
LinearLayout more_account_container = headerLayout.findViewById(R.id.more_account_container);
2018-11-04 16:00:44 +01:00
SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
ImageView icon = new ImageView(activity);
2019-09-06 17:55:14 +02:00
FloatingActionButton.LayoutParams layoutparmans = new FloatingActionButton.LayoutParams((int) Helper.convertDpToPixel(35, activity), (int) Helper.convertDpToPixel(35, activity));
FloatingActionButton.LayoutParams layoutparmanImg = new FloatingActionButton.LayoutParams((int) Helper.convertDpToPixel(25, activity), (int) Helper.convertDpToPixel(25, activity));
2018-11-04 16:00:44 +01:00
MenuFloating actionButton = null;
2019-09-06 17:55:14 +02:00
if (theme == THEME_LIGHT) {
2018-11-04 16:00:44 +01:00
icon.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush));
actionButton = new MenuFloating.Builder(activity)
.setContentView(icon, layoutparmanImg)
2019-09-06 17:55:14 +02:00
.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular))
2018-11-04 16:00:44 +01:00
.setLayoutParams(layoutparmans)
.setTag("THEME")
.intoView(more_option_container)
.build();
2019-09-06 17:55:14 +02:00
} else if (theme == THEME_DARK) {
2018-11-04 16:00:44 +01:00
icon.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush_white));
actionButton = new MenuFloating.Builder(activity)
.setContentView(icon, layoutparmanImg)
2019-09-06 17:55:14 +02:00
.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_dark))
2018-11-04 16:00:44 +01:00
.setLayoutParams(layoutparmans)
.setTag("THEME")
.intoView(more_option_container)
.build();
2019-09-06 17:55:14 +02:00
} else if (theme == THEME_BLACK) {
2018-11-04 16:00:44 +01:00
icon.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush_white));
actionButton = new MenuFloating.Builder(activity)
.setContentView(icon, layoutparmanImg)
2019-09-06 17:55:14 +02:00
.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_black))
2018-11-04 16:00:44 +01:00
.setLayoutParams(layoutparmans)
.setTag("THEME")
.intoView(more_option_container)
.build();
}
SubActionButton.Builder itemBuilder = new SubActionButton.Builder(activity);
// repeat many times:
ImageView itemIconLight = new ImageView(activity);
itemIconLight.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush));
SubActionButton buttonLight = itemBuilder
2019-09-06 17:55:14 +02:00
.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular))
2018-11-04 16:00:44 +01:00
.setContentView(itemIconLight).build();
ImageView itemDark = new ImageView(activity);
itemDark.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush_white));
SubActionButton buttonDark = itemBuilder
2019-09-06 17:55:14 +02:00
.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_dark))
2018-11-04 16:00:44 +01:00
.setContentView(itemDark).build();
ImageView itemBlack = new ImageView(activity);
itemBlack.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_brush_white));
SubActionButton buttonBlack = itemBuilder
2019-09-06 17:55:14 +02:00
.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_black))
2018-11-04 16:00:44 +01:00
.setContentView(itemBlack).build();
FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(activity)
.addSubActionView(buttonLight)
.addSubActionView(buttonDark)
.addSubActionView(buttonBlack)
.attachTo(actionButton)
.setStartAngle(0)
.setEndAngle(90)
.build();
2019-09-06 17:55:14 +02:00
if (actionButton != null) {
2018-11-04 16:28:32 +01:00
actionButton.setFocusableInTouchMode(true);
actionButton.setFocusable(true);
actionButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
2019-09-06 17:55:14 +02:00
if (actionMenu.isOpen())
actionMenu.close(true);
else
actionMenu.open(true);
return false;
}
});
2018-11-04 16:28:32 +01:00
actionButton.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
2018-11-05 18:01:17 +01:00
try {
actionMenu.close(true);
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
}
2018-11-05 18:01:17 +01:00
2018-11-04 16:28:32 +01:00
}
});
}
2018-11-04 16:00:44 +01:00
buttonLight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
actionMenu.close(true);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(Helper.SET_THEME, Helper.THEME_LIGHT);
editor.apply();
activity.recreate();
}
});
buttonDark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
actionMenu.close(true);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(Helper.SET_THEME, Helper.THEME_DARK);
editor.apply();
activity.recreate();
}
});
buttonBlack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
actionMenu.close(true);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(Helper.SET_THEME, Helper.THEME_BLACK);
editor.apply();
activity.recreate();
}
});
2018-12-22 16:43:16 +01:00
SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
final List<Account> accounts = new AccountDAO(activity, db).getAllAccount();
2019-09-06 17:55:14 +02:00
if (activity.isFinishing())
return;
2019-09-06 17:55:14 +02:00
if (accounts != null && accounts.size() > 1) {
2018-12-22 16:43:16 +01:00
FloatingActionButton.LayoutParams layoutparmansAcc = new FloatingActionButton.LayoutParams((int) Helper.convertDpToPixel(37, activity), (int) Helper.convertDpToPixel(37, activity));
2018-12-22 17:59:39 +01:00
FloatingActionButton.LayoutParams layoutparmanImgAcc = new FloatingActionButton.LayoutParams((int) Helper.convertDpToPixel(35, activity), (int) Helper.convertDpToPixel(35, activity));
2018-12-22 16:43:16 +01:00
MenuFloating actionButtonAcc = null;
SharedPreferences mSharedPreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String currrentUserId = mSharedPreferences.getString(Helper.PREF_KEY_ID, null);
2019-09-06 17:55:14 +02:00
for (final Account accountChoice : accounts) {
if (!accountChoice.getAvatar().startsWith("http"))
accountChoice.setAvatar("https://" + accountChoice.getInstance() + accountChoice.getAvatar());
if (currrentUserId != null && (!currrentUserId.equals(accountChoice.getId()) || !getLiveInstance(activity).equals(accountChoice.getInstance()))) {
2018-12-22 16:43:16 +01:00
icon = new ImageView(activity);
ImageView finalIcon = icon;
Glide.with(activity.getApplicationContext())
2018-12-22 16:43:16 +01:00
.asBitmap()
2018-12-22 17:59:39 +01:00
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(270)))
2019-09-06 17:55:14 +02:00
.listener(new RequestListener<Bitmap>() {
2018-12-22 17:59:39 +01:00
@Override
public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
2019-09-06 17:55:14 +02:00
2018-12-22 17:59:39 +01:00
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
2019-09-06 17:55:14 +02:00
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)
2019-01-05 14:21:49 +01:00
finalIcon.setImageResource(R.drawable.missing);
2019-09-06 17:55:14 +02:00
else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE)
2019-01-05 14:21:49 +01:00
finalIcon.setImageResource(R.drawable.missing_peertube);
2018-12-22 17:59:39 +01:00
return false;
}
})
2018-12-22 16:43:16 +01:00
.load(accountChoice.getAvatar())
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
finalIcon.setImageBitmap(resource);
}
});
MenuFloating.Builder actionButtonAccBuild = new MenuFloating.Builder(activity);
2019-09-06 17:55:14 +02:00
if (theme == THEME_LIGHT) {
actionButtonAccBuild.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular));
} else if (theme == THEME_DARK) {
actionButtonAccBuild.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_dark));
} else if (theme == THEME_BLACK) {
actionButtonAccBuild.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_black));
2018-12-22 16:43:16 +01:00
}
actionButtonAcc = actionButtonAccBuild
2018-12-22 17:59:39 +01:00
.setContentView(finalIcon, layoutparmanImgAcc)
.setLayoutParams(layoutparmansAcc)
2018-12-22 16:43:16 +01:00
.setTag("ACCOUNT")
.intoView(more_account_container)
.build();
break;
}
}
FloatingActionMenu.Builder actionMenuAccBuilder = new FloatingActionMenu.Builder(activity);
2019-09-06 17:55:14 +02:00
for (final Account accountChoice : accounts) {
2018-12-22 16:43:16 +01:00
if (currrentUserId != null && !currrentUserId.equals(accountChoice.getId())) {
SubActionButton.Builder itemBuilderAcc = new SubActionButton.Builder(activity);
2019-09-06 17:55:14 +02:00
if (!accountChoice.getAvatar().startsWith("http"))
accountChoice.setAvatar("https://" + accountChoice.getInstance() + accountChoice.getAvatar());
2018-12-22 16:43:16 +01:00
ImageView itemIconAcc = new ImageView(activity);
Glide.with(activity.getApplicationContext())
2018-12-22 16:43:16 +01:00
.asBitmap()
2018-12-22 17:59:39 +01:00
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(270)))
2018-12-22 16:43:16 +01:00
.load(accountChoice.getAvatar())
2019-09-06 17:55:14 +02:00
.listener(new RequestListener<Bitmap>() {
2018-12-22 17:59:39 +01:00
@Override
public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
2019-09-06 17:55:14 +02:00
2018-12-22 17:59:39 +01:00
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
2019-09-06 17:55:14 +02:00
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA)
2019-01-05 14:21:49 +01:00
itemIconAcc.setImageResource(R.drawable.missing);
2019-09-06 17:55:14 +02:00
else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE)
2019-01-05 14:21:49 +01:00
itemIconAcc.setImageResource(R.drawable.missing_peertube);
2018-12-22 17:59:39 +01:00
return false;
}
})
2018-12-22 16:43:16 +01:00
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
itemIconAcc.setImageBitmap(resource);
}
});
2018-12-22 17:59:39 +01:00
2019-09-06 17:55:14 +02:00
if (accounts.size() > 2) {
if (accountChoice.getSocial() != null && accountChoice.getSocial().equals("PEERTUBE"))
itemBuilderAcc.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_peertube));
else
itemBuilderAcc.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.circular_mastodon));
SubActionButton subActionButtonAcc = itemBuilderAcc.setContentView(itemIconAcc, layoutparmanImgAcc)
2018-12-22 17:59:39 +01:00
.setLayoutParams(layoutparmansAcc)
.build();
subActionButtonAcc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
2019-09-06 17:55:14 +02:00
if (!accountChoice.getToken().equals("null")) {
2019-01-29 14:08:02 +01:00
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, accountChoice.getToken());
editor.putString(Helper.PREF_KEY_ID, accountChoice.getId());
editor.putString(Helper.PREF_INSTANCE, accountChoice.getInstance().trim());
editor.putBoolean(Helper.PREF_IS_MODERATOR, accountChoice.isModerator());
editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, accountChoice.isAdmin());
editor.commit();
if (accountChoice.getSocial() != null && accountChoice.getSocial().equals("PEERTUBE"))
2019-08-20 11:30:49 +02:00
Toasty.info(activity.getApplicationContext(), activity.getString(R.string.toast_account_changed, "@" + accountChoice.getAcct()), Toast.LENGTH_LONG).show();
2019-01-29 14:08:02 +01:00
else
2019-10-21 18:19:38 +02:00
Toasty.info(activity, activity.getString(R.string.toast_account_changed, "@" + accountChoice.getUsername() + "@" + accountChoice.getInstance()), Toast.LENGTH_LONG).show();
2019-01-29 14:08:02 +01:00
Intent changeAccount = new Intent(activity, MainActivity.class);
changeAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(changeAccount);
2019-09-06 17:55:14 +02:00
} else { //The account was logged out
2019-01-29 14:08:02 +01:00
Intent intent = new Intent(activity, LoginActivity.class);
intent.putExtra("instance", accountChoice.getInstance());
2019-01-30 10:01:26 +01:00
intent.putExtra("social", accountChoice.getSocial());
2019-01-29 14:08:02 +01:00
activity.startActivity(intent);
}
2018-12-22 17:59:39 +01:00
}
});
actionMenuAccBuilder.addSubActionView(subActionButtonAcc);
}
2018-12-22 16:43:16 +01:00
}
}
2019-09-06 17:55:14 +02:00
if (actionButtonAcc != null) {
2019-01-23 19:23:26 +01:00
FloatingActionMenu actionMenuAcc = actionMenuAccBuilder.attachTo(actionButtonAcc)
.setStartAngle(0)
.setEndAngle(135)
.build();
2019-09-06 17:55:14 +02:00
if (accounts.size() > 2) {
2018-12-22 17:59:39 +01:00
actionButtonAcc.setFocusableInTouchMode(true);
actionButtonAcc.setFocusable(true);
actionButtonAcc.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
2019-09-06 17:55:14 +02:00
if (actionMenuAcc.isOpen())
2018-12-22 17:59:39 +01:00
actionMenuAcc.close(true);
else
actionMenuAcc.open(true);
return false;
}
});
actionButtonAcc.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
try {
actionMenuAcc.close(true);
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
}
2018-12-22 17:59:39 +01:00
}
});
2019-09-06 17:55:14 +02:00
} else {
2018-12-22 17:59:39 +01:00
actionButtonAcc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
2019-09-06 17:55:14 +02:00
for (final Account accountChoice : accounts) {
2018-12-22 17:59:39 +01:00
if (!currrentUserId.equals(accountChoice.getId())) {
2019-09-06 17:55:14 +02:00
if (!accountChoice.getToken().equals("null")) {
2019-01-29 14:08:02 +01:00
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, accountChoice.getToken());
editor.putString(Helper.PREF_KEY_ID, accountChoice.getId());
editor.putString(Helper.PREF_INSTANCE, accountChoice.getInstance().trim());
editor.putBoolean(Helper.PREF_IS_MODERATOR, accountChoice.isModerator());
editor.putBoolean(Helper.PREF_IS_ADMINISTRATOR, accountChoice.isAdmin());
editor.commit();
Intent changeAccount = new Intent(activity, MainActivity.class);
changeAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(changeAccount);
2019-09-06 17:55:14 +02:00
} else { //The account was logged out
2019-01-29 14:08:02 +01:00
Intent intent = new Intent(activity, LoginActivity.class);
intent.putExtra("instance", accountChoice.getInstance());
2019-01-30 10:01:26 +01:00
intent.putExtra("social", accountChoice.getSocial());
2019-01-29 14:08:02 +01:00
activity.startActivity(intent);
}
2018-12-22 17:59:39 +01:00
}
}
}
});
}
2018-12-22 16:43:16 +01:00
}
}
2019-09-06 17:55:14 +02:00
if (account == null) {
Helper.logout(activity);
Intent myIntent = new Intent(activity, LoginActivity.class);
2019-09-06 17:55:14 +02:00
Toasty.error(activity.getApplicationContext(), activity.getString(R.string.toast_error), Toast.LENGTH_LONG).show();
activity.startActivity(myIntent);
activity.finish(); //User is logged out to get a new token
2019-09-06 17:55:14 +02:00
} else {
Account.makeAccountNameEmoji(activity, ((BaseMainActivity) activity), account);
username.setText(String.format("@%s", account.getUsername() + "@" + account.getInstance()));
2018-09-16 15:05:33 +02:00
displayedName.setText(account.getdisplayNameSpan(), TextView.BufferType.SPANNABLE);
2019-08-02 13:41:08 +02:00
loadGiF(activity, account.getAvatar(), profilePicture);
String urlHeader = account.getHeader();
2019-09-06 17:55:14 +02:00
if (urlHeader.startsWith("/")) {
2018-01-24 15:56:33 +01:00
urlHeader = Helper.getLiveInstanceWithProtocol(activity) + account.getHeader();
}
ImageView owner_accounts = headerLayout.findViewById(R.id.owner_accounts);
ImageView header_option_info = headerLayout.findViewById(R.id.header_option_info);
ImageView header_option_menu = headerLayout.findViewById(R.id.header_option_menu);
2019-09-06 17:55:14 +02:00
if (theme == Helper.THEME_DARK || theme == Helper.THEME_BLACK) {
changeDrawableColor(activity, owner_accounts, R.color.dark_text);
changeDrawableColor(activity, header_option_info, R.color.dark_text);
changeDrawableColor(activity, header_option_menu, R.color.dark_text);
} else {
changeDrawableColor(activity, owner_accounts, R.color.light_black);
changeDrawableColor(activity, header_option_info, R.color.light_black);
changeDrawableColor(activity, header_option_menu, R.color.light_black);
}
2017-12-02 11:02:25 +01:00
if (!urlHeader.contains("missing.png")) {
2019-08-19 11:02:22 +02:00
ImageView backgroundImage = headerLayout.findViewById(R.id.back_ground_image);
Glide.with(activity.getApplicationContext())
2017-12-02 11:02:25 +01:00
.asBitmap()
.load(urlHeader)
.into(new SimpleTarget<Bitmap>() {
@Override
2018-01-26 18:07:26 +01:00
public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
2019-08-19 11:02:22 +02:00
2018-01-10 10:37:55 +01:00
backgroundImage.setImageBitmap(resource);
2019-09-06 17:55:14 +02:00
if (theme == THEME_LIGHT) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
backgroundImage.setImageAlpha(80);
2019-09-06 17:55:14 +02:00
} else {
backgroundImage.setAlpha(80);
}
2019-09-06 17:55:14 +02:00
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
backgroundImage.setImageAlpha(60);
2019-09-06 17:55:14 +02:00
} else {
backgroundImage.setAlpha(60);
}
2017-12-02 11:02:25 +01:00
}
2017-12-02 11:02:25 +01:00
}
});
}
}
2017-06-11 11:58:46 +02:00
profilePicture.setOnClickListener(null);
profilePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (account != null) {
Intent intent = new Intent(activity, ShowAccountActivity.class);
Bundle b = new Bundle();
2019-09-06 17:55:14 +02:00
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
2019-01-04 17:09:53 +01:00
b.putBoolean("peertubeaccount", true);
b.putString("accountId", account.getAcct());
2019-09-06 17:55:14 +02:00
} else
2019-01-04 17:09:53 +01:00
b.putString("accountId", account.getId());
2017-06-11 11:58:46 +02:00
intent.putExtras(b);
activity.startActivity(intent);
}
}
});
}
2017-06-19 19:20:20 +02:00
/**
* Retrieves the cache size
2019-09-06 17:55:14 +02:00
*
2017-06-19 19:20:20 +02:00
* @param directory File
* @return long value in Mo
*/
public static long cacheSize(File directory) {
long length = 0;
2019-09-06 17:55:14 +02:00
if (directory == null || directory.length() == 0)
2017-06-19 19:20:20 +02:00
return -1;
for (File file : directory.listFiles()) {
2019-09-06 17:55:14 +02:00
if (file.isFile()) {
2017-06-19 19:20:20 +02:00
try {
length += file.length();
2019-07-22 12:27:46 +02:00
} catch (NullPointerException e) {
2017-06-19 19:20:20 +02:00
return -1;
}
2019-09-06 17:55:14 +02:00
} else {
if (!file.getName().equals("databases") && !file.getName().equals("shared_prefs")) {
2019-07-22 12:27:46 +02:00
length += cacheSize(file);
}
}
2017-06-19 19:20:20 +02:00
}
return length;
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (String aChildren : children) {
2018-11-18 13:33:12 +01:00
if (!aChildren.equals("databases") && !aChildren.equals("shared_prefs")) {
boolean success = deleteDir(new File(dir, aChildren));
if (!success) {
return false;
}
2017-06-19 19:20:20 +02:00
}
}
return dir.delete();
2019-09-06 17:55:14 +02:00
} else {
2017-06-19 19:20:20 +02:00
return dir != null && dir.isFile() && dir.delete();
}
}
2017-12-03 14:32:11 +01:00
/***
* Check if the account bio contents urls & tags and fills the content with ClickableSpan
* Click on url => webview or external app
* Click on tag => HashTagActivity
* @param context Context
* @param fullContent String, should be the st
* @return TextView
*/
2018-11-14 18:12:59 +01:00
public static SpannableString clickableElementsDescription(final Context context, String fullContent) {
SpannableString spannableString;
fullContent = Helper.shortnameToUnicode(fullContent, true);
2018-11-14 18:12:59 +01:00
SpannableString spannableStringT = new SpannableString(fullContent);
Pattern aLink = Pattern.compile("(<\\s?a\\s?href=\"https?:\\/\\/([\\da-z\\.-]+\\.[a-z\\.]{2,10})\\/(@[\\/\\w._-]*)\"\\s?[^.]*<\\s?\\/\\s?a\\s?>)");
Matcher matcherALink = aLink.matcher(spannableStringT.toString());
ArrayList<Account> accountsMentionUnknown = new ArrayList<>();
2019-09-06 17:55:14 +02:00
while (matcherALink.find()) {
String acct = matcherALink.group(3).replace("@", "");
2018-11-14 18:12:59 +01:00
String instance = matcherALink.group(2);
Account account = new Account();
account.setAcct(acct);
account.setInstance(instance);
accountsMentionUnknown.add(account);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
2019-01-26 19:18:53 +01:00
spannableString = new SpannableString(Html.fromHtml(spannableStringT.toString(), Html.TO_HTML_PARAGRAPH_LINES_INDIVIDUAL));
else
//noinspection deprecation
2019-01-26 19:18:53 +01:00
spannableString = new SpannableString(Html.fromHtml(spannableStringT.toString()));
2018-11-14 18:12:59 +01:00
URLSpan[] urls = spannableString.getSpans(0, spannableString.length(), URLSpan.class);
2019-09-06 17:55:14 +02:00
for (URLSpan span : urls)
2018-11-14 18:12:59 +01:00
spannableString.removeSpan(span);
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
2018-11-14 18:12:59 +01:00
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
Matcher matcher;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
matcher = Patterns.WEB_URL.matcher(spannableString);
else
matcher = urlPattern.matcher(spannableString);
2019-09-06 17:55:14 +02:00
while (matcher.find()) {
2018-11-14 18:12:59 +01:00
int matchStart = matcher.start(1);
int matchEnd = matcher.end();
final String url = spannableString.toString().substring(matchStart, matchEnd);
2019-01-02 15:22:23 +01:00
2019-09-06 17:55:14 +02:00
if (url.startsWith("http"))
if (matchEnd <= spannableString.toString().length() && matchEnd >= matchStart)
2019-01-02 15:22:23 +01:00
spannableString.setSpan(new ClickableSpan() {
@Override
2019-08-17 14:46:20 +02:00
public void onClick(@NotNull View textView) {
2019-01-02 15:22:23 +01:00
Helper.openBrowser(context, url);
}
2019-09-06 17:55:14 +02:00
2019-01-02 15:22:23 +01:00
@Override
2019-08-17 14:46:20 +02:00
public void updateDrawState(@NotNull TextPaint ds) {
2019-01-02 15:22:23 +01:00
super.updateDrawState(ds);
ds.setUnderlineText(false);
if (theme == THEME_DARK)
ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot));
else if (theme == THEME_BLACK)
ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot));
else if (theme == THEME_LIGHT)
ds.setColor(ContextCompat.getColor(context, R.color.mastodonC4));
}
}, matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
2018-11-14 18:12:59 +01:00
matcher = hashtagPattern.matcher(spannableString);
2019-09-06 17:55:14 +02:00
while (matcher.find()) {
int matchStart = matcher.start(1);
int matchEnd = matcher.end();
final String tag = spannableString.toString().substring(matchStart, matchEnd);
2019-09-06 17:55:14 +02:00
if (matchEnd <= spannableString.toString().length() && matchEnd >= matchStart)
2018-11-14 18:12:59 +01:00
spannableString.setSpan(new ClickableSpan() {
@Override
public void onClick(View textView) {
Intent intent = new Intent(context, HashTagActivity.class);
Bundle b = new Bundle();
b.putString("tag", tag.substring(1));
intent.putExtras(b);
context.startActivity(intent);
}
2019-09-06 17:55:14 +02:00
2018-11-14 18:12:59 +01:00
@Override
2019-08-17 14:46:20 +02:00
public void updateDrawState(@NotNull TextPaint ds) {
2018-11-14 18:12:59 +01:00
super.updateDrawState(ds);
ds.setUnderlineText(false);
if (theme == THEME_DARK)
ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot));
else if (theme == THEME_BLACK)
ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot));
else if (theme == THEME_LIGHT)
ds.setColor(ContextCompat.getColor(context, R.color.mastodonC4));
}
}, matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
2019-09-06 17:55:14 +02:00
if (accountsMentionUnknown.size() > 0) {
for (Account account : accountsMentionUnknown) {
2018-11-14 18:12:59 +01:00
String targetedAccount = "@" + account.getAcct();
if (spannableString.toString().toLowerCase().contains(targetedAccount.toLowerCase())) {
//Accounts can be mentioned several times so we have to loop
2019-09-06 17:55:14 +02:00
for (int startPosition = -1; (startPosition = spannableString.toString().toLowerCase().indexOf(targetedAccount.toLowerCase(), startPosition + 1)) != -1; startPosition++) {
2018-11-14 18:12:59 +01:00
int endPosition = startPosition + targetedAccount.length();
2019-09-06 17:55:14 +02:00
if (endPosition <= spannableString.toString().length() && endPosition >= startPosition)
2018-11-14 18:12:59 +01:00
spannableString.setSpan(new ClickableSpan() {
2019-09-06 17:55:14 +02:00
@Override
public void onClick(@NotNull View textView) {
CrossActions.doCrossProfile(context, account);
}
@Override
public void updateDrawState(@NotNull TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
if (theme == THEME_DARK)
ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot));
else if (theme == THEME_BLACK)
ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot));
else if (theme == THEME_LIGHT)
ds.setColor(ContextCompat.getColor(context, R.color.mastodonC4));
}
},
startPosition, endPosition,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
2018-11-14 18:12:59 +01:00
}
}
2019-01-02 15:22:23 +01:00
matcher = android.util.Patterns.EMAIL_ADDRESS.matcher(spannableString);
2019-09-06 17:55:14 +02:00
while (matcher.find()) {
2019-01-02 15:22:23 +01:00
int matchStart = matcher.start(0);
int matchEnd = matcher.end();
final String email = spannableString.toString().substring(matchStart, matchEnd);
2019-09-06 17:55:14 +02:00
if (matchEnd <= spannableString.toString().length() && matchEnd >= matchStart) {
2019-01-02 15:22:23 +01:00
urls = spannableString.getSpans(matchStart, matchEnd, URLSpan.class);
2019-09-06 17:55:14 +02:00
for (URLSpan span : urls)
2019-01-02 15:22:23 +01:00
spannableString.removeSpan(span);
spannableString.setSpan(new ClickableSpan() {
@Override
2019-08-17 14:46:20 +02:00
public void onClick(@NotNull View textView) {
2019-01-02 15:22:23 +01:00
try {
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{email});
context.startActivity(Intent.createChooser(emailIntent, context.getString(R.string.send_email)));
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2019-01-02 15:22:23 +01:00
Toasty.error(context, context.getString(R.string.toast_no_apps), Toast.LENGTH_LONG).show();
}
}
2019-09-06 17:55:14 +02:00
2019-01-02 15:22:23 +01:00
@Override
2019-08-17 14:46:20 +02:00
public void updateDrawState(@NotNull TextPaint ds) {
2019-01-02 15:22:23 +01:00
super.updateDrawState(ds);
ds.setUnderlineText(false);
if (theme == THEME_DARK)
ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot));
else if (theme == THEME_BLACK)
ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot));
else if (theme == THEME_LIGHT)
ds.setColor(ContextCompat.getColor(context, R.color.light_link_toot));
}
}, matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
matcher = Helper.xmppPattern.matcher(spannableString);
2019-09-06 17:55:14 +02:00
while (matcher.find()) {
2019-01-02 15:22:23 +01:00
int matchStart = matcher.start(0);
int matchEnd = matcher.end();
final String url = spannableString.toString().substring(matchStart, matchEnd);
2019-09-06 17:55:14 +02:00
if (matchEnd <= spannableString.toString().length() && matchEnd >= matchStart) {
2019-01-02 15:22:23 +01:00
urls = spannableString.getSpans(matchStart, matchEnd, URLSpan.class);
2019-09-06 17:55:14 +02:00
for (URLSpan span : urls)
2019-01-02 15:22:23 +01:00
spannableString.removeSpan(span);
spannableString.setSpan(new ClickableSpan() {
@Override
2019-08-17 14:46:20 +02:00
public void onClick(@NotNull View textView) {
2019-01-02 15:22:23 +01:00
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2019-01-02 15:22:23 +01:00
Toasty.error(context, context.getString(R.string.toast_no_apps), Toast.LENGTH_LONG).show();
}
}
2019-09-06 17:55:14 +02:00
2019-01-02 15:22:23 +01:00
@Override
2019-08-17 14:46:20 +02:00
public void updateDrawState(@NotNull TextPaint ds) {
2019-01-02 15:22:23 +01:00
super.updateDrawState(ds);
ds.setUnderlineText(false);
if (theme == THEME_DARK)
ds.setColor(ContextCompat.getColor(context, R.color.dark_link_toot));
else if (theme == THEME_BLACK)
ds.setColor(ContextCompat.getColor(context, R.color.black_link_toot));
else if (theme == THEME_LIGHT)
ds.setColor(ContextCompat.getColor(context, R.color.light_link_toot));
}
}, matchStart, matchEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
2018-11-14 18:12:59 +01:00
2019-01-02 15:22:23 +01:00
}
2017-07-31 19:29:14 +02:00
return spannableString;
}
2019-10-14 18:54:04 +02:00
public static CustomWebview initializeWebview(Activity activity, int webviewId) {
2019-10-14 18:54:04 +02:00
CustomWebview webView = activity.findViewById(webviewId);
final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean javascript = sharedpreferences.getBoolean(Helper.SET_JAVASCRIPT, true);
webView.getSettings().setJavaScriptEnabled(javascript);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setSupportMultipleWindows(false);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
//noinspection deprecation
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
webView.getSettings().setMediaPlaybackRequiresUserGesture(true);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
boolean cookies = sharedpreferences.getBoolean(Helper.SET_COOKIES, false);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptThirdPartyCookies(webView, cookies);
}
2017-07-01 15:24:28 +02:00
webView.setBackgroundColor(Color.TRANSPARENT);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
return webView;
}
public static String md5(final String s) {
final String MD5 = "MD5";
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest
.getInstance(MD5);
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuilder hexString = new StringBuilder();
for (byte aMessageDigest : messageDigest) {
2017-10-27 16:00:54 +02:00
StringBuilder h = new StringBuilder(Integer.toHexString(0xFF & aMessageDigest));
while (h.length() < 2)
2017-10-27 16:00:54 +02:00
h.insert(0, "0");
hexString.append(h);
}
return hexString.toString();
2019-09-06 17:55:14 +02:00
} catch (NoSuchAlgorithmException ignored) {
}
return "";
}
2017-07-01 15:24:28 +02:00
/**
* change color of a drawable
2019-09-06 17:55:14 +02:00
*
* @param drawable int the drawable
2017-07-01 15:24:28 +02:00
* @param hexaColor example 0xffff00
*/
2019-09-06 17:55:14 +02:00
public static Drawable changeDrawableColor(Context context, int drawable, int hexaColor) {
2017-07-01 15:24:28 +02:00
Drawable mDrawable = ContextCompat.getDrawable(context, drawable);
2017-10-28 17:15:06 +02:00
int color = Color.parseColor(context.getString(hexaColor));
2017-12-28 17:56:03 +01:00
assert mDrawable != null;
2017-10-28 17:15:06 +02:00
mDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
2017-10-28 14:32:18 +02:00
DrawableCompat.setTint(mDrawable, ContextCompat.getColor(context, hexaColor));
2017-07-01 15:24:28 +02:00
return mDrawable;
}
2019-09-06 17:55:14 +02:00
2017-11-02 14:06:59 +01:00
/**
* change color of a drawable
2019-09-06 17:55:14 +02:00
*
2017-11-02 14:06:59 +01:00
* @param imageView int the ImageView
* @param hexaColor example 0xffff00
*/
2019-09-06 17:55:14 +02:00
public static void changeDrawableColor(Context context, ImageView imageView, int hexaColor) {
if (imageView == null)
2019-06-08 12:49:29 +02:00
return;
2017-11-02 14:06:59 +01:00
imageView.setColorFilter(context.getResources().getColor(hexaColor));
}
2017-11-02 14:06:59 +01:00
/**
* change color of a drawable
2019-09-06 17:55:14 +02:00
*
2017-11-02 14:06:59 +01:00
* @param imageButton int the ImageButton
2019-09-06 17:55:14 +02:00
* @param hexaColor example 0xffff00
2017-11-02 14:06:59 +01:00
*/
2019-09-06 17:55:14 +02:00
public static void changeDrawableColor(Context context, ImageButton imageButton, int hexaColor) {
if (imageButton == null)
2019-06-08 12:49:29 +02:00
return;
2017-11-02 14:06:59 +01:00
imageButton.setColorFilter(context.getResources().getColor(hexaColor));
}
/**
* change color of a drawable
2019-09-06 17:55:14 +02:00
*
* @param button int the button
* @param hexaColor example 0xffff00
*/
2019-09-06 17:55:14 +02:00
public static void changeButtonTextColor(Context context, Button button, int hexaColor) {
if (button == null)
2019-06-08 12:49:29 +02:00
return;
button.setTextColor(context.getResources().getColor(hexaColor));
}
2019-09-06 17:55:14 +02:00
/**
* Returns the current locale of the device
2019-09-06 17:55:14 +02:00
*
* @param context Context
* @return String locale
*/
public static String currentLocale(Context context) {
String locale;
Locale current;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
current = context.getResources().getConfiguration().getLocales().get(0);
} else {
//noinspection deprecation
current = context.getResources().getConfiguration().locale;
}
locale = current.toString();
locale = locale.split("_")[0];
return locale;
}
2017-07-10 18:43:36 +02:00
/**
* Compare date with these in shared pref.
2019-09-06 17:55:14 +02:00
*
* @param context Context
* @param newDate String
2017-07-10 18:43:36 +02:00
* @param shouldBeGreater boolean if date passed as a parameter should be greater
* @return boolean
*/
2019-09-06 17:55:14 +02:00
public static boolean compareDate(Context context, String newDate, boolean shouldBeGreater) {
2017-07-10 18:43:36 +02:00
String dateRef;
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
if (shouldBeGreater) {
dateRef = sharedpreferences.getString(Helper.SET_TIME_FROM, "07:00");
2019-09-06 17:55:14 +02:00
} else {
2017-07-10 18:43:36 +02:00
dateRef = sharedpreferences.getString(Helper.SET_TIME_TO, "22:00");
}
2019-09-06 17:55:14 +02:00
try {
2017-07-10 18:43:36 +02:00
Locale userLocale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
userLocale = context.getResources().getConfiguration().getLocales().get(0);
} else {
userLocale = context.getResources().getConfiguration().locale;
}
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", userLocale);
Date newDateD = formatter.parse(newDate);
Date dateRefD = formatter.parse(dateRef);
if (shouldBeGreater) {
return (newDateD.after(dateRefD));
2019-09-06 17:55:14 +02:00
} else {
2017-07-10 18:43:36 +02:00
return (newDateD.before(dateRefD));
}
} catch (java.text.ParseException e) {
return false;
}
}
/**
* Tells if the the service can notify depending of the current hour and minutes
2019-09-06 17:55:14 +02:00
*
2017-07-10 18:43:36 +02:00
* @param context Context
* @return boolean
*/
2019-09-06 17:55:14 +02:00
public static boolean canNotify(Context context) {
2017-07-10 18:43:36 +02:00
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean notify = sharedpreferences.getBoolean(Helper.SET_NOTIFY, true);
2019-09-06 17:55:14 +02:00
if (!notify)
return false;
2018-09-19 10:13:28 +02:00
boolean enable_time_slot = sharedpreferences.getBoolean(Helper.SET_ENABLE_TIME_SLOT, true);
2019-09-06 17:55:14 +02:00
if (!enable_time_slot)
2018-09-19 10:13:28 +02:00
return true;
2017-07-10 18:43:36 +02:00
String dateIni = sharedpreferences.getString(Helper.SET_TIME_FROM, "07:00");
String dateEnd = sharedpreferences.getString(Helper.SET_TIME_TO, "22:00");
2018-12-16 16:59:40 +01:00
int notification = sharedpreferences.getInt(Helper.SET_NOTIFICATION_ACTION, Helper.ACTION_ACTIVE);
2017-07-10 18:43:36 +02:00
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
2019-09-06 17:55:14 +02:00
String hourS = String.valueOf(hour).length() == 1 ? "0" + String.valueOf(hour) : String.valueOf(hour);
String minuteS = String.valueOf(minute).length() == 1 ? "0" + String.valueOf(minute) : String.valueOf(minute);
2017-07-10 18:43:36 +02:00
String currentDate = hourS + ":" + minuteS;
2019-09-06 17:55:14 +02:00
try {
2017-07-10 18:43:36 +02:00
Locale userLocale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
userLocale = context.getResources().getConfiguration().getLocales().get(0);
} else {
userLocale = context.getResources().getConfiguration().locale;
}
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", userLocale);
Date dateIniD = formatter.parse(dateIni);
Date dateEndD = formatter.parse(dateEnd);
Date currentDateD = formatter.parse(currentDate);
2018-12-16 16:59:40 +01:00
boolean canNotify = false;
2019-09-06 17:55:14 +02:00
if (currentDateD.before(dateEndD) && currentDateD.after(dateIniD) && notification == Helper.ACTION_ACTIVE)
2018-12-16 16:59:40 +01:00
canNotify = true;
2019-09-06 17:55:14 +02:00
else if (currentDateD.after(dateEndD) && currentDateD.before(dateIniD) && notification == Helper.ACTION_SILENT)
2018-12-16 16:59:40 +01:00
canNotify = true;
return canNotify;
2017-07-10 18:43:36 +02:00
} catch (java.text.ParseException e) {
return true;
}
}
2017-07-15 14:59:09 +02:00
2018-09-16 15:05:33 +02:00
2019-04-21 12:09:30 +02:00
/**
* Unserialized a
2019-09-06 17:55:14 +02:00
*
2019-04-21 12:09:30 +02:00
* @param serializedListTimeline String serialized List
* @return List
*/
2019-09-06 17:55:14 +02:00
public static app.fedilab.android.client.Entities.List restoreListtimelineFromString(String serializedListTimeline) {
2019-04-21 12:09:30 +02:00
Gson gson = new Gson();
try {
2019-05-18 11:10:30 +02:00
return gson.fromJson(serializedListTimeline, app.fedilab.android.client.Entities.List.class);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2019-04-21 12:09:30 +02:00
return null;
}
}
/**
* Serialized a List class
2019-09-06 17:55:14 +02:00
*
2019-04-21 12:09:30 +02:00
* @param listTimeline List to serialize
* @return String serialized List
*/
2019-09-06 17:55:14 +02:00
public static String listTimelineToStringStorage(app.fedilab.android.client.Entities.List listTimeline) {
2019-04-21 12:09:30 +02:00
Gson gson = new Gson();
try {
return gson.toJson(listTimeline);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2019-04-21 12:09:30 +02:00
return null;
}
}
2019-04-21 10:22:07 +02:00
/**
* Unserialized a TagTimeline
2019-09-06 17:55:14 +02:00
*
2019-04-21 10:22:07 +02:00
* @param serializedTagTimeline String serialized TagTimeline
* @return TagTimeline
*/
2019-09-06 17:55:14 +02:00
public static TagTimeline restoreTagTimelineFromString(String serializedTagTimeline) {
2019-04-21 10:22:07 +02:00
Gson gson = new Gson();
try {
return gson.fromJson(serializedTagTimeline, TagTimeline.class);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2019-04-21 10:22:07 +02:00
return null;
}
}
/**
* Serialized a TagTimeline class
2019-09-06 17:55:14 +02:00
*
2019-04-21 10:22:07 +02:00
* @param tagTimeline TagTimeline to serialize
* @return String serialized TagTimeline
*/
2019-09-06 17:55:14 +02:00
public static String tagTimelineToStringStorage(TagTimeline tagTimeline) {
2019-04-21 10:22:07 +02:00
Gson gson = new Gson();
try {
return gson.toJson(tagTimeline);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2019-04-21 10:22:07 +02:00
return null;
}
}
/**
* Unserialized a RemoteInstance
2019-09-06 17:55:14 +02:00
*
2019-04-21 10:22:07 +02:00
* @param serializedRemoteInstance String serialized RemoteInstance
* @return RemoteInstance
*/
2019-09-06 17:55:14 +02:00
public static RemoteInstance restoreRemoteInstanceFromString(String serializedRemoteInstance) {
2019-04-21 10:22:07 +02:00
Gson gson = new Gson();
try {
return gson.fromJson(serializedRemoteInstance, RemoteInstance.class);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2019-04-21 10:22:07 +02:00
return null;
}
}
/**
* Serialized a RemoteInstance class
2019-09-06 17:55:14 +02:00
*
2019-04-21 10:22:07 +02:00
* @param remoteInstance RemoteInstance to serialize
* @return String serialized RemoteInstance
*/
2019-09-06 17:55:14 +02:00
public static String remoteInstanceToStringStorage(RemoteInstance remoteInstance) {
2019-04-21 10:22:07 +02:00
Gson gson = new Gson();
try {
return gson.toJson(remoteInstance);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2019-04-21 10:22:07 +02:00
return null;
}
}
2018-11-24 18:56:12 +01:00
/**
* Unserialized a Locale
2019-09-06 17:55:14 +02:00
*
2018-11-24 18:56:12 +01:00
* @param serializedLocale String serialized locale
* @return Locale
*/
2019-09-06 17:55:14 +02:00
public static Locale restoreLocaleFromString(String serializedLocale) {
2018-11-24 18:56:12 +01:00
Gson gson = new Gson();
try {
return gson.fromJson(serializedLocale, Locale.class);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-11-24 18:56:12 +01:00
return null;
}
}
/**
* Serialized a Locale class
2019-09-06 17:55:14 +02:00
*
2018-11-24 18:56:12 +01:00
* @param locale Locale to serialize
* @return String serialized Locale
*/
2019-09-06 17:55:14 +02:00
public static String localeToStringStorage(Locale locale) {
2018-11-24 18:56:12 +01:00
Gson gson = new Gson();
2018-12-17 18:27:01 +01:00
try {
return gson.toJson(locale);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
2018-11-24 18:56:12 +01:00
}
2018-09-16 15:05:33 +02:00
2017-07-17 18:53:12 +02:00
/**
* Serialized a Status class
2019-09-06 17:55:14 +02:00
*
2017-07-17 18:53:12 +02:00
* @param status Status to serialize
* @return String serialized Status
*/
2019-09-06 17:55:14 +02:00
public static String statusToStringStorage(Status status) {
2017-12-15 18:03:06 +01:00
Gson gson = new Gson();
2018-12-17 18:27:01 +01:00
try {
return gson.toJson(status);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
2017-07-15 14:59:09 +02:00
}
2018-11-18 13:33:12 +01:00
/**
* Unserialized a Card
2019-09-06 17:55:14 +02:00
*
2018-11-18 13:33:12 +01:00
* @param serializedCard String serialized card
* @return Card
*/
2019-09-06 17:55:14 +02:00
public static Card restoreCardFromString(String serializedCard) {
2018-11-18 13:33:12 +01:00
Gson gson = new Gson();
try {
return gson.fromJson(serializedCard, Card.class);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-11-18 13:33:12 +01:00
return null;
}
}
/**
* Serialized a Card class
2019-09-06 17:55:14 +02:00
*
2018-11-18 13:33:12 +01:00
* @param card Card to serialize
* @return String serialized Status
*/
2019-09-06 17:55:14 +02:00
public static String cardToStringStorage(Card card) {
2018-11-18 13:33:12 +01:00
Gson gson = new Gson();
2018-12-17 18:27:01 +01:00
try {
return gson.toJson(card);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
2018-11-18 13:33:12 +01:00
}
2017-07-17 18:53:12 +02:00
/**
* Unserialized a Status
2019-09-06 17:55:14 +02:00
*
2017-07-17 18:53:12 +02:00
* @param serializedStatus String serialized status
* @return Status
*/
2019-09-06 17:55:14 +02:00
public static Status restoreStatusFromString(String serializedStatus) {
2017-12-15 18:03:06 +01:00
Gson gson = new Gson();
2017-12-10 18:05:51 +01:00
try {
2017-12-15 18:03:06 +01:00
return gson.fromJson(serializedStatus, Status.class);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2017-12-15 18:03:06 +01:00
return null;
2017-12-10 18:05:51 +01:00
}
2017-07-15 14:59:09 +02:00
}
2017-07-17 18:53:12 +02:00
2018-09-10 19:21:42 +02:00
/**
* Serialized a List<String>
2019-09-06 17:55:14 +02:00
*
2018-09-10 19:21:42 +02:00
* @param list List<String> to serialize
* @return String serialized List
*/
2019-09-06 17:55:14 +02:00
public static String arrayToStringStorage(List<String> list) {
2018-09-10 19:21:42 +02:00
Gson gson = new Gson();
2018-12-17 18:27:01 +01:00
try {
return gson.toJson(list);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
2018-09-10 19:21:42 +02:00
}
/**
* Unserialized a List<String>
2019-09-06 17:55:14 +02:00
*
2018-09-10 19:21:42 +02:00
* @param serializedArray String serialized array
* @return List<String> list
*/
2019-09-06 17:55:14 +02:00
public static List<String> restoreArrayFromString(String serializedArray) {
2018-09-10 19:21:42 +02:00
Gson gson = new Gson();
try {
return gson.fromJson(serializedArray, List.class);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-09-10 19:21:42 +02:00
return null;
}
}
/**
* Serialized an Application class
2019-09-06 17:55:14 +02:00
*
* @param application Application to serialize
* @return String serialized Application
*/
2019-09-06 17:55:14 +02:00
public static String applicationToStringStorage(Application application) {
Gson gson = new Gson();
2018-12-17 18:27:01 +01:00
try {
return gson.toJson(application);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
}
/**
* Unserialized an Application
2019-09-06 17:55:14 +02:00
*
* @param serializedApplication String serialized application
* @return Application
*/
2019-09-06 17:55:14 +02:00
public static Application restoreApplicationFromString(String serializedApplication) {
Gson gson = new Gson();
try {
return gson.fromJson(serializedApplication, Application.class);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
return null;
}
}
2018-02-15 07:55:24 +01:00
/**
* Serialized a Account class
2019-09-06 17:55:14 +02:00
*
2018-02-15 07:55:24 +01:00
* @param account Account to serialize
* @return String serialized Account
*/
2019-09-06 17:55:14 +02:00
public static String accountToStringStorage(Account account) {
2018-02-15 07:55:24 +01:00
Gson gson = new Gson();
2018-11-07 18:09:21 +01:00
try {
return gson.toJson(account);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-11-07 18:09:21 +01:00
e.printStackTrace();
return null;
}
2018-02-15 07:55:24 +01:00
}
/**
* Unserialized an Account
2019-09-06 17:55:14 +02:00
*
2018-02-15 07:55:24 +01:00
* @param serializedAccount String serialized account
* @return Account
*/
2019-09-06 17:55:14 +02:00
public static Account restoreAccountFromString(String serializedAccount) {
2018-02-15 07:55:24 +01:00
Gson gson = new Gson();
try {
return gson.fromJson(serializedAccount, Account.class);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-02-15 07:55:24 +01:00
return null;
}
}
/**
* Serialized a List of Emojis class
2019-09-06 17:55:14 +02:00
*
2018-02-15 07:55:24 +01:00
* @param emojis Emojis List to serialize
* @return String serialized List of Emojis
*/
2019-09-06 17:55:14 +02:00
public static String emojisToStringStorage(List<Emojis> emojis) {
2018-02-15 07:55:24 +01:00
Gson gson = new Gson();
2018-12-17 18:27:01 +01:00
try {
return gson.toJson(emojis);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
2018-02-15 07:55:24 +01:00
}
/**
* Unserialized a list of Emojis
2019-09-06 17:55:14 +02:00
*
2018-02-15 07:55:24 +01:00
* @param serializedEmojis String serialized emojis
* @return List<Emojis>
*/
2019-09-06 17:55:14 +02:00
public static List<Emojis> restoreEmojisFromString(String serializedEmojis) {
Type listType = new TypeToken<ArrayList<Emojis>>() {
}.getType();
2018-12-17 18:27:01 +01:00
try {
return new Gson().fromJson(serializedEmojis, listType);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
2018-02-15 07:55:24 +01:00
}
/**
* Serialized a List of a Attachment class
2019-09-06 17:55:14 +02:00
*
2018-02-15 07:55:24 +01:00
* @param attachments Attachment List to serialize
* @return String serialized List of Attachment
*/
2019-09-06 17:55:14 +02:00
public static String attachmentToStringStorage(List<Attachment> attachments) {
2018-02-15 07:55:24 +01:00
Gson gson = new Gson();
2018-12-17 18:27:01 +01:00
try {
return gson.toJson(attachments);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
2018-02-15 07:55:24 +01:00
}
/**
* Unserialized a list of Attachment
2019-09-06 17:55:14 +02:00
*
2018-02-15 07:55:24 +01:00
* @param serializedAttachment String serialized attachment
* @return List<Attachment>
*/
2019-09-06 17:55:14 +02:00
public static ArrayList<Attachment> restoreAttachmentFromString(String serializedAttachment) {
Type listType = new TypeToken<ArrayList<Attachment>>() {
}.getType();
2018-11-10 08:22:13 +01:00
try {
return new Gson().fromJson(serializedAttachment, listType);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-11-10 08:22:13 +01:00
e.printStackTrace();
return null;
}
2018-02-15 07:55:24 +01:00
}
/**
* Serialized a List of a Mention class
2019-09-06 17:55:14 +02:00
*
2018-02-15 07:55:24 +01:00
* @param mentions Mention List to serialize
* @return String serialized List of Mention
*/
2019-09-06 17:55:14 +02:00
public static String mentionToStringStorage(List<Mention> mentions) {
2018-02-15 07:55:24 +01:00
Gson gson = new Gson();
2018-12-17 18:27:01 +01:00
try {
return gson.toJson(mentions);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
2018-02-15 07:55:24 +01:00
}
/**
* Unserialized a list of Mention
2019-09-06 17:55:14 +02:00
*
2018-02-15 07:55:24 +01:00
* @param serializedMention String serialized mention
* @return String serialized List of Mention
*/
2019-09-06 17:55:14 +02:00
public static List<Mention> restoreMentionFromString(String serializedMention) {
Type listType = new TypeToken<ArrayList<Mention>>() {
}.getType();
2018-12-17 18:27:01 +01:00
try {
return new Gson().fromJson(serializedMention, listType);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
2018-02-15 07:55:24 +01:00
}
/**
* Serialized a List of a Tag class
2019-09-06 17:55:14 +02:00
*
2018-02-15 07:55:24 +01:00
* @param tags Tag List to serialize
* @return String serialized List of Tag
*/
2019-09-06 17:55:14 +02:00
public static String tagToStringStorage(List<Tag> tags) {
2018-02-15 07:55:24 +01:00
Gson gson = new Gson();
2018-12-17 18:27:01 +01:00
try {
return gson.toJson(tags);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
2018-02-15 07:55:24 +01:00
}
/**
* Unserialized a list of Tag
2019-09-06 17:55:14 +02:00
*
2018-02-15 07:55:24 +01:00
* @param serializedTag String serialized tag
* @return String serialized List of Tag
*/
2019-09-06 17:55:14 +02:00
public static List<Tag> restoreTagFromString(String serializedTag) {
Type listType = new TypeToken<ArrayList<Tag>>() {
}.getType();
2018-12-17 18:27:01 +01:00
try {
return new Gson().fromJson(serializedTag, listType);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2018-12-17 18:27:01 +01:00
return null;
}
2018-02-15 07:55:24 +01:00
}
2017-07-17 18:53:12 +02:00
/**
* Check if a job id is in array of ids
2019-09-06 17:55:14 +02:00
*
2017-07-17 18:53:12 +02:00
* @param jobIds int[]
2019-09-06 17:55:14 +02:00
* @param id int id to check
2017-07-17 18:53:12 +02:00
* @return boolean
*/
2019-09-06 17:55:14 +02:00
public static boolean isJobPresent(int[] jobIds, int id) {
for (int x : jobIds) {
if (x == id) {
return true;
}
2017-07-17 18:53:12 +02:00
}
return false;
}
2017-07-26 09:21:47 +02:00
2019-09-06 17:55:14 +02:00
public static void unCheckAllMenuItems(NavigationView navigationView) {
2017-07-26 09:21:47 +02:00
navigationView.setCheckedItem(R.id.menu_none);
unCheckAllMenuItemsRec(navigationView.getMenu());
}
private static void unCheckAllMenuItemsRec(@NonNull final Menu menu) {
int size = menu.size();
for (int i = 0; i < size; i++) {
final MenuItem item = menu.getItem(i);
2019-09-06 17:55:14 +02:00
if (item.hasSubMenu()) {
2017-07-26 09:21:47 +02:00
unCheckAllMenuItemsRec(item.getSubMenu());
} else {
item.setChecked(false);
}
}
}
2017-07-31 19:29:14 +02:00
/**
* Changes the menu layout
2019-09-06 17:55:14 +02:00
*
* @param activity Activity must be an instance of MainActivity
*/
2019-09-06 17:55:14 +02:00
public static void switchLayout(Activity activity) {
//Check if the class calling the method is an instance of MainActivity
final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
2017-10-27 14:19:13 +02:00
final NavigationView navigationView = activity.findViewById(R.id.nav_view);
2019-06-11 19:38:26 +02:00
TabLayout tableLayout = activity.findViewById(R.id.tabLayout);
String userID = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
2019-06-05 14:35:42 +02:00
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null);
SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
2019-09-06 17:55:14 +02:00
Account account = new AccountDAO(activity, db).getUniqAccount(userID, instance);
if (account != null) {
if (account.isLocked()) {
2019-09-06 17:55:14 +02:00
if (navigationView.getMenu().findItem(R.id.nav_follow_request) != null)
navigationView.getMenu().findItem(R.id.nav_follow_request).setVisible(true);
} else {
2019-09-06 17:55:14 +02:00
if (navigationView.getMenu().findItem(R.id.nav_follow_request) != null)
navigationView.getMenu().findItem(R.id.nav_follow_request).setVisible(false);
}
2019-08-28 16:21:50 +02:00
2019-09-06 17:55:14 +02:00
if (MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.MASTODON && MainActivity.social != UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
MenuItem adminItem = navigationView.getMenu().findItem(R.id.nav_administration);
2019-09-06 17:55:14 +02:00
if (adminItem != null) {
adminItem.setVisible(false);
}
2017-12-15 20:01:58 +01:00
}
}
tableLayout.setVisibility(View.VISIBLE);
}
2017-09-02 18:17:00 +02:00
2017-10-03 19:16:15 +02:00
2017-09-16 12:10:01 +02:00
/**
* Get a bitmap from a view
2019-09-06 17:55:14 +02:00
*
2017-09-16 12:10:01 +02:00
* @param view The view to convert
* @return Bitmap
*/
2018-01-26 10:13:32 +01:00
public static Bitmap convertTootIntoBitmap(Context context, String name, View view) {
2017-09-16 15:16:16 +02:00
2019-09-06 17:55:14 +02:00
if (view.getWidth() == 0 || view.getHeight() == 0) {
Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show();
return null;
}
2019-09-06 17:55:14 +02:00
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth() + (int) Helper.convertDpToPixel(10, context), view.getHeight() + (int) Helper.convertDpToPixel(30, context), Bitmap.Config.ARGB_8888);
2017-09-16 12:10:01 +02:00
Canvas canvas = new Canvas(returnedBitmap);
2019-09-06 17:55:14 +02:00
canvas.drawBitmap(returnedBitmap, view.getWidth() + (int) Helper.convertDpToPixel(10, context), 0, null);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
2017-09-16 12:10:01 +02:00
bgDrawable.draw(canvas);
2018-01-26 08:10:37 +01:00
else {
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
if (theme == Helper.THEME_DARK) {
canvas.drawColor(ContextCompat.getColor(context, R.color.mastodonC1));
2018-05-11 11:28:05 +02:00
2019-09-06 17:55:14 +02:00
} else if (theme == Helper.THEME_BLACK) {
2018-05-11 11:28:05 +02:00
canvas.drawColor(ContextCompat.getColor(context, R.color.black));
2019-09-06 17:55:14 +02:00
} else {
2018-01-26 08:10:37 +01:00
canvas.drawColor(Color.WHITE);
}
}
2017-09-16 12:10:01 +02:00
view.draw(canvas);
2017-09-16 16:52:51 +02:00
Paint paint = new Paint();
int mastodonC4 = ContextCompat.getColor(context, R.color.mastodonC4);
paint.setColor(mastodonC4);
paint.setStrokeWidth(12);
2019-09-06 17:55:14 +02:00
paint.setTextSize((int) Helper.convertDpToPixel(14, context));
2017-09-16 16:52:51 +02:00
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
2019-09-06 17:55:14 +02:00
canvas.drawText(name + " - #Fedilab", 0, view.getHeight() + (int) Helper.convertDpToPixel(15, context), paint);
2017-09-16 15:16:16 +02:00
2017-09-16 12:10:01 +02:00
return returnedBitmap;
}
2017-11-14 14:32:39 +01:00
2017-11-25 11:01:34 +01:00
@SuppressLint("DefaultLocale")
public static String withSuffix(long count) {
if (count < 1000) return "" + count;
int exp = (int) (Math.log(count) / Math.log(1000));
Locale locale = null;
try {
locale = Locale.getDefault();
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
}
if (locale != null)
return String.format(locale, "%.1f %c",
count / Math.pow(1000, exp),
"kMGTPE".charAt(exp - 1));
2017-11-25 11:01:34 +01:00
else
2019-09-06 17:55:14 +02:00
return String.format("%.1f %c",
2017-11-25 11:01:34 +01:00
count / Math.pow(1000, exp),
2019-09-06 17:55:14 +02:00
"kMGTPE".charAt(exp - 1));
2017-11-25 11:01:34 +01:00
}
2017-12-02 12:38:58 +01:00
public static Bitmap addBorder(Bitmap resource, Context context) {
int w = resource.getWidth();
int h = resource.getHeight();
int radius = Math.min(h / 2, w / 2);
Bitmap output = Bitmap.createBitmap(w + 8, h + 8, Bitmap.Config.ARGB_8888);
Paint p = new Paint();
p.setAntiAlias(true);
Canvas c = new Canvas(output);
c.drawARGB(0, 0, 0, 0);
p.setStyle(Paint.Style.FILL);
c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);
p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
c.drawBitmap(resource, 4, 4, p);
p.setXfermode(null);
p.setStyle(Paint.Style.STROKE);
p.setColor(ContextCompat.getColor(context, R.color.white));
p.setStrokeWidth(3);
c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);
return output;
}
2018-10-17 14:34:29 +02:00
public static String secondsToString(int pTime) {
2019-09-06 17:55:14 +02:00
int hour = pTime / 3600;
int min = (pTime - (hour * 3600)) / 60;
int sec = pTime - (hour * 3600) - (min * 60);
String strHour = "0", strMin = "0", strSec = "0";
2018-10-17 14:34:29 +02:00
2019-09-06 17:55:14 +02:00
if (hour > 0)
2018-10-17 14:34:29 +02:00
strHour = String.format(Locale.getDefault(), "%02d", hour);
2019-09-06 17:55:14 +02:00
if (min > 0)
2018-10-17 14:34:29 +02:00
strMin = String.format(Locale.getDefault(), "%02d", min);
strSec = String.format(Locale.getDefault(), "%02d", sec);
2019-09-06 17:55:14 +02:00
if (hour > 0)
return String.format(Locale.getDefault(), "%s:%s:%s", strHour, strMin, strSec);
2018-10-17 14:34:29 +02:00
else
2019-09-06 17:55:14 +02:00
return String.format(Locale.getDefault(), "%s:%s", strMin, strSec);
2018-10-17 14:34:29 +02:00
}
2019-09-06 17:55:14 +02:00
public static void loadGiF(final Context context, String url, final ImageView imageView) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean disableGif = sharedpreferences.getBoolean(SET_DISABLE_GIF, false);
2019-09-06 17:55:14 +02:00
if (url != null && url.startsWith("/")) {
2019-08-02 16:49:02 +02:00
url = Helper.getLiveInstanceWithProtocol(context) + url;
}
2019-09-06 17:55:14 +02:00
if (!(context instanceof MainApplication) && ((Activity) context).isFinishing()) {
2019-08-03 12:07:17 +02:00
return;
}
2019-09-06 17:55:14 +02:00
if (disableGif) {
2019-08-02 15:25:54 +02:00
try {
Glide.with(imageView.getContext())
.asBitmap()
.load(url)
.thumbnail(0.1f)
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
.into(imageView);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2019-08-05 18:10:49 +02:00
try {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
Glide.with(imageView.getContext())
.asDrawable()
.load(R.drawable.missing)
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
.into(imageView);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
Glide.with(imageView.getContext())
.asDrawable()
.load(R.drawable.missing_peertube)
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
.into(imageView);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
Glide.with(imageView.getContext())
.asDrawable()
.load(R.drawable.gnu_default_avatar)
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
.into(imageView);
}
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
}
2019-08-02 15:25:54 +02:00
}
2019-09-06 17:55:14 +02:00
} else {
2019-08-02 15:25:54 +02:00
try {
Glide.with(imageView.getContext())
.load(url)
.thumbnail(0.1f)
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
.into(imageView);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
2019-08-05 18:10:49 +02:00
try {
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || BaseMainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
Glide.with(imageView.getContext())
.asDrawable()
.load(R.drawable.missing)
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
.into(imageView);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PEERTUBE) {
Glide.with(imageView.getContext())
.asDrawable()
.load(R.drawable.missing_peertube)
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
.into(imageView);
} else if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.GNU || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.FRIENDICA) {
Glide.with(imageView.getContext())
.asDrawable()
.load(R.drawable.gnu_default_avatar)
.apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
.into(imageView);
}
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
}
2019-08-02 15:25:54 +02:00
}
}
2019-07-30 11:48:37 +02:00
}
2019-08-02 13:41:08 +02:00
/**
* Manage URLs to open (built-in or external app)
2019-09-06 17:55:14 +02:00
*
* @param context Context
2019-09-06 17:55:14 +02:00
* @param url String url to open
*/
2019-09-06 17:55:14 +02:00
public static void openBrowser(Context context, String url) {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
boolean embedded_browser = sharedpreferences.getBoolean(Helper.SET_EMBEDDED_BROWSER, true);
2019-09-06 17:55:14 +02:00
if (embedded_browser) {
Intent intent = new Intent(context, WebviewActivity.class);
Bundle b = new Bundle();
String finalUrl = url;
2019-10-05 08:50:24 +02:00
if (!url.toLowerCase().startsWith("http://") && !url.toLowerCase().startsWith("https://"))
finalUrl = "http://" + url;
b.putString("url", finalUrl);
intent.putExtras(b);
context.startActivity(intent);
2019-09-06 17:55:14 +02:00
} else {
2018-02-09 16:44:18 +01:00
boolean custom_tabs = sharedpreferences.getBoolean(Helper.SET_CUSTOM_TABS, true);
2019-09-06 17:55:14 +02:00
if (custom_tabs) {
2018-02-09 16:44:18 +01:00
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
builder.setToolbarColor(ContextCompat.getColor(context, R.color.mastodonC1));
2018-12-31 12:06:50 +01:00
try {
customTabsIntent.launchUrl(context, Uri.parse(url));
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show();
}
} else {
2018-02-09 16:44:18 +01:00
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
2018-09-08 11:30:58 +02:00
try {
context.startActivity(intent);
2019-09-06 17:55:14 +02:00
} catch (Exception e) {
Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show();
2018-09-08 11:30:58 +02:00
}
2018-02-09 16:44:18 +01:00
}
}
}
2019-09-06 17:55:14 +02:00
public static void installProvider() {
2019-02-14 10:06:18 +01:00
boolean patch_provider = true;
2018-12-15 18:47:28 +01:00
try {
2019-02-14 10:06:18 +01:00
Context ctx = MainApplication.getApp();
SharedPreferences sharedpreferences = ctx.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
patch_provider = sharedpreferences.getBoolean(Helper.SET_SECURITY_PROVIDER, true);
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
}
2019-10-21 18:19:38 +02:00
if (patch_provider) {
2019-02-14 10:06:18 +01:00
try {
2019-09-06 17:55:14 +02:00
Security.insertProviderAt(Conscrypt.newProvider(), 1);
} catch (Exception ignored) {
}
2019-10-21 18:19:38 +02:00
}
2017-12-14 07:26:37 +01:00
}
2019-09-06 17:55:14 +02:00
public enum MediaType {
2018-04-22 13:16:52 +02:00
MEDIA,
PROFILE
}
2019-09-06 17:55:14 +02:00
2019-09-28 17:25:51 +02:00
public static String compressImagePath(Context context, android.net.Uri uriFile) {
ContentResolver cr = context.getContentResolver();
String mime = cr.getType(uriFile);
File destinationDirectory = new File(context.getCacheDir().getAbsolutePath()+"/compress");
if (!destinationDirectory.exists()) {
destinationDirectory.mkdirs();
}
if (mime == null || mime.toLowerCase().contains("image")) {
ExifInterface exif = null;
try (InputStream inputStream = context.getContentResolver().openInputStream(uriFile)) {
assert inputStream != null;
exif = new ExifInterface(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
Matrix matrix;
if (exif != null) {
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationDegree = 0;
if (rotation == ExifInterface.ORIENTATION_ROTATE_90) {
rotationDegree = 90;
} else if (rotation == ExifInterface.ORIENTATION_ROTATE_180) {
rotationDegree = 180;
} else if (rotation == ExifInterface.ORIENTATION_ROTATE_270) {
rotationDegree = 270;
}
matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationDegree);
}
}
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
boolean compressed = sharedpreferences.getBoolean(Helper.SET_PICTURE_COMPRESSED, true);
if( compressed) {
try {
return SiliCompressor.with(context).compress(uriFile.toString(), destinationDirectory);
}catch (Exception ignored){}
}
} else {
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
boolean compressed = sharedpreferences.getBoolean(Helper.SET_VIDEO_COMPRESSED, true);
if( compressed) {
try {
2019-10-20 12:02:46 +02:00
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(getRealPathFromURI(context,uriFile));
int width = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
int height = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
retriever.release();
2019-10-20 18:40:12 +02:00
int newHeight = height;
if( width > DEFAULT_VIDEO_WIDTH) {
newHeight = height * DEFAULT_VIDEO_WIDTH / width;
}
2019-10-20 12:02:46 +02:00
return SiliCompressor.with(context).compressVideo(getRealPathFromURI(context,uriFile), context.getCacheDir().getAbsolutePath()+"/compress/", DEFAULT_VIDEO_WIDTH, newHeight, DEFAULT_VIDEO_BITRATE);
2019-09-28 17:25:51 +02:00
} catch (Exception ignored) { }
}
}
return null;
}
2019-09-20 18:32:10 +02:00
public static ByteArrayInputStream compressImage(Context context, android.net.Uri uriFile) {
2019-07-22 15:54:24 +02:00
ContentResolver cr = context.getContentResolver();
String mime = cr.getType(uriFile);
2018-04-22 13:16:52 +02:00
ByteArrayInputStream bs = null;
2019-09-20 18:32:10 +02:00
2019-09-21 16:29:33 +02:00
File destinationDirectory = new File(context.getCacheDir().getAbsolutePath()+"/compress");
if (!destinationDirectory.exists()) {
destinationDirectory.mkdirs();
}
2019-09-21 10:45:17 +02:00
InputStream resizedIS = null;
2019-09-21 16:29:33 +02:00
if (mime == null || mime.toLowerCase().contains("image")) {
2019-07-22 15:54:24 +02:00
ExifInterface exif = null;
try (InputStream inputStream = context.getContentResolver().openInputStream(uriFile)) {
assert inputStream != null;
exif = new ExifInterface(inputStream);
} catch (Exception e) {
e.printStackTrace();
2018-04-22 13:16:52 +02:00
}
2019-09-20 18:32:10 +02:00
Matrix matrix;
if (exif != null) {
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationDegree = 0;
if (rotation == ExifInterface.ORIENTATION_ROTATE_90) {
rotationDegree = 90;
} else if (rotation == ExifInterface.ORIENTATION_ROTATE_180) {
rotationDegree = 180;
} else if (rotation == ExifInterface.ORIENTATION_ROTATE_270) {
rotationDegree = 270;
2019-07-22 15:54:24 +02:00
}
2019-09-20 18:32:10 +02:00
matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationDegree);
2019-07-22 15:54:24 +02:00
}
2019-09-20 18:32:10 +02:00
}
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
boolean compressed = sharedpreferences.getBoolean(Helper.SET_PICTURE_COMPRESSED, true);
if( compressed) {
2018-04-22 13:16:52 +02:00
try {
2019-09-21 16:29:33 +02:00
String filePath = SiliCompressor.with(context).compress(uriFile.toString(), destinationDirectory);
2019-09-21 10:45:17 +02:00
resizedIS = new FileInputStream(filePath);
2019-09-21 16:29:33 +02:00
} catch (IOException|ArithmeticException e) {
2018-04-22 13:16:52 +02:00
e.printStackTrace();
2019-09-20 18:32:10 +02:00
}
2019-09-21 16:29:33 +02:00
if( resizedIS == null){
try {
resizedIS = context.getContentResolver().openInputStream(uriFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
2019-09-20 18:32:10 +02:00
}else{
try {
resizedIS = context.getContentResolver().openInputStream(uriFile);
2018-04-22 13:16:52 +02:00
} catch (IOException e) {
e.printStackTrace();
}
}
2019-09-20 18:32:10 +02:00
try {
byte[] buff = new byte[8 * 1024];
int bytesRead;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
assert resizedIS != null;
while ((bytesRead = resizedIS.read(buff)) != -1) {
bao.write(buff, 0, bytesRead);
}
byte[] data = bao.toByteArray();
bs = new ByteArrayInputStream(data);
} catch (IOException e) {
e.printStackTrace();
}
2019-09-06 17:55:14 +02:00
} else {
2019-09-21 10:45:17 +02:00
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
boolean compressed = sharedpreferences.getBoolean(Helper.SET_VIDEO_COMPRESSED, true);
if( compressed) {
String filePath = null;
try {
2019-10-20 12:02:46 +02:00
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(getRealPathFromURI(context,uriFile));
int width = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
int height = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
retriever.release();
2019-10-20 18:40:12 +02:00
int newHeight = height;
if( width > DEFAULT_VIDEO_WIDTH) {
newHeight = height * DEFAULT_VIDEO_WIDTH / width;
}
2019-10-20 12:02:46 +02:00
filePath = SiliCompressor.with(context).compressVideo(getRealPathFromURI(context,uriFile), context.getCacheDir().getAbsolutePath()+"/compress/", DEFAULT_VIDEO_WIDTH, newHeight, DEFAULT_VIDEO_BITRATE);
2019-09-21 16:29:33 +02:00
2019-09-21 10:45:17 +02:00
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
assert filePath != null;
resizedIS = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
2019-09-21 16:29:33 +02:00
if( resizedIS == null){
try {
resizedIS = context.getContentResolver().openInputStream(uriFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
2019-09-21 10:45:17 +02:00
}else{
try {
resizedIS = context.getContentResolver().openInputStream(uriFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
2018-04-22 13:16:52 +02:00
try {
byte[] buff = new byte[8 * 1024];
int bytesRead;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
2019-09-21 10:45:17 +02:00
assert resizedIS != null;
while ((bytesRead = resizedIS.read(buff)) != -1) {
2018-04-22 13:16:52 +02:00
bao.write(buff, 0, bytesRead);
}
byte[] data = bao.toByteArray();
2019-09-06 17:55:14 +02:00
bs = new ByteArrayInputStream(data);
2018-04-22 13:16:52 +02:00
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return bs;
}
2018-04-22 18:02:00 +02:00
2019-09-21 16:29:33 +02:00
public static String getRealPathFromURI(Context context, Uri uri) throws URISyntaxException {
String selection = null;
String[] selectionArgs = null;
// Uri is different in versions after KITKAT (Android 4.4), we need to
if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
uri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("image".equals(type)) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{
split[1]
};
}
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
String[] projection = {
MediaStore.Images.Media.DATA
};
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(uri, projection, selection, selectionArgs, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
2018-04-23 07:00:12 +02:00
public static String getFileName(Context context, Uri uri) {
ContentResolver resolver = context.getContentResolver();
Cursor returnCursor =
resolver.query(uri, null, null, null, null);
assert returnCursor != null;
2018-04-28 16:54:06 +02:00
try {
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String name = returnCursor.getString(nameIndex);
returnCursor.close();
Random r = new Random();
int suf = r.nextInt(9999 - 1000) + 1000;
2019-09-06 17:55:14 +02:00
return String.valueOf(suf) + name;
} catch (Exception e) {
2018-04-28 16:54:06 +02:00
Random r = new Random();
int suf = r.nextInt(9999 - 1000) + 1000;
ContentResolver cr = context.getContentResolver();
String mime = cr.getType(uri);
2019-09-06 17:55:14 +02:00
if (mime != null && mime.split("/").length > 1)
return "__" + String.valueOf(suf) + "." + mime.split("/")[1];
2018-04-28 16:54:06 +02:00
else
2019-09-06 17:55:14 +02:00
return "__" + String.valueOf(suf) + ".jpg";
2018-04-28 16:54:06 +02:00
}
2018-04-23 07:00:12 +02:00
}
2019-09-06 17:55:14 +02:00
public static Bitmap compressImageIfNeeded(Context context, Bitmap bmToCompress) {
int size = bmToCompress.getByteCount();
2019-09-06 17:55:14 +02:00
double resizeby = 33554432; //4Mo
double resize = ((double) size) / resizeby;
if (resize > 1) {
Bitmap newBitmap = Bitmap.createScaledBitmap(bmToCompress, (int) (bmToCompress.getWidth() / resize),
(int) (bmToCompress.getHeight() / resize), true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
return newBitmap;
}
return bmToCompress;
}
2018-04-28 16:54:06 +02:00
@SuppressWarnings({"WeakerAccess", "unused"})
2018-04-22 18:02:00 +02:00
public static void largeLog(String content) {
if (content.length() > 4000) {
Log.v(Helper.TAG, content.substring(0, 4000));
largeLog(content.substring(4000));
} else {
Log.v(Helper.TAG, content);
}
}
2018-08-14 11:10:49 +02:00
2018-08-15 11:24:57 +02:00
/**
* Allows to split the toot by dot "." for sentences - adds number at the end automatically
2019-09-06 17:55:14 +02:00
*
* @param content String initial content
2018-08-15 11:24:57 +02:00
* @param maxChars int the max chars per toot (minus 10 to write the page: 1/x, 2/x etc.)
* @return ArrayList<String> split toot
*/
2019-10-06 16:35:08 +02:00
public static ArrayList<String> splitToots(String content, int maxChars, boolean reportMentions) {
2019-06-13 19:02:09 +02:00
String[] splitContent = content.split("\\s");
2019-07-27 18:34:48 +02:00
2018-12-08 12:05:58 +01:00
ArrayList<String> mentions = new ArrayList<>();
2019-10-06 16:35:08 +02:00
int mentionLength = 0;
StringBuilder mentionString = new StringBuilder();
if( reportMentions) {
Matcher matcher = mentionLongPattern.matcher(content);
while (matcher.find()) {
String mentionLong = matcher.group(1);
if (!mentions.contains(mentionLong)) {
mentions.add(mentionLong);
}
2019-07-27 18:34:48 +02:00
}
2019-10-06 16:35:08 +02:00
matcher = mentionPattern.matcher(content);
while (matcher.find()) {
String mention = matcher.group(1);
if (!mentions.contains(mention)) {
mentions.add(mention);
}
2019-07-27 18:34:48 +02:00
}
2019-10-06 16:35:08 +02:00
for (String mention : mentions) {
mentionString.append(mention).append(" ");
}
mentionLength = mentionString.length() + 1;
2018-12-08 12:05:58 +01:00
}
2019-09-06 17:55:14 +02:00
int maxCharsPerMessage = (maxChars - 10) - mentionLength;
2019-07-27 18:34:48 +02:00
int totalCurrent = 0;
ArrayList<String> reply = new ArrayList<>();
int index = 0;
2019-09-06 17:55:14 +02:00
for (int i = 0; i < splitContent.length; i++) {
if ((totalCurrent + splitContent[i].length() + 1) < maxCharsPerMessage) {
totalCurrent += (splitContent[i].length() + 1);
2018-12-08 12:05:58 +01:00
} else {
2019-07-27 18:34:48 +02:00
if (content.length() > totalCurrent && totalCurrent > 0) {
2019-10-13 17:01:46 +02:00
String tempContent = content.substring(0, (totalCurrent));
2019-07-27 18:34:48 +02:00
content = content.substring(totalCurrent);
reply.add(index, tempContent);
index++;
2019-10-13 17:01:46 +02:00
totalCurrent = splitContent[i].length() + 1;
2018-12-08 12:05:58 +01:00
}
2018-08-15 11:24:57 +02:00
}
}
2019-09-06 17:55:14 +02:00
if (totalCurrent > 0) {
2019-07-27 18:34:48 +02:00
reply.add(index, content);
}
2019-09-06 17:55:14 +02:00
if (reply.size() > 1) {
2019-07-27 18:34:48 +02:00
int i = 0;
2019-09-06 17:55:14 +02:00
for (String r : reply) {
2019-09-14 12:30:16 +02:00
if (mentions.size() > 0 ) {
String tmpMention = mentionString.toString();
for (String mention : mentions) {
if(r.contains(mention)){
tmpMention = tmpMention.replace(mention,"");
}
}
reply.set(i, r + " " + tmpMention + " - " + (i + 1) + "/" + reply.size());
2019-09-06 17:55:14 +02:00
} else {
reply.set(i, r + " - " + (i + 1) + "/" + reply.size());
2019-07-27 18:34:48 +02:00
}
i++;
2019-06-16 17:59:24 +02:00
}
2018-08-15 11:24:57 +02:00
}
return reply;
}
2019-09-06 17:55:14 +02:00
public static int countLength(String text) {
if (text == null) {
2019-05-28 15:54:02 +02:00
return 0;
}
2019-09-06 17:55:14 +02:00
if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.MASTODON || MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
2019-05-28 15:54:02 +02:00
Matcher matcherALink = Patterns.WEB_URL.matcher(text);
2019-09-06 17:55:14 +02:00
while (matcherALink.find()) {
2019-05-28 15:54:02 +02:00
int matchStart = matcherALink.start();
int matchEnd = matcherALink.end();
final String url = text.substring(matcherALink.start(1), matcherALink.end(1));
2019-09-06 17:55:14 +02:00
if (matchEnd <= text.length() && matchEnd >= matchStart) {
if (url.length() > 23) {
text = text.replaceFirst(url, "abcdefghijklmnopkrstuvw");
2019-05-28 15:54:02 +02:00
}
}
}
}
return text.length() - countWithEmoji(text);
}
2019-07-20 15:15:47 +02:00
2019-09-06 17:55:14 +02:00
public static int countWithEmoji(String text) {
2019-05-28 15:54:02 +02:00
int emojiCount = 0;
for (int i = 0; i < text.length(); i++) {
int type = Character.getType(text.charAt(i));
if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) {
emojiCount++;
}
}
2019-09-06 17:55:14 +02:00
return emojiCount / 2;
2019-05-28 15:54:02 +02:00
}
2019-09-06 17:55:14 +02:00
public static boolean filterToots(Status status, RetrieveFeedsAsyncTask.Type type, boolean showAccountActivity, boolean showAccountActivityBoost, boolean showAccountActivityReplies) {
2018-09-26 13:45:13 +02:00
String filter;
2019-09-06 17:55:14 +02:00
if (status == null)
2018-11-15 19:09:44 +01:00
return true;
2019-08-18 18:20:48 +02:00
2019-09-06 17:55:14 +02:00
if (type != null) {
2019-01-14 18:16:45 +01:00
if (type == RetrieveFeedsAsyncTask.Type.HOME)
2019-08-18 18:20:48 +02:00
filter = regex_home;
2019-01-14 18:16:45 +01:00
else if (type == RetrieveFeedsAsyncTask.Type.LOCAL)
2019-08-18 18:20:48 +02:00
filter = regex_local;
2019-01-14 18:16:45 +01:00
else
2019-08-18 18:20:48 +02:00
filter = regex_public;
2019-09-06 17:55:14 +02:00
} else {
2019-08-18 18:20:48 +02:00
filter = regex_public;
2019-01-14 18:16:45 +01:00
}
2018-11-10 08:52:17 +01:00
2018-12-15 18:27:54 +01:00
String content = status.getContent();
2019-09-06 17:55:14 +02:00
if (status.getSpoiler_text() != null)
content += " " + status.getSpoiler_text();
if (status.getAccount() == null)
2019-01-15 18:06:28 +01:00
return false;
2019-08-18 18:20:48 +02:00
2019-09-06 17:55:14 +02:00
if (type == RetrieveFeedsAsyncTask.Type.ART && !MainActivity.show_art_nsfw && status.isSensitive())
2019-01-15 18:06:28 +01:00
return false;
2019-09-06 17:55:14 +02:00
if (MainActivity.filters != null) {
for (Filters mfilter : filters) {
2018-12-15 18:27:54 +01:00
ArrayList<String> filterContext = mfilter.getContext();
2019-09-06 17:55:14 +02:00
if (
2018-12-15 18:27:54 +01:00
(type == RetrieveFeedsAsyncTask.Type.HOME && filterContext.contains("home")) ||
(type == RetrieveFeedsAsyncTask.Type.LOCAL && filterContext.contains("public")) ||
(type == RetrieveFeedsAsyncTask.Type.PUBLIC && filterContext.contains("public"))
2019-09-06 17:55:14 +02:00
) {
2018-12-15 18:27:54 +01:00
if (mfilter.isWhole_word() && content.contains(mfilter.getPhrase())) {
2019-01-15 18:06:28 +01:00
return false;
2018-12-15 18:27:54 +01:00
} else {
try {
2019-09-06 17:55:14 +02:00
if (mfilter.getPhrase().contains("#"))
2019-01-21 11:59:53 +01:00
mfilter.setPhrase(mfilter.getPhrase().replaceAll("\\#", "\\#"));
2018-12-15 18:27:54 +01:00
Pattern filterPattern = Pattern.compile("(" + mfilter.getPhrase() + ")", Pattern.CASE_INSENSITIVE);
Matcher matcher = filterPattern.matcher(content);
if (matcher.find())
2019-01-15 18:06:28 +01:00
return false;
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
}
2018-09-26 13:45:13 +02:00
}
}
}
2018-12-15 18:27:54 +01:00
}
2019-09-06 17:55:14 +02:00
if (filter != null && filter.length() > 0) {
2018-12-15 18:27:54 +01:00
try {
Pattern filterPattern = Pattern.compile("(" + filter + ")", Pattern.CASE_INSENSITIVE);
Matcher matcher = filterPattern.matcher(content);
if (matcher.find())
2019-01-15 18:06:28 +01:00
return false;
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
}
2018-12-15 18:27:54 +01:00
}
2019-01-15 18:06:28 +01:00
if (type == RetrieveFeedsAsyncTask.Type.HOME) {
2019-08-18 18:20:48 +02:00
if (status.getReblog() != null && !MainActivity.show_boosts)
2019-01-15 18:06:28 +01:00
return false;
2019-08-18 18:20:48 +02:00
else if (status.getIn_reply_to_id() != null && !status.getIn_reply_to_id().equals("null") && !MainActivity.show_replies) {
2019-01-15 18:06:28 +01:00
return false;
2018-09-26 13:45:13 +02:00
}
2019-01-15 18:06:28 +01:00
} else {
2019-09-06 17:55:14 +02:00
if (showAccountActivity) {
2019-08-18 18:29:42 +02:00
if (status.getReblog() != null && !showAccountActivityBoost)
2019-01-15 18:06:28 +01:00
return false;
2019-08-18 18:29:42 +02:00
else if (status.getIn_reply_to_id() != null && !status.getIn_reply_to_id().equals("null") && !showAccountActivityReplies)
2019-01-15 18:06:28 +01:00
return false;
2018-10-20 16:26:45 +02:00
}
2018-12-15 18:27:54 +01:00
}
2019-10-20 16:13:19 +02:00
if (mutedAccount != null && mutedAccount.size() > 0 && (mutedAccount.contains(status.getAccount().getId()) || (status.getReblog() != null && mutedAccount.contains(status.getReblog().getAccount().getId()))) )
2019-01-15 18:06:28 +01:00
return false;
2019-09-06 17:55:14 +02:00
if (status.isNotice())
2019-02-05 18:05:21 +01:00
return false;
2019-01-15 18:06:28 +01:00
return true;
2018-11-10 08:52:17 +01:00
}
2018-11-03 12:06:44 +01:00
public static void colorizeIconMenu(Menu menu, int toolbarIconsColor) {
final PorterDuffColorFilter colorFilter
= new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.MULTIPLY);
2019-09-06 17:55:14 +02:00
for (int i = 0; i < menu.size(); i++) {
2018-11-03 12:06:44 +01:00
MenuItem v = menu.getItem(i);
v.getIcon().setColorFilter(colorFilter);
}
}
/**
* Code from "Michal Pawlowski"
* https://snow.dog/blog/how-to-dynamicaly-change-android-toolbar-icons-color
2019-09-06 17:55:14 +02:00
*
* @param toolbarView toolbar view being colored
2018-11-03 12:06:44 +01:00
* @param toolbarIconsColor the target color of toolbar icons
2019-09-06 17:55:14 +02:00
* @param activity reference to activity needed to register observers
2018-11-03 12:06:44 +01:00
*/
public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) {
final PorterDuffColorFilter colorFilter
= new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_ATOP);
2019-09-06 17:55:14 +02:00
for (int i = 0; i < toolbarView.getChildCount(); i++) {
2018-11-03 12:06:44 +01:00
final View v = toolbarView.getChildAt(i);
//Step 1 : Changing the color of back button (or open drawer button).
2019-09-06 17:55:14 +02:00
if (v instanceof ImageButton) {
2018-11-03 12:06:44 +01:00
//Action Bar back button
2019-09-06 17:55:14 +02:00
((ImageButton) v).getDrawable().setColorFilter(colorFilter);
2018-11-03 12:06:44 +01:00
}
2019-09-06 17:55:14 +02:00
if (v instanceof ImageView) {
2018-11-03 12:06:44 +01:00
//Action Bar back button
2019-09-06 17:55:14 +02:00
if (v.getId() != R.id.pp_actionBar)
((ImageView) v).setColorFilter(colorFilter);
2018-11-03 12:06:44 +01:00
}
2019-09-06 17:55:14 +02:00
if (v instanceof MenuItem) {
((MenuItem) v).getIcon().setColorFilter(colorFilter);
2018-11-03 12:06:44 +01:00
}
2019-09-06 17:55:14 +02:00
if (v instanceof ActionMenuView) {
for (int j = 0; j < ((ActionMenuView) v).getChildCount(); j++) {
2018-11-03 12:06:44 +01:00
//Step 2: Changing the color of any ActionMenuViews - icons that
//are not back button, nor text, nor overflow menu icon.
2019-09-06 17:55:14 +02:00
final View innerView = ((ActionMenuView) v).getChildAt(j);
2018-11-03 12:06:44 +01:00
2019-09-06 17:55:14 +02:00
if (innerView instanceof ActionMenuItemView) {
int drawablesCount = ((ActionMenuItemView) innerView).getCompoundDrawables().length;
for (int k = 0; k < drawablesCount; k++) {
if (((ActionMenuItemView) innerView).getCompoundDrawables()[k] != null) {
2018-11-03 12:06:44 +01:00
final int finalK = k;
//Important to set the color filter in seperate thread,
//by adding it to the message queue
//Won't work otherwise.
innerView.post(new Runnable() {
@Override
public void run() {
((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
}
});
}
}
}
}
}
2019-09-06 17:55:14 +02:00
if (v instanceof LinearLayout) {
for (int j = 0; j < ((LinearLayout) v).getChildCount(); j++) {
2019-05-04 19:06:24 +02:00
//Action Bar back button
if (((LinearLayout) v).getChildAt(j) instanceof ImageView)
2019-09-06 17:55:14 +02:00
((ImageView) ((LinearLayout) v).getChildAt(j)).setColorFilter(colorFilter);
2019-05-04 19:06:24 +02:00
}
}
2018-11-03 12:06:44 +01:00
//Step 3: Changing the color of title and subtitle.
toolbarView.setTitleTextColor(toolbarIconsColor);
toolbarView.setSubtitleTextColor(toolbarIconsColor);
//Step 4: Changing the color of the Overflow Menu icon.
setOverflowButtonColor(activity, colorFilter);
}
}
/**
* It's important to set overflowDescription atribute in styles, so we can grab the reference
* to the overflow icon. Check: res/values/styles.xml
2019-09-06 17:55:14 +02:00
*
2018-11-03 12:06:44 +01:00
* @param activity
* @param colorFilter
*/
private static void setOverflowButtonColor(final Activity activity, final PorterDuffColorFilter colorFilter) {
2019-09-06 17:55:14 +02:00
@SuppressLint("PrivateResource") final String overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description);
2018-11-03 12:06:44 +01:00
final ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
final ViewTreeObserver viewTreeObserver = decorView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
final ArrayList<View> outViews = new ArrayList<>();
decorView.findViewsWithText(outViews, overflowDescription,
View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
if (outViews.isEmpty()) {
return;
}
2019-09-06 17:55:14 +02:00
androidx.appcompat.widget.AppCompatImageView overflow = (androidx.appcompat.widget.AppCompatImageView) outViews.get(0);
2018-11-03 12:06:44 +01:00
overflow.setColorFilter(colorFilter);
2019-09-06 17:55:14 +02:00
removeOnGlobalLayoutListener(decorView, this);
2018-11-03 12:06:44 +01:00
}
});
}
private static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
2019-09-06 17:55:14 +02:00
} else {
2018-11-03 12:06:44 +01:00
v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
}
2018-11-23 19:18:38 +01:00
2018-11-24 18:56:12 +01:00
2019-09-06 17:55:14 +02:00
public static String getLocalesTwoChars(int stringLocaleId) {
switch (stringLocaleId) {
2018-12-15 10:59:43 +01:00
case R.string.default_language:
return Locale.getDefault().getLanguage();
case R.string.english:
return "en";
case R.string.french:
return "fr";
case R.string.arabic:
return "ar";
case R.string.kabyle:
return "kab";
case R.string.italian:
return "it";
case R.string.catalan:
return "ca";
case R.string.german:
return "de";
case R.string.spanish:
return "es";
case R.string.welsh:
return "cy";
case R.string.polish:
return "pl";
case R.string.traditional_chinese:
return "zh-TW";
case R.string.simplified_chinese:
return "zh-CN";
case R.string.basque:
return "eu";
case R.string.hindi:
return "hi";
case R.string.japanese:
return "ja";
case R.string.dutch:
return "nl";
case R.string.galician:
return "gl";
case R.string.greek:
return "el";
case R.string.portuguese:
return "pt";
case R.string.serbian:
return "sr";
case R.string.ukrainian:
return "uk";
case R.string.russian:
return "ru";
2018-12-21 19:25:51 +01:00
case R.string.norwegian:
return "no";
2018-12-15 10:59:43 +01:00
default:
return Locale.getDefault().getLanguage();
}
}
2018-11-24 18:56:12 +01:00
2019-09-06 17:55:14 +02:00
public static int languageSpinnerPosition(Context context) {
2018-11-24 18:56:12 +01:00
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE);
2018-12-15 10:59:43 +01:00
String defaultLocaleString = sharedpreferences.getString(Helper.SET_DEFAULT_LOCALE_NEW, "NOT_DEFINED");
2019-09-06 17:55:14 +02:00
switch (defaultLocaleString) {
2018-12-15 10:59:43 +01:00
case "NOT_DEFINED":
return 0;
case "en":
return 1;
case "fr":
return 2;
case "de":
return 3;
case "it":
return 4;
case "ja":
return 5;
case "zh-TW":
return 6;
case "zh-CN":
return 7;
case "eu":
return 8;
case "ar":
return 9;
case "nl":
return 10;
case "gl":
return 11;
case "el":
return 12;
case "pt":
return 13;
case "es":
return 14;
case "pl":
return 15;
case "sr":
return 16;
case "uk":
return 17;
case "ru":
return 18;
2018-12-21 19:25:51 +01:00
case "no":
return 19;
2019-08-20 15:31:38 +02:00
case "kab":
return 20;
2018-12-15 10:59:43 +01:00
default:
return 0;
2018-11-24 18:56:12 +01:00
}
}
2019-09-06 17:55:14 +02:00
public static String[] getLocales(Context context) {
2019-08-20 15:31:38 +02:00
String[] locale = new String[21];
locale[0] = context.getString(R.string.default_language);
locale[1] = context.getString(R.string.english);
locale[2] = context.getString(R.string.french);
locale[3] = context.getString(R.string.german);
locale[4] = context.getString(R.string.italian);
locale[5] = context.getString(R.string.japanese);
locale[6] = context.getString(R.string.simplified_chinese);
locale[7] = context.getString(R.string.traditional_chinese);
locale[8] = context.getString(R.string.basque);
locale[9] = context.getString(R.string.arabic);
locale[10] = context.getString(R.string.dutch);
locale[11] = context.getString(R.string.galician);
locale[12] = context.getString(R.string.greek);
locale[13] = context.getString(R.string.portuguese);
locale[14] = context.getString(R.string.spanish);
locale[15] = context.getString(R.string.polish);
locale[16] = context.getString(R.string.serbian);
locale[17] = context.getString(R.string.ukrainian);
locale[18] = context.getString(R.string.russian);
locale[19] = context.getString(R.string.norwegian);
locale[20] = context.getString(R.string.kabyle);
return locale;
}
2019-09-06 17:55:14 +02:00
public static boolean containsCaseInsensitive(String s, List<String> l) {
for (String string : l) {
if (string.equalsIgnoreCase(s)) {
return true;
}
}
return false;
}
2019-09-06 17:55:14 +02:00
public static boolean isTablet(Context context) {
return context.getResources().getBoolean(R.bool.isTablet);
}
2019-01-08 18:11:40 +01:00
2019-09-06 17:55:14 +02:00
public static void changeMaterialSpinnerColor(Context context, MaterialSpinner materialSpinner) {
2019-01-08 18:11:40 +01:00
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
2019-09-06 17:55:14 +02:00
if (theme == THEME_BLACK) {
2019-01-08 18:11:40 +01:00
materialSpinner.setBackgroundColor(ContextCompat.getColor(context, R.color.black_3));
materialSpinner.setArrowColor(ContextCompat.getColor(context, R.color.dark_text));
materialSpinner.setTextColor(ContextCompat.getColor(context, R.color.dark_text));
2019-09-06 17:55:14 +02:00
} else if (theme == THEME_DARK) {
2019-01-08 18:11:40 +01:00
materialSpinner.setBackgroundColor(ContextCompat.getColor(context, R.color.mastodonC1));
materialSpinner.setArrowColor(ContextCompat.getColor(context, R.color.dark_text));
materialSpinner.setTextColor(ContextCompat.getColor(context, R.color.dark_text));
2019-09-06 17:55:14 +02:00
} else {
2019-01-08 18:11:40 +01:00
materialSpinner.setBackgroundColor(ContextCompat.getColor(context, R.color.white));
materialSpinner.setArrowColor(ContextCompat.getColor(context, R.color.black));
materialSpinner.setTextColor(ContextCompat.getColor(context, R.color.black));
}
}
2019-01-18 16:11:48 +01:00
public static class CacheTask extends AsyncTask<Void, Void, Void> {
private float cacheSize;
private WeakReference<Context> contextReference;
public CacheTask(Context context) {
contextReference = new WeakReference<>(context);
}
@Override
protected Void doInBackground(Void... params) {
long sizeCache = Helper.cacheSize(contextReference.get().getCacheDir().getParentFile());
cacheSize = 0;
if (sizeCache > 0) {
cacheSize = (float) sizeCache / 1000000.0f;
}
return null;
}
@Override
protected void onPostExecute(Void result) {
int style;
SharedPreferences sharedpreferences = contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
final int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
if (theme == Helper.THEME_DARK) {
style = R.style.DialogDark;
} else if (theme == Helper.THEME_BLACK) {
style = R.style.DialogBlack;
} else {
style = R.style.Dialog;
}
AlertDialog.Builder builder = new AlertDialog.Builder(contextReference.get(), style);
2019-09-06 17:55:14 +02:00
LayoutInflater inflater = ((MainActivity) contextReference.get()).getLayoutInflater();
View dialogView = inflater.inflate(R.layout.popup_cache, new LinearLayout((MainActivity) contextReference.get()), false);
2019-08-22 19:57:51 +02:00
TextView message = dialogView.findViewById(R.id.message);
message.setText(contextReference.get().getString(R.string.cache_message, String.format("%s %s", String.format(Locale.getDefault(), "%.2f", cacheSize), contextReference.get().getString(R.string.cache_units))));
builder.setView(dialogView);
2019-01-18 16:11:48 +01:00
builder.setTitle(R.string.cache_title);
2019-08-22 19:57:51 +02:00
final CheckBox cache_timeline = dialogView.findViewById(R.id.cache_timeline);
final CheckBox cache_owntoots = dialogView.findViewById(R.id.cache_owntoots);
final CheckBox cache_bookmarks = dialogView.findViewById(R.id.cache_bookmarks);
final SwitchCompat clean_all = dialogView.findViewById(R.id.clean_all);
2019-01-18 16:11:48 +01:00
final float finalCacheSize = cacheSize;
2019-08-22 19:57:51 +02:00
builder
2019-01-18 16:11:48 +01:00
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
String path = contextReference.get().getCacheDir().getParentFile().getPath();
File dir = new File(path);
if (dir.isDirectory()) {
Helper.deleteDir(dir);
}
2019-07-22 12:27:46 +02:00
SQLiteDatabase db = Sqlite.getInstance(contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
new StatusCacheDAO(contextReference.get(), db).removeDuplicate();
2019-09-06 17:55:14 +02:00
if (clean_all.isChecked()) {
if (cache_timeline.isChecked()) {
2019-08-22 19:57:51 +02:00
new TimelineCacheDAO(contextReference.get(), db).removeAll();
}
2019-09-06 17:55:14 +02:00
if (cache_owntoots.isChecked()) {
2019-08-23 09:29:30 +02:00
new StatusCacheDAO(contextReference.get(), db).removeAll(ARCHIVE_CACHE);
2019-08-22 19:57:51 +02:00
}
2019-09-06 17:55:14 +02:00
if (cache_bookmarks.isChecked()) {
2019-08-23 09:29:30 +02:00
new StatusCacheDAO(contextReference.get(), db).removeAll(BOOKMARK_CACHE);
2019-08-22 19:57:51 +02:00
}
2019-09-06 17:55:14 +02:00
} else {
if (cache_timeline.isChecked()) {
2019-08-22 19:57:51 +02:00
new TimelineCacheDAO(contextReference.get(), db).removeAllConnected();
}
2019-09-06 17:55:14 +02:00
if (cache_owntoots.isChecked()) {
2019-08-23 09:29:30 +02:00
new StatusCacheDAO(contextReference.get(), db).removeAllStatus(ARCHIVE_CACHE);
2019-08-22 19:57:51 +02:00
}
2019-09-06 17:55:14 +02:00
if (cache_bookmarks.isChecked()) {
2019-08-23 09:29:30 +02:00
new StatusCacheDAO(contextReference.get(), db).removeAllStatus(BOOKMARK_CACHE);
2019-08-22 19:57:51 +02:00
}
}
2019-01-18 16:11:48 +01:00
} catch (Exception ignored) {
}
}
});
Toasty.success(contextReference.get(), contextReference.get().getString(R.string.toast_cache_clear, String.format("%s %s", String.format(Locale.getDefault(), "%.2f", finalCacheSize), contextReference.get().getString(R.string.cache_units))), Toast.LENGTH_LONG).show();
dialog.dismiss();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
2019-02-23 14:39:51 +01:00
public static String getFilePathFromURI(Context context, Uri contentUri) {
//copy file and send new file path
String fileName = getFileName(contentUri);
if (!TextUtils.isEmpty(fileName)) {
File copyFile = new File(context.getCacheDir() + File.separator + fileName);
copy(context, contentUri, copyFile);
return copyFile.getAbsolutePath();
}
return null;
}
public static String getFileName(Uri uri) {
if (uri == null) return null;
String fileName = null;
String path = uri.getPath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}
public static void copy(Context context, Uri srcUri, File dstFile) {
try {
InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
if (inputStream == null) return;
OutputStream outputStream = new FileOutputStream(dstFile);
copyStream(inputStream, outputStream);
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2019-03-02 15:43:40 +01:00
2019-04-17 16:25:42 +02:00
/*
* List from ClearUrls
* https://gitlab.com/KevinRoebert/ClearUrls/blob/master/data/data.min.json#L106
*/
private static final String[] UTM_PARAMS = {
"utm_\\w+",
"ga_source",
"ga_medium",
"ga_term",
"ga_content",
"ga_campaign",
"ga_place",
"yclid",
"_openstat",
"fb_action_ids",
"fb_action_types",
"fb_source",
"fb_ref",
"fbclid",
"action_object_map",
"action_type_map",
"action_ref_map",
"gs_l",
"mkt_tok",
"hmb_campaign",
"hmb_medium",
"hmb_source",
"[\\?|&]ref[\\_]?"
};
2019-09-06 17:55:14 +02:00
public static String remove_tracking_param(String original_content) {
if (original_content == null)
2019-04-17 16:25:42 +02:00
return original_content;
String cleaned_content = original_content;
2019-09-06 17:55:14 +02:00
for (String utm : UTM_PARAMS) {
cleaned_content = cleaned_content.replaceAll("&amp;" + utm + "=[0-9a-zA-Z._-]*", "");
cleaned_content = cleaned_content.replaceAll("&" + utm + "=[0-9a-zA-Z._-]*", "");
cleaned_content = cleaned_content.replaceAll("\\?" + utm + "=[0-9a-zA-Z._-]*", "?");
2019-04-17 16:25:42 +02:00
}
return cleaned_content;
}
2019-03-02 15:43:40 +01:00
2019-04-21 09:12:10 +02:00
public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Map.Entry<T, E> entry : map.entrySet()) {
2019-04-21 12:09:30 +02:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (Objects.equals(value, entry.getValue())) {
return entry.getKey();
}
2019-04-21 09:12:10 +02:00
}
}
return null;
}
2019-04-21 12:09:30 +02:00
2019-09-06 17:55:14 +02:00
public static void download(Context context, String file, String url) {
FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(context)
.setDownloadConcurrentLimit(3)
.build();
Fetch fetch = Fetch.Impl.getInstance(fetchConfiguration);
FetchListener fetchListener = new FetchListener() {
@Override
public void onWaitingNetwork(@NotNull Download download) {
}
2019-09-06 17:55:14 +02:00
@Override
public void onStarted(@NotNull Download download, @NotNull List<? extends DownloadBlock> list, int i) {
}
2019-09-06 17:55:14 +02:00
@Override
public void onResumed(@NotNull Download download) {
}
2019-09-06 17:55:14 +02:00
@Override
public void onRemoved(@NotNull Download download) {
}
2019-09-06 17:55:14 +02:00
@Override
public void onQueued(@NotNull Download download, boolean b) {
}
2019-09-06 17:55:14 +02:00
@Override
public void onProgress(@NotNull Download download, long l, long l1) {
}
2019-09-06 17:55:14 +02:00
@Override
public void onPaused(@NotNull Download download) {
}
2019-09-06 17:55:14 +02:00
@Override
public void onError(@NotNull Download download, @NotNull Error error, @org.jetbrains.annotations.Nullable Throwable throwable) {
2019-09-06 17:55:14 +02:00
Toasty.error(context, context.getString(R.string.toast_error), Toast.LENGTH_LONG).show();
}
2019-09-06 17:55:14 +02:00
@Override
public void onDownloadBlockUpdated(@NotNull Download download, @NotNull DownloadBlock downloadBlock, int i) {
}
2019-09-06 17:55:14 +02:00
@Override
public void onDeleted(@NotNull Download download) {
}
2019-09-06 17:55:14 +02:00
@Override
public void onCompleted(@NotNull Download download) {
2019-09-06 17:55:14 +02:00
if (download.getFileUri().getPath() != null) {
String url = download.getUrl();
final String fileName = URLUtil.guessFileName(url, null, null);
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
String mime = Helper.getMimeType(url);
File file = new File(download.getFileUri().getPath());
final Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
2019-09-06 17:55:14 +02:00
Uri uri = Uri.parse("file://" + file.getAbsolutePath());
intent.setDataAndType(uri, mime);
2019-08-01 17:41:59 +02:00
SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context));
Account account = new AccountDAO(context, db).getUniqAccount(userId, instance);
2019-08-01 18:15:11 +02:00
Helper.notify_user(context, account, intent, BitmapFactory.decodeResource(context.getResources(),
2019-09-25 13:55:03 +02:00
R.mipmap.ic_launcher_bubbles), Helper.NotifType.STORE, context.getString(R.string.save_over), context.getString(R.string.download_from, fileName));
}
}
2019-09-06 17:55:14 +02:00
@Override
public void onCancelled(@NotNull Download download) {
}
2019-09-06 17:55:14 +02:00
@Override
public void onAdded(@NotNull Download download) {
}
};
fetch.addListener(fetchListener);
final Request request = new Request(url, file);
request.setPriority(Priority.HIGH);
request.setNetworkType(NetworkType.ALL);
fetch.enqueue(request, updatedRequest -> {
//Request was successfully enqueued for download.
}, error -> {
});
}
2019-04-21 12:09:30 +02:00
2019-06-05 18:23:44 +02:00
public static Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
2019-06-12 08:05:36 +02:00
public static volatile boolean orbotConnected = false;
public static void initNetCipher(Context context) {
Context appContext = context.getApplicationContext();
try {
StrongOkHttpClientBuilder.forMaxSecurity(appContext).build(new StrongBuilder.Callback<OkHttpClient>() {
@Override
public void onConnected(OkHttpClient okHttpClient) {
2019-06-12 10:04:52 +02:00
UploadService.HTTP_STACK = new OkHttpStack(getHttpClient(context));
2019-06-12 08:05:36 +02:00
orbotConnected = true;
}
@Override
public void onConnectionException(Exception exc) {
orbotConnected = false;
}
@Override
public void onTimeout() {
orbotConnected = false;
}
@Override
public void onInvalid() {
orbotConnected = false;
}
});
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
}
2019-06-12 08:05:36 +02:00
}
2019-06-12 10:04:52 +02:00
public static OkHttpClient getHttpClient(Context context) {
2019-10-20 11:25:28 +02:00
SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
boolean proxyEnabled = sharedpreferences.getBoolean(Helper.SET_PROXY_ENABLED, false);
2019-06-12 10:04:52 +02:00
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
.followRedirects(true)
.followSslRedirects(true)
.retryOnConnectionFailure(true)
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.cache(null);
2019-10-20 11:25:28 +02:00
if (proxyEnabled) {
Proxy proxy;
int type = sharedpreferences.getInt(Helper.SET_PROXY_TYPE, 0);
try {
String host = sharedpreferences.getString(Helper.SET_PROXY_HOST, "127.0.0.1");
int port = sharedpreferences.getInt(Helper.SET_PROXY_PORT, 8118);
if (type == 0)
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
else
proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(host, port));
final String login = sharedpreferences.getString(Helper.SET_PROXY_LOGIN, null);
final String pwd = sharedpreferences.getString(Helper.SET_PROXY_PASSWORD, null);
if (login != null) {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
assert pwd != null;
return (new PasswordAuthentication(login,
pwd.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
}
} catch (Exception e) {
proxy = null;
}
if( proxy != null) {
clientBuilder.proxy(proxy);
}
}
2019-06-12 10:04:52 +02:00
return enableTls12OnPreLollipop(clientBuilder).build();
}
private static OkHttpClient.Builder enableTls12OnPreLollipop(OkHttpClient.Builder client) {
if (Build.VERSION.SDK_INT < 22) {
try {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, null);
client.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));
ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.build();
List<ConnectionSpec> specs = new ArrayList<>();
specs.add(cs);
specs.add(ConnectionSpec.COMPATIBLE_TLS);
specs.add(ConnectionSpec.CLEARTEXT);
client.connectionSpecs(specs);
2019-09-06 17:55:14 +02:00
} catch (Exception ignored) {
}
2019-06-12 10:04:52 +02:00
}
return client;
}
2019-09-06 17:55:14 +02:00
public static void exportInstanceBlock(Context context, String username) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
2019-09-06 17:55:14 +02:00
String backupDBPath = "instance_mute_" + timeStamp + ".csv";
File sd = Environment.getExternalStorageDirectory();
final String filename = sd + "/" + backupDBPath;
new AsyncTask<Void, Void, List<String>>() {
private WeakReference<Context> contextReference = new WeakReference<>(context);
APIResponse apiResponse;
@Override
protected void onPreExecute() {
}
@Override
protected List<String> doInBackground(Void... voids) {
apiResponse = new API(contextReference.get()).getBlockedDomain(null);
return apiResponse.getDomains();
}
2019-09-06 17:55:14 +02:00
@Override
2019-09-06 17:55:14 +02:00
protected void onPostExecute(List<String> domains) {
if (domains == null) {
return;
}
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
int style;
if (theme == Helper.THEME_DARK) {
style = R.style.DialogDark;
2019-09-06 17:55:14 +02:00
} else if (theme == Helper.THEME_BLACK) {
style = R.style.DialogBlack;
2019-09-06 17:55:14 +02:00
} else {
style = R.style.Dialog;
}
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style);
2019-09-06 17:55:14 +02:00
LayoutInflater inflater = ((MutedInstanceActivity) context).getLayoutInflater();
ScrollView scrollView = new ScrollView(context);
LinearLayout linearLayout_main = new LinearLayout(context);
linearLayout_main.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout_main.setOrientation(LinearLayout.VERTICAL);
2019-09-06 17:55:14 +02:00
for (String domain : domains) {
View item = inflater.inflate(R.layout.muted_instance_popup, new LinearLayout(context), false);
CheckBox checkBox = item.findViewById(R.id.popup_domain);
checkBox.setText(domain);
linearLayout_main.addView(item);
}
scrollView.addView(linearLayout_main);
dialogBuilder.setView(scrollView);
HashMap<String, String> domainBlocked = new HashMap<>();
dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
2019-09-06 17:55:14 +02:00
for (int i = 0; i < linearLayout_main.getChildCount(); i++) {
LinearLayout linearLayout = (LinearLayout) linearLayout_main.getChildAt(i);
CheckBox checkBox = linearLayout.findViewById(R.id.popup_domain);
EditText editText = linearLayout.findViewById(R.id.popup_comment);
2019-09-06 17:55:14 +02:00
if (checkBox.isChecked()) {
String comment = null;
String domain = checkBox.getText().toString().trim();
2019-09-06 17:55:14 +02:00
if (editText.getText() != null) {
comment = editText.getText().toString().trim();
}
domainBlocked.put(domain, comment);
}
}
2019-09-06 17:55:14 +02:00
if (domainBlocked.size() > 0) {
new Thread() {
public void run() {
try {
FileWriter fw = new FileWriter(filename);
fw.append("INSTANCE");
fw.append(',');
fw.append("COMMENT");
fw.append('\n');
Iterator it = domainBlocked.entrySet().iterator();
while (it.hasNext()) {
2019-09-06 17:55:14 +02:00
Map.Entry pair = (Map.Entry) it.next();
fw.append((String) pair.getKey());
fw.append(',');
2019-09-06 17:55:14 +02:00
fw.append((String) pair.getValue());
fw.append('\n');
it.remove();
}
fw.close();
} catch (Exception ignored) {
}
final Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(filename));
intent.setDataAndType(uri, "text/csv");
2019-08-01 17:41:59 +02:00
SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(context));
Account account = new AccountDAO(context, db).getUniqAccount(userId, instance);
2019-09-06 17:55:14 +02:00
Helper.notify_user(context, account, intent, BitmapFactory.decodeResource(context.getResources(),
2019-09-25 13:55:03 +02:00
R.mipmap.ic_launcher_bubbles), Helper.NotifType.STORE, context.getString(R.string.muted_instance_exported), context.getString(R.string.download_from, backupDBPath));
}
}.start();
}
dialog.dismiss();
}
});
dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
2019-09-06 17:55:14 +02:00
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
2019-09-06 17:55:14 +02:00
public static void importInstanceBlock(Context context, HashMap<String, String> instances) {
final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
int style;
if (theme == Helper.THEME_DARK) {
style = R.style.DialogDark;
2019-09-06 17:55:14 +02:00
} else if (theme == Helper.THEME_BLACK) {
style = R.style.DialogBlack;
2019-09-06 17:55:14 +02:00
} else {
style = R.style.Dialog;
}
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, style);
2019-09-06 17:55:14 +02:00
LayoutInflater inflater = ((MutedInstanceActivity) context).getLayoutInflater();
ScrollView scrollView = new ScrollView(context);
LinearLayout linearLayout_main = new LinearLayout(context);
linearLayout_main.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout_main.setOrientation(LinearLayout.VERTICAL);
Iterator it = instances.entrySet().iterator();
while (it.hasNext()) {
2019-09-06 17:55:14 +02:00
Map.Entry pair = (Map.Entry) it.next();
View item = inflater.inflate(R.layout.muted_instance_popup, new LinearLayout(context), false);
CheckBox checkBox = item.findViewById(R.id.popup_domain);
checkBox.setText(pair.getKey().toString().trim());
item.findViewById(R.id.popup_comment).setVisibility(View.GONE);
2019-09-06 17:55:14 +02:00
if (pair.getValue() != null) {
TextView textView = item.findViewById(R.id.comment_text);
textView.setText(pair.getValue().toString());
textView.setVisibility(View.VISIBLE);
}
linearLayout_main.addView(item);
it.remove();
}
scrollView.addView(linearLayout_main);
dialogBuilder.setView(scrollView);
HashMap<String, String> domainBlocked = new HashMap<>();
dialogBuilder.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
2019-09-06 17:55:14 +02:00
for (int i = 0; i < linearLayout_main.getChildCount(); i++) {
LinearLayout linearLayout = (LinearLayout) linearLayout_main.getChildAt(i);
CheckBox checkBox = linearLayout.findViewById(R.id.popup_domain);
2019-09-06 17:55:14 +02:00
if (checkBox.isChecked()) {
String domain = checkBox.getText().toString().trim();
domainBlocked.put(domain, null);
}
}
2019-09-06 17:55:14 +02:00
if (domainBlocked.size() > 0) {
new Thread() {
public void run() {
Iterator it = domainBlocked.entrySet().iterator();
while (it.hasNext()) {
2019-09-06 17:55:14 +02:00
Map.Entry pair = (Map.Entry) it.next();
try {
sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
2019-09-06 17:55:14 +02:00
new PostActionAsyncTask(context, API.StatusAction.BLOCK_DOMAIN, pair.getKey().toString().trim(), ((MutedInstanceActivity) context)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
it.remove();
}
}
}.start();
}
dialog.dismiss();
}
});
dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
new AsyncTask<Void, Void, List<String>>() {
private WeakReference<Context> contextReference = new WeakReference<>(context);
APIResponse apiResponse;
@Override
protected void onPreExecute() {
}
@Override
protected List<String> doInBackground(Void... voids) {
apiResponse = new API(contextReference.get()).getBlockedDomain(null);
return apiResponse.getDomains();
}
2019-09-06 17:55:14 +02:00
@Override
2019-09-06 17:55:14 +02:00
protected void onPostExecute(List<String> domains) {
if (domains == null) {
return;
}
}
2019-09-06 17:55:14 +02:00
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
2019-07-26 15:58:54 +02:00
2019-09-06 17:55:14 +02:00
public static String[] ALPHA = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
2019-08-19 19:25:42 +02:00
"s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "!", ",", "?",
2019-09-06 17:55:14 +02:00
".", "'"};
public static String[] MORSE = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..",
2019-08-19 19:25:42 +02:00
"--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
"..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----", "-.-.--", "--..--",
2019-09-06 17:55:14 +02:00
"..--..", ".-.-.-", ".----.",};
2019-08-19 19:25:42 +02:00
2019-09-06 17:55:14 +02:00
public static Bitmap drawableToBitmap(Drawable drawable) {
2019-07-26 15:58:54 +02:00
Bitmap bitmap;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
2019-09-06 17:55:14 +02:00
if (bitmapDrawable.getBitmap() != null) {
2019-07-26 15:58:54 +02:00
return bitmapDrawable.getBitmap();
}
}
2019-09-06 17:55:14 +02:00
if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
2019-07-26 15:58:54 +02:00
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
2019-09-22 18:35:16 +02:00
2019-10-19 15:51:07 +02:00
public static HashMap<String, Integer> sleeps = new HashMap<>();
2019-10-21 15:07:16 +02:00
2019-10-27 15:16:40 +01:00
public static void startStreaming(Context context) {
2019-10-19 15:51:07 +02:00
int liveNotifications = Helper.liveNotifType(context);
switch (liveNotifications){
case Helper.NOTIF_LIVE:
Intent streamingIntent = new Intent(context, LiveNotificationService.class);
context.startService(streamingIntent);
break;
case Helper.NOTIF_DELAYED:
streamingIntent = new Intent(context, LiveNotificationDelayedService.class);
context.startService(streamingIntent);
break;
}
}
2017-05-05 16:36:04 +02:00
}