This repository was archived by the owner on Nov 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathGCMRegistrar.java
More file actions
210 lines (177 loc) · 7.99 KB
/
GCMRegistrar.java
File metadata and controls
210 lines (177 loc) · 7.99 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
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
package io.Pushfish.api.Async;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import io.Pushfish.api.HttpUtil;
import io.Pushfish.api.PushfishApi.DeviceUuidFactory;
import io.Pushfish.api.SettingsActivity;
// TODO: Cleanup
public class GCMRegistrar {
public static final String PROPERTY_REG_ID = "registration_id";
public static final String PROPERTY_PRIVATE_KEY = "private_key";
private static final String PROPERTY_APP_VERSION = "app_version";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
protected String TAG = "GCM";
private GoogleCloudMessaging gcm;
private Context mContext;
public GCMRegistrar(Context context) {
this.mContext = context;
gcm = GoogleCloudMessaging.getInstance(context);
}
public boolean checkPlayServices(android.app.Activity self) {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
if (resultCode != ConnectionResult.SUCCESS) {
Log.e(TAG, "This device does not support GCM");
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode) && self != null) {
GooglePlayServicesUtil.getErrorDialog(resultCode, self, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(mContext, "Sorry, you need to have the Google Play services installed :<", Toast.LENGTH_SHORT).show();
}
return false;
} else {
Log.i(TAG, "Pushfish is ready for Take-Off!");
}
return true;
}
private void storeRegistrationId(String regId) {
final SharedPreferences prefs = getGcmPreferences(mContext);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, getAppVersion());
editor.apply();
}
public String getRegistrationId() {
final SharedPreferences prefs = getGcmPreferences(mContext);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty() || registrationId.equals(""))
return "";
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
if (registeredVersion != getAppVersion())
return "";
return registrationId;
}
public int getAppVersion() {
try {
PackageInfo packageInfo = mContext.getPackageManager()
.getPackageInfo(mContext.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException("Could not get package name: " + e);
}
}
private SharedPreferences getGcmPreferences(Context context) {
return context.getSharedPreferences(GCMRegistrar.class.getSimpleName(), Context.MODE_PRIVATE);
}
public AsyncRegistrar registerInBackground() {
return this.registerInBackground(false);
}
public AsyncRegistrar registerInBackground(boolean force) {
AsyncRegistrar task = new AsyncRegistrar();
task.execute(force);
return task;
}
public boolean shouldRegister() {
return getRegistrationId().equals("");
}
public void forgetRegistration() {
SharedPreferences.Editor editor = getGcmPreferences(mContext).edit();
editor.putString(PROPERTY_REG_ID, "");
editor.putInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
editor.commit();
}
private static boolean asyncAlreadyRunning = false;
public class AsyncRegistrar extends AsyncTask<Boolean, Void, Void> {
@Override
protected Void doInBackground(Boolean... params) {
if(asyncAlreadyRunning) {
return null;
}
asyncAlreadyRunning = true;
boolean force = params.length > 0 && params[0];
if (!force && shouldRegister()) {
Log.i(TAG, "Already registered, no need to re-register");
asyncAlreadyRunning = false;
return null; // No need to re-register
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
String url = SettingsActivity.getRegisterUrl(mContext) + "/gcm";
String senderId = SettingsActivity.getSenderId(mContext);
Looper.prepare();
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(mContext);
}
String regid = gcm.register(senderId);
Map<String, String> data = new HashMap<>();
data.put("regId", regid);
data.put("uuid", new DeviceUuidFactory(mContext).getDeviceUuid().toString());
// Should we be doing crypto magic?
if(preferences.getBoolean("general_encrypt_gcm", true)) {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024, new SecureRandom());
KeyPair kp = kpg.genKeyPair();
PublicKey publicKey = kp.getPublic();
PrivateKey privateKey = kp.getPrivate();
String B64DerPublicKey = Base64.encodeToString(publicKey.getEncoded(), Base64.NO_WRAP);
String B64DerPrivateKey = Base64.encodeToString(privateKey.getEncoded(), Base64.NO_WRAP);
data.put("pubkey", B64DerPublicKey);
SharedPreferences.Editor editor = getGcmPreferences(mContext).edit();
editor.putString(PROPERTY_PRIVATE_KEY, B64DerPrivateKey);
editor.commit();
}
for (int i = 1; i <= 10; i++) {
Log.i(TAG, "Attempt #" + i + " to register device");
try {
HttpUtil.Post(url, data);
break;
} catch (Exception ignore) {
Log.e(TAG, ignore.getMessage());
if (i == 10)
throw new IOException();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
storeRegistrationId(regid);
} catch (IOException ignore) {
Toast.makeText(mContext, "Could not register with GCM server", Toast.LENGTH_SHORT).show();
} catch (NoSuchAlgorithmException e) {
Toast.makeText(mContext, "Could not build crypto keypair. Disabling encryption...", Toast.LENGTH_LONG).show();
SharedPreferences.Editor prefEditor = preferences.edit();
prefEditor.putBoolean("general_encrypt_gcm", false);
prefEditor.commit();
return this.doInBackground(params);
}
Log.i(TAG, "Registered!");
if (force) {
Toast.makeText(mContext, "Registered to " + url, Toast.LENGTH_SHORT).show();
}
Log.i(TAG, "Registered to " + url);
asyncAlreadyRunning = false;
return null;
}
}
}