mirror of
https://github.com/szkolny-eu/szkolny-android.git
synced 2025-06-13 14:10:46 +02:00
[Firebase] Implement base for per-register FCM tasks.
This commit is contained in:
@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright (c) Kuba Szczodrzyński 2020-1-11.
|
||||
*/
|
||||
|
||||
package pl.szczodrzynski.edziennik.data.firebase
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import androidx.legacy.content.WakefulBroadcastReceiver
|
||||
import com.google.gson.JsonObject
|
||||
|
||||
class FirebaseBroadcastReceiver : WakefulBroadcastReceiver() {
|
||||
companion object {
|
||||
private const val TAG = "FirebaseBroadcast"
|
||||
}
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val extras = intent.extras
|
||||
val json = JsonObject()
|
||||
extras?.keySet()?.forEach { key ->
|
||||
extras.get(key)?.let {
|
||||
when (it) {
|
||||
is String -> json.addProperty(key, it)
|
||||
is Int -> json.addProperty(key, it)
|
||||
is Long -> json.addProperty(key, it)
|
||||
is Float -> json.addProperty(key, it)
|
||||
is Boolean -> json.addProperty(key, it)
|
||||
else -> json.addProperty(key, it.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
Log.d(TAG, "Intent(action=${intent?.action}, extras=$json)")
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright (c) Kuba Szczodrzyński 2020-1-11.
|
||||
*/
|
||||
|
||||
package pl.szczodrzynski.edziennik.data.firebase
|
||||
|
||||
class FirebaseSendException(reason: String?) : Exception(reason) {
|
||||
companion object {
|
||||
const val ERROR_UNKNOWN = 0
|
||||
const val ERROR_INVALID_PARAMETERS = 1
|
||||
const val ERROR_SIZE = 2
|
||||
const val ERROR_TTL_EXCEEDED = 3
|
||||
const val ERROR_TOO_MANY_MESSAGES = 4
|
||||
}
|
||||
|
||||
val errorCode = when (reason) {
|
||||
"service_not_available" -> ERROR_TTL_EXCEEDED
|
||||
"toomanymessages" -> ERROR_TOO_MANY_MESSAGES
|
||||
"invalid_parameters" -> ERROR_INVALID_PARAMETERS
|
||||
"messagetoobig" -> ERROR_SIZE
|
||||
"missing_to" -> ERROR_INVALID_PARAMETERS
|
||||
else -> ERROR_UNKNOWN
|
||||
}
|
||||
}
|
@ -0,0 +1,190 @@
|
||||
/*
|
||||
* Copyright (c) Kuba Szczodrzyński 2020-1-11.
|
||||
*/
|
||||
|
||||
package pl.szczodrzynski.edziennik.data.firebase
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.PendingIntent
|
||||
import android.app.PendingIntent.CanceledException
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import com.google.firebase.iid.zzaq
|
||||
import com.google.firebase.iid.zzv
|
||||
import com.google.firebase.messaging.MessagingAnalytics
|
||||
import com.google.firebase.messaging.zzc
|
||||
import com.google.gson.JsonObject
|
||||
import pl.szczodrzynski.edziennik.*
|
||||
import java.util.*
|
||||
|
||||
@SuppressLint("Registered")
|
||||
open class FirebaseService : zzc() {
|
||||
companion object {
|
||||
private const val TAG = "FirebaseService"
|
||||
}
|
||||
|
||||
private val messageQueue = ArrayDeque<String>(10)
|
||||
|
||||
open fun onMessageReceived(message: Message) = Unit
|
||||
open fun onDeletedMessages() = Unit
|
||||
open fun onMessageSent(messageId: String?) = Unit
|
||||
open fun onSendError(messageId: String?, exception: Exception) = Unit
|
||||
open fun onNewToken(token: String?) = Unit
|
||||
|
||||
// apparently this gets the correct intent from some
|
||||
// kind of queue inside Firebase's InstanceID Receiver
|
||||
final override fun zza(intent: Intent?) = zzaq.zza()?.zzb()
|
||||
final override fun zzb(intent: Intent?): Boolean {
|
||||
val action = intent?.action
|
||||
if (action == "com.google.firebase.messaging.NOTIFICATION_OPEN") {
|
||||
intent.getParcelableExtra<PendingIntent>("pending_intent")?.let {
|
||||
try {
|
||||
it.send()
|
||||
} catch (e: CanceledException) {
|
||||
Log.e(TAG, "Notification pending intent canceled")
|
||||
}
|
||||
}
|
||||
|
||||
if (MessagingAnalytics.shouldUploadMetrics(intent)) {
|
||||
MessagingAnalytics.logNotificationOpen(intent)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
final override fun zzc(intent: Intent?) {
|
||||
val action = intent?.action
|
||||
val json = intent?.toJsonObject()
|
||||
Log.d(TAG, "zzc Intent(action=$action, extras=$json)")
|
||||
if (action == null || json == null)
|
||||
return
|
||||
|
||||
when (action) {
|
||||
"com.google.firebase.messaging.NOTIFICATION_DISMISS" -> {
|
||||
if (MessagingAnalytics.shouldUploadMetrics(intent)) {
|
||||
MessagingAnalytics.logNotificationDismiss(intent)
|
||||
}
|
||||
}
|
||||
"com.google.firebase.messaging.NEW_TOKEN" -> {
|
||||
onNewToken(json.getString("token"))
|
||||
}
|
||||
"com.google.android.c2dm.intent.RECEIVE",
|
||||
"com.google.firebase.messaging.RECEIVE_DIRECT_BOOT" -> {
|
||||
val messageId = json.getString("google.message_id")
|
||||
if (messageId != null) {
|
||||
// send back an acknowledgement to Google Play Services
|
||||
val ackBundle = Bundle(
|
||||
"google.message_id" to messageId
|
||||
)
|
||||
zzv.zza(this).zza(2, ackBundle)
|
||||
}
|
||||
// check for duplicate message
|
||||
// and add it to queue
|
||||
if (messageId.isNotNullNorEmpty()) {
|
||||
if (messageQueue.contains(messageId)) {
|
||||
Log.d(TAG, "Received duplicate message: $messageId")
|
||||
return
|
||||
}
|
||||
if (messageQueue.size >= 10)
|
||||
messageQueue.remove()
|
||||
messageQueue += messageId
|
||||
}
|
||||
// process the received message
|
||||
processMessage(messageId, json, intent)
|
||||
}
|
||||
else -> {
|
||||
Log.d(TAG, "Unknown intent action: $action")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun processMessage(messageId: String?, json: JsonObject, intent: Intent) {
|
||||
// remove something that the original FMS removes
|
||||
json.remove("androidx.contentpager.content.wakelockid")
|
||||
|
||||
// get the message type
|
||||
when (val it = json.getString("message_type") ?: "gcm") {
|
||||
"gcm" -> { // 0
|
||||
if (MessagingAnalytics.shouldUploadMetrics(intent)) {
|
||||
MessagingAnalytics.logNotificationReceived(intent)
|
||||
}
|
||||
|
||||
onMessageReceived(Message(messageId, json))
|
||||
}
|
||||
"deleted_messages" -> { // 1
|
||||
onDeletedMessages()
|
||||
}
|
||||
"send_event" -> { // 2
|
||||
onMessageSent(messageId)
|
||||
}
|
||||
"send_error" -> { // 3
|
||||
onSendError(
|
||||
messageId ?: json.getString("message_id"),
|
||||
FirebaseSendException(json.getString("error"))
|
||||
)
|
||||
}
|
||||
else -> {
|
||||
Log.w(TAG, "Received message with unknown type: $it")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class Message(val messageId: String?, private val json: JsonObject) {
|
||||
val data = json.deepCopy()
|
||||
val from by lazy { s("from") ?: "" }
|
||||
val to by lazy { s("google.to") }
|
||||
val messageType by lazy { s("message_type") }
|
||||
val collapseKey by lazy { s("collapse_key") }
|
||||
val sentTime by lazy { l("google.sent_time") }
|
||||
val ttl by lazy { i("google.ttl") }
|
||||
val originalPriority by lazy { getPriority(s("google.original_priority") ?: s("priority")) }
|
||||
val priority by lazy { getPriority(
|
||||
s("google.delivered_priority") ?: if (i("google.priority_reduced") == 1)
|
||||
"normal"
|
||||
else s("google.priority")
|
||||
) }
|
||||
val isNotificationMessage by lazy { isNotificationMessage(json) }
|
||||
val notificationTitle by lazy { s("gcm.notification.title") }
|
||||
val notificationText by lazy { s("gcm.notification.body") }
|
||||
|
||||
init {
|
||||
data.also {
|
||||
val toRemove = mutableListOf<String>()
|
||||
it.keySet().forEach { key ->
|
||||
if (key.startsWith("google.")
|
||||
|| key.startsWith("gcm.")
|
||||
|| key == "from"
|
||||
|| key == "message_type"
|
||||
|| key == "collapse_key")
|
||||
toRemove += key
|
||||
}
|
||||
toRemove.forEach { key ->
|
||||
it.remove(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun s(key: String): String? = json.getString(key)
|
||||
private fun l(key: String): Long = json.getLong(key) ?: 0L
|
||||
private fun i(key: String): Int = json.getInt(key) ?: 0
|
||||
private fun isNotificationMessage(json: JsonObject): Boolean {
|
||||
return json.getInt("gcm.n.e") == 1
|
||||
|| json.getInt("gcm.notification.e") == 1
|
||||
|| json.getString("gcm.n.icon") != null
|
||||
|| json.getString("gcm.notification.icon") != null
|
||||
}
|
||||
private fun getPriority(str: String?): Int {
|
||||
return when (str) {
|
||||
"high" -> 1
|
||||
"normal" -> 2
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return "Message(messageId=$messageId, from=$from, data=$data)"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,328 @@
|
||||
/*
|
||||
* Copyright (c) Kuba Szczodrzyński 2020-1-11.
|
||||
*/
|
||||
|
||||
package pl.szczodrzynski.edziennik.data.firebase;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.AsyncTask;
|
||||
import android.util.Log;
|
||||
|
||||
import com.google.firebase.messaging.FirebaseMessagingService;
|
||||
import com.google.firebase.messaging.RemoteMessage;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import pl.szczodrzynski.edziennik.App;
|
||||
import pl.szczodrzynski.edziennik.BuildConfig;
|
||||
import pl.szczodrzynski.edziennik.MainActivity;
|
||||
import pl.szczodrzynski.edziennik.R;
|
||||
import pl.szczodrzynski.edziennik.data.api.task.EdziennikTask;
|
||||
import pl.szczodrzynski.edziennik.data.db.entity.Event;
|
||||
import pl.szczodrzynski.edziennik.data.db.entity.EventType;
|
||||
import pl.szczodrzynski.edziennik.data.db.entity.FeedbackMessage;
|
||||
import pl.szczodrzynski.edziennik.data.db.entity.LoginStore;
|
||||
import pl.szczodrzynski.edziennik.data.db.entity.Profile;
|
||||
import pl.szczodrzynski.edziennik.data.db.entity.Team;
|
||||
import pl.szczodrzynski.edziennik.data.db.full.EventFull;
|
||||
import pl.szczodrzynski.edziennik.network.ServerRequest;
|
||||
import pl.szczodrzynski.edziennik.ui.modules.base.DebugFragment;
|
||||
import pl.szczodrzynski.edziennik.utils.models.Notification;
|
||||
|
||||
import static pl.szczodrzynski.edziennik.App.APP_URL;
|
||||
import static pl.szczodrzynski.edziennik.data.db.entity.Event.TYPE_HOMEWORK;
|
||||
import static pl.szczodrzynski.edziennik.utils.Utils.d;
|
||||
import static pl.szczodrzynski.edziennik.utils.Utils.strToInt;
|
||||
|
||||
public class MyFirebaseMessagingService extends FirebaseMessagingService {
|
||||
private static final String TAG = "FirebaseMessaging";
|
||||
|
||||
@Override
|
||||
public void onNewToken(String s) {
|
||||
super.onNewToken(s);
|
||||
|
||||
Log.d(TAG, "New token: "+s);
|
||||
App app = (App)getApplicationContext();
|
||||
if (app.config.getSync().getTokenApp() == null || !app.config.getSync().getTokenApp().equals(s)) {
|
||||
app.config.getSync().setTokenApp(s);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessageReceived(RemoteMessage remoteMessage) {
|
||||
App app = ((App) getApplicationContext());
|
||||
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
|
||||
|
||||
String from = remoteMessage.getFrom();
|
||||
if (from != null) {
|
||||
switch (from) {
|
||||
case "640759989760":
|
||||
app.debugLog("Firebase got push from App "+remoteMessage.getData().toString());
|
||||
//processAppPush
|
||||
processAppPush(app, remoteMessage);
|
||||
break;
|
||||
case "747285019373":
|
||||
app.debugLog("Firebase got push from Mobidziennik "+remoteMessage.getData().toString());
|
||||
processMobidziennikPush(app, remoteMessage);
|
||||
break;
|
||||
case "513056078587":
|
||||
app.debugLog("Firebase got push from Librus "+remoteMessage.getData().toString());
|
||||
processLibrusPush(app, remoteMessage);
|
||||
break;
|
||||
case "987828170337":
|
||||
app.debugLog("Firebase got push from Vulcan "+remoteMessage.getData().toString());
|
||||
processVulcanPush(app, remoteMessage);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processMobidziennikPush(App app, RemoteMessage remoteMessage) {
|
||||
SharedPreferences sharedPreferences = getSharedPreferences("pushtest_mobidziennik", Context.MODE_PRIVATE);
|
||||
sharedPreferences.edit().putString(Long.toString(System.currentTimeMillis()), remoteMessage.getData().toString()+"\n"+remoteMessage.toString()+"\n"+remoteMessage.getMessageType()).apply();
|
||||
String studentIdStr = remoteMessage.getData().get("id_ucznia");
|
||||
if (studentIdStr != null) {
|
||||
int studentId = strToInt(studentIdStr);
|
||||
AsyncTask.execute(() -> {
|
||||
List<Profile> profileList = app.db.profileDao().getAllNow();
|
||||
|
||||
Profile profile = null;
|
||||
|
||||
for (Profile profileFull: profileList) {
|
||||
if (profileFull.getLoginStoreType() == LoginStore.LOGIN_TYPE_MOBIDZIENNIK
|
||||
&& studentId == profileFull.getStudentData("studentId", -1)) {
|
||||
profile = profileFull;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (profile != null) {
|
||||
if (remoteMessage.getData().get("id_wiadomosci") != null) {
|
||||
/*app.notifier.add(new Notification(app.getContext(), remoteMessage.getData().get("message"))
|
||||
.withProfileData(profile.id, profile.name)
|
||||
.withTitle(remoteMessage.getData().get("title"))
|
||||
.withType(Notification.TYPE_NEW_MESSAGE)
|
||||
.withFragmentRedirect(MainActivity.DRAWER_ITEM_MESSAGES)
|
||||
);
|
||||
app.notifier.postAll(profile);
|
||||
app.saveConfig("notifications");*/
|
||||
d(TAG, "Syncing profile " + profile.getId());
|
||||
EdziennikTask.Companion.syncProfile(profile.getId(), null, null).enqueue(app);
|
||||
} else {
|
||||
/*app.notifier.add(new Notification(app.getContext(), remoteMessage.getData().get("message"))
|
||||
.withProfileData(profile.id, profile.name)
|
||||
.withTitle(remoteMessage.getData().get("title"))
|
||||
.withType(Notification.TYPE_SERVER_MESSAGE)
|
||||
.withFragmentRedirect(MainActivity.DRAWER_ITEM_HOME)
|
||||
);
|
||||
app.notifier.postAll(profile);
|
||||
app.saveConfig("notifications");*/
|
||||
d(TAG, "Syncing profile " + profile.getId());
|
||||
EdziennikTask.Companion.syncProfile(profile.getId(), null, null).enqueue(app);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void processLibrusPush(App app, RemoteMessage remoteMessage) {
|
||||
SharedPreferences sharedPreferences = getSharedPreferences("pushtest_librus", Context.MODE_PRIVATE);
|
||||
sharedPreferences.edit().putString(Long.toString(System.currentTimeMillis()), remoteMessage.getData().toString()+"\n"+remoteMessage.toString()+"\n"+remoteMessage.getMessageType()).apply();
|
||||
}
|
||||
|
||||
private void processVulcanPush(App app, RemoteMessage remoteMessage) {
|
||||
SharedPreferences sharedPreferences = getSharedPreferences("pushtest_vulcan", Context.MODE_PRIVATE);
|
||||
sharedPreferences.edit().putString(Long.toString(System.currentTimeMillis()), remoteMessage.getData().toString()+"\n"+remoteMessage.toString()+"\n"+remoteMessage.getMessageType()).apply();
|
||||
}
|
||||
|
||||
private void processAppPush(App app, RemoteMessage remoteMessage) {
|
||||
// Check if message contains a data payload.
|
||||
String type = remoteMessage.getData().get("type");
|
||||
if (remoteMessage.getData().size() > 0
|
||||
&& type != null) {
|
||||
//Log.d(TAG, "Message data payload: " + remoteMessage.sync());
|
||||
switch (type) {
|
||||
case "app_update":
|
||||
int versionCode = Integer.parseInt(remoteMessage.getData().get("update_version_code"));
|
||||
if (BuildConfig.VERSION_CODE < versionCode) {
|
||||
String updateVersion = remoteMessage.getData().get("update_version");
|
||||
String updateUrl = remoteMessage.getData().get("update_url");
|
||||
String updateFilename = remoteMessage.getData().get("update_filename");
|
||||
boolean updateMandatory = Boolean.parseBoolean(remoteMessage.getData().get("update_mandatory"));
|
||||
boolean updateDirect = Boolean.parseBoolean(remoteMessage.getData().get("update_direct"));
|
||||
|
||||
if (app.appConfig.updateVersion == null || !app.appConfig.updateVersion.equals(updateVersion)) {
|
||||
app.appConfig.updateVersion = updateVersion;
|
||||
app.appConfig.updateUrl = updateUrl;
|
||||
app.appConfig.updateFilename = updateFilename;
|
||||
app.appConfig.updateMandatory = updateMandatory;
|
||||
app.appConfig.updateDirect = updateDirect;
|
||||
app.saveConfig("updateVersion", "updateUrl", "updateFilename", "updateMandatory");
|
||||
}
|
||||
if (!remoteMessage.getData().containsKey("update_silent")) {
|
||||
app.notifier.notificationUpdatesShow(
|
||||
updateVersion,
|
||||
updateUrl,
|
||||
updateFilename,
|
||||
updateDirect);
|
||||
}
|
||||
} else {
|
||||
if (app.appConfig.updateVersion == null || !app.appConfig.updateVersion.equals("")) {
|
||||
app.appConfig.updateVersion = "";
|
||||
app.appConfig.updateMandatory = false;
|
||||
app.saveConfig("updateVersion", "updateMandatory");
|
||||
}
|
||||
app.notifier.notificationUpdatesHide();
|
||||
}
|
||||
break;
|
||||
case "message":
|
||||
app.notifier.add(new Notification(app.getContext(), remoteMessage.getData().get("message"))
|
||||
.withTitle(remoteMessage.getData().get("title"))
|
||||
.withType(pl.szczodrzynski.edziennik.data.db.entity.Notification.TYPE_SERVER_MESSAGE)
|
||||
.withFragmentRedirect(MainActivity.DRAWER_ITEM_NOTIFICATIONS)
|
||||
);
|
||||
app.notifier.postAll();
|
||||
app.saveConfig("notifications");
|
||||
break;
|
||||
case "feedback_message_from_dev":
|
||||
AsyncTask.execute(() -> {
|
||||
FeedbackMessage feedbackMessage = new FeedbackMessage(true, remoteMessage.getData().get("message"));
|
||||
if (feedbackMessage.text.startsWith("test")) {
|
||||
// todo
|
||||
}
|
||||
else {
|
||||
feedbackMessage.sentTime = Long.parseLong(remoteMessage.getData().get("sent_time"));
|
||||
if (feedbackMessage.text.startsWith("devmode")) {
|
||||
app.config.setDevModePassword(feedbackMessage.text.replace("devmode", ""));
|
||||
app.checkDevModePassword();
|
||||
feedbackMessage.text = "devmode "+(App.devMode ? "allowed" : "disallowed");
|
||||
}
|
||||
Intent intent = new Intent("pl.szczodrzynski.edziennik.ui.modules.base.FeedbackActivity");
|
||||
intent.putExtra("type", "user_chat");
|
||||
intent.putExtra("message", app.gson.toJson(feedbackMessage));
|
||||
app.sendBroadcast(intent);
|
||||
app.db.feedbackMessageDao().add(feedbackMessage);
|
||||
|
||||
app.notifier.add(new Notification(app.getContext(), feedbackMessage.text)
|
||||
.withTitle(remoteMessage.getData().get("title"))
|
||||
.withType(pl.szczodrzynski.edziennik.data.db.entity.Notification.TYPE_FEEDBACK_MESSAGE)
|
||||
.withFragmentRedirect(MainActivity.TARGET_FEEDBACK)
|
||||
);
|
||||
app.notifier.postAll();
|
||||
app.saveConfig("notifications");
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "feedback_message_from_user":
|
||||
AsyncTask.execute(() -> {
|
||||
FeedbackMessage feedbackMessage = new FeedbackMessage(true, remoteMessage.getData().get("message"));
|
||||
feedbackMessage.fromUser = remoteMessage.getData().get("from_user");
|
||||
feedbackMessage.fromUserName = remoteMessage.getData().get("from_user_name");
|
||||
feedbackMessage.sentTime = Long.parseLong(remoteMessage.getData().get("sent_time"));
|
||||
Intent intent = new Intent("pl.szczodrzynski.edziennik.ui.modules.base.FeedbackActivity");
|
||||
intent.putExtra("type", "user_chat");
|
||||
intent.putExtra("message", app.gson.toJson(feedbackMessage));
|
||||
app.sendBroadcast(intent);
|
||||
app.db.feedbackMessageDao().add(feedbackMessage);
|
||||
});
|
||||
app.notifier.add(new Notification(app.getContext(), remoteMessage.getData().get("message"))
|
||||
.withTitle(remoteMessage.getData().get("title"))
|
||||
.withType(pl.szczodrzynski.edziennik.data.db.entity.Notification.TYPE_FEEDBACK_MESSAGE)
|
||||
.withFragmentRedirect(MainActivity.TARGET_FEEDBACK)
|
||||
);
|
||||
app.notifier.postAll();
|
||||
app.saveConfig("notifications");
|
||||
break;
|
||||
case "ping":
|
||||
// just a ping
|
||||
break;
|
||||
/* ______ _ _
|
||||
| ____| | | | |
|
||||
| |____ _____ _ __ | |_ ______ ___| |__ __ _ _ __ ___
|
||||
| __\ \ / / _ \ '_ \| __| |______| / __| '_ \ / _` | '__/ _ \
|
||||
| |___\ V / __/ | | | |_ \__ \ | | | (_| | | | __/
|
||||
|______\_/ \___|_| |_|\__| |___/_| |_|\__,_|_| \__*/
|
||||
case "event":
|
||||
case "event_removed":
|
||||
AsyncTask.execute(() -> {
|
||||
String teamCode = remoteMessage.getData().get("team");
|
||||
String teamUnshareCode = remoteMessage.getData().get("team_unshare");
|
||||
while (teamCode != null || teamUnshareCode != null) {
|
||||
d(TAG, "Got an event for teamCode " + teamCode + " and teamUnshareCode " + teamUnshareCode);
|
||||
// get the target Profile by the corresponding teamCode
|
||||
List<Profile> profiles = app.db.profileDao().getByTeamCodeNowWithRegistration(teamCode == null ? teamUnshareCode : teamCode);
|
||||
for (Profile profile : profiles) {
|
||||
d(TAG, "Matched profile " + profile.getName());
|
||||
if (teamCode != null) {
|
||||
// SHARING
|
||||
JsonObject jEvent = new JsonParser().parse(remoteMessage.getData().get("data")).getAsJsonObject();
|
||||
d(TAG, "An event is there! " + jEvent.toString());
|
||||
// get the target Team from teamCode
|
||||
Team team = app.db.teamDao().getByCodeNow(profile.getId(), teamCode);
|
||||
if (team != null) {
|
||||
d(TAG, "The target team is " + team.name + ", ID " + team.id);
|
||||
// create the event from Json. Add the missing teamId and !!profileId!!
|
||||
Event event = app.gson.fromJson(jEvent.toString(), Event.class);
|
||||
if (jEvent.get("colorDefault") != null) {
|
||||
event.color = -1;
|
||||
}
|
||||
event.profileId = profile.getId();
|
||||
event.teamId = team.id;
|
||||
d(TAG, "Created the event! " + event);
|
||||
|
||||
// TODO? i guess
|
||||
Event oldEvent = app.db.eventDao().getByIdNow(profile.getId(), event.id);
|
||||
if (event.sharedBy != null && event.sharedBy.equals(profile.getUserCode())) {
|
||||
d(TAG, "Shared by self! Changing name");
|
||||
event.sharedBy = "self";
|
||||
event.sharedByName = profile.getStudentNameLong();
|
||||
}
|
||||
d(TAG, "Old event found? " + oldEvent);
|
||||
EventType eventType = app.db.eventTypeDao().getByIdNow(profile.getId(), event.type);
|
||||
app.notifier.add(new Notification(app.getContext(), app.getString((oldEvent == null ? R.string.notification_shared_event_format : R.string.notification_shared_event_modified_format), event.sharedByName, eventType == null ? "wydarzenie" : eventType.name, event.eventDate.getFormattedString(), event.topic))
|
||||
.withProfileData(profile.getId(), profile.getName())
|
||||
.withType(event.type == TYPE_HOMEWORK ? pl.szczodrzynski.edziennik.data.db.entity.Notification.TYPE_NEW_SHARED_HOMEWORK : pl.szczodrzynski.edziennik.data.db.entity.Notification.TYPE_NEW_SHARED_EVENT)
|
||||
.withFragmentRedirect(event.type == TYPE_HOMEWORK ? MainActivity.DRAWER_ITEM_HOMEWORK : MainActivity.DRAWER_ITEM_AGENDA)
|
||||
.withLongExtra("eventDate", event.eventDate.getValue())
|
||||
);
|
||||
d(TAG, "Finishing adding event " + event);
|
||||
app.db.eventDao().add(event);
|
||||
try {
|
||||
app.db.metadataDao().setBoth(profile.getId(), event, false, true, jEvent.get("addedDate").getAsLong());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// UNSHARING
|
||||
long eventId = Long.parseLong(remoteMessage.getData().get("remove_id"));
|
||||
EventFull oldEvent = app.db.eventDao().getByIdNow(profile.getId(), eventId);
|
||||
if (oldEvent != null) {
|
||||
app.notifier.add(new Notification(app.getContext(), app.getString(R.string.notification_shared_event_removed_format, oldEvent.sharedByName, oldEvent.typeName, oldEvent.eventDate.getFormattedString(), oldEvent.topic))
|
||||
.withProfileData(profile.getId(), profile.getName())
|
||||
.withType(oldEvent.type == TYPE_HOMEWORK ? pl.szczodrzynski.edziennik.data.db.entity.Notification.TYPE_NEW_SHARED_HOMEWORK : pl.szczodrzynski.edziennik.data.db.entity.Notification.TYPE_NEW_SHARED_EVENT)
|
||||
.withFragmentRedirect(oldEvent.type == TYPE_HOMEWORK ? MainActivity.DRAWER_ITEM_HOMEWORK : MainActivity.DRAWER_ITEM_AGENDA)
|
||||
.withLongExtra("eventDate", oldEvent.eventDate.getValue())
|
||||
);
|
||||
app.db.eventDao().remove(oldEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (teamCode != null) {
|
||||
teamCode = null;
|
||||
} else {
|
||||
teamUnshareCode = null;
|
||||
}
|
||||
}
|
||||
app.notifier.postAll();
|
||||
app.saveConfig();
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright (c) Kuba Szczodrzyński 2020-1-11.
|
||||
*/
|
||||
|
||||
package pl.szczodrzynski.edziennik.data.firebase
|
||||
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.launch
|
||||
import pl.szczodrzynski.edziennik.App
|
||||
import kotlin.coroutines.CoroutineContext
|
||||
|
||||
class MyFirebaseService : FirebaseService(), CoroutineScope {
|
||||
companion object {
|
||||
private const val TAG = "MyFirebaseService"
|
||||
}
|
||||
|
||||
private val app by lazy { applicationContext as App }
|
||||
|
||||
private val job = Job()
|
||||
override val coroutineContext: CoroutineContext
|
||||
get() = job + Dispatchers.Main
|
||||
|
||||
override fun onNewToken(token: String?) {
|
||||
Log.d(TAG, "Got new token: $token")
|
||||
app.config.sync.tokenApp = token
|
||||
}
|
||||
|
||||
override fun onMessageReceived(message: Message) {
|
||||
launch(Dispatchers.Default) {
|
||||
Log.d(TAG, "Message received from ${message.from}: $message")
|
||||
val profiles = app.db.profileDao().profilesForSyncNow
|
||||
when (message.from) {
|
||||
"640759989760" -> SzkolnyAppFirebase(app, profiles, message)
|
||||
"747285019373" -> SzkolnyMobidziennikFirebase(app, profiles, message)
|
||||
"513056078587" -> SzkolnyLibrusFirebase(app, profiles, message)
|
||||
"987828170337" -> SzkolnyVulcanFirebase(app, profiles, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
/*
|
||||
* Copyright (c) Kuba Szczodrzyński 2020-1-11.
|
||||
*/
|
||||
|
||||
package pl.szczodrzynski.edziennik.data.firebase
|
||||
|
||||
import pl.szczodrzynski.edziennik.App
|
||||
import pl.szczodrzynski.edziennik.data.db.entity.Profile
|
||||
|
||||
class SzkolnyAppFirebase(val app: App, val profiles: List<Profile>, val message: FirebaseService.Message) {
|
||||
init {
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (c) Kuba Szczodrzyński 2020-1-11.
|
||||
*/
|
||||
|
||||
package pl.szczodrzynski.edziennik.data.firebase
|
||||
|
||||
import pl.szczodrzynski.edziennik.App
|
||||
import pl.szczodrzynski.edziennik.data.db.entity.Profile
|
||||
|
||||
class SzkolnyLibrusFirebase(val app: App, val profiles: List<Profile>, val message: FirebaseService.Message) {
|
||||
/*{
|
||||
"gcm.notification.e": "1",
|
||||
"userId": "1234567u",
|
||||
"gcm.notification.sound": "default",
|
||||
"gcm.notification.title": "Synergia",
|
||||
"gcm.notification.sound2": "notify",
|
||||
"image": "www/assets/images/iconPush_01.png",
|
||||
"gcm.notification.body": "Dodano nieobecność nauczyciela od godziny 15:30 do godziny 16:15",
|
||||
"gcm.notification.icon": "notification_event.png",
|
||||
"objectType": "Calendars/TeacherFreeDays",
|
||||
}*/
|
||||
init {
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Copyright (c) Kuba Szczodrzyński 2020-1-11.
|
||||
*/
|
||||
|
||||
package pl.szczodrzynski.edziennik.data.firebase
|
||||
|
||||
import pl.szczodrzynski.edziennik.App
|
||||
import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_ATTENDANCE
|
||||
import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_BEHAVIOUR
|
||||
import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_GRADES
|
||||
import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_MESSAGES
|
||||
import pl.szczodrzynski.edziennik.data.api.task.EdziennikTask
|
||||
import pl.szczodrzynski.edziennik.data.api.task.IApiTask
|
||||
import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_RECEIVED
|
||||
import pl.szczodrzynski.edziennik.data.db.entity.Profile
|
||||
import pl.szczodrzynski.edziennik.getLong
|
||||
import pl.szczodrzynski.edziennik.getString
|
||||
|
||||
class SzkolnyMobidziennikFirebase(val app: App, val profiles: List<Profile>, val message: FirebaseService.Message) {
|
||||
/*{
|
||||
"id": "123456",
|
||||
"body": "Janósz Kowalski (Nauczyciele) - Temat wiadomości",
|
||||
"icon": "push",
|
||||
"type": "wiadOdebrana",
|
||||
"color": "#025b8e",
|
||||
"login": "1234@2019@szkola",
|
||||
"notId": "1234567",
|
||||
"sound": "default",
|
||||
"title": "Nowa wiadomość - mobiDziennik",
|
||||
"global_id": "123456",
|
||||
"vibrate": "true",
|
||||
"sync_url": "https://szkola.mobidziennik.pl/api2/logowanie"
|
||||
}*/
|
||||
/*{
|
||||
"body": "Kowalski Janósz - zapowiedziany sprawdzian na jutro:\njęzyk niemiecki (kartkówka - nieregularne 2)",
|
||||
"icon": "push",
|
||||
"type": "sprawdzianyJutro",
|
||||
"color": "#025b8e",
|
||||
"login": "1234@2019@szkola",
|
||||
"notId": "1234567",
|
||||
"sound": "default",
|
||||
"title": "Sprawdziany jutro - mobiDziennik",
|
||||
"global_id": "123456",
|
||||
"vibrate": "true",
|
||||
"sync_url": "https://szkola.mobidziennik.pl/api2/logowanie"
|
||||
}*/
|
||||
init { run {
|
||||
val type = message.data.getString("type") ?: return@run
|
||||
if (type == "sprawdzianyJutro" || type == "zadaniaJutro" || type == "autoryzacjaUrzadzenia")
|
||||
return@run
|
||||
val globalId = message.data.getLong("global_id")
|
||||
|
||||
/* assets/www/js/push.js */
|
||||
val viewIdPair = when (type) {
|
||||
"wiadOdebrana" -> DRAWER_ITEM_MESSAGES to TYPE_RECEIVED
|
||||
"oceny", "ocenyKoncowe" -> DRAWER_ITEM_GRADES to 0
|
||||
"uwagi" -> DRAWER_ITEM_BEHAVIOUR to 0
|
||||
"nieobecnoscPierwszaLekcja", "nieobecnosciDzisiaj" -> DRAWER_ITEM_ATTENDANCE to 0
|
||||
else -> return@run
|
||||
}
|
||||
|
||||
val tasks = profiles.filter {
|
||||
it.getStudentData("globalId", 0L) == globalId
|
||||
}.map {
|
||||
EdziennikTask.syncProfile(it.id, listOf(viewIdPair))
|
||||
}
|
||||
IApiTask.enqueueAll(app, tasks)
|
||||
}}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright (c) Kuba Szczodrzyński 2020-1-11.
|
||||
*/
|
||||
|
||||
package pl.szczodrzynski.edziennik.data.firebase
|
||||
|
||||
import pl.szczodrzynski.edziennik.App
|
||||
import pl.szczodrzynski.edziennik.data.db.entity.Profile
|
||||
|
||||
class SzkolnyVulcanFirebase(val app: App, val profiles: List<Profile>, val message: FirebaseService.Message) {
|
||||
/*{
|
||||
"data": {
|
||||
"loginid": 12345,
|
||||
"pupilid": 1234,
|
||||
"unitid": 2,
|
||||
"event": "CDC",
|
||||
"day": "2019-09-09",
|
||||
"table": "Frekwencja"
|
||||
},
|
||||
"title": "Frekwencja",
|
||||
"message: "Uczeń Janósz otrzymał nieobecność na 7 lekcji"
|
||||
}*/
|
||||
init {
|
||||
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user