summaryrefslogtreecommitdiffstats
path: root/app/src/main/java/app/fedilab/android/mastodon/client/entities/api/EmojiInstance.java
blob: ce672178ff41661f40f6702cc73cb32374cdc02a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package app.fedilab.android.mastodon.client.entities.api;
/* Copyright 2021 Thomas Schneider
 *
 * This file is a part of Fedilab
 *
 * 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.
 *
 * Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with Fedilab; if not,
 * see <http://www.gnu.org/licenses>. */

import static app.fedilab.android.BaseMainActivity.emojis;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteBlobTooBigException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;

import java.io.Serializable;
import java.net.IDN;
import java.util.ArrayList;
import java.util.List;

import app.fedilab.android.BaseMainActivity;
import app.fedilab.android.mastodon.client.endpoints.MastodonInstanceService;
import app.fedilab.android.mastodon.exception.DBException;
import app.fedilab.android.mastodon.helper.Helper;
import app.fedilab.android.mastodon.viewmodel.mastodon.InstancesVM;
import app.fedilab.android.sqlite.Sqlite;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class EmojiInstance implements Serializable {
    private final SQLiteDatabase db;
    @SerializedName("instance")
    public String instance;
    @SerializedName("emojiList")
    public List<Emoji> emojiList;
    private Context context;

    public EmojiInstance() {
        db = null;
    }

    public EmojiInstance(Context context) {
        //Creation of the DB with tables
        this.context = context;
        this.db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
    }

    /**
     * Serialized a list of Emoji class
     *
     * @param emojis List of {@link Emoji} to serialize
     * @return String serialized emoji list
     */
    public static String mastodonEmojiListToStringStorage(List<Emoji> emojis) {
        Gson gson = new Gson();
        try {
            return gson.toJson(emojis);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Unserialized a Emoji List
     *
     * @param serializedEmojiList String serialized account
     * @return List of {@link Emoji}
     */
    public static List<Emoji> restoreEmojiListFromString(String serializedEmojiList) {
        Gson gson = new Gson();
        try {
            return gson.fromJson(serializedEmojiList, new TypeToken<List<Emoji>>() {
            }.getType());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Insert or update emoji
     *
     * @param emojiInstance {@link EmojiInstance}
     * @return long - db id
     * @throws DBException exception with database
     */
    public long insertOrUpdate(EmojiInstance emojiInstance) throws DBException {
        if (db == null) {
            throw new DBException("db is null. Wrong initialization.");
        }
        if (emojiInstance == null) {
            return -1;
        }
        boolean exists = emojiInstanceExist(emojiInstance);
        long idReturned;
        if (exists) {
            idReturned = updateEmojiInstance(emojiInstance);
        } else {
            idReturned = insertEmojiInstance(emojiInstance);
        }
        return idReturned;
    }

    /**
     * Check if emojis exists in db
     *
     * @param emojiInstance EmojiInstance {@link EmojiInstance}
     * @return boolean - emojiInstance exists
     * @throws DBException Exception
     */
    public boolean emojiInstanceExist(EmojiInstance emojiInstance) throws DBException {
        if (db == null) {
            throw new DBException("db is null. Wrong initialization.");
        }
        Cursor mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_EMOJI_INSTANCE
                + " where " + Sqlite.COL_INSTANCE + " = '" + emojiInstance.instance + "'", null);
        mCount.moveToFirst();
        int count = mCount.getInt(0);
        mCount.close();
        return (count > 0);
    }

    /**
     * Insert emojis in db
     *
     * @param emojiInstance {@link EmojiInstance}
     * @return long - db id
     * @throws DBException exception with database
     */
    private long insertEmojiInstance(EmojiInstance emojiInstance) throws DBException {
        if (db == null) {
            throw new DBException("db is null. Wrong initialization.");
        }
        ContentValues values = new ContentValues();
        values.put(Sqlite.COL_INSTANCE, emojiInstance.instance);
        values.put(Sqlite.COL_EMOJI_LIST, mastodonEmojiListToStringStorage(emojiInstance.emojiList));
        //Inserts token
        try {
            return db.insertOrThrow(Sqlite.TABLE_EMOJI_INSTANCE, null, values);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * update emojis in db
     *
     * @param emojiInstance {@link EmojiInstance}
     * @return long - db id
     * @throws DBException exception with database
     */
    private long updateEmojiInstance(EmojiInstance emojiInstance) throws DBException {
        if (db == null) {
            throw new DBException("db is null. Wrong initialization.");
        }
        ContentValues values = new ContentValues();
        values.put(Sqlite.COL_EMOJI_LIST, mastodonEmojiListToStringStorage(emojiInstance.emojiList));
        //Inserts token
        try {
            return db.update(Sqlite.TABLE_EMOJI_INSTANCE,
                    values, Sqlite.COL_INSTANCE + " =  ?",
                    new String[]{emojiInstance.instance});
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }


    private MastodonInstanceService init(String instance) {
        final OkHttpClient okHttpClient = Helper.myOkHttpClient(context);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://" + (instance != null ? IDN.toASCII(instance, IDN.ALLOW_UNASSIGNED) : null) + "/api/v1/")
                .addConverterFactory(GsonConverterFactory.create(Helper.getDateBuilder()))
                .client(okHttpClient)
                .build();
        return retrofit.create(MastodonInstanceService.class);
    }

    /**
     * Returns the emojis for an instance
     *
     * @param instance String
     * @return List<Emoji> - List of {@link Emoji}
     */
    public List<Emoji> getEmojiList(String instance) throws DBException {
        if (db == null) {
            throw new DBException("db is null. Wrong initialization.");
        }
        try {
            Cursor c = db.query(Sqlite.TABLE_EMOJI_INSTANCE, null, Sqlite.COL_INSTANCE + " = '" + instance + "'", null, null, null, null, "1");
            return cursorToEmojiList(c);
        } catch (Exception e) {
            MastodonInstanceService mastodonInstanceService = init(instance);
            Call<List<Emoji>> emojiCall = mastodonInstanceService.customEmoji();
            if (emojiCall != null) {
                try {
                    Response<List<Emoji>> emojiResponse = emojiCall.execute();
                    if (emojiResponse.isSuccessful()) {
                        return emojiResponse.body();
                    }
                } catch (Exception err) {
                    err.printStackTrace();
                }
            }
            return null;
        }
    }

    public interface EmojiFilteredCallBack{
        void get(List<Emoji> emojiList);
    }

    /**
     * Returns the emojis for an instance
     *
     * @param instance String
     * @param filter String
     * @param callBack EmojiFilteredCallBack  - Get filtered emojis
     *
     * @return List<Emoji> - List of {@link Emoji}
     */
    public void getEmojiListFiltered(@NonNull String instance, @NonNull String filter, EmojiFilteredCallBack callBack) throws DBException {
        if (db == null) {
            throw new DBException("db is null. Wrong initialization.");
        }
        new Thread(() -> {
            List<Emoji> emojiArrayList= new ArrayList<>();
            List<Emoji> emojiFiltered= new ArrayList<>();
            if (emojis == null || !emojis.containsKey(BaseMainActivity.currentInstance) || emojis.get(BaseMainActivity.