forked from criticalmaps/criticalmaps-android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatModel.java
More file actions
80 lines (62 loc) · 2.54 KB
/
ChatModel.java
File metadata and controls
80 lines (62 loc) · 2.54 KB
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
package de.stephanlindauer.criticalmaps.model;
import androidx.annotation.NonNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import de.stephanlindauer.criticalmaps.model.chat.ReceivedChatMessage;
import de.stephanlindauer.criticalmaps.utils.AeSimpleSHA1;
import timber.log.Timber;
@Singleton
public class ChatModel {
private final UserModel userModel;
private List<ReceivedChatMessage> receivedChatMessages = new ArrayList<>();
public static final int MESSAGE_MAX_LENGTH = 255;
@Inject
public ChatModel(UserModel userModel) {
this.userModel = userModel;
}
@NonNull
public List<ReceivedChatMessage> getReceivedChatMessages() {
return this.receivedChatMessages;
}
public void setFromJson(JSONArray jsonArray) throws JSONException,
UnsupportedEncodingException {
receivedChatMessages = new ArrayList<>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String device = URLDecoder.decode(jsonObject.getString("device"), "UTF-8");
String identifier = URLDecoder.decode(jsonObject.getString("identifier"), "UTF-8");
String message = URLDecoder.decode(jsonObject.getString("message"), "UTF-8");
Date timestamp = new Date(Long.parseLong(jsonObject.getString("timestamp")) * 1000);
receivedChatMessages.add(new ReceivedChatMessage(message, timestamp));
}
receivedChatMessages.sort(Comparator.comparing(ReceivedChatMessage::getTimestamp));
}
public JSONObject createNewOutgoingMessage(String message) {
JSONObject messageObject = new JSONObject();
try {
messageObject.put("text", urlEncodeMessage(message));
messageObject.put("identifier", AeSimpleSHA1.SHA1(message + Math.random()));
messageObject.put("device", userModel.getChangingDeviceToken());
} catch (JSONException e) {
Timber.d(e);
}
return messageObject;
}
private String urlEncodeMessage(String messageToEncode) {
try {
return URLEncoder.encode(messageToEncode, "UTF-8");
} catch (UnsupportedEncodingException e) {
return "";
}
}
}