cordova-plugin-mserviceinterface-2.0 1.0.26 → 1.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/package.json +28 -28
  2. package/plugin.xml +154 -153
  3. package/src/android/CallbackProgressDialog.java +53 -53
  4. package/src/android/FileProvider.java +7 -7
  5. package/src/android/backgroundNotification.java +120 -120
  6. package/src/android/doubleogradle.gradle +5 -5
  7. package/src/android/mInterface.java +2206 -2087
  8. package/src/android/mInterfaceReceiver.java +59 -59
  9. package/src/android/mInterfaceService.java +752 -749
  10. package/src/android/mInterfaceUtil.java +1686 -1686
  11. package/src/android/res/xml/network_security_config.xml +8 -8
  12. package/src/android/res/xml/opener_paths.xml +16 -16
  13. package/src/ios/InternetConnection.h +64 -64
  14. package/src/ios/InternetConnection.m +242 -242
  15. package/src/ios/SSZipArchive.h +146 -146
  16. package/src/ios/SSZipArchive.m +1180 -1180
  17. package/src/ios/SSZipCommon.h +66 -66
  18. package/src/ios/UICKeyChainStore.h +64 -64
  19. package/src/ios/UICKeyChainStore.m +434 -434
  20. package/src/ios/XMLConverter.h +61 -61
  21. package/src/ios/XMLConverter.m +243 -243
  22. package/src/ios/ZipArchive.h +19 -19
  23. package/src/ios/aes/aes.h +270 -270
  24. package/src/ios/aes/aes_ni.c +687 -687
  25. package/src/ios/aes/aes_ni.h +59 -59
  26. package/src/ios/aes/aescrypt.c +301 -301
  27. package/src/ios/aes/aeskey.c +554 -554
  28. package/src/ios/aes/aesopt.h +776 -776
  29. package/src/ios/aes/aestab.c +418 -418
  30. package/src/ios/aes/aestab.h +173 -173
  31. package/src/ios/aes/brg_endian.h +127 -127
  32. package/src/ios/aes/brg_types.h +191 -191
  33. package/src/ios/aes/fileenc.c +145 -145
  34. package/src/ios/aes/fileenc.h +121 -121
  35. package/src/ios/aes/hmac.c +209 -209
  36. package/src/ios/aes/hmac.h +119 -119
  37. package/src/ios/aes/prng.c +155 -155
  38. package/src/ios/aes/prng.h +82 -82
  39. package/src/ios/aes/pwd2key.c +181 -181
  40. package/src/ios/aes/pwd2key.h +45 -45
  41. package/src/ios/aes/sha1.c +283 -283
  42. package/src/ios/aes/sha1.h +72 -72
  43. package/src/ios/mInterface.h +1 -0
  44. package/src/ios/mInterface.m +15 -3
  45. package/src/ios/minizip/crypt.c +146 -146
  46. package/src/ios/minizip/crypt.h +66 -66
  47. package/src/ios/minizip/ioapi.c +353 -353
  48. package/src/ios/minizip/ioapi.h +154 -154
  49. package/src/ios/minizip/ioapi_buf.c +452 -452
  50. package/src/ios/minizip/ioapi_buf.h +52 -52
  51. package/src/ios/minizip/ioapi_mem.c +167 -167
  52. package/src/ios/minizip/ioapi_mem.h +52 -52
  53. package/src/ios/minizip/minishared.c +292 -292
  54. package/src/ios/minizip/minishared.h +50 -50
  55. package/src/ios/minizip/unzip.c +2007 -2007
  56. package/src/ios/minizip/unzip.h +254 -254
  57. package/src/ios/minizip/zip.c +2007 -2007
  58. package/src/ios/minizip/zip.h +215 -215
  59. package/www/mInterface.js +3 -3
@@ -1,2087 +1,2206 @@
1
- package com.selfservit.util;
2
-
3
- import android.Manifest;
4
- import android.app.Activity;
5
- import android.app.ActivityManager;
6
- import android.app.AlertDialog;
7
- import android.app.ProgressDialog;
8
- import android.content.ActivityNotFoundException;
9
- import android.content.ContentResolver;
10
- import android.content.ContentUris;
11
- import android.content.Context;
12
- import android.content.DialogInterface;
13
- import android.content.Intent;
14
- import android.content.IntentSender;
15
- import android.content.pm.ActivityInfo;
16
- import android.content.pm.PackageManager;
17
- import android.database.Cursor;
18
- import android.graphics.Bitmap;
19
- import android.graphics.BitmapFactory;
20
- import android.graphics.Canvas;
21
- import android.graphics.Matrix;
22
- import android.graphics.Paint;
23
- import android.location.Location;
24
- import android.media.MediaMetadataRetriever;
25
- import android.media.ThumbnailUtils;
26
- import android.net.ConnectivityManager;
27
- import android.net.NetworkInfo;
28
- import android.net.Uri;
29
- import android.os.AsyncTask;
30
- import android.os.Build;
31
- import android.os.Bundle;
32
- import android.os.Environment;
33
- import android.os.PowerManager;
34
- import android.provider.DocumentsContract;
35
- import android.provider.MediaStore;
36
- import android.provider.OpenableColumns;
37
- import android.provider.Settings;
38
- import android.support.annotation.NonNull;
39
- import android.support.annotation.Nullable;
40
- import android.support.annotation.RequiresApi;
41
- import android.support.v4.app.ActivityCompat;
42
- import android.util.Base64;
43
- import android.util.Log;
44
- import android.util.Patterns;
45
- import android.view.KeyEvent;
46
- import android.webkit.MimeTypeMap;
47
- import android.widget.ProgressBar;
48
- import android.widget.Toast;
49
- import android.media.ExifInterface;
50
-
51
- import com.google.android.gms.common.ConnectionResult;
52
- import com.google.android.gms.common.api.GoogleApiClient;
53
- import com.google.android.gms.common.api.PendingResult;
54
- import com.google.android.gms.common.api.ResultCallback;
55
- import com.google.android.gms.common.api.Status;
56
- import com.google.android.gms.location.LocationRequest;
57
- import com.google.android.gms.location.LocationServices;
58
- import com.google.android.gms.location.LocationSettingsRequest;
59
- import com.google.android.gms.location.LocationSettingsResult;
60
- import com.google.android.gms.location.LocationSettingsStatusCodes;
61
- import com.google.android.gms.tasks.Task;
62
- import com.google.zxing.integration.android.IntentIntegrator;
63
- import com.google.zxing.integration.android.IntentResult;
64
-
65
- import org.apache.cordova.CallbackContext;
66
- import org.apache.cordova.CordovaInterface;
67
- import org.apache.cordova.CordovaPlugin;
68
- import org.apache.cordova.CordovaResourceApi;
69
- import org.apache.cordova.CordovaWebView;
70
- import org.apache.cordova.PermissionHelper;
71
- import org.apache.cordova.PluginResult;
72
- import org.json.JSONArray;
73
- import org.json.JSONException;
74
- import org.json.JSONObject;
75
-
76
- import java.io.BufferedInputStream;
77
- import java.io.BufferedReader;
78
- import java.io.ByteArrayOutputStream;
79
- import java.io.File;
80
- import java.io.FileOutputStream;
81
- import java.io.IOException;
82
- import java.io.InputStream;
83
- import java.io.InputStreamReader;
84
- import java.io.OutputStream;
85
- import java.io.OutputStreamWriter;
86
- import java.net.HttpURLConnection;
87
- import java.net.URL;
88
- import java.text.SimpleDateFormat;
89
- import java.util.Date;
90
- import java.util.List;
91
- import java.util.Stack;
92
- import java.util.TimeZone;
93
- import java.util.regex.Matcher;
94
- import java.util.regex.Pattern;
95
- import java.util.zip.ZipEntry;
96
- import java.util.zip.ZipInputStream;
97
-
98
- import static android.app.Activity.RESULT_OK;
99
-
100
- public class mInterface extends CordovaPlugin implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<LocationSettingsResult> {
101
- private static final String TAG = "mInterface";
102
- public Stack<ProgressDialog> spinnerDialogStack = new Stack<ProgressDialog>();
103
- private static final int PICK_FILE_REQUEST = 1;
104
- public CallbackContext callback;
105
- private static JSONArray arguments = null;
106
- private String pictureFilePath;
107
- private static final int REQUEST_IMAGE_CAPTURE = 111;
108
- private static final int PICK_IMAGE_FROM_GALLERY = 112;
109
- private static final int REQUEST_LIVE_IMAGE_CAPTURE = 113;
110
- private static final int LOCATION_ACCURACY_REQUEST_NEW = 115;
111
- private final static int NEW_FILE_PICK_REQUEST = 200;
112
- private int SCANCODEINT = 0;
113
- private static final String ANY = "any";
114
- private static final String PORTRAIT_PRIMARY = "portrait-primary";
115
- private static final String PORTRAIT_SECONDARY = "portrait-secondary";
116
- private static final String LANDSCAPE_PRIMARY = "landscape-primary";
117
- private static final String LANDSCAPE_SECONDARY = "landscape-secondary";
118
- private static final String PORTRAIT = "portrait";
119
- private static final String LANDSCAPE = "landscape";
120
- private static final String ANDROID_PLATFORM = "Android";
121
-
122
- String currentLocationInd = "";
123
- Location mCurrentLocation1;
124
- LocationRequest mLocationRequest1;
125
- GoogleApiClient mGoogleApiClient1;
126
- private static final long INTERVAL = 5 * 60 * 1000;
127
- private static final long FASTEST_INTERVAL = 5 * 60 * 1000;
128
- public static String attachmentDestPath = "";
129
- /* START SERVICE WHEN USER COMES FROM INACTIVE TO ACTIVE STATE IF SERVICE NOT RUNNING */
130
- @Override
131
- public void onResume(boolean multitasking) {
132
- super.onResume(multitasking);
133
- //To avoid starting service after getting permissions initially.
134
- if (!mInterfaceUtil.deviceID.equalsIgnoreCase("")) {
135
- if (!isServiceRunning(mInterfaceService.class) || !isProcessRunning()) {
136
- cordova.getActivity().startService(new Intent(cordova.getActivity().getApplicationContext(), mInterfaceService.class));
137
- }
138
- }
139
- }
140
-
141
- @RequiresApi(api = Build.VERSION_CODES.O)
142
- @Override
143
- public boolean execute(final String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
144
- mInterfaceUtil.rootDirectory = new File(cordova.getActivity().getExternalFilesDir(""), "");
145
- if (mInterfaceUtil.packageName.equals("")) {
146
- mInterfaceUtil.packageName = cordova.getActivity().getApplicationContext().getPackageName().split("\\.")[2];
147
- }
148
- /* START BACKGROUND SERVICE IF NOT RUNNING ALREADY */
149
- if (action.equals("StartService")) {
150
- boolean appInfoUpdated = new mInterfaceUtil().updateAppInfo(args);
151
- //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
152
- if (!isServiceRunning(backgroundNotification.class)) {
153
- cordova.getActivity().startService(new Intent(cordova.getActivity().getApplicationContext(), backgroundNotification.class));
154
- }
155
- if (!isServiceRunning(mInterfaceService.class)) {
156
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
157
- cordova.getActivity().startForegroundService(new Intent(cordova.getActivity().getApplicationContext(), mInterfaceService.class));
158
- } else {
159
- cordova.getActivity().startService(new Intent(cordova.getActivity().getApplicationContext(), mInterfaceService.class));
160
- }
161
- } else {
162
- System.out.println("Service is already running");
163
- }
164
- callbackContext.success("Success");
165
- }else if (action.equals("showToastWithOptions")) {
166
- try {
167
- if(args.getJSONObject(0).optString("duration").equals("long")){
168
- Toast.makeText(cordova.getActivity().getApplicationContext(),args.getJSONObject(0).optString("message"), Toast.LENGTH_LONG).show();
169
- } else {
170
- Toast.makeText(cordova.getActivity().getApplicationContext(),args.getJSONObject(0).optString("message"), Toast.LENGTH_SHORT).show();
171
- }
172
- } catch (Exception exception) {
173
- callbackContext.success("Show Toast having exception");
174
- }
175
- } else if (action.equals("CheckLocationAccuracy")) {
176
- int locationInt = 111;
177
- try {
178
- locationInt = Settings.Secure.getInt(this.cordova.getActivity().getContentResolver(), Settings.Secure.LOCATION_MODE);
179
- callbackContext.success(Integer.toString(locationInt));
180
- } catch (Settings.SettingNotFoundException e) {
181
- System.out.println("Exception is: " + e.getMessage());
182
- callbackContext.error(e.getMessage());
183
- }
184
- }else if (action.equals("GetBase64String")) {
185
- try {
186
- String imageString = getBase64String(args.getJSONObject(0).optString("filePath"));
187
- callbackContext.success(imageString);
188
- } catch (Exception e) {
189
- System.out.println("Exception is: " + e.getMessage());
190
- callbackContext.error(e.getMessage());
191
- }
192
- } else if (action.equals("GetSyncIndicator")) {
193
- try {
194
- File newQueueFolder, oldQueueFolder;
195
- Boolean syncIndication = false;
196
- BufferedReader readerObj;
197
- String currentLine, sendData = "";
198
- URL requestPath;
199
- HttpURLConnection urlConObj;
200
- OutputStreamWriter oStreamObj;
201
- String currentLinedata = "";
202
- String client_id = args.getJSONObject(0).optString("client_id");
203
- String country_code = args.getJSONObject(0).optString("country_code");
204
- String user_id = args.getJSONObject(0).optString("user_id");
205
- String client_url = args.getJSONObject(0).optString("client_url");
206
- String requestUrl = client_url + "/common/components/QueueManager/GetSyncInd.aspx?client_id=" + client_id + "&country_code=" + country_code + "&user_id=" + user_id;
207
-
208
- try {
209
- oldQueueFolder = new File(mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/database/queue");
210
- newQueueFolder = new File(mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/" + client_id + "/" + country_code + "/database/queue");
211
- if(oldQueueFolder.exists()) {
212
- if(oldQueueFolder.listFiles().length == 0){
213
- syncIndication = true;
214
- }
215
- } else{
216
- syncIndication = true;
217
- }
218
- if(syncIndication) {
219
- if(newQueueFolder.exists()){
220
- if(newQueueFolder.listFiles().length != 0){
221
- syncIndication = false;
222
- }
223
- }
224
- }
225
- if(syncIndication) {
226
- requestPath = new URL(requestUrl);
227
- urlConObj = (HttpURLConnection)requestPath.openConnection();
228
- urlConObj.setDoOutput(true);
229
- urlConObj.setRequestMethod("POST");
230
- urlConObj.setRequestProperty("CONTENT-TYPE", "application/text");
231
- urlConObj.connect();
232
- oStreamObj = new OutputStreamWriter(urlConObj.getOutputStream());
233
- oStreamObj.write(sendData);
234
- oStreamObj.flush();
235
- oStreamObj.close();
236
-
237
- /* GET RESPONSE FROM SERVER*/
238
- readerObj = new BufferedReader(new InputStreamReader(urlConObj.getInputStream()));
239
- currentLine = readerObj.readLine();
240
- readerObj.close();
241
- currentLinedata = currentLine.toString();
242
- urlConObj.disconnect();
243
- if(currentLinedata.equals("true")) {
244
- syncIndication = true;
245
- } else {
246
- syncIndication = false;
247
- }
248
- }
249
- callbackContext.success(String.valueOf(syncIndication));
250
- }catch(Exception e) {
251
- callbackContext.success(e.getMessage());
252
- }
253
- } catch (Exception e) {
254
- callbackContext.success(e.getMessage());
255
- }
256
- }
257
- else if (action.equals("TurnOnAutomaticDateTime")) {
258
- Intent intent = new Intent(android.provider.Settings.ACTION_DATE_SETTINGS);
259
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
260
- cordova.getActivity().getApplicationContext().startActivity(intent);
261
- callbackContext.success();
262
- } else if (action.equals("CheckAutomaticTime")) {
263
- boolean timeValue = isTimeAutomatic(cordova.getActivity().getApplicationContext());
264
- String valueString = "";
265
- if (timeValue == true) {
266
- valueString = "true";
267
- } else {
268
- valueString = "false";
269
- }
270
- callbackContext.success(valueString);
271
- } else if (action.equals("ServiceCheck")) {
272
- String str = "false";
273
- if (isServiceRunning(mInterfaceService.class)) {
274
- str = "true";
275
- System.out.println("service check is: " + str + " " + isServiceRunning(mInterfaceService.class));
276
- }
277
- callbackContext.success(str);
278
- } else if (action.equals("EnableGPSService")) {
279
- EnableGPSAutoMatically(callbackContext);
280
- } else if (action.equals("GetPermissions")) {
281
- getPermissions(args, callbackContext);
282
- return true;
283
- } else if (action.equals("AppVersion")) {
284
- appVersion(callbackContext);
285
- return true;
286
- } else if (action.equals("DeviceInfo")) {
287
- deviceInfo(callbackContext);
288
- return true;
289
- } else if (action.equals("GetStorageRoot")) {
290
- getStorageRoot(callbackContext);
291
- return true;
292
- } else if (action.equals("RotateScreen")) {
293
- rotateScreen(args, callbackContext);
294
- return true;
295
- } else if (action.equals("UnZip")) {
296
- unzip(args, callbackContext);
297
- return true;
298
- } else if (action.equals("EnableGPSService")) {
299
- EnableGPSAutoMatically(callbackContext);
300
- } else if ("GoHome".equals(action)) {
301
- try {
302
- Intent i = new Intent(Intent.ACTION_MAIN);
303
- i.addCategory(Intent.CATEGORY_HOME);
304
- this.cordova.getActivity().startActivity(i);
305
- } catch (Exception e) {
306
- return false;
307
- }
308
- callbackContext.success();
309
- return true;
310
- } else if ("GoBack".equals(action)) {
311
- try {
312
- // try to send it back and back to previous app
313
- boolean sentAppToBackground = this.cordova.getActivity().moveTaskToBack(true);
314
- // if not possible jump to home
315
- if (!sentAppToBackground) {
316
- Intent i = new Intent(Intent.ACTION_MAIN);
317
- i.setAction(Intent.ACTION_MAIN);
318
- i.addCategory(Intent.CATEGORY_HOME);
319
- this.cordova.getActivity().startActivity(i);
320
- }
321
- } catch (Exception e) {
322
- return false;
323
- }
324
- callbackContext.success();
325
- return true;
326
- } else if (action.equals("Spinner")) {
327
- if (args.getJSONObject(0).optString("show").equals("true")) {
328
- final boolean isFixed = true;
329
- Runnable runnable = new Runnable() {
330
- public void run() {
331
- DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() {
332
- public void onCancel(DialogInterface dialog) {
333
- if (!isFixed) {
334
- while (!mInterface.this.spinnerDialogStack.empty()) {
335
- mInterface.this.spinnerDialogStack.pop().dismiss();
336
- callbackContext.success();
337
- }
338
- }
339
- }
340
- };
341
- ProgressDialog dialog;
342
- if (isFixed) {
343
- //If there is a progressDialog yet change the text
344
- if (!mInterface.this.spinnerDialogStack.empty()) {
345
- dialog = mInterface.this.spinnerDialogStack.peek();
346
- } else {
347
- dialog = CallbackProgressDialog.show(cordova.getActivity(), true, false, null, callbackContext);
348
- mInterface.this.spinnerDialogStack.push(dialog);
349
- }
350
- } else {
351
- //If there is a progressDialog yet change the text
352
- if (!mInterface.this.spinnerDialogStack.empty()) {
353
- dialog = mInterface.this.spinnerDialogStack.peek();
354
- } else {
355
- dialog = ProgressDialog.show(cordova.getActivity(), "", "", true, true, onCancelListener);
356
- mInterface.this.spinnerDialogStack.push(dialog);
357
- }
358
- }
359
- dialog.setContentView(new ProgressBar(cordova.getActivity()));
360
- }
361
- };
362
- this.cordova.getActivity().runOnUiThread(runnable);
363
- } else {
364
- Runnable runnable = new Runnable() {
365
- public void run() {
366
- if (!mInterface.this.spinnerDialogStack.empty()) {
367
- mInterface.this.spinnerDialogStack.pop().dismiss();
368
- }
369
-
370
- }
371
- };
372
- this.cordova.getActivity().runOnUiThread(runnable);
373
- }
374
- callbackContext.success("success");
375
- } else if (action.equals("GetPackageName")) {
376
- callbackContext.success(cordova.getActivity().getApplicationContext().getPackageName());
377
- } else if (action.equals("GetLocation")) {
378
- /* SEND CURRENT LOCATION VIA PLUGIN CALLBACK */
379
- callbackContext.success(new mInterfaceUtil().getLocation(cordova.getActivity().getApplicationContext()));
380
- } else if (action.equals("CheckLocation")) {
381
- /* SEND CURRENT LOCATION SETTING STATUS VIA PLUGIN CALLBACK */
382
- callbackContext.success(new mInterfaceUtil().checkLocation(cordova.getActivity().getApplicationContext()));
383
- } else if ("GetCurrentLocation".equals(action)) {
384
- currentLocationInd = "true";
385
- callback = callbackContext;
386
- createLocationRequest1();
387
- this.mGoogleApiClient1 = new GoogleApiClient.Builder(cordova.getActivity())
388
- .addConnectionCallbacks(this)
389
- .addOnConnectionFailedListener(this)
390
- .addApi(LocationServices.API)
391
- .build();
392
- mGoogleApiClient1.connect();
393
- } else if (action.equals("GetSyncIndicator")) {
394
- try {
395
- File newQueueFolder, oldQueueFolder;
396
- Boolean syncIndication = false;
397
- BufferedReader readerObj;
398
- String currentLine, sendData = "";
399
- URL requestPath;
400
- HttpURLConnection urlConObj;
401
- OutputStreamWriter oStreamObj;
402
- String currentLinedata = "";
403
- String client_id = args.getJSONObject(0).optString("client_id");
404
- String country_code = args.getJSONObject(0).optString("country_code");
405
- String user_id = args.getJSONObject(0).optString("user_id");
406
- String client_url = args.getJSONObject(0).optString("client_url");
407
- String requestUrl = client_url + "/common/components/QueueManager/GetSyncInd.aspx?client_id=" + client_id + "&country_code=" + country_code + "&user_id=" + user_id;
408
- try {
409
- oldQueueFolder = new File(mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/database/queue");
410
- newQueueFolder = new File(mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/" + client_id + "/" + country_code + "/database/queue");
411
- if (oldQueueFolder.exists()) {
412
- if (oldQueueFolder.listFiles().length == 0) {
413
- syncIndication = true;
414
- }
415
- } else {
416
- syncIndication = true;
417
- }
418
- if (syncIndication) {
419
- if (newQueueFolder.exists()) {
420
- if (newQueueFolder.listFiles().length != 0) {
421
- syncIndication = false;
422
- }
423
- }
424
- }
425
- if (syncIndication) {
426
- requestPath = new URL(requestUrl);
427
- urlConObj = (HttpURLConnection) requestPath.openConnection();
428
- urlConObj.setDoOutput(true);
429
- urlConObj.setRequestMethod("POST");
430
- urlConObj.setRequestProperty("CONTENT-TYPE", "application/text");
431
- urlConObj.connect();
432
- oStreamObj = new OutputStreamWriter(urlConObj.getOutputStream());
433
- oStreamObj.write(sendData);
434
- oStreamObj.flush();
435
- oStreamObj.close();
436
-
437
- /* GET RESPONSE FROM SERVER*/
438
- readerObj = new BufferedReader(new InputStreamReader(urlConObj.getInputStream()));
439
- currentLine = readerObj.readLine();
440
- readerObj.close();
441
- currentLinedata = currentLine.toString();
442
- urlConObj.disconnect();
443
- if (currentLinedata.equals("true")) {
444
- syncIndication = true;
445
- } else {
446
- syncIndication = false;
447
- }
448
- }
449
- callbackContext.success(String.valueOf(syncIndication));
450
- } catch (Exception e) {
451
- callbackContext.success(e.getMessage());
452
- }
453
- } catch (Exception e) {
454
- callbackContext.success(e.getMessage());
455
- }
456
- }
457
- else if (action.equals("FileChooser")) {
458
- attachmentDestPath = args.optJSONObject(0).optString("destinationPath");
459
- chooseFile(callbackContext);
460
- return true;
461
- } else if (action.equals("GetThumbnail")) {
462
- String filePath = mInterfaceUtil.rootDirectory + "/" +args.optJSONObject(0).optString("filePath");
463
- String thumbnail= getFileThumbnail(filePath, args.optJSONObject(0).optString("fileExtension"));
464
- callback.success(thumbnail);
465
- return true;
466
- }
467
- else if (action.equals("DownloadChatAttachFile")) {
468
- String url = args.optJSONObject(0).optString("url"),
469
- filePath = args.optJSONObject(0).optString("filePath"),
470
- thumbnailInd = args.optJSONObject(0).optString("thumbnailInd");
471
- PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
472
- pluginResult.setKeepCallback(true);
473
- callbackContext.sendPluginResult(pluginResult);
474
- new mInterfaceUtil().DownloadChatAttachment(url,filePath, thumbnailInd, cordova.getActivity().getApplicationContext(),callbackContext, cordova.getActivity());
475
- return true;
476
- }
477
- else if (action.equals("SendChatAttachment")) {
478
- String filePath = args.optJSONObject(0).optString("filePath"),
479
- serverPath = args.optJSONObject(0).optString("serverPath"),
480
- fileName = args.optJSONObject(0).optString("fileName"),
481
- attachURL = mInterfaceUtil.clientUrl + "/common/components/msvFileHandler//UploadFiles.aspx?client_id=" + mInterfaceUtil.clientID + "&country_code=" + mInterfaceUtil.countryCode + "&path=" + serverPath;
482
- PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
483
- pluginResult.setKeepCallback(true);
484
- callbackContext.sendPluginResult(pluginResult);
485
- new mInterfaceUtil().sendChatAttachment(filePath,fileName, attachURL, cordova.getActivity(),callbackContext);
486
- return true;
487
- }
488
- else if (action.equals("SendAttachmentToServer")) {
489
- String statusIndication = "false";
490
- JSONObject inputFileObj;
491
- try {
492
- for (int index = 0; index < args.length(); index++) {
493
- inputFileObj = args.getJSONObject(index);
494
- String filePath = inputFileObj.optString("filePath"),
495
- serverPath = inputFileObj.optString("serverPath"),
496
- fileName = inputFileObj.optString("fileName"),
497
- attachURL = mInterfaceUtil.clientUrl + "/common/components/msvFileHandler//UploadFiles.aspx?client_id=" + mInterfaceUtil.clientID + "&country_code=" + mInterfaceUtil.countryCode + "&path=" + serverPath;
498
- statusIndication = new mInterfaceUtil().sendAttachmentToServer(filePath, fileName, attachURL);
499
- if (statusIndication.equals("false")) {
500
- break;
501
- }
502
- }
503
- if (statusIndication.equals("true")) {
504
- callbackContext.success("success");
505
- } else {
506
- callbackContext.error("failure");
507
- }
508
- } catch (Exception e) {
509
- e.printStackTrace();
510
- callbackContext.error("failure");
511
- }
512
- return true;
513
- }
514
- else if (action.equals("ReadFile")) {
515
- try {
516
- new mInterfaceUtil().readFile(args, callbackContext);
517
- } catch (Exception e) {
518
- e.printStackTrace();
519
- }
520
- return true;
521
- } else if (action.equals("DeleteFile")) {
522
- new mInterfaceUtil().deleteFile(args, callbackContext);
523
- return true;
524
- } else if (action.equals("DeleteMultipleFiles")) {
525
- System.out.println("args.length(): " + args.length());
526
- for (int index = 0; index < args.length(); index++) {
527
- String path = args.optString(index);
528
- new mInterfaceUtil().deleteMultipleFiles(path, callbackContext);
529
- }
530
- callbackContext.success();
531
- return true;
532
- } else if (action.equals("CreateFile")) {
533
- new mInterfaceUtil().createFile(args, callbackContext);
534
- return true;
535
- } else if (action.equals("ValidateFile")) {
536
- new mInterfaceUtil().validateFile(args, callbackContext);
537
- return true;
538
- } else if (action.equals("CreateDirectory")) {
539
- new mInterfaceUtil().createDirectory(args, callbackContext);
540
- return true;
541
- } else if (action.equals("DeleteDirectory")) {
542
- new mInterfaceUtil().deleteDirectory(args, callbackContext);
543
- return true;
544
- } else if (action.equals("UploadFile")) {
545
- String filePath = args.getJSONObject(0).optString("filePath");
546
- String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
547
- String url = args.getJSONObject(0).optString("url");
548
- new mInterfaceUtil().sendFilesToServer(filePath, fileName, url);
549
- return true;
550
- } else if (action.equals("CopyFile")) {
551
- arguments = args;
552
- new mInterfaceUtil().copyFile(callbackContext, arguments);
553
- }else if (action.equals("CopyAttachmentFile")) {
554
- arguments = args;
555
- new mInterfaceUtil().copyAttachmentFile(callbackContext, arguments);
556
- } else if (action.equals("CopyConfigFile")) {
557
- arguments = args;
558
- new mInterfaceUtil().copyConfigFile(callbackContext, arguments);
559
- } else if (action.equals("GetNewDate")) {
560
- new mInterfaceUtil().getNewDate(callbackContext);
561
- } else if (action.equals("RefreshTimeProfile")) {
562
- JSONObject timeObj = args.getJSONObject(0);
563
- String date, hour, minute;
564
- date = timeObj.optString("serverDate").toString();
565
- hour = timeObj.optString("serverHour").toString();
566
- minute = timeObj.optString("serverMinute").toString();
567
- String returnStatus = new mInterfaceUtil().refreshTimeProfile(date, hour, minute);
568
- if (returnStatus.equals("true")) {
569
- callbackContext.success("success");
570
- } else {
571
- callbackContext.error("failure");
572
- }
573
- } else if (action.equals("UpdateChoice")) {
574
- /* OPEN THE PLAYSTORE MSERVICE APP */
575
- String appVersion, softwareProductVersion, softwareProductSubVersion;
576
- JSONObject versionObj;
577
- AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_HOLO_DARK);
578
- AlertDialog alertDialog;
579
- versionObj = args.getJSONObject(0);
580
- appVersion = versionObj.optString("appVersion").toString();
581
- softwareProductVersion = versionObj.optString("softwareProductVersion").toString();
582
- softwareProductSubVersion = versionObj.optString("softwareProductSubVersion").toString();
583
- builder.setTitle("New Update");
584
- builder.setMessage("Your mservice version is " + appVersion + ". There is an updated version " + softwareProductVersion + "." + softwareProductSubVersion + " available. Please update.");
585
- builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
586
- @Override
587
- public void onClick(DialogInterface dialog, int which) {
588
- cordova.getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + cordova.getActivity().getApplicationContext().getPackageName())));
589
- callbackContext.error("failure");
590
- }
591
- });
592
- builder.setNegativeButton("Not Now", new DialogInterface.OnClickListener() {
593
- @Override
594
- public void onClick(DialogInterface dialog, int which) {
595
- dialog.cancel();
596
- callbackContext.success("Success");
597
- }
598
- });
599
- alertDialog = builder.create();
600
- alertDialog.setCanceledOnTouchOutside(false);
601
- alertDialog.show();
602
- alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
603
-
604
- @Override
605
- public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
606
- if (keyCode == KeyEvent.KEYCODE_BACK) {
607
- dialog.dismiss();
608
- callbackContext.error("failure");
609
- }
610
- return true;
611
- }
612
-
613
- });
614
- } else if (action.equals("UpdateConfirm")) {
615
- /* OPEN THE PLAYSTORE MSERVICE APP */
616
- String appVersion, softwareProductVersion, softwareProductSubVersion;
617
- JSONObject versionObj;
618
- AlertDialog alertDialog;
619
- AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_HOLO_DARK);
620
- versionObj = args.getJSONObject(0);
621
- appVersion = versionObj.optString("appVersion").toString();
622
- softwareProductVersion = versionObj.optString("softwareProductVersion").toString();
623
- softwareProductSubVersion = versionObj.optString("softwareProductSubVersion").toString();
624
- builder.setTitle("New Update");
625
- builder.setMessage("Your mservice version is " + appVersion + ". Please upgrade the app to " + softwareProductVersion + "." + softwareProductSubVersion + " to proceed.");
626
- builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
627
- @Override
628
- public void onClick(DialogInterface dialog, int which) {
629
- cordova.getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + cordova.getActivity().getApplicationContext().getPackageName())));
630
- callbackContext.error("failure");
631
- }
632
- });
633
- alertDialog = builder.create();
634
- alertDialog.setCanceledOnTouchOutside(false);
635
- alertDialog.show();
636
- alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
637
-
638
- @Override
639
- public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
640
- if (keyCode == KeyEvent.KEYCODE_BACK) {
641
- dialog.dismiss();
642
- callbackContext.error("failure");
643
- }
644
- return true;
645
- }
646
- });
647
- } else if (action.equals("UpdateNew")) {
648
- cordova.getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + cordova.getActivity().getApplicationContext().getPackageName())));
649
- callbackContext.error("failure");
650
- } else if (action.equals("OpenFileWithViewer")) {
651
- Context context = cordova.getActivity().getApplicationContext();
652
- String filePath = mInterfaceUtil.rootDirectory + "/" + args.optString(0);
653
- File imageFilePath = new File(filePath);
654
- try {
655
- Intent intent = new Intent(Intent.ACTION_VIEW);
656
- Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", imageFilePath);
657
- intent.setDataAndType(contentUri, getMimeType(filePath));
658
- intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NO_HISTORY);
659
- cordova.getActivity().startActivity(intent);
660
- callbackContext.success();
661
- } catch (ActivityNotFoundException e) {
662
- callbackContext.error(1);
663
- }
664
- } else if (action.equals("CaptureImageFromCamera")) {
665
- try {
666
- captureImage(callbackContext);
667
- return true;
668
- } catch (Exception e) {
669
- callbackContext.error("ms058");
670
- }
671
- } else if (action.equals("PickImageFromGallery")) {
672
- try {
673
- pickImageFromGallery(callbackContext);
674
- return true;
675
- } catch (Exception e) {
676
- callbackContext.error("ms059");
677
- }
678
- } else if (action.equals("CaptureFromCamera")) {
679
- try {
680
- captureImageLiveCamera(callbackContext);
681
- return true;
682
- } catch (Exception e) {
683
- callbackContext.error(1);
684
- }
685
- } else if (action.equals("DeleteSrcFile")) {
686
- try {
687
- String filePath = args.getJSONObject(0).optString("filePath");
688
- String fileName = args.getJSONObject(0).optString("fileName");
689
- File fullPath = new File(filePath + "/" + fileName);
690
- if (fullPath.exists()) {
691
- fullPath.delete();
692
- callbackContext.success();
693
- } else {
694
- callbackContext.error("Expected file is not there to delete..");
695
- }
696
- } catch (Exception e) {
697
- callbackContext.error(1);
698
- }
699
- } else if (action.equals("DownloadFile")) {
700
- callback = callbackContext;
701
- final DownloadTask downloadTask = new DownloadTask(cordova.getActivity());
702
- downloadTask.execute(args.optJSONObject(0).optString("url"), args.optJSONObject(0).optString("filePath"), args.optJSONObject(0).optString("thumbnailInd"));
703
- return true;
704
- }else if ("QueueProcessor".equals(action)) {
705
- new mInterfaceUtil().queueProcessor(callbackContext);
706
- return true;
707
- } else if (action.equals("ScanQRCode")) {
708
- try {
709
- scanQRCode(callbackContext);
710
- return true;
711
- } catch (Exception e) {
712
- callbackContext.error("ms060");
713
- }
714
- } else if (action.equals("ScanBarCode")) {
715
- try {
716
- scanBarCode(callbackContext);
717
- return true;
718
- } catch (Exception e) {
719
- callbackContext.error("ms061");
720
- }
721
- } else if (action.equals("GetSubDirectoryList")) {
722
- new mInterfaceUtil().getSubDirectoryList(args, callbackContext);
723
- return true;
724
- } else if (action.equals("GetFileList")) {
725
- new mInterfaceUtil().getFileList(args, callbackContext);
726
- return true;
727
- } else if (action.equals("GetAppStateInfo")) {
728
- boolean appInfoUpdated = new mInterfaceUtil().updateAppInfo(args);
729
- if (appInfoUpdated) {
730
- System.out.println("app info updated");
731
- new mInterfaceUtil().getAppStateInfo(callbackContext, cordova.getActivity().getApplicationContext());
732
- } else {
733
- System.out.println("app info not updated");
734
- callbackContext.success("");
735
- }
736
- return true;
737
- } else if (action.equals("UpdateAppInfo")) {
738
- boolean appInfoUpdated = new mInterfaceUtil().updateAppInfo(args);
739
- if (appInfoUpdated) {
740
- callbackContext.success("success");
741
- } else {
742
- callbackContext.error("failed to update app info");
743
- }
744
- return true;
745
- }
746
- else if (action.equals("MoveFile")) {
747
- arguments = args;
748
- new mInterfaceUtil().moveFile(callbackContext, arguments);
749
- }else if (action.equals("SendAttachment")) {
750
-
751
- JSONObject appInfo = args.getJSONObject(0);
752
- mInterfaceUtil.app_id = appInfo.optString("app_id").toString();
753
- mInterfaceUtil.platform = appInfo.optString("platform").toString();
754
- mInterfaceUtil.deviceID = appInfo.optString("device_id").toString();
755
- new mInterfaceUtil().moveFile(callbackContext, arguments);
756
- }
757
- else if (action.equals("OpenSms")) {
758
- String contact_number, smsBody;
759
- Intent smsIntent;
760
- PluginResult result;
761
- try {
762
- contact_number = args.getJSONObject(0).optString("contact_number");
763
- if(contact_number != null ) {
764
- if(!contact_number.equals("") ) {
765
- if(validateMobileNumber(contact_number)){
766
- smsBody = args.getJSONObject(0).optString("msgBody");
767
- smsIntent = new Intent(Intent.ACTION_VIEW);
768
- smsIntent.putExtra("sms_body", smsBody);
769
- smsIntent.setData(Uri.parse("sms:" + contact_number));
770
- smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
771
- cordova.getActivity().getApplicationContext().startActivity(smsIntent);
772
- }else{
773
- result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_INVALID");
774
- callback.sendPluginResult(result);
775
- }
776
- }else{
777
- result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_NOT_AVAILABLE");
778
- callback.sendPluginResult(result);
779
- }
780
- }else{
781
- result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_NOT_AVAILABLE");
782
- callback.sendPluginResult(result);
783
- }
784
- } catch (JSONException e) {
785
- e.printStackTrace();
786
- result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
787
- callback.sendPluginResult(result);
788
- }
789
- return true;
790
- }else if (action.equals("OpenDialPad")) {
791
- Intent intent;
792
- PluginResult result;
793
- try {
794
- String contact_number = args.getJSONObject(0).optString("contact_number");
795
- if(contact_number != null ) {
796
- if(!contact_number.equals("") ) {
797
- if(validateMobileNumber(contact_number)){
798
-
799
- intent = new Intent(Intent.ACTION_DIAL);
800
- intent.setData(Uri.parse("tel:" + contact_number));
801
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
802
- cordova.getActivity().getApplicationContext().startActivity(intent);
803
- }else{
804
- result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_INVALID");
805
- callback.sendPluginResult(result);
806
- }
807
- }else{
808
- result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_NOT_AVAILABLE");
809
- callback.sendPluginResult(result);
810
- }
811
- }else{
812
- result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_NOT_AVAILABLE");
813
- callback.sendPluginResult(result);
814
- }
815
-
816
- return true;
817
- } catch (Exception exception) {
818
- System.out.println(exception.getMessage());
819
- result = new PluginResult(PluginResult.Status.ERROR, exception.getMessage());
820
- callback.sendPluginResult(result);
821
- }
822
- }else if (action.equals("OpenEmail")) {
823
- PluginResult result;
824
- String toEmail, ccEmail, subject, body, mailto;
825
- try{
826
- toEmail = args.getJSONObject(0).optString("toEmail");
827
- ccEmail = args.getJSONObject(0).optString("ccEmail");
828
- subject = args.getJSONObject(0).optString("subject");
829
- body = args.getJSONObject(0).optString("body");
830
- if(toEmail != null ) {
831
- if(!toEmail.equals("") ) {
832
- if(Patterns.EMAIL_ADDRESS.matcher(toEmail).matches()){
833
- mailto = "mailto:" + toEmail +
834
- "?cc=" + ccEmail +
835
- "&subject=" + Uri.encode(subject) +
836
- "&body=" + Uri.encode(body);
837
- Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
838
- emailIntent.setData(Uri.parse(mailto));
839
- emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
840
- cordova.getActivity().getApplicationContext().startActivity(emailIntent);
841
- }else{
842
- result = new PluginResult(PluginResult.Status.ERROR, "EMAIL_INVALID");
843
- callback.sendPluginResult(result);
844
- }
845
- }else{
846
- result = new PluginResult(PluginResult.Status.ERROR, "EMAIL_NOT_AVAILABLE");
847
- callback.sendPluginResult(result);
848
- }
849
- }else{
850
- result = new PluginResult(PluginResult.Status.ERROR, "EMAIL_NOT_AVAILABLE");
851
- callback.sendPluginResult(result);
852
- }
853
- } catch (Exception e) {
854
- e.printStackTrace();
855
- result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
856
- callback.sendPluginResult(result);
857
- }
858
-
859
- }
860
- return true;
861
- }
862
-
863
- private boolean validateMobileNumber(String mobileNo) {
864
- String regex;
865
- boolean result = false;
866
- try {
867
- regex = "^\\+?\\d[\\d ]+$";
868
- if (mobileNo.matches(regex)) {
869
- result = true;
870
- }
871
- } catch (Exception e) {
872
- e.printStackTrace();
873
- }
874
- return result;
875
- }
876
-
877
- public static boolean isTimeAutomatic(Context c) {
878
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
879
- return Settings.Global.getInt(c.getContentResolver(), Settings.Global.AUTO_TIME, 0) == 1;
880
- } else {
881
- return android.provider.Settings.System.getInt(c.getContentResolver(), android.provider.Settings.System.AUTO_TIME, 0) == 1;
882
- }
883
- }
884
-
885
- public void createLocationRequest1() {
886
- mLocationRequest1 = new LocationRequest();
887
- mLocationRequest1.setInterval(INTERVAL);
888
- mLocationRequest1.setFastestInterval(FASTEST_INTERVAL);
889
- mLocationRequest1.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
890
- }
891
-
892
- protected void startLocationUpdates1() {
893
- Context context1 = cordova.getActivity().getApplicationContext();
894
- if (ActivityCompat.checkSelfPermission(context1, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
895
- //ActivityCompat.requestPermissions(cordova.getActivity(), new String[]{Manifest.permission.READ_PHONE_STATE}, 5);
896
- }
897
- PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient1, mLocationRequest1, this);
898
- }
899
-
900
- public void scanQRCode(CallbackContext callbackContext) {
901
- callback = callbackContext;
902
- SCANCODEINT = 118;
903
- IntentIntegrator integrator = new IntentIntegrator(this.cordova.getActivity());
904
- integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
905
- integrator.setPrompt("Scan");
906
- integrator.setCameraId(0);
907
- integrator.setBeepEnabled(true);
908
- integrator.setBarcodeImageEnabled(true);
909
- integrator.initiateScan();
910
- cordova.setActivityResultCallback(this);
911
- PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
912
- pluginResult.setKeepCallback(true);
913
- callbackContext.sendPluginResult(pluginResult);
914
- }
915
-
916
- public void scanBarCode(CallbackContext callbackContext) {
917
- callback = callbackContext;
918
- SCANCODEINT = 119;
919
- IntentIntegrator integrator = new IntentIntegrator(this.cordova.getActivity());
920
- integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
921
- integrator.setPrompt("Scan");
922
- integrator.setCameraId(0);
923
- integrator.setBeepEnabled(true);
924
- integrator.setBarcodeImageEnabled(true);
925
- integrator.initiateScan();
926
- cordova.setActivityResultCallback(this);
927
- PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
928
- pluginResult.setKeepCallback(true);
929
- callbackContext.sendPluginResult(pluginResult);
930
- }
931
-
932
- private void getStorageRoot(CallbackContext callbackContext) {
933
- callbackContext.success("file://" + mInterfaceUtil.rootDirectory + "/");
934
- }
935
-
936
- private void getPermissions(JSONArray args, CallbackContext callbackContext) {
937
- try {
938
- callback = callbackContext;
939
- Context context = cordova.getActivity().getApplicationContext();
940
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
941
- String[]permissions = args.optJSONObject(0).optString("permissions").split(",");
942
- if ((ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)) != PackageManager.PERMISSION_GRANTED || (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA)) != PackageManager.PERMISSION_GRANTED) {
943
- PermissionHelper.requestPermissions(this, 1, permissions);
944
- } else {
945
- callback.success("success");
946
- }
947
- } else {
948
- callback.success("success");
949
- }
950
- } catch (Exception e) {
951
- e.printStackTrace();
952
- }
953
- }
954
- public void captureImageLiveCamera(CallbackContext callbackContext) {
955
- callback = callbackContext;
956
- Context context = cordova.getActivity().getApplicationContext();
957
- Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
958
- File photoFile = null;
959
- try {
960
- photoFile = createImageFile();
961
- } catch (IOException ex) {
962
- callback.error("there is error in create image");
963
- }
964
- //Continue only if the File was successfully created
965
- if (photoFile != null) {
966
- Uri photoURISample;
967
- if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
968
- photoURISample = Uri.fromFile(photoFile);
969
- } else {
970
- photoURISample = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", photoFile);
971
- }
972
- takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURISample);
973
- cordova.startActivityForResult(this, takePictureIntent, REQUEST_LIVE_IMAGE_CAPTURE);
974
- PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
975
- pluginResult.setKeepCallback(true);
976
- callbackContext.sendPluginResult(pluginResult);
977
- }
978
- }
979
-
980
- public void captureImage(CallbackContext callbackContext) {
981
- callback = callbackContext;
982
- Context context = cordova.getActivity().getApplicationContext();
983
- Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
984
- File photoFile = null;
985
- try {
986
- photoFile = createImageFile();
987
- } catch (IOException ex) {
988
- callback.error("there is error in create image");
989
- }
990
- // Continue only if the File was successfully created
991
- if (photoFile != null) {
992
- Uri photoURISample;
993
- if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
994
- photoURISample = Uri.fromFile(photoFile);
995
- } else {
996
- photoURISample = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", photoFile);
997
- }
998
- takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURISample);
999
- cordova.startActivityForResult(this, takePictureIntent, REQUEST_IMAGE_CAPTURE);
1000
- PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
1001
- pluginResult.setKeepCallback(true);
1002
- callbackContext.sendPluginResult(pluginResult);
1003
- }
1004
- }
1005
-
1006
- public void pickImageFromGallery(CallbackContext callbackContext) {
1007
- Intent openFile,
1008
- selectFile;
1009
- PluginResult pluginResult;
1010
- callback = callbackContext;
1011
- if (Build.MANUFACTURER.equals("samsung")) {
1012
- /* SELECT FILE FOR SAMSUNG DEVICES */
1013
- openFile = new Intent("com.sec.android.app.myfiles.PICK_DATA");
1014
- openFile.putExtra("CONTENT_TYPE", "*/*");
1015
- } else {
1016
- /* SELECT FILE FOR EXCEPT SAMSUNG DEVICES */
1017
- openFile = new Intent(Intent.ACTION_GET_CONTENT);
1018
- openFile.setType("*/*");
1019
- openFile.addCategory(Intent.CATEGORY_OPENABLE);
1020
- openFile.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
1021
- }
1022
- selectFile = Intent.createChooser(openFile, "Select File");
1023
- cordova.startActivityForResult(this, selectFile, PICK_IMAGE_FROM_GALLERY);
1024
- pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
1025
- pluginResult.setKeepCallback(true);
1026
- callbackContext.sendPluginResult(pluginResult);
1027
- }
1028
-
1029
- private static String getMimeType(String path) {
1030
- String mimeType = null;
1031
- String extension = MimeTypeMap.getFileExtensionFromUrl(path);
1032
- if (extension != null) {
1033
- MimeTypeMap mime = MimeTypeMap.getSingleton();
1034
- mimeType = mime.getMimeTypeFromExtension(extension.toLowerCase());
1035
- }
1036
- return mimeType;
1037
- }
1038
-
1039
- private File createImageFile() throws IOException {
1040
- String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
1041
- String imageFileName = "JPEG_" + timeStamp + "_";
1042
- String filePath = mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/images";
1043
- File storageDir = new File(filePath);
1044
- if (!storageDir.exists()) {
1045
- storageDir.mkdirs();
1046
- }
1047
- File image = File.createTempFile(imageFileName, /* prefix */".jpg", /* suffix */storageDir /* directory */);
1048
- pictureFilePath = image.getAbsolutePath();
1049
- return image;
1050
- }
1051
-
1052
- public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
1053
- final int height = options.outHeight;
1054
- final int width = options.outWidth;
1055
- int inSampleSize = 1;
1056
- if (height > reqHeight || width > reqWidth) {
1057
- final int heightRatio = Math.round((float) height / (float) reqHeight);
1058
- final int widthRatio = Math.round((float) width / (float) reqWidth);
1059
- inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
1060
- }
1061
- final float totalPixels = width * height;
1062
- final float totalReqPixelsCap = reqWidth * reqHeight * 2;
1063
- while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
1064
- inSampleSize++;
1065
- }
1066
- return inSampleSize;
1067
- }
1068
-
1069
- public void convertImageTo64BaseString(CallbackContext callbackContext, String imageSourcePath, String imgSrcType, String destinationPath) {
1070
- String compressedImagePathStr = "";
1071
- String compressedImageName = "";
1072
- String filePath = imageSourcePath;
1073
- Bitmap scaledBitmap = null;
1074
- BitmapFactory.Options options = new BitmapFactory.Options();
1075
- //by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
1076
- //you try the use the bitmap here, you will get null.
1077
- options.inJustDecodeBounds = true;
1078
- String[] bits = imageSourcePath.split("/");
1079
-
1080
- String fileNameToSend = bits[bits.length-1];
1081
- if (fileNameToSend.indexOf(".") > 0)
1082
- fileNameToSend = fileNameToSend.substring(0, fileNameToSend.lastIndexOf("."));
1083
- Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
1084
- int actualHeight = options.outHeight;
1085
- int actualWidth = options.outWidth;
1086
- //max Height and width values of the compressed image is taken as 816x612
1087
- float maxHeight = 816.0f;
1088
- float maxWidth = 612.0f;
1089
- float imgRatio = actualWidth / actualHeight;
1090
- float maxRatio = maxWidth / maxHeight;
1091
- //width and height values are set maintaining the aspect ratio of the image
1092
- if (actualHeight > maxHeight || actualWidth > maxWidth) {
1093
- if (imgRatio < maxRatio) {
1094
- imgRatio = maxHeight / actualHeight;
1095
- actualWidth = (int) (imgRatio * actualWidth);
1096
- actualHeight = (int) maxHeight;
1097
- } else if (imgRatio > maxRatio) {
1098
- imgRatio = maxWidth / actualWidth;
1099
- actualHeight = (int) (imgRatio * actualHeight);
1100
- actualWidth = (int) maxWidth;
1101
- } else {
1102
- actualHeight = (int) maxHeight;
1103
- actualWidth = (int) maxWidth;
1104
- }
1105
- }
1106
- options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
1107
- options.inJustDecodeBounds = false;
1108
- //this options allow android to claim the bitmap memory if it runs low on memory
1109
- options.inPurgeable = true;
1110
- options.inInputShareable = true;
1111
- options.inTempStorage = new byte[16 * 1024];
1112
- try {
1113
- //load the bitmap from its path
1114
- bmp = BitmapFactory.decodeFile(filePath, options);
1115
- } catch (OutOfMemoryError exception) {
1116
- exception.printStackTrace();
1117
- }
1118
- try {
1119
- scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
1120
- } catch (OutOfMemoryError exception) {
1121
- exception.printStackTrace();
1122
- }
1123
- float ratioX = actualWidth / (float) options.outWidth;
1124
- float ratioY = actualHeight / (float) options.outHeight;
1125
- float middleX = actualWidth / 2.0f;
1126
- float middleY = actualHeight / 2.0f;
1127
- Matrix scaleMatrix = new Matrix();
1128
- scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
1129
- Canvas canvas = new Canvas(scaledBitmap);
1130
- canvas.setMatrix(scaleMatrix);
1131
- canvas.drawBitmap(bmp, middleX - bmp.getWidth()/2, middleY - bmp.getHeight()/2, new Paint(Paint.FILTER_BITMAP_FLAG));
1132
- //check the rotation of the image and display it properly
1133
- ExifInterface exif;
1134
- try {
1135
- exif = new ExifInterface(filePath);
1136
- int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
1137
- Log.d("EXIF", "Exif: " + orientation);
1138
- Matrix matrix = new Matrix();
1139
- if (orientation == 6) {
1140
- matrix.postRotate(90);
1141
- Log.d("EXIF", "Exif: " + orientation);
1142
- } else if (orientation == 3) {
1143
- matrix.postRotate(180);
1144
- Log.d("EXIF", "Exif: " + orientation);
1145
- } else if (orientation == 8) {
1146
- matrix.postRotate(270);
1147
- Log.d("EXIF", "Exif: " + orientation);
1148
- }
1149
- scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
1150
- } catch (IOException e) {
1151
- e.printStackTrace();
1152
- }
1153
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
1154
- try {
1155
- if(imgSrcType.equals("compress")) {
1156
- String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
1157
- if(!destinationPath.equalsIgnoreCase("")){
1158
- compressedImagePathStr = mInterfaceUtil.rootDirectory + "/" + destinationPath;
1159
- }else{
1160
- compressedImagePathStr = mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/" + "images";
1161
- }
1162
- compressedImageName = compressedImagePathStr + "/" + fileNameToSend + "_" + timeStamp + ".jpg";
1163
- File fileSavedPath = new File(compressedImagePathStr);
1164
- if (!fileSavedPath.exists()) {
1165
- fileSavedPath.mkdirs();
1166
- }
1167
- FileOutputStream out = new FileOutputStream(compressedImageName);
1168
- scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, out);
1169
- } else {
1170
- scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);
1171
- }
1172
- String encodedImage = null;
1173
- byte[] byteArray;
1174
- try {
1175
- byteArray = baos.toByteArray();
1176
- encodedImage = Base64.encodeToString(byteArray, Base64.NO_WRAP);
1177
- imgSrcType = imgSrcType;
1178
- if (imgSrcType.equals("camera")) {
1179
- File file = new File(imageSourcePath);
1180
- if (file.exists()) {
1181
- file.delete();
1182
- }
1183
- callbackContext.success(encodedImage);
1184
- } else if (imgSrcType.equals("gallery")) {
1185
- callbackContext.success(encodedImage);
1186
- } else if (imgSrcType.equals("compress")) {
1187
- try {
1188
- JSONObject fileProperities = null;
1189
- String imgFilePath, fileName, fileExtension = "";
1190
- imgFilePath = compressedImageName.substring(0, compressedImageName.lastIndexOf("/"));
1191
- String[] fileName1 = compressedImageName.split("/");
1192
- fileName = fileName1[fileName1.length - 1];
1193
- File file = new File(compressedImageName);
1194
- long fileSize = file.length();
1195
- fileExtension = "." + compressedImageName.substring(compressedImageName.lastIndexOf(".") + 1).toLowerCase();
1196
- fileProperities = new JSONObject();
1197
- fileProperities.put("filePath", imgFilePath);
1198
- fileProperities.put("fileName", fileName);
1199
- fileProperities.put("fileSize", fileSize);
1200
- fileProperities.put("fileExtension", fileExtension);
1201
- fileProperities.put("thumbnail", getFileThumbnail(imgFilePath+ "/" +fileName, fileExtension));
1202
- callback.success(fileProperities);
1203
- } catch (Exception e) {
1204
- callback.error(e.getMessage());
1205
- }
1206
- }
1207
- } catch (Exception e) {
1208
- callbackContext.error(e.getMessage());
1209
- }
1210
- } catch (Exception e) {
1211
- e.printStackTrace();
1212
- }
1213
- }
1214
-
1215
- public String getBase64String(String imageSourcePath) {
1216
- String resultString="";
1217
- String filePath = mInterfaceUtil.rootDirectory + "/" + imageSourcePath;
1218
- File image = new File(filePath);
1219
- BitmapFactory.Options bmOptions = new BitmapFactory.Options();
1220
- Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
1221
- try {
1222
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1223
- bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
1224
- resultString = Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP);
1225
- } catch (Exception e) {
1226
- e.printStackTrace();
1227
- }
1228
- return resultString;
1229
- }
1230
-
1231
- public void chooseFile(CallbackContext callbackContext) {
1232
- try {
1233
- PluginResult pluginResult;
1234
- callback = callbackContext;
1235
- cordova.startActivityForResult(this, getPickImageChooserIntent(), NEW_FILE_PICK_REQUEST);
1236
- pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
1237
- pluginResult.setKeepCallback(true);
1238
- callbackContext.sendPluginResult(pluginResult);
1239
- } catch (Exception e) {
1240
- callbackContext.error(e.getMessage());
1241
- }
1242
- }
1243
- public Intent getPickImageChooserIntent() {
1244
- Intent openFile, selectFile;
1245
- if (Build.MANUFACTURER.equals("samsung")) {
1246
- openFile = new Intent("com.sec.android.app.myfiles.PICK_DATA");
1247
- openFile.putExtra("CONTENT_TYPE", "*/*");
1248
- } else {
1249
- openFile = new Intent(Intent.ACTION_GET_CONTENT);
1250
- openFile.setType("*/*");
1251
- openFile.addCategory(Intent.CATEGORY_OPENABLE);
1252
- openFile.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
1253
- }
1254
- selectFile = Intent.createChooser(openFile, "Select File");
1255
- return selectFile;
1256
- }
1257
- //App version plugin
1258
- public void appVersion(CallbackContext callbackContext) {
1259
- try {
1260
- PackageManager packageManager = this.cordova.getActivity().getPackageManager();
1261
- JSONObject r = new JSONObject();
1262
- try {
1263
- r.put("version", packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionName);
1264
- r.put("build", packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionCode);
1265
- } catch (JSONException e) {
1266
- e.printStackTrace();
1267
- }
1268
- callbackContext.success(r);
1269
- } catch (PackageManager.NameNotFoundException e) {
1270
- callbackContext.error("Exception thrown");
1271
- }
1272
- }
1273
-
1274
- //Rotate Screen plugin
1275
- public void rotateScreen(JSONArray args, CallbackContext callbackContext) {
1276
- String orientation = args.optString(0);
1277
- Activity activity = cordova.getActivity();
1278
- if (orientation.equals(ANY)) {
1279
- activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1280
- } else if (orientation.equals(LANDSCAPE_PRIMARY)) {
1281
- activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
1282
- } else if (orientation.equals(PORTRAIT_PRIMARY)) {
1283
- activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
1284
- } else if (orientation.equals(LANDSCAPE)) {
1285
- activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
1286
- } else if (orientation.equals(PORTRAIT)) {
1287
- activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
1288
- } else if (orientation.equals(LANDSCAPE_SECONDARY)) {
1289
- activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
1290
- } else if (orientation.equals(PORTRAIT_SECONDARY)) {
1291
- activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
1292
- }
1293
- callbackContext.success();
1294
- }
1295
-
1296
- public void deviceInfo(CallbackContext callbackContext) throws JSONException {
1297
- String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
1298
- JSONObject r = new JSONObject();
1299
- boolean a = android.os.Build.FINGERPRINT.contains("generic") ||
1300
- android.os.Build.PRODUCT.contains("sdk");
1301
- @SuppressWarnings("deprecation")
1302
- String sdkversion = android.os.Build.VERSION.SDK;
1303
- r.put("uuid", uuid);
1304
- r.put("version", android.os.Build.VERSION.RELEASE);
1305
- r.put("platform", ANDROID_PLATFORM);
1306
- r.put("model", android.os.Build.MODEL);
1307
- r.put("manufacturer", android.os.Build.MANUFACTURER);
1308
- r.put("isVirtual", a);
1309
- r.put("serial", android.os.Build.SERIAL);
1310
- r.put("timeZone", TimeZone.getDefault());
1311
- r.put("sdkVersion", sdkversion);
1312
- r.put("productName", android.os.Build.PRODUCT);
1313
- callbackContext.success(r);
1314
- }
1315
-
1316
- @Override
1317
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
1318
- switch (requestCode) {
1319
- case LOCATION_ACCURACY_REQUEST_NEW:
1320
- switch (resultCode) {
1321
- case Activity.RESULT_OK:
1322
- callback.success();
1323
- break;
1324
- case Activity.RESULT_CANCELED:
1325
- callback.error("oops! you have cancelled...");
1326
- break;
1327
- }
1328
- break;
1329
- }
1330
- if (SCANCODEINT == 118 && callback != null) {
1331
- if (resultCode == RESULT_OK) {
1332
- SCANCODEINT = 0;
1333
- IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
1334
- callback.success(result.getContents());
1335
- } else if (resultCode == Activity.RESULT_CANCELED) {
1336
- SCANCODEINT = 0;
1337
- callback.error("canceled");
1338
- } else {
1339
- SCANCODEINT = 0;
1340
- callback.error(resultCode);
1341
- }
1342
- } else if (SCANCODEINT == 119 && callback != null) {
1343
- if (resultCode == RESULT_OK) {
1344
- SCANCODEINT = 0;
1345
- IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
1346
- callback.success(result.getContents());
1347
- } else if (resultCode == Activity.RESULT_CANCELED) {
1348
- SCANCODEINT = 0;
1349
- callback.error("canceled");
1350
- } else {
1351
- SCANCODEINT = 0;
1352
- callback.error(resultCode);
1353
- }
1354
- } else if (requestCode == PICK_IMAGE_FROM_GALLERY && callback != null) {
1355
- if (resultCode == RESULT_OK) {
1356
- String fileName = null, getfilePath = null, filePath = null, fileType, storageDefinition, fileExtension;
1357
- final String docId, type, id;
1358
- final String[] split;
1359
- final String tag, path;
1360
- final int splitIndex;
1361
- Cursor cursor;
1362
- Uri uri = data.getData(); //get uri for selected file
1363
- fileType = this.cordova.getActivity().getContentResolver().getType(uri); // get mimeType for selected file
1364
- File getFileName, file;
1365
- try {
1366
- //API LEVEL 19 AND ABOVE (TO GET FILEPATH)
1367
- if (Build.VERSION.SDK_INT >= 19 && !Build.MANUFACTURER.equals("samsung") && DocumentsContract.isDocumentUri(cordova.getActivity(), uri)) {
1368
- if ("com.android.externalstorage.documents".equals(uri.getAuthority())) { // ExternalStorageProvider
1369
- docId = DocumentsContract.getDocumentId(uri);
1370
- split = docId.split(":");
1371
- type = split[0];
1372
- if ("primary".equalsIgnoreCase(type)) {
1373
- getfilePath = mInterfaceUtil.rootDirectory + "/" + split[1];
1374
- } else {
1375
- if (Environment.isExternalStorageRemovable()) {
1376
- storageDefinition = System.getenv("EXTERNAL_STORAGE");
1377
- getfilePath = storageDefinition;
1378
- } else {
1379
- splitIndex = docId.indexOf(':', 1);
1380
- tag = docId.substring(0, splitIndex);
1381
- path = docId.substring(splitIndex + 1);
1382
- if (new mInterfaceUtil().getPathToNonPrimaryVolume(cordova.getActivity(), tag) != null) {
1383
- storageDefinition = new mInterfaceUtil().getPathToNonPrimaryVolume(cordova.getActivity(), tag) + "/" + path;
1384
- file = new File(storageDefinition);
1385
- if (file.exists() && file.canRead()) {
1386
- getfilePath = storageDefinition;
1387
- }
1388
- }
1389
- }
1390
- }
1391
- } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { // DownloadsProvider
1392
- id = DocumentsContract.getDocumentId(uri);
1393
- final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
1394
- getfilePath = new mInterfaceUtil().getDataColumn(cordova.getActivity(), contentUri, null, null);
1395
- } else if ("com.android.providers.media.documents".equals(uri.getAuthority())) { // MediaProvider
1396
- docId = DocumentsContract.getDocumentId(uri);
1397
- split = docId.split(":");
1398
- type = split[0];
1399
- Uri contentUri = null;
1400
- if ("image".equals(type)) {
1401
- contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
1402
- } else if ("video".equals(type)) {
1403
- contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
1404
- } else if ("audio".equals(type)) {
1405
- contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
1406
- }
1407
- final String selection = "_id=?";
1408
- final String[] selectionArgs = new String[]{
1409
- split[1]
1410
- };
1411
- getfilePath = new mInterfaceUtil().getDataColumn(cordova.getActivity(), contentUri, selection, selectionArgs);
1412
- }
1413
- // *** API Level 19 and Above (To Get FileName,FileExtension and FileSize)**** //
1414
- cursor = cordova.getActivity().getContentResolver().query(uri, null, null, null, null, null);
1415
- try {
1416
- if (cursor != null && cursor.moveToFirst()) {
1417
- fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
1418
- }
1419
- } finally {
1420
- cursor.close();
1421
- }
1422
- // *** API Level 19 below and SAMSUNG (To Get FileProperties of MediaFiles)**** //
1423
- } else {
1424
- if (fileType != null) {
1425
- String[] projection = {
1426
- MediaStore.Images.Media.DATA,
1427
- MediaStore.Images.Media.SIZE,
1428
- MediaStore.Images.Media.DISPLAY_NAME
1429
- };
1430
- cursor = cordova.getActivity().getContentResolver().query(uri, projection, null, null, null);
1431
- if (cursor.moveToFirst()) {
1432
- getfilePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
1433
- fileName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));
1434
- }
1435
- cursor.close();
1436
- // API LEVEL 19 BELOW AND SAMSUNG (TO GET FILEPROPERTIES OF NORMAL FILES(EX:txt,.pdf,etc..,))
1437
- } else {
1438
- getfilePath = data.getData().getPath();
1439
- filePath = getfilePath.substring(0, getfilePath.lastIndexOf(File.separator));
1440
- getFileName = new File(getfilePath);
1441
- fileName = getFileName.getName();
1442
- }
1443
- }
1444
- filePath = getfilePath.substring(0, getfilePath.lastIndexOf(File.separator));
1445
- fileExtension = "." + getfilePath.substring(getfilePath.lastIndexOf(".") + 1).toLowerCase();
1446
- if (filePath != null) {
1447
- try {
1448
- if (fileExtension.equals(".heic")) {
1449
- convertImageTo64BaseString(callback, filePath + "/" + fileName, "gallery","");
1450
- } else if (fileExtension.equals(".jpeg") || fileExtension.equals(".jpg") || fileExtension.equals(".png")) {
1451
- convertImageTo64BaseString(callback, filePath + "/" + fileName, "gallery","");
1452
- } else {
1453
- callback.error("Only JPEG or PNG file extensions are allowed to attach.");
1454
- }
1455
- } catch (Exception e) {
1456
- callback.error("Only JPEG or PNG file extensions are allowed to attach.");
1457
- }
1458
- } else {
1459
- callback.error("File path was null");
1460
- }
1461
- } catch (Exception e) {
1462
- e.printStackTrace();
1463
- }
1464
- } else if (resultCode == Activity.RESULT_CANCELED) {
1465
- callback.error("failure");
1466
- } else {
1467
- callback.error(resultCode);
1468
- }
1469
- } else if(requestCode == NEW_FILE_PICK_REQUEST && callback != null) {
1470
- try {
1471
- Uri uri = data.getData();
1472
- String fileName = null, extension = null, filePath = null;
1473
- JSONObject fileProperities = null;
1474
- Cursor cursor = null;
1475
- if (uri.getScheme().equals("file")) {
1476
- fileName = uri.getLastPathSegment();
1477
-
1478
- if (fileName.indexOf(".") > 0){
1479
- fileName = fileName.substring(0, fileName.lastIndexOf("."));
1480
- String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
1481
- extension = "." + fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
1482
- fileName = fileName + "_" + timeStamp + extension;
1483
- }
1484
- } else {
1485
- try {
1486
- cursor = cordova.getActivity().getApplicationContext().getContentResolver().query(uri, new String[]{ MediaStore.Images.ImageColumns.DISPLAY_NAME }, null, null, null);
1487
- if (cursor != null && cursor.moveToFirst()) {
1488
- fileName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
1489
- extension = "." + fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
1490
- if (!extension.equals(".jpeg") && !extension.equals(".jpg") && !extension.equals(".png")) {
1491
- String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
1492
- fileName = fileName.substring(0, fileName.lastIndexOf("."));
1493
- fileName = fileName + "_" + timeStamp + extension;
1494
- }
1495
-
1496
- }
1497
- } finally {
1498
- if (cursor != null) {
1499
- cursor.close();
1500
- }
1501
- }
1502
- }
1503
-
1504
- extension = "." + fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
1505
-
1506
- filePath = copyFileFromUri(cordova.getActivity().getApplicationContext(), uri, fileName, attachmentDestPath,callback);
1507
- File file = new File(filePath);
1508
- String mimeType = getMimeType(filePath);
1509
- System.out.println("Mime type is: " + mimeType);
1510
- double fileSize = file.length();
1511
- if (filePath != null) {
1512
- try {
1513
- if(requestCode == NEW_FILE_PICK_REQUEST) {
1514
- if(extension.equals(".heic")) {
1515
- convertImageTo64BaseString(callback, filePath, "compress",attachmentDestPath);
1516
- } else if (mimeType != null) {
1517
- if (mimeType.contains("image")) {
1518
- convertImageTo64BaseString(callback, filePath, "compress",attachmentDestPath);
1519
- } else {
1520
- fileProperities = new JSONObject();
1521
- fileProperities.put("filePath", filePath.substring(0, filePath.lastIndexOf(File.separator)));
1522
- fileProperities.put("fileName", fileName);
1523
- fileProperities.put("fileSize", fileSize);
1524
- fileProperities.put("fileExtension", extension);
1525
- fileProperities.put("thumbnail", getFileThumbnail(filePath, extension));
1526
- callback.success(fileProperities);
1527
- }
1528
- } else {
1529
- fileProperities = new JSONObject();
1530
- fileProperities.put("filePath", filePath.substring(0, filePath.lastIndexOf(File.separator)));
1531
- fileProperities.put("fileName", fileName);
1532
- fileProperities.put("fileSize", fileSize);
1533
- fileProperities.put("fileExtension", extension);
1534
- fileProperities.put("thumbnail", getFileThumbnail(filePath, extension));
1535
- callback.success(fileProperities);
1536
- }
1537
- }
1538
- } catch (Exception e) {
1539
- callback.error(e.getMessage());
1540
- }
1541
- } else {
1542
- callback.error("Selected file path is null");
1543
- }
1544
- } catch (Exception e) {
1545
- callback.error(e.getMessage());
1546
- }
1547
- } else if (requestCode == REQUEST_IMAGE_CAPTURE && callback != null) {
1548
- if (resultCode == RESULT_OK) {
1549
- convertImageTo64BaseString(callback, pictureFilePath, "camera","");
1550
- } else if (resultCode == Activity.RESULT_CANCELED) {
1551
- // TODO NO_RESULT or error callback?
1552
- File file = new File(pictureFilePath);
1553
- if (file.exists()) {
1554
- file.delete();
1555
- }
1556
- callback.error("failure");
1557
- } else {
1558
- callback.error(resultCode);
1559
- }
1560
- } else if (requestCode == REQUEST_LIVE_IMAGE_CAPTURE && callback != null) {
1561
- if (resultCode == RESULT_OK) {
1562
- convertImageTo64BaseString(callback, pictureFilePath, "compress",attachmentDestPath);
1563
- } else if (resultCode == Activity.RESULT_CANCELED) {
1564
- // TODO NO_RESULT or error callback?
1565
- File file = new File(pictureFilePath);
1566
- if (file.exists()) {
1567
- file.delete();
1568
- }
1569
- callback.error("failure");
1570
- } else {
1571
- callback.error(resultCode);
1572
- }
1573
- } else if (requestCode == PICK_FILE_REQUEST && callback != null) {
1574
- if (resultCode == RESULT_OK) {
1575
- String fileName = null,
1576
- getfilePath = null,
1577
- filePath = null,
1578
- fileExtension,
1579
- fileType,
1580
- fileSize = null,
1581
- storageDefinition;
1582
- ;
1583
- final String docId,
1584
- type,
1585
- id;
1586
- final String[] split;
1587
- final String tag,
1588
- path;
1589
- final int splitIndex;
1590
- Cursor cursor;
1591
- long getSize;
1592
- JSONObject fileProperities = null;
1593
- Uri uri = data.getData(); //get uri for selected file
1594
- fileType = this.cordova.getActivity().getContentResolver().getType(uri); // get mimeType for selected file
1595
- File getFileName,
1596
- file;
1597
- try {
1598
- //API LEVEL 19 AND ABOVE (TO GET FILEPATH)
1599
- if (Build.VERSION.SDK_INT >= 19 && !Build.MANUFACTURER.equals("samsung") && DocumentsContract.isDocumentUri(cordova.getActivity(), uri)) {
1600
- if ("com.android.externalstorage.documents".equals(uri.getAuthority())) { // ExternalStorageProvider
1601
- docId = DocumentsContract.getDocumentId(uri);
1602
- split = docId.split(":");
1603
- type = split[0];
1604
- if ("primary".equalsIgnoreCase(type)) {
1605
- getfilePath = mInterfaceUtil.rootDirectory + "/" + split[1];
1606
- } else {
1607
- if (Environment.isExternalStorageRemovable()) {
1608
- storageDefinition = System.getenv("EXTERNAL_STORAGE");
1609
- getfilePath = storageDefinition;
1610
- } else {
1611
- splitIndex = docId.indexOf(':', 1);
1612
- tag = docId.substring(0, splitIndex);
1613
- path = docId.substring(splitIndex + 1);
1614
- if (new mInterfaceUtil().getPathToNonPrimaryVolume(cordova.getActivity(), tag) != null) {
1615
- storageDefinition = new mInterfaceUtil().getPathToNonPrimaryVolume(cordova.getActivity(), tag) + "/" + path;
1616
- file = new File(storageDefinition);
1617
- if (file.exists() && file.canRead()) {
1618
- getfilePath = storageDefinition;
1619
- }
1620
- }
1621
- }
1622
- }
1623
- } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { // DownloadsProvider
1624
- id = DocumentsContract.getDocumentId(uri);
1625
- final Uri contentUri = ContentUris.withAppendedId(
1626
- Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
1627
- getfilePath = new mInterfaceUtil().getDataColumn(cordova.getActivity(), contentUri, null, null);
1628
-
1629
- } else if ("com.android.providers.media.documents".equals(uri.getAuthority())) { // MediaProvider
1630
- docId = DocumentsContract.getDocumentId(uri);
1631
- split = docId.split(":");
1632
- type = split[0];
1633
- Uri contentUri = null;
1634
- if ("image".equals(type)) {
1635
- contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
1636
- } else if ("video".equals(type)) {
1637
- contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
1638
- } else if ("audio".equals(type)) {
1639
- contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
1640
- }
1641
- final String selection = "_id=?";
1642
- final String[] selectionArgs = new String[]{
1643
- split[1]
1644
- };
1645
- getfilePath = new mInterfaceUtil().getDataColumn(cordova.getActivity(), contentUri, selection, selectionArgs);
1646
- }
1647
- // *** API Level 19 and Above (To Get FileName,FileExtension and FileSize)**** //
1648
- cursor = cordova.getActivity().getContentResolver().query(uri, null, null, null, null, null);
1649
- try {
1650
- if (cursor != null && cursor.moveToFirst()) {
1651
- fileName = cursor.getString(
1652
- cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
1653
- if (!cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))) {
1654
- fileSize = cursor.getString(cursor.getColumnIndex(OpenableColumns.SIZE));
1655
- }
1656
- }
1657
- } finally {
1658
- cursor.close();
1659
- }
1660
- // *** API Level 19 below and SAMSUNG (To Get FileProperties of MediaFiles)**** //
1661
- } else {
1662
- if (fileType != null) {
1663
- String[] projection = {
1664
- MediaStore.Images.Media.DATA,
1665
- MediaStore.Images.Media.SIZE,
1666
- MediaStore.Images.Media.DISPLAY_NAME
1667
- };
1668
- cursor = cordova.getActivity().getContentResolver().query(uri, projection, null, null, null);
1669
- if (cursor.moveToFirst()) {
1670
- getfilePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
1671
- fileName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));
1672
- fileSize = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE));
1673
- }
1674
- cursor.close();
1675
- // API LEVEL 19 BELOW AND SAMSUNG (TO GET FILEPROPERTIES OF NORMAL FILES(EX:txt,.pdf,etc..,))
1676
- } else {
1677
- getfilePath = data.getData().getPath();
1678
- filePath = getfilePath.substring(0, getfilePath.lastIndexOf(File.separator));
1679
- getFileName = new File(getfilePath);
1680
- fileName = getFileName.getName();
1681
- getSize = getFileName.length();
1682
- fileSize = String.valueOf(getSize);
1683
- }
1684
- }
1685
- filePath = getfilePath.substring(0, getfilePath.lastIndexOf(File.separator));
1686
- fileExtension = "." + getfilePath.substring(getfilePath.lastIndexOf(".") + 1).toLowerCase();
1687
- // SEND BELOW JSON OBJECT TO PLUGIN CALLBACK
1688
- if (filePath != null) {
1689
- try {
1690
- if (fileExtension.equals(".jpeg") || fileExtension.equals(".jpg") || fileExtension.equals(".png")) {
1691
- convertImageTo64BaseString(callback, filePath + "/" + fileName, "compress",attachmentDestPath);
1692
- } else {
1693
- fileProperities = new JSONObject();
1694
- fileProperities.put("filePath", filePath);
1695
- fileProperities.put("fileName", fileName);
1696
- fileProperities.put("fileSize", fileSize);
1697
- fileProperities.put("fileExtension", fileExtension);
1698
- callback.success(fileProperities);
1699
- }
1700
- } catch (Exception e) {
1701
- callback.error("Failed to process PICK_FILE_REQUEST");
1702
- }
1703
- } else {
1704
- callback.error("File path was null");
1705
- }
1706
- } catch (Exception e) {
1707
- e.printStackTrace();
1708
- }
1709
- } else if (resultCode == Activity.RESULT_CANCELED) {
1710
- // TODO NO_RESULT or error callback?
1711
- callback.error("failure");
1712
- } else {
1713
- callback.error(resultCode);
1714
- }
1715
- } else {
1716
- callback.error("failure");
1717
- }
1718
- }
1719
-
1720
- @Override
1721
- public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
1722
- try {
1723
- boolean indicator = true;
1724
- for (int i = 0; i < grantResults.length; i++) {
1725
- if (grantResults[i] != 0) {
1726
- indicator = false;
1727
- break;
1728
- }
1729
- }
1730
- if (indicator) {
1731
- callback.success("success");
1732
- } else {
1733
- callback.error("failure");
1734
- }
1735
- } catch (Exception e) {
1736
- e.printStackTrace();
1737
- }
1738
- }
1739
- public String copyFileFromUri(Context context, Uri fileUri, String fileName, String destinationPath, CallbackContext callback) {
1740
- InputStream inputStream = null;
1741
- OutputStream outputStream = null;
1742
- String outPutFilePath = null;
1743
- File saveDirectory;
1744
- try {
1745
- ContentResolver content = context.getContentResolver();
1746
- inputStream = content.openInputStream(fileUri);
1747
- File root = mInterfaceUtil.rootDirectory;
1748
- if(root == null) {
1749
- System.out.println("Failed to get root");
1750
- }
1751
- if(!destinationPath.equalsIgnoreCase("")){
1752
- saveDirectory = new File(mInterfaceUtil.rootDirectory + "/" + destinationPath);
1753
- }else{
1754
- saveDirectory = new File(mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/" + "images");
1755
- }
1756
-
1757
- saveDirectory.mkdirs();
1758
- outPutFilePath = saveDirectory + "/" + fileName;
1759
- outputStream = new FileOutputStream(outPutFilePath);
1760
- if(outputStream != null) {
1761
- byte[] buffer = new byte[1000];
1762
- int bytesRead = 0;
1763
- while ((bytesRead = inputStream.read( buffer, 0, buffer.length )) >= 0) {
1764
- outputStream.write( buffer, 0, buffer.length );
1765
- }
1766
- } else {
1767
- callback.error("Error occurred in opening outputStream");
1768
- }
1769
- } catch (Exception e) {
1770
- callback.error("Exception occurred " + e.getMessage());
1771
- }
1772
- return outPutFilePath;
1773
- }
1774
- /* CHECKING THE BACKGROUND SERVICE RUNNING OR NOT */
1775
- private boolean isServiceRunning(Class<?> serviceClass) {
1776
- ActivityManager manager = (ActivityManager) cordova.getActivity().getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
1777
- for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
1778
- if (serviceClass.getName().equals(service.service.getClassName())) {
1779
- return true;
1780
- }
1781
- }
1782
- return false;
1783
- }
1784
-
1785
- private boolean isProcessRunning() {
1786
- ActivityManager manager1 = (ActivityManager) cordova.getActivity().getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
1787
- for (ActivityManager.RunningAppProcessInfo processInfo : manager1.getRunningAppProcesses()) {
1788
- if (processInfo.processName.equals(cordova.getActivity().getPackageName())) {
1789
- return true;
1790
- }
1791
- }
1792
- return false;
1793
- }
1794
-
1795
- private void EnableGPSAutoMatically(CallbackContext callbackContext) {
1796
- callback = callbackContext;
1797
- createLocationRequest1();
1798
- mGoogleApiClient1 = new GoogleApiClient.Builder(cordova.getActivity())
1799
- .addApi(LocationServices.API).addConnectionCallbacks(this)
1800
- .addOnConnectionFailedListener(this).build();
1801
- mGoogleApiClient1.connect();
1802
- LocationRequest locationRequest = LocationRequest.create();
1803
- locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
1804
- locationRequest.setInterval(30 * 1000);
1805
- locationRequest.setFastestInterval(5 * 1000);
1806
- LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
1807
- .addLocationRequest(locationRequest);
1808
- builder.setAlwaysShow(true); // this is the key ingredient
1809
- PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
1810
- .checkLocationSettings(mGoogleApiClient1, builder.build());
1811
- result.setResultCallback(this);
1812
- }
1813
-
1814
- @Override
1815
- public void onConnected(@Nullable Bundle bundle) {
1816
- if (mGoogleApiClient1.isConnected()) {
1817
- startLocationUpdates1();
1818
- }
1819
- }
1820
-
1821
- @Override
1822
- public void onConnectionSuspended(int i) {
1823
- }
1824
-
1825
- @Override
1826
- public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
1827
- }
1828
-
1829
- @Override
1830
- public void onResult(LocationSettingsResult locationSettingsResult) {
1831
- final Status status = locationSettingsResult.getStatus();
1832
- switch (status.getStatusCode()) {
1833
- case LocationSettingsStatusCodes.SUCCESS:
1834
- break;
1835
- case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
1836
- try {
1837
- this.cordova.setActivityResultCallback(this);
1838
- status.startResolutionForResult(this.cordova.getActivity(), LOCATION_ACCURACY_REQUEST_NEW);
1839
- } catch (IntentSender.SendIntentException e) {
1840
- System.out.println("PendingIntent unable to execute request: ");
1841
- }
1842
- break;
1843
- case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
1844
- System.out.println("Location settings are inadequate, and cannot be fixed here. Dialog not created.");
1845
- break;
1846
- }
1847
- }
1848
-
1849
- @Override
1850
- public void onLocationChanged(Location location) {
1851
- mCurrentLocation1 = location;
1852
- try {
1853
- System.out.println(String.valueOf(mCurrentLocation1.getLatitude()) + "," + String.valueOf(mCurrentLocation1.getLongitude()));
1854
- if (currentLocationInd.equals("true")) {
1855
- currentLocationInd = "";
1856
- callback.success(String.valueOf(mCurrentLocation1.getLatitude()) + "," + String.valueOf(mCurrentLocation1.getLongitude()));
1857
- }
1858
- } catch (Exception e) {
1859
- callback.error(e.getMessage());
1860
- }
1861
- }
1862
-
1863
- private class DownloadTask extends AsyncTask<String, Integer, String> {
1864
-
1865
- private Context context;
1866
- private PowerManager.WakeLock mWakeLock;
1867
-
1868
- public DownloadTask(Context context) {
1869
- this.context = context;
1870
- }
1871
-
1872
- @Override
1873
- protected String doInBackground(String... sUrl) {
1874
- InputStream input = null;
1875
- OutputStream output = null;
1876
- HttpURLConnection connection = null;
1877
- try {
1878
- URL url = new URL(sUrl[0]);
1879
- connection = (HttpURLConnection) url.openConnection();
1880
- connection.connect();
1881
- // expect HTTP 200 OK, so we don't mistakenly save error report
1882
- // instead of the file
1883
- if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
1884
- return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage();
1885
- }
1886
- // this will be useful to display download percentage
1887
- // might be -1: server did not report the length
1888
- int fileLength = connection.getContentLength();
1889
- // download the file
1890
- input = connection.getInputStream();
1891
- File rootPath = mInterfaceUtil.rootDirectory;
1892
- File filesourceDirecory = new File(rootPath + "/" + pathComponent(sUrl[1]));
1893
- if (!filesourceDirecory.exists()) {
1894
- filesourceDirecory.mkdirs();
1895
- }
1896
- File fileSavePath = new File(rootPath + "/" + sUrl[1]);
1897
- output = new FileOutputStream(fileSavePath);
1898
- byte data[] = new byte[4096];
1899
- long total = 0;
1900
- int count;
1901
- while ((count = input.read(data)) != -1) {
1902
- // allow canceling with back button
1903
- if (isCancelled()) {
1904
- input.close();
1905
- return null;
1906
- }
1907
- total += count;
1908
- // publishing the progress....
1909
- if (fileLength > 0) // only if total length is known
1910
- publishProgress((int) (total * 100 / fileLength));
1911
- output.write(data, 0, count);
1912
- }
1913
- } catch (Exception e) {
1914
- callback.error("Failure..." + e.getMessage());
1915
- }
1916
- if(sUrl[2].equalsIgnoreCase("true")){
1917
- return sUrl[1];
1918
- }else{
1919
- return null;
1920
- }
1921
- }
1922
-
1923
- @Override
1924
- protected void onPostExecute(String result) {
1925
- try {
1926
- if (result != null) {
1927
- if(result.indexOf('.') != -1){
1928
- String extension = "." + result.substring(result.lastIndexOf(".") + 1).toLowerCase(),
1929
- filePath = mInterfaceUtil.rootDirectory+"/"+result;
1930
- String thumbnail = getFileThumbnail(filePath,extension);
1931
- callback.success(thumbnail);
1932
- } else{
1933
- callback.error("Failure...");
1934
- }
1935
- } else {
1936
- System.out.println("success");
1937
- callback.success("");
1938
- }
1939
- } catch (Exception e) {
1940
- e.printStackTrace();
1941
- }
1942
- }
1943
- }
1944
-
1945
- public static String pathComponent(String filename) {
1946
- int i = filename.lastIndexOf(File.separator);
1947
- return (i > -1) ? filename.substring(0, i) : filename;
1948
- }
1949
-
1950
- private void unzip(final JSONArray args, final CallbackContext callbackContext) {
1951
- this.cordova.getThreadPool().execute(new Runnable() {
1952
- public void run() {
1953
- unzipSync(args, callbackContext);
1954
- }
1955
- });
1956
- }
1957
-
1958
- private void unzipSync(JSONArray args, CallbackContext callbackContext) {
1959
- InputStream inputStream = null;
1960
- try {
1961
- String zipFileName = args.getJSONObject(0).optString("filePath");
1962
- String outputDirectory = args.getJSONObject(0).optString("destination");
1963
- // Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile://
1964
- // Accept a path or a URI for the source zip.
1965
- File root = mInterfaceUtil.rootDirectory;
1966
- //callbackContext.success("file://"+root+"/");
1967
- Uri uri = null;
1968
- Uri zipUri = getUriForArg(root + "/" + zipFileName);
1969
- Uri outputUri = getUriForArg(root + "/" + outputDirectory);
1970
- CordovaResourceApi resourceApi = webView.getResourceApi();
1971
- File tempFile = resourceApi.mapUriToFile(zipUri);
1972
- if (tempFile == null || !tempFile.exists()) {
1973
- String errorMessage = "Zip file does not exist";
1974
- callbackContext.error(errorMessage);
1975
- return;
1976
- }
1977
- File outputDir = resourceApi.mapUriToFile(outputUri);
1978
- outputDirectory = outputDir.getAbsolutePath();
1979
- outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator;
1980
- if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())) {
1981
- String errorMessage = "Could not create output directory";
1982
- callbackContext.error(errorMessage);
1983
- return;
1984
- }
1985
- CordovaResourceApi.OpenForReadResult zipFile = resourceApi.openForRead(zipUri);
1986
- inputStream = new BufferedInputStream(zipFile.inputStream);
1987
- // The inputstream is now pointing at the start of the actual zip file content.
1988
- ZipInputStream zis = new ZipInputStream(inputStream);
1989
- inputStream = zis;
1990
- ZipEntry ze;
1991
- byte[] buffer = new byte[32 * 1024];
1992
- boolean anyEntries = false;
1993
- while ((ze = zis.getNextEntry()) != null) {
1994
- anyEntries = true;
1995
- String compressedName = ze.getName();
1996
- if (ze.isDirectory()) {
1997
- File dir = new File(outputDirectory + compressedName);
1998
- dir.mkdirs();
1999
- } else {
2000
- File file = new File(outputDirectory + compressedName);
2001
- file.getParentFile().mkdirs();
2002
- if (file.exists() || file.createNewFile()) {
2003
- Log.w("Zip", "extracting: " + file.getPath());
2004
- FileOutputStream fout = new FileOutputStream(file);
2005
- int count;
2006
- while ((count = zis.read(buffer)) != -1) {
2007
- fout.write(buffer, 0, count);
2008
- }
2009
- fout.close();
2010
- }
2011
-
2012
- }
2013
- zis.closeEntry();
2014
- }
2015
- if (anyEntries)
2016
- callbackContext.success();
2017
- else
2018
- callbackContext.error("Bad zip file");
2019
- } catch (Exception e) {
2020
- String errorMessage = "An error occurred while unzipping.";
2021
- callbackContext.error(errorMessage);
2022
- } finally {
2023
- if (inputStream != null) {
2024
- try {
2025
- inputStream.close();
2026
- } catch (IOException e) {
2027
- }
2028
- }
2029
- }
2030
- }
2031
-
2032
- private Uri getUriForArg(String arg) {
2033
- CordovaResourceApi resourceApi = webView.getResourceApi();
2034
- Uri tmpTarget = Uri.parse(arg);
2035
- return resourceApi.remapUri(
2036
- tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(arg)));
2037
- }
2038
-
2039
-
2040
- public boolean isConnected() {
2041
- ConnectivityManager online = (ConnectivityManager)cordova.getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
2042
- NetworkInfo networkInfo = online.getActiveNetworkInfo();
2043
- if (networkInfo != null && networkInfo.isConnected()) {
2044
- return true;
2045
- } else {
2046
- return false;
2047
- }
2048
- }
2049
-
2050
-
2051
- public String getFileThumbnail(String filePath,String extension){
2052
- Bitmap thumb;
2053
- String imgString = "";
2054
- try {
2055
- if(extension.equalsIgnoreCase(".mp4")){
2056
- thumb = ThumbnailUtils.createVideoThumbnail(filePath,
2057
- MediaStore.Images.Thumbnails.MINI_KIND);
2058
- imgString = convertBitmapToString(thumb);
2059
- }else if(extension.equalsIgnoreCase(".heic") || extension.equalsIgnoreCase(".jpeg")|| extension.equalsIgnoreCase(".jpg")|| extension.equalsIgnoreCase(".png")){
2060
- thumb = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(filePath),
2061
- 76, 76);
2062
-
2063
- imgString = convertBitmapToString(thumb);
2064
- }else if(extension.equalsIgnoreCase(".mp3")){
2065
- MediaMetadataRetriever mmr = new MediaMetadataRetriever();
2066
- byte[] bytes;
2067
- BitmapFactory.Options bfo=new BitmapFactory.Options();
2068
-
2069
- mmr.setDataSource(cordova.getActivity().getApplicationContext(), Uri.fromFile(new File(filePath)));
2070
- bytes = mmr.getEmbeddedPicture();
2071
- if (bytes != null){
2072
- thumb = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, bfo);
2073
- imgString = convertBitmapToString(thumb);
2074
- }
2075
- }
2076
- }catch (Exception e){
2077
-
2078
- }
2079
- return imgString;
2080
- }
2081
-
2082
- public String convertBitmapToString(Bitmap bitmap) {
2083
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
2084
- bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
2085
- return Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP);
2086
- }
2087
- }
1
+ package com.selfservit.util;
2
+
3
+ import android.Manifest;
4
+ import android.app.Activity;
5
+ import android.app.ActivityManager;
6
+ import android.app.AlertDialog;
7
+ import android.app.ProgressDialog;
8
+ import android.content.ActivityNotFoundException;
9
+ import android.content.ContentResolver;
10
+ import android.content.ContentUris;
11
+ import android.content.Context;
12
+ import android.content.DialogInterface;
13
+ import android.content.Intent;
14
+ import android.content.IntentSender;
15
+ import android.content.pm.ActivityInfo;
16
+ import android.content.pm.PackageManager;
17
+ import android.database.Cursor;
18
+ import android.graphics.Bitmap;
19
+ import android.graphics.BitmapFactory;
20
+ import android.graphics.Canvas;
21
+ import android.graphics.Matrix;
22
+ import android.graphics.Paint;
23
+ import android.location.Location;
24
+ import android.media.MediaMetadataRetriever;
25
+ import android.media.ThumbnailUtils;
26
+ import android.net.ConnectivityManager;
27
+ import android.net.NetworkInfo;
28
+ import android.net.Uri;
29
+ import android.os.AsyncTask;
30
+ import android.os.Build;
31
+ import android.os.Bundle;
32
+ import android.os.Environment;
33
+ import android.os.PowerManager;
34
+ import android.provider.DocumentsContract;
35
+ import android.provider.MediaStore;
36
+ import android.provider.OpenableColumns;
37
+ import android.provider.Settings;
38
+ import android.support.annotation.NonNull;
39
+ import android.support.annotation.Nullable;
40
+ import android.support.annotation.RequiresApi;
41
+ import android.support.v4.app.ActivityCompat;
42
+ import android.util.Base64;
43
+ import android.util.Log;
44
+ import android.util.Patterns;
45
+ import android.view.KeyEvent;
46
+ import android.webkit.MimeTypeMap;
47
+ import android.widget.ProgressBar;
48
+ import android.widget.Toast;
49
+ import android.media.ExifInterface;
50
+
51
+ import com.google.android.gms.common.ConnectionResult;
52
+ import com.google.android.gms.common.api.GoogleApiClient;
53
+ import com.google.android.gms.common.api.PendingResult;
54
+ import com.google.android.gms.common.api.ResultCallback;
55
+ import com.google.android.gms.common.api.Status;
56
+ import com.google.android.gms.location.LocationRequest;
57
+ import com.google.android.gms.location.LocationServices;
58
+ import com.google.android.gms.location.LocationSettingsRequest;
59
+ import com.google.android.gms.location.LocationSettingsResult;
60
+ import com.google.android.gms.location.LocationSettingsStatusCodes;
61
+ import com.google.android.gms.tasks.Task;
62
+ import com.google.zxing.integration.android.IntentIntegrator;
63
+ import com.google.zxing.integration.android.IntentResult;
64
+
65
+ import org.apache.cordova.CallbackContext;
66
+ import org.apache.cordova.CordovaInterface;
67
+ import org.apache.cordova.CordovaPlugin;
68
+ import org.apache.cordova.CordovaResourceApi;
69
+ import org.apache.cordova.CordovaWebView;
70
+ import org.apache.cordova.PermissionHelper;
71
+ import org.apache.cordova.PluginResult;
72
+ import org.json.JSONArray;
73
+ import org.json.JSONException;
74
+ import org.json.JSONObject;
75
+
76
+ import java.io.BufferedInputStream;
77
+ import java.io.BufferedReader;
78
+ import java.io.ByteArrayOutputStream;
79
+ import java.io.File;
80
+ import java.io.FileOutputStream;
81
+ import java.io.IOException;
82
+ import java.io.InputStream;
83
+ import java.io.InputStreamReader;
84
+ import java.io.OutputStream;
85
+ import java.io.OutputStreamWriter;
86
+ import java.net.HttpURLConnection;
87
+ import java.net.URL;
88
+ import java.text.SimpleDateFormat;
89
+ import java.util.ArrayList;
90
+ import java.util.Arrays;
91
+ import java.util.Date;
92
+ import java.util.List;
93
+ import java.util.Stack;
94
+ import java.util.TimeZone;
95
+ import java.util.regex.Matcher;
96
+ import java.util.regex.Pattern;
97
+ import java.util.zip.ZipEntry;
98
+ import java.util.zip.ZipInputStream;
99
+ import java.util.List;
100
+ import java.util.ArrayList;
101
+ import java.util.Arrays;
102
+
103
+ import static android.app.Activity.RESULT_OK;
104
+
105
+ public class mInterface extends CordovaPlugin implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<LocationSettingsResult> {
106
+ private static final String TAG = "mInterface";
107
+ public Stack<ProgressDialog> spinnerDialogStack = new Stack<ProgressDialog>();
108
+ private static final int PICK_FILE_REQUEST = 1;
109
+ public CallbackContext callback;
110
+ private static JSONArray arguments = null;
111
+ private String pictureFilePath;
112
+ private String cameraAttachmentInd = "false";
113
+ private String galleryAttachmentInd = "false";
114
+ private static final int REQUEST_IMAGE_CAPTURE = 111;
115
+ private static final int PICK_IMAGE_FROM_GALLERY = 112;
116
+ private static final int REQUEST_LIVE_IMAGE_CAPTURE = 113;
117
+ private static final int LOCATION_ACCURACY_REQUEST_NEW = 115;
118
+ private final static int NEW_FILE_PICK_REQUEST = 200;
119
+ private int SCANCODEINT = 0;
120
+ private static final String ANY = "any";
121
+ private static final String PORTRAIT_PRIMARY = "portrait-primary";
122
+ private static final String PORTRAIT_SECONDARY = "portrait-secondary";
123
+ private static final String LANDSCAPE_PRIMARY = "landscape-primary";
124
+ private static final String LANDSCAPE_SECONDARY = "landscape-secondary";
125
+ private static final String PORTRAIT = "portrait";
126
+ private static final String LANDSCAPE = "landscape";
127
+ private static final String ANDROID_PLATFORM = "Android";
128
+
129
+ String currentLocationInd = "";
130
+ Location mCurrentLocation1;
131
+ LocationRequest mLocationRequest1;
132
+ GoogleApiClient mGoogleApiClient1;
133
+ private static final long INTERVAL = 5 * 60 * 1000;
134
+ private static final long FASTEST_INTERVAL = 5 * 60 * 1000;
135
+ public static String attachmentDestPath = "";
136
+ /* START SERVICE WHEN USER COMES FROM INACTIVE TO ACTIVE STATE IF SERVICE NOT RUNNING */
137
+ @Override
138
+ public void onResume(boolean multitasking) {
139
+ super.onResume(multitasking);
140
+ //To avoid starting service after getting permissions initially.
141
+ if (!mInterfaceUtil.deviceID.equalsIgnoreCase("")) {
142
+ if (!isServiceRunning(mInterfaceService.class) || !isProcessRunning()) {
143
+ cordova.getActivity().startService(new Intent(cordova.getActivity().getApplicationContext(), mInterfaceService.class));
144
+ }
145
+ }
146
+ }
147
+
148
+ @RequiresApi(api = Build.VERSION_CODES.O)
149
+ @Override
150
+ public boolean execute(final String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
151
+ mInterfaceUtil.rootDirectory = new File(cordova.getActivity().getExternalFilesDir(""), "");
152
+ if (mInterfaceUtil.packageName.equals("")) {
153
+ mInterfaceUtil.packageName = cordova.getActivity().getApplicationContext().getPackageName().split("\\.")[2];
154
+ }
155
+ /* START BACKGROUND SERVICE IF NOT RUNNING ALREADY */
156
+ if (action.equals("StartService")) {
157
+ boolean appInfoUpdated = new mInterfaceUtil().updateAppInfo(args);
158
+ //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
159
+ if (!isServiceRunning(backgroundNotification.class)) {
160
+ cordova.getActivity().startService(new Intent(cordova.getActivity().getApplicationContext(), backgroundNotification.class));
161
+ }
162
+ if (!isServiceRunning(mInterfaceService.class)) {
163
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
164
+ cordova.getActivity().startForegroundService(new Intent(cordova.getActivity().getApplicationContext(), mInterfaceService.class));
165
+ } else {
166
+ cordova.getActivity().startService(new Intent(cordova.getActivity().getApplicationContext(), mInterfaceService.class));
167
+ }
168
+ } else {
169
+ System.out.println("Service is already running");
170
+ }
171
+ callbackContext.success("Success");
172
+ }else if (action.equals("showToastWithOptions")) {
173
+ try {
174
+ if(args.getJSONObject(0).optString("duration").equals("long")){
175
+ Toast.makeText(cordova.getActivity().getApplicationContext(),args.getJSONObject(0).optString("message"), Toast.LENGTH_LONG).show();
176
+ } else {
177
+ Toast.makeText(cordova.getActivity().getApplicationContext(),args.getJSONObject(0).optString("message"), Toast.LENGTH_SHORT).show();
178
+ }
179
+ } catch (Exception exception) {
180
+ callbackContext.success("Show Toast having exception");
181
+ }
182
+ } else if (action.equals("CheckLocationAccuracy")) {
183
+ int locationInt = 111;
184
+ try {
185
+ locationInt = Settings.Secure.getInt(this.cordova.getActivity().getContentResolver(), Settings.Secure.LOCATION_MODE);
186
+ callbackContext.success(Integer.toString(locationInt));
187
+ } catch (Settings.SettingNotFoundException e) {
188
+ System.out.println("Exception is: " + e.getMessage());
189
+ callbackContext.error(e.getMessage());
190
+ }
191
+ }else if (action.equals("GetBase64String")) {
192
+ try {
193
+ String imageString = getBase64String(args.getJSONObject(0).optString("filePath"));
194
+ callbackContext.success(imageString);
195
+ } catch (Exception e) {
196
+ System.out.println("Exception is: " + e.getMessage());
197
+ callbackContext.error(e.getMessage());
198
+ }
199
+ } else if (action.equals("GetSyncIndicator")) {
200
+ try {
201
+ File newQueueFolder, oldQueueFolder;
202
+ Boolean syncIndication = false;
203
+ BufferedReader readerObj;
204
+ String currentLine, sendData = "";
205
+ URL requestPath;
206
+ HttpURLConnection urlConObj;
207
+ OutputStreamWriter oStreamObj;
208
+ String currentLinedata = "";
209
+ String client_id = args.getJSONObject(0).optString("client_id");
210
+ String country_code = args.getJSONObject(0).optString("country_code");
211
+ String user_id = args.getJSONObject(0).optString("user_id");
212
+ String client_url = args.getJSONObject(0).optString("client_url");
213
+ String requestUrl = client_url + "/common/components/QueueManager/GetSyncInd.aspx?client_id=" + client_id + "&country_code=" + country_code + "&user_id=" + user_id;
214
+
215
+ try {
216
+ oldQueueFolder = new File(mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/database/queue");
217
+ newQueueFolder = new File(mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/" + client_id + "/" + country_code + "/database/queue");
218
+ if(oldQueueFolder.exists()) {
219
+ if(oldQueueFolder.listFiles().length == 0){
220
+ syncIndication = true;
221
+ }
222
+ } else{
223
+ syncIndication = true;
224
+ }
225
+ if(syncIndication) {
226
+ if(newQueueFolder.exists()){
227
+ if(newQueueFolder.listFiles().length != 0){
228
+ syncIndication = false;
229
+ }
230
+ }
231
+ }
232
+ if(syncIndication) {
233
+ requestPath = new URL(requestUrl);
234
+ urlConObj = (HttpURLConnection)requestPath.openConnection();
235
+ urlConObj.setDoOutput(true);
236
+ urlConObj.setRequestMethod("POST");
237
+ urlConObj.setRequestProperty("CONTENT-TYPE", "application/text");
238
+ urlConObj.connect();
239
+ oStreamObj = new OutputStreamWriter(urlConObj.getOutputStream());
240
+ oStreamObj.write(sendData);
241
+ oStreamObj.flush();
242
+ oStreamObj.close();
243
+
244
+ /* GET RESPONSE FROM SERVER*/
245
+ readerObj = new BufferedReader(new InputStreamReader(urlConObj.getInputStream()));
246
+ currentLine = readerObj.readLine();
247
+ readerObj.close();
248
+ currentLinedata = currentLine.toString();
249
+ urlConObj.disconnect();
250
+ if(currentLinedata.equals("true")) {
251
+ syncIndication = true;
252
+ } else {
253
+ syncIndication = false;
254
+ }
255
+ }
256
+ callbackContext.success(String.valueOf(syncIndication));
257
+ }catch(Exception e) {
258
+ callbackContext.success(e.getMessage());
259
+ }
260
+ } catch (Exception e) {
261
+ callbackContext.success(e.getMessage());
262
+ }
263
+ }
264
+ else if (action.equals("TurnOnAutomaticDateTime")) {
265
+ Intent intent = new Intent(android.provider.Settings.ACTION_DATE_SETTINGS);
266
+ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
267
+ cordova.getActivity().getApplicationContext().startActivity(intent);
268
+ callbackContext.success();
269
+ } else if (action.equals("CheckAutomaticTime")) {
270
+ boolean timeValue = isTimeAutomatic(cordova.getActivity().getApplicationContext());
271
+ String valueString = "";
272
+ if (timeValue == true) {
273
+ valueString = "true";
274
+ } else {
275
+ valueString = "false";
276
+ }
277
+ callbackContext.success(valueString);
278
+ } else if (action.equals("ServiceCheck")) {
279
+ String str = "false";
280
+ if (isServiceRunning(mInterfaceService.class)) {
281
+ str = "true";
282
+ System.out.println("service check is: " + str + " " + isServiceRunning(mInterfaceService.class));
283
+ }
284
+ callbackContext.success(str);
285
+ } else if (action.equals("EnableGPSService")) {
286
+ EnableGPSAutoMatically(callbackContext);
287
+ } else if (action.equals("GetPermissions")) {
288
+ getPermissions(args, callbackContext);
289
+ return true;
290
+ } else if (action.equals("GetLocationPermission")) {
291
+ getLocationPermission(args, callbackContext);
292
+ return true;
293
+ } else if (action.equals("CheckLocationPermission")) {
294
+ checkLocationPermission(args, callbackContext);
295
+ return true;
296
+ } else if (action.equals("AppVersion")) {
297
+ appVersion(callbackContext);
298
+ return true;
299
+ } else if (action.equals("DeviceInfo")) {
300
+ deviceInfo(callbackContext);
301
+ return true;
302
+ } else if (action.equals("GetStorageRoot")) {
303
+ getStorageRoot(callbackContext);
304
+ return true;
305
+ } else if (action.equals("RotateScreen")) {
306
+ rotateScreen(args, callbackContext);
307
+ return true;
308
+ } else if (action.equals("UnZip")) {
309
+ unzip(args, callbackContext);
310
+ return true;
311
+ } else if (action.equals("EnableGPSService")) {
312
+ EnableGPSAutoMatically(callbackContext);
313
+ } else if ("GoHome".equals(action)) {
314
+ try {
315
+ Intent i = new Intent(Intent.ACTION_MAIN);
316
+ i.addCategory(Intent.CATEGORY_HOME);
317
+ this.cordova.getActivity().startActivity(i);
318
+ } catch (Exception e) {
319
+ return false;
320
+ }
321
+ callbackContext.success();
322
+ return true;
323
+ } else if ("GoBack".equals(action)) {
324
+ try {
325
+ // try to send it back and back to previous app
326
+ boolean sentAppToBackground = this.cordova.getActivity().moveTaskToBack(true);
327
+ // if not possible jump to home
328
+ if (!sentAppToBackground) {
329
+ Intent i = new Intent(Intent.ACTION_MAIN);
330
+ i.setAction(Intent.ACTION_MAIN);
331
+ i.addCategory(Intent.CATEGORY_HOME);
332
+ this.cordova.getActivity().startActivity(i);
333
+ }
334
+ } catch (Exception e) {
335
+ return false;
336
+ }
337
+ callbackContext.success();
338
+ return true;
339
+ } else if (action.equals("Spinner")) {
340
+ if (args.getJSONObject(0).optString("show").equals("true")) {
341
+ final boolean isFixed = true;
342
+ Runnable runnable = new Runnable() {
343
+ public void run() {
344
+ DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() {
345
+ public void onCancel(DialogInterface dialog) {
346
+ if (!isFixed) {
347
+ while (!mInterface.this.spinnerDialogStack.empty()) {
348
+ mInterface.this.spinnerDialogStack.pop().dismiss();
349
+ callbackContext.success();
350
+ }
351
+ }
352
+ }
353
+ };
354
+ ProgressDialog dialog;
355
+ if (isFixed) {
356
+ //If there is a progressDialog yet change the text
357
+ if (!mInterface.this.spinnerDialogStack.empty()) {
358
+ dialog = mInterface.this.spinnerDialogStack.peek();
359
+ } else {
360
+ dialog = CallbackProgressDialog.show(cordova.getActivity(), true, false, null, callbackContext);
361
+ mInterface.this.spinnerDialogStack.push(dialog);
362
+ }
363
+ } else {
364
+ //If there is a progressDialog yet change the text
365
+ if (!mInterface.this.spinnerDialogStack.empty()) {
366
+ dialog = mInterface.this.spinnerDialogStack.peek();
367
+ } else {
368
+ dialog = ProgressDialog.show(cordova.getActivity(), "", "", true, true, onCancelListener);
369
+ mInterface.this.spinnerDialogStack.push(dialog);
370
+ }
371
+ }
372
+ dialog.setContentView(new ProgressBar(cordova.getActivity()));
373
+ }
374
+ };
375
+ this.cordova.getActivity().runOnUiThread(runnable);
376
+ } else {
377
+ Runnable runnable = new Runnable() {
378
+ public void run() {
379
+ if (!mInterface.this.spinnerDialogStack.empty()) {
380
+ mInterface.this.spinnerDialogStack.pop().dismiss();
381
+ }
382
+
383
+ }
384
+ };
385
+ this.cordova.getActivity().runOnUiThread(runnable);
386
+ }
387
+ callbackContext.success("success");
388
+ } else if (action.equals("GetPackageName")) {
389
+ callbackContext.success(cordova.getActivity().getApplicationContext().getPackageName());
390
+ } else if (action.equals("GetLocation")) {
391
+ /* SEND CURRENT LOCATION VIA PLUGIN CALLBACK */
392
+ callbackContext.success(new mInterfaceUtil().getLocation(cordova.getActivity().getApplicationContext()));
393
+ } else if (action.equals("CheckLocation")) {
394
+ /* SEND CURRENT LOCATION SETTING STATUS VIA PLUGIN CALLBACK */
395
+ callbackContext.success(new mInterfaceUtil().checkLocation(cordova.getActivity().getApplicationContext()));
396
+ } else if ("GetCurrentLocation".equals(action)) {
397
+ currentLocationInd = "true";
398
+ callback = callbackContext;
399
+ createLocationRequest1();
400
+ this.mGoogleApiClient1 = new GoogleApiClient.Builder(cordova.getActivity())
401
+ .addConnectionCallbacks(this)
402
+ .addOnConnectionFailedListener(this)
403
+ .addApi(LocationServices.API)
404
+ .build();
405
+ mGoogleApiClient1.connect();
406
+ } else if (action.equals("GetSyncIndicator")) {
407
+ try {
408
+ File newQueueFolder, oldQueueFolder;
409
+ Boolean syncIndication = false;
410
+ BufferedReader readerObj;
411
+ String currentLine, sendData = "";
412
+ URL requestPath;
413
+ HttpURLConnection urlConObj;
414
+ OutputStreamWriter oStreamObj;
415
+ String currentLinedata = "";
416
+ String client_id = args.getJSONObject(0).optString("client_id");
417
+ String country_code = args.getJSONObject(0).optString("country_code");
418
+ String user_id = args.getJSONObject(0).optString("user_id");
419
+ String client_url = args.getJSONObject(0).optString("client_url");
420
+ String requestUrl = client_url + "/common/components/QueueManager/GetSyncInd.aspx?client_id=" + client_id + "&country_code=" + country_code + "&user_id=" + user_id;
421
+ try {
422
+ oldQueueFolder = new File(mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/database/queue");
423
+ newQueueFolder = new File(mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/" + client_id + "/" + country_code + "/database/queue");
424
+ if (oldQueueFolder.exists()) {
425
+ if (oldQueueFolder.listFiles().length == 0) {
426
+ syncIndication = true;
427
+ }
428
+ } else {
429
+ syncIndication = true;
430
+ }
431
+ if (syncIndication) {
432
+ if (newQueueFolder.exists()) {
433
+ if (newQueueFolder.listFiles().length != 0) {
434
+ syncIndication = false;
435
+ }
436
+ }
437
+ }
438
+ if (syncIndication) {
439
+ requestPath = new URL(requestUrl);
440
+ urlConObj = (HttpURLConnection) requestPath.openConnection();
441
+ urlConObj.setDoOutput(true);
442
+ urlConObj.setRequestMethod("POST");
443
+ urlConObj.setRequestProperty("CONTENT-TYPE", "application/text");
444
+ urlConObj.connect();
445
+ oStreamObj = new OutputStreamWriter(urlConObj.getOutputStream());
446
+ oStreamObj.write(sendData);
447
+ oStreamObj.flush();
448
+ oStreamObj.close();
449
+
450
+ /* GET RESPONSE FROM SERVER*/
451
+ readerObj = new BufferedReader(new InputStreamReader(urlConObj.getInputStream()));
452
+ currentLine = readerObj.readLine();
453
+ readerObj.close();
454
+ currentLinedata = currentLine.toString();
455
+ urlConObj.disconnect();
456
+ if (currentLinedata.equals("true")) {
457
+ syncIndication = true;
458
+ } else {
459
+ syncIndication = false;
460
+ }
461
+ }
462
+ callbackContext.success(String.valueOf(syncIndication));
463
+ } catch (Exception e) {
464
+ callbackContext.success(e.getMessage());
465
+ }
466
+ } catch (Exception e) {
467
+ callbackContext.success(e.getMessage());
468
+ }
469
+ }
470
+ else if (action.equals("FileChooser")) {
471
+ attachmentDestPath = args.optJSONObject(0).optString("destinationPath");
472
+ chooseFile(callbackContext);
473
+ return true;
474
+ } else if (action.equals("GetThumbnail")) {
475
+ String filePath = mInterfaceUtil.rootDirectory + "/" +args.optJSONObject(0).optString("filePath");
476
+ String thumbnail= getFileThumbnail(filePath, args.optJSONObject(0).optString("fileExtension"));
477
+ callback.success(thumbnail);
478
+ return true;
479
+ }
480
+ else if (action.equals("DownloadChatAttachFile")) {
481
+ String url = args.optJSONObject(0).optString("url"),
482
+ filePath = args.optJSONObject(0).optString("filePath"),
483
+ thumbnailInd = args.optJSONObject(0).optString("thumbnailInd");
484
+ PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
485
+ pluginResult.setKeepCallback(true);
486
+ callbackContext.sendPluginResult(pluginResult);
487
+ new mInterfaceUtil().DownloadChatAttachment(url,filePath, thumbnailInd, cordova.getActivity().getApplicationContext(),callbackContext, cordova.getActivity());
488
+ return true;
489
+ }
490
+ else if (action.equals("SendChatAttachment")) {
491
+ String filePath = args.optJSONObject(0).optString("filePath"),
492
+ serverPath = args.optJSONObject(0).optString("serverPath"),
493
+ fileName = args.optJSONObject(0).optString("fileName"),
494
+ attachURL = mInterfaceUtil.clientUrl + "/common/components/msvFileHandler//UploadFiles.aspx?client_id=" + mInterfaceUtil.clientID + "&country_code=" + mInterfaceUtil.countryCode + "&path=" + serverPath;
495
+ PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
496
+ pluginResult.setKeepCallback(true);
497
+ callbackContext.sendPluginResult(pluginResult);
498
+ new mInterfaceUtil().sendChatAttachment(filePath,fileName, attachURL, cordova.getActivity(),callbackContext);
499
+ return true;
500
+ }
501
+ else if (action.equals("SendAttachmentToServer")) {
502
+ String statusIndication = "false";
503
+ JSONObject inputFileObj;
504
+ try {
505
+ for (int index = 0; index < args.length(); index++) {
506
+ inputFileObj = args.getJSONObject(index);
507
+ String filePath = inputFileObj.optString("filePath"),
508
+ serverPath = inputFileObj.optString("serverPath"),
509
+ fileName = inputFileObj.optString("fileName"),
510
+ attachURL = mInterfaceUtil.clientUrl + "/common/components/msvFileHandler//UploadFiles.aspx?client_id=" + mInterfaceUtil.clientID + "&country_code=" + mInterfaceUtil.countryCode + "&path=" + serverPath;
511
+ statusIndication = new mInterfaceUtil().sendAttachmentToServer(filePath, fileName, attachURL);
512
+ if (statusIndication.equals("false")) {
513
+ break;
514
+ }
515
+ }
516
+ if (statusIndication.equals("true")) {
517
+ callbackContext.success("success");
518
+ } else {
519
+ callbackContext.error("failure");
520
+ }
521
+ } catch (Exception e) {
522
+ e.printStackTrace();
523
+ callbackContext.error("failure");
524
+ }
525
+ return true;
526
+ }
527
+ else if (action.equals("ReadFile")) {
528
+ try {
529
+ new mInterfaceUtil().readFile(args, callbackContext);
530
+ } catch (Exception e) {
531
+ e.printStackTrace();
532
+ }
533
+ return true;
534
+ } else if (action.equals("DeleteFile")) {
535
+ new mInterfaceUtil().deleteFile(args, callbackContext);
536
+ return true;
537
+ } else if (action.equals("DeleteMultipleFiles")) {
538
+ System.out.println("args.length(): " + args.length());
539
+ for (int index = 0; index < args.length(); index++) {
540
+ String path = args.optString(index);
541
+ new mInterfaceUtil().deleteMultipleFiles(path, callbackContext);
542
+ }
543
+ callbackContext.success();
544
+ return true;
545
+ } else if (action.equals("CreateFile")) {
546
+ new mInterfaceUtil().createFile(args, callbackContext);
547
+ return true;
548
+ } else if (action.equals("ValidateFile")) {
549
+ new mInterfaceUtil().validateFile(args, callbackContext);
550
+ return true;
551
+ } else if (action.equals("CreateDirectory")) {
552
+ new mInterfaceUtil().createDirectory(args, callbackContext);
553
+ return true;
554
+ } else if (action.equals("DeleteDirectory")) {
555
+ new mInterfaceUtil().deleteDirectory(args, callbackContext);
556
+ return true;
557
+ } else if (action.equals("UploadFile")) {
558
+ String filePath = args.getJSONObject(0).optString("filePath");
559
+ String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
560
+ String url = args.getJSONObject(0).optString("url");
561
+ new mInterfaceUtil().sendFilesToServer(filePath, fileName, url);
562
+ return true;
563
+ } else if (action.equals("CopyFile")) {
564
+ arguments = args;
565
+ new mInterfaceUtil().copyFile(callbackContext, arguments);
566
+ }else if (action.equals("CopyAttachmentFile")) {
567
+ arguments = args;
568
+ new mInterfaceUtil().copyAttachmentFile(callbackContext, arguments);
569
+ } else if (action.equals("CopyConfigFile")) {
570
+ arguments = args;
571
+ new mInterfaceUtil().copyConfigFile(callbackContext, arguments);
572
+ } else if (action.equals("GetNewDate")) {
573
+ new mInterfaceUtil().getNewDate(callbackContext);
574
+ } else if (action.equals("RefreshTimeProfile")) {
575
+ JSONObject timeObj = args.getJSONObject(0);
576
+ String date, hour, minute;
577
+ date = timeObj.optString("serverDate").toString();
578
+ hour = timeObj.optString("serverHour").toString();
579
+ minute = timeObj.optString("serverMinute").toString();
580
+ String returnStatus = new mInterfaceUtil().refreshTimeProfile(date, hour, minute);
581
+ if (returnStatus.equals("true")) {
582
+ callbackContext.success("success");
583
+ } else {
584
+ callbackContext.error("failure");
585
+ }
586
+ } else if (action.equals("UpdateChoice")) {
587
+ /* OPEN THE PLAYSTORE MSERVICE APP */
588
+ String appVersion, softwareProductVersion, softwareProductSubVersion;
589
+ JSONObject versionObj;
590
+ AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_HOLO_DARK);
591
+ AlertDialog alertDialog;
592
+ versionObj = args.getJSONObject(0);
593
+ appVersion = versionObj.optString("appVersion").toString();
594
+ softwareProductVersion = versionObj.optString("softwareProductVersion").toString();
595
+ softwareProductSubVersion = versionObj.optString("softwareProductSubVersion").toString();
596
+ builder.setTitle("New Update");
597
+ builder.setMessage("Your mservice version is " + appVersion + ". There is an updated version " + softwareProductVersion + "." + softwareProductSubVersion + " available. Please update.");
598
+ builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
599
+ @Override
600
+ public void onClick(DialogInterface dialog, int which) {
601
+ cordova.getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + cordova.getActivity().getApplicationContext().getPackageName())));
602
+ callbackContext.error("failure");
603
+ }
604
+ });
605
+ builder.setNegativeButton("Not Now", new DialogInterface.OnClickListener() {
606
+ @Override
607
+ public void onClick(DialogInterface dialog, int which) {
608
+ dialog.cancel();
609
+ callbackContext.success("Success");
610
+ }
611
+ });
612
+ alertDialog = builder.create();
613
+ alertDialog.setCanceledOnTouchOutside(false);
614
+ alertDialog.show();
615
+ alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
616
+
617
+ @Override
618
+ public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
619
+ if (keyCode == KeyEvent.KEYCODE_BACK) {
620
+ dialog.dismiss();
621
+ callbackContext.error("failure");
622
+ }
623
+ return true;
624
+ }
625
+
626
+ });
627
+ } else if (action.equals("UpdateConfirm")) {
628
+ /* OPEN THE PLAYSTORE MSERVICE APP */
629
+ String appVersion, softwareProductVersion, softwareProductSubVersion;
630
+ JSONObject versionObj;
631
+ AlertDialog alertDialog;
632
+ AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_HOLO_DARK);
633
+ versionObj = args.getJSONObject(0);
634
+ appVersion = versionObj.optString("appVersion").toString();
635
+ softwareProductVersion = versionObj.optString("softwareProductVersion").toString();
636
+ softwareProductSubVersion = versionObj.optString("softwareProductSubVersion").toString();
637
+ builder.setTitle("New Update");
638
+ builder.setMessage("Your mservice version is " + appVersion + ". Please upgrade the app to " + softwareProductVersion + "." + softwareProductSubVersion + " to proceed.");
639
+ builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
640
+ @Override
641
+ public void onClick(DialogInterface dialog, int which) {
642
+ cordova.getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + cordova.getActivity().getApplicationContext().getPackageName())));
643
+ callbackContext.error("failure");
644
+ }
645
+ });
646
+ alertDialog = builder.create();
647
+ alertDialog.setCanceledOnTouchOutside(false);
648
+ alertDialog.show();
649
+ alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
650
+
651
+ @Override
652
+ public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
653
+ if (keyCode == KeyEvent.KEYCODE_BACK) {
654
+ dialog.dismiss();
655
+ callbackContext.error("failure");
656
+ }
657
+ return true;
658
+ }
659
+ });
660
+ } else if (action.equals("UpdateNew")) {
661
+ cordova.getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + cordova.getActivity().getApplicationContext().getPackageName())));
662
+ callbackContext.error("failure");
663
+ } else if (action.equals("OpenFileWithViewer")) {
664
+ Context context = cordova.getActivity().getApplicationContext();
665
+ String filePath = mInterfaceUtil.rootDirectory + "/" + args.optString(0);
666
+ File imageFilePath = new File(filePath);
667
+ try {
668
+ Intent intent = new Intent(Intent.ACTION_VIEW);
669
+ Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", imageFilePath);
670
+ intent.setDataAndType(contentUri, getMimeType(filePath));
671
+ intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NO_HISTORY);
672
+ cordova.getActivity().startActivity(intent);
673
+ callbackContext.success();
674
+ } catch (ActivityNotFoundException e) {
675
+ callbackContext.error(1);
676
+ }
677
+ } else if (action.equals("CaptureImageFromCamera")) {
678
+ try {
679
+ if(args.length()>0){
680
+ attachmentDestPath = args.optJSONObject(0).optString("destinationPath");
681
+ cameraAttachmentInd = args.getJSONObject(0).optString("attachmentInd");
682
+ }
683
+ captureImage(callbackContext);
684
+ return true;
685
+ } catch (Exception e) {
686
+ callbackContext.error("ms058");
687
+ }
688
+ } else if (action.equals("PickImageFromGallery")) {
689
+ try {
690
+ if(args.length()>0) {
691
+ attachmentDestPath = args.optJSONObject(0).optString("destinationPath");
692
+ galleryAttachmentInd = args.getJSONObject(0).optString("attachmentInd");
693
+ }
694
+ pickImageFromGallery(callbackContext);
695
+ return true;
696
+ } catch (Exception e) {
697
+ callbackContext.error("ms059");
698
+ }
699
+ } else if (action.equals("CaptureFromCamera")) {
700
+ try {
701
+ captureImageLiveCamera(callbackContext);
702
+ return true;
703
+ } catch (Exception e) {
704
+ callbackContext.error(1);
705
+ }
706
+ } else if (action.equals("DeleteSrcFile")) {
707
+ try {
708
+ String filePath = args.getJSONObject(0).optString("filePath");
709
+ String fileName = args.getJSONObject(0).optString("fileName");
710
+ File fullPath = new File(filePath + "/" + fileName);
711
+ if (fullPath.exists()) {
712
+ fullPath.delete();
713
+ callbackContext.success();
714
+ } else {
715
+ callbackContext.error("Expected file is not there to delete..");
716
+ }
717
+ } catch (Exception e) {
718
+ callbackContext.error(1);
719
+ }
720
+ } else if (action.equals("DownloadFile")) {
721
+ callback = callbackContext;
722
+ final DownloadTask downloadTask = new DownloadTask(cordova.getActivity());
723
+ downloadTask.execute(args.optJSONObject(0).optString("url"), args.optJSONObject(0).optString("filePath"), args.optJSONObject(0).optString("thumbnailInd"));
724
+ return true;
725
+ }else if ("QueueProcessor".equals(action)) {
726
+ new mInterfaceUtil().queueProcessor(callbackContext);
727
+ return true;
728
+ } else if (action.equals("ScanQRCode")) {
729
+ try {
730
+ scanQRCode(callbackContext);
731
+ return true;
732
+ } catch (Exception e) {
733
+ callbackContext.error("ms060");
734
+ }
735
+ } else if (action.equals("ScanBarCode")) {
736
+ try {
737
+ scanBarCode(callbackContext);
738
+ return true;
739
+ } catch (Exception e) {
740
+ callbackContext.error("ms061");
741
+ }
742
+ } else if (action.equals("GetSubDirectoryList")) {
743
+ new mInterfaceUtil().getSubDirectoryList(args, callbackContext);
744
+ return true;
745
+ } else if (action.equals("GetFileList")) {
746
+ new mInterfaceUtil().getFileList(args, callbackContext);
747
+ return true;
748
+ } else if (action.equals("GetAppStateInfo")) {
749
+ boolean appInfoUpdated = new mInterfaceUtil().updateAppInfo(args);
750
+ if (appInfoUpdated) {
751
+ System.out.println("app info updated");
752
+ new mInterfaceUtil().getAppStateInfo(callbackContext, cordova.getActivity().getApplicationContext());
753
+ } else {
754
+ System.out.println("app info not updated");
755
+ callbackContext.success("");
756
+ }
757
+ return true;
758
+ } else if (action.equals("UpdateAppInfo")) {
759
+ boolean appInfoUpdated = new mInterfaceUtil().updateAppInfo(args);
760
+ if (appInfoUpdated) {
761
+ callbackContext.success("success");
762
+ } else {
763
+ callbackContext.error("failed to update app info");
764
+ }
765
+ return true;
766
+ }
767
+ else if (action.equals("MoveFile")) {
768
+ arguments = args;
769
+ new mInterfaceUtil().moveFile(callbackContext, arguments);
770
+ }else if (action.equals("SendAttachment")) {
771
+
772
+ JSONObject appInfo = args.getJSONObject(0);
773
+ mInterfaceUtil.app_id = appInfo.optString("app_id").toString();
774
+ mInterfaceUtil.platform = appInfo.optString("platform").toString();
775
+ mInterfaceUtil.deviceID = appInfo.optString("device_id").toString();
776
+ new mInterfaceUtil().moveFile(callbackContext, arguments);
777
+ }
778
+ else if (action.equals("OpenSms")) {
779
+ String contact_number, smsBody;
780
+ Intent smsIntent;
781
+ PluginResult result;
782
+ try {
783
+ contact_number = args.getJSONObject(0).optString("contact_number");
784
+ if(contact_number != null ) {
785
+ if(!contact_number.equals("") ) {
786
+ if(validateMobileNumber(contact_number)){
787
+ smsBody = args.getJSONObject(0).optString("msgBody");
788
+ smsIntent = new Intent(Intent.ACTION_VIEW);
789
+ smsIntent.putExtra("sms_body", smsBody);
790
+ smsIntent.setData(Uri.parse("sms:" + contact_number));
791
+ smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
792
+ cordova.getActivity().getApplicationContext().startActivity(smsIntent);
793
+ }else{
794
+ result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_INVALID");
795
+ callback.sendPluginResult(result);
796
+ }
797
+ }else{
798
+ result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_NOT_AVAILABLE");
799
+ callback.sendPluginResult(result);
800
+ }
801
+ }else{
802
+ result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_NOT_AVAILABLE");
803
+ callback.sendPluginResult(result);
804
+ }
805
+ } catch (JSONException e) {
806
+ e.printStackTrace();
807
+ result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
808
+ callback.sendPluginResult(result);
809
+ }
810
+ return true;
811
+ }else if (action.equals("OpenDialPad")) {
812
+ Intent intent;
813
+ PluginResult result;
814
+ try {
815
+ String contact_number = args.getJSONObject(0).optString("contact_number");
816
+ if(contact_number != null ) {
817
+ if(!contact_number.equals("") ) {
818
+ if(validateMobileNumber(contact_number)){
819
+
820
+ intent = new Intent(Intent.ACTION_DIAL);
821
+ intent.setData(Uri.parse("tel:" + contact_number));
822
+ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
823
+ cordova.getActivity().getApplicationContext().startActivity(intent);
824
+ }else{
825
+ result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_INVALID");
826
+ callback.sendPluginResult(result);
827
+ }
828
+ }else{
829
+ result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_NOT_AVAILABLE");
830
+ callback.sendPluginResult(result);
831
+ }
832
+ }else{
833
+ result = new PluginResult(PluginResult.Status.ERROR, "MOBILE_NOT_AVAILABLE");
834
+ callback.sendPluginResult(result);
835
+ }
836
+
837
+ return true;
838
+ } catch (Exception exception) {
839
+ System.out.println(exception.getMessage());
840
+ result = new PluginResult(PluginResult.Status.ERROR, exception.getMessage());
841
+ callback.sendPluginResult(result);
842
+ }
843
+ }else if (action.equals("OpenEmail")) {
844
+ PluginResult result;
845
+ String toEmail, ccEmail, subject, body, mailto;
846
+ try{
847
+ toEmail = args.getJSONObject(0).optString("toEmail");
848
+ ccEmail = args.getJSONObject(0).optString("ccEmail");
849
+ subject = args.getJSONObject(0).optString("subject");
850
+ body = args.getJSONObject(0).optString("body");
851
+ if(toEmail != null ) {
852
+ if(!toEmail.equals("") ) {
853
+ if(Patterns.EMAIL_ADDRESS.matcher(toEmail).matches()){
854
+ mailto = "mailto:" + toEmail +
855
+ "?cc=" + ccEmail +
856
+ "&subject=" + Uri.encode(subject) +
857
+ "&body=" + Uri.encode(body);
858
+ Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
859
+ emailIntent.setData(Uri.parse(mailto));
860
+ emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
861
+ cordova.getActivity().getApplicationContext().startActivity(emailIntent);
862
+ }else{
863
+ result = new PluginResult(PluginResult.Status.ERROR, "EMAIL_INVALID");
864
+ callback.sendPluginResult(result);
865
+ }
866
+ }else{
867
+ result = new PluginResult(PluginResult.Status.ERROR, "EMAIL_NOT_AVAILABLE");
868
+ callback.sendPluginResult(result);
869
+ }
870
+ }else{
871
+ result = new PluginResult(PluginResult.Status.ERROR, "EMAIL_NOT_AVAILABLE");
872
+ callback.sendPluginResult(result);
873
+ }
874
+ } catch (Exception e) {
875
+ e.printStackTrace();
876
+ result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
877
+ callback.sendPluginResult(result);
878
+ }
879
+
880
+ }
881
+ return true;
882
+ }
883
+
884
+ private boolean validateMobileNumber(String mobileNo) {
885
+ String regex;
886
+ boolean result = false;
887
+ try {
888
+ regex = "^\\+?\\d[\\d ]+$";
889
+ if (mobileNo.matches(regex)) {
890
+ result = true;
891
+ }
892
+ } catch (Exception e) {
893
+ e.printStackTrace();
894
+ }
895
+ return result;
896
+ }
897
+
898
+ public static boolean isTimeAutomatic(Context c) {
899
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
900
+ return Settings.Global.getInt(c.getContentResolver(), Settings.Global.AUTO_TIME, 0) == 1;
901
+ } else {
902
+ return android.provider.Settings.System.getInt(c.getContentResolver(), android.provider.Settings.System.AUTO_TIME, 0) == 1;
903
+ }
904
+ }
905
+
906
+ public void createLocationRequest1() {
907
+ mLocationRequest1 = new LocationRequest();
908
+ mLocationRequest1.setInterval(INTERVAL);
909
+ mLocationRequest1.setFastestInterval(FASTEST_INTERVAL);
910
+ mLocationRequest1.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
911
+ }
912
+
913
+ protected void startLocationUpdates1() {
914
+ Context context1 = cordova.getActivity().getApplicationContext();
915
+ if (ActivityCompat.checkSelfPermission(context1, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
916
+ //ActivityCompat.requestPermissions(cordova.getActivity(), new String[]{Manifest.permission.READ_PHONE_STATE}, 5);
917
+ }
918
+ PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient1, mLocationRequest1, this);
919
+ }
920
+
921
+ public void scanQRCode(CallbackContext callbackContext) {
922
+ callback = callbackContext;
923
+ SCANCODEINT = 118;
924
+ IntentIntegrator integrator = new IntentIntegrator(this.cordova.getActivity());
925
+ integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
926
+ integrator.setPrompt("Scan");
927
+ integrator.setCameraId(0);
928
+ integrator.setBeepEnabled(true);
929
+ integrator.setBarcodeImageEnabled(true);
930
+ integrator.initiateScan();
931
+ cordova.setActivityResultCallback(this);
932
+ PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
933
+ pluginResult.setKeepCallback(true);
934
+ callbackContext.sendPluginResult(pluginResult);
935
+ }
936
+
937
+ public void scanBarCode(CallbackContext callbackContext) {
938
+ callback = callbackContext;
939
+ SCANCODEINT = 119;
940
+ IntentIntegrator integrator = new IntentIntegrator(this.cordova.getActivity());
941
+ integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
942
+ integrator.setPrompt("Scan");
943
+ integrator.setCameraId(0);
944
+ integrator.setBeepEnabled(true);
945
+ integrator.setBarcodeImageEnabled(true);
946
+ integrator.initiateScan();
947
+ cordova.setActivityResultCallback(this);
948
+ PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
949
+ pluginResult.setKeepCallback(true);
950
+ callbackContext.sendPluginResult(pluginResult);
951
+ }
952
+
953
+ private void getStorageRoot(CallbackContext callbackContext) {
954
+ callbackContext.success("file://" + mInterfaceUtil.rootDirectory + "/");
955
+ }
956
+
957
+ private void checkLocationPermission(JSONArray args, CallbackContext callbackContext) {
958
+ boolean permissionGranted = true;
959
+ List<String> list;
960
+ try {
961
+ callback = callbackContext;
962
+ Context context = cordova.getActivity().getApplicationContext();
963
+ if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
964
+ String[] permissions = args.optJSONObject(0).optString("permissions").split(",");
965
+ list = new ArrayList<String>(Arrays.asList(permissions));
966
+ permissions = list.toArray(new String[0]);
967
+
968
+ for (int i = 0; i < permissions.length; i++) {
969
+ if (ActivityCompat.checkSelfPermission(context, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
970
+ permissionGranted = false;
971
+ }
972
+ };
973
+ if (!permissionGranted) {
974
+ callback.error("failure");
975
+ } else {
976
+ callback.success("success");
977
+ }
978
+ } else {
979
+ callback.success("success");
980
+ }
981
+ } catch (Exception e) {
982
+ e.printStackTrace();
983
+ }
984
+ }
985
+ private void getLocationPermission(JSONArray args, CallbackContext callbackContext) {
986
+ boolean permissionGranted = true;
987
+ List<String> list;
988
+ try {
989
+ callback = callbackContext;
990
+ Context context = cordova.getActivity().getApplicationContext();
991
+ if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
992
+ String[] permissions = args.optJSONObject(0).optString("permissions").split(",");
993
+ list = new ArrayList<String>(Arrays.asList(permissions));
994
+ permissions = list.toArray(new String[0]);
995
+
996
+ for (int i = 0; i < permissions.length; i++) {
997
+ if (ActivityCompat.checkSelfPermission(context, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
998
+ permissionGranted = false;
999
+ }
1000
+ };
1001
+ if (!permissionGranted) {
1002
+ PermissionHelper.requestPermissions(this, 111, permissions);
1003
+ } else {
1004
+ callback.success("success");
1005
+ }
1006
+ } else {
1007
+ callback.success("success");
1008
+ }
1009
+ } catch (Exception e) {
1010
+ e.printStackTrace();
1011
+ }
1012
+ }
1013
+ private void getPermissions(JSONArray args, CallbackContext callbackContext) {
1014
+ boolean permissionGranted = true;
1015
+ List<String> list;
1016
+ try {
1017
+ callback = callbackContext;
1018
+ Context context = cordova.getActivity().getApplicationContext();
1019
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1020
+ String[] permissions = args.optJSONObject(0).optString("permissions").split(",");
1021
+ if (Build.VERSION.SDK_INT != Build.VERSION_CODES.Q) {
1022
+ list = new ArrayList<String>(Arrays.asList(permissions));
1023
+ list.remove("android.permission.ACCESS_BACKGROUND_LOCATION");
1024
+ permissions = list.toArray(new String[0]);
1025
+ };
1026
+ for (int i = 0; i < permissions.length; i++) {
1027
+ if (ActivityCompat.checkSelfPermission(context, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
1028
+ permissionGranted = false;
1029
+ }
1030
+ };
1031
+ if (!permissionGranted) {
1032
+ PermissionHelper.requestPermissions(this, 1, permissions);
1033
+ } else {
1034
+ callback.success("success");
1035
+ }
1036
+ } else {
1037
+ callback.success("success");
1038
+ }
1039
+ } catch (Exception e) {
1040
+ e.printStackTrace();
1041
+ }
1042
+ }
1043
+ public void captureImageLiveCamera(CallbackContext callbackContext) {
1044
+ callback = callbackContext;
1045
+ Context context = cordova.getActivity().getApplicationContext();
1046
+ Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
1047
+ File photoFile = null;
1048
+ try {
1049
+ photoFile = createImageFile();
1050
+ } catch (IOException ex) {
1051
+ callback.error("there is error in create image");
1052
+ }
1053
+ //Continue only if the File was successfully created
1054
+ if (photoFile != null) {
1055
+ Uri photoURISample;
1056
+ if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
1057
+ photoURISample = Uri.fromFile(photoFile);
1058
+ } else {
1059
+ photoURISample = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", photoFile);
1060
+ }
1061
+ takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURISample);
1062
+ cordova.startActivityForResult(this, takePictureIntent, REQUEST_LIVE_IMAGE_CAPTURE);
1063
+ PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
1064
+ pluginResult.setKeepCallback(true);
1065
+ callbackContext.sendPluginResult(pluginResult);
1066
+ }
1067
+ }
1068
+
1069
+ public void captureImage(CallbackContext callbackContext) {
1070
+ callback = callbackContext;
1071
+ Context context = cordova.getActivity().getApplicationContext();
1072
+ Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
1073
+ File photoFile = null;
1074
+ try {
1075
+ photoFile = createImageFile();
1076
+ } catch (IOException ex) {
1077
+ callback.error("there is error in create image");
1078
+ }
1079
+ // Continue only if the File was successfully created
1080
+ if (photoFile != null) {
1081
+ Uri photoURISample;
1082
+ if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
1083
+ photoURISample = Uri.fromFile(photoFile);
1084
+ } else {
1085
+ photoURISample = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", photoFile);
1086
+ }
1087
+ takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURISample);
1088
+ cordova.startActivityForResult(this, takePictureIntent, REQUEST_IMAGE_CAPTURE);
1089
+ PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
1090
+ pluginResult.setKeepCallback(true);
1091
+ callbackContext.sendPluginResult(pluginResult);
1092
+ }
1093
+ }
1094
+
1095
+ public void pickImageFromGallery(CallbackContext callbackContext) {
1096
+ Intent openFile,
1097
+ selectFile;
1098
+ PluginResult pluginResult;
1099
+ callback = callbackContext;
1100
+ if (Build.MANUFACTURER.equals("samsung")) {
1101
+ /* SELECT FILE FOR SAMSUNG DEVICES */
1102
+ openFile = new Intent("com.sec.android.app.myfiles.PICK_DATA");
1103
+ openFile.putExtra("CONTENT_TYPE", "*/*");
1104
+ } else {
1105
+ /* SELECT FILE FOR EXCEPT SAMSUNG DEVICES */
1106
+ openFile = new Intent(Intent.ACTION_GET_CONTENT);
1107
+ openFile.setType("*/*");
1108
+ openFile.addCategory(Intent.CATEGORY_OPENABLE);
1109
+ openFile.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
1110
+ }
1111
+ selectFile = Intent.createChooser(openFile, "Select File");
1112
+ cordova.startActivityForResult(this, selectFile, PICK_IMAGE_FROM_GALLERY);
1113
+ pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
1114
+ pluginResult.setKeepCallback(true);
1115
+ callbackContext.sendPluginResult(pluginResult);
1116
+ }
1117
+
1118
+ private static String getMimeType(String path) {
1119
+ String mimeType = null;
1120
+ String extension = MimeTypeMap.getFileExtensionFromUrl(path);
1121
+ if (extension != null) {
1122
+ MimeTypeMap mime = MimeTypeMap.getSingleton();
1123
+ mimeType = mime.getMimeTypeFromExtension(extension.toLowerCase());
1124
+ }
1125
+ return mimeType;
1126
+ }
1127
+
1128
+ private File createImageFile() throws IOException {
1129
+ String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
1130
+ String imageFileName = "JPEG_" + timeStamp + "_";
1131
+ String filePath = mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/images";
1132
+ File storageDir = new File(filePath);
1133
+ if (!storageDir.exists()) {
1134
+ storageDir.mkdirs();
1135
+ }
1136
+ File image = File.createTempFile(imageFileName, /* prefix */".jpg", /* suffix */storageDir /* directory */);
1137
+ pictureFilePath = image.getAbsolutePath();
1138
+ return image;
1139
+ }
1140
+
1141
+ public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
1142
+ final int height = options.outHeight;
1143
+ final int width = options.outWidth;
1144
+ int inSampleSize = 1;
1145
+ if (height > reqHeight || width > reqWidth) {
1146
+ final int heightRatio = Math.round((float) height / (float) reqHeight);
1147
+ final int widthRatio = Math.round((float) width / (float) reqWidth);
1148
+ inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
1149
+ }
1150
+ final float totalPixels = width * height;
1151
+ final float totalReqPixelsCap = reqWidth * reqHeight * 2;
1152
+ while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
1153
+ inSampleSize++;
1154
+ }
1155
+ return inSampleSize;
1156
+ }
1157
+
1158
+ public void convertImageTo64BaseString(CallbackContext callbackContext, String imageSourcePath, String imgSrcType, String destinationPath) {
1159
+ String compressedImagePathStr = "";
1160
+ String compressedImageName = "";
1161
+ String filePath = imageSourcePath;
1162
+ Bitmap scaledBitmap = null;
1163
+ BitmapFactory.Options options = new BitmapFactory.Options();
1164
+ //by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
1165
+ //you try the use the bitmap here, you will get null.
1166
+ options.inJustDecodeBounds = true;
1167
+ String[] bits = imageSourcePath.split("/");
1168
+
1169
+ String fileNameToSend = bits[bits.length-1];
1170
+ if (fileNameToSend.indexOf(".") > 0)
1171
+ fileNameToSend = fileNameToSend.substring(0, fileNameToSend.lastIndexOf("."));
1172
+ Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
1173
+ int actualHeight = options.outHeight;
1174
+ int actualWidth = options.outWidth;
1175
+ //max Height and width values of the compressed image is taken as 816x612
1176
+ float maxHeight = 816.0f;
1177
+ float maxWidth = 612.0f;
1178
+ float imgRatio = actualWidth / actualHeight;
1179
+ float maxRatio = maxWidth / maxHeight;
1180
+ //width and height values are set maintaining the aspect ratio of the image
1181
+ if (actualHeight > maxHeight || actualWidth > maxWidth) {
1182
+ if (imgRatio < maxRatio) {
1183
+ imgRatio = maxHeight / actualHeight;
1184
+ actualWidth = (int) (imgRatio * actualWidth);
1185
+ actualHeight = (int) maxHeight;
1186
+ } else if (imgRatio > maxRatio) {
1187
+ imgRatio = maxWidth / actualWidth;
1188
+ actualHeight = (int) (imgRatio * actualHeight);
1189
+ actualWidth = (int) maxWidth;
1190
+ } else {
1191
+ actualHeight = (int) maxHeight;
1192
+ actualWidth = (int) maxWidth;
1193
+ }
1194
+ }
1195
+ options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
1196
+ options.inJustDecodeBounds = false;
1197
+ //this options allow android to claim the bitmap memory if it runs low on memory
1198
+ options.inPurgeable = true;
1199
+ options.inInputShareable = true;
1200
+ options.inTempStorage = new byte[16 * 1024];
1201
+ try {
1202
+ //load the bitmap from its path
1203
+ bmp = BitmapFactory.decodeFile(filePath, options);
1204
+ } catch (OutOfMemoryError exception) {
1205
+ exception.printStackTrace();
1206
+ }
1207
+ try {
1208
+ scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
1209
+ } catch (OutOfMemoryError exception) {
1210
+ exception.printStackTrace();
1211
+ }
1212
+ float ratioX = actualWidth / (float) options.outWidth;
1213
+ float ratioY = actualHeight / (float) options.outHeight;
1214
+ float middleX = actualWidth / 2.0f;
1215
+ float middleY = actualHeight / 2.0f;
1216
+ Matrix scaleMatrix = new Matrix();
1217
+ scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
1218
+ Canvas canvas = new Canvas(scaledBitmap);
1219
+ canvas.setMatrix(scaleMatrix);
1220
+ canvas.drawBitmap(bmp, middleX - bmp.getWidth()/2, middleY - bmp.getHeight()/2, new Paint(Paint.FILTER_BITMAP_FLAG));
1221
+ //check the rotation of the image and display it properly
1222
+ ExifInterface exif;
1223
+ try {
1224
+ exif = new ExifInterface(filePath);
1225
+ int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
1226
+ Log.d("EXIF", "Exif: " + orientation);
1227
+ Matrix matrix = new Matrix();
1228
+ if (orientation == 6) {
1229
+ matrix.postRotate(90);
1230
+ Log.d("EXIF", "Exif: " + orientation);
1231
+ } else if (orientation == 3) {
1232
+ matrix.postRotate(180);
1233
+ Log.d("EXIF", "Exif: " + orientation);
1234
+ } else if (orientation == 8) {
1235
+ matrix.postRotate(270);
1236
+ Log.d("EXIF", "Exif: " + orientation);
1237
+ }
1238
+ scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
1239
+ } catch (IOException e) {
1240
+ e.printStackTrace();
1241
+ }
1242
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
1243
+ try {
1244
+ if(imgSrcType.equals("compress")) {
1245
+ String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
1246
+ if(!destinationPath.equalsIgnoreCase("")){
1247
+ compressedImagePathStr = mInterfaceUtil.rootDirectory + "/" + destinationPath;
1248
+ }else{
1249
+ compressedImagePathStr = mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/" + "images";
1250
+ }
1251
+ compressedImageName = compressedImagePathStr + "/" + fileNameToSend + "_" + timeStamp + ".jpg";
1252
+ File fileSavedPath = new File(compressedImagePathStr);
1253
+ if (!fileSavedPath.exists()) {
1254
+ fileSavedPath.mkdirs();
1255
+ }
1256
+ FileOutputStream out = new FileOutputStream(compressedImageName);
1257
+ scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, out);
1258
+ } else {
1259
+ scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);
1260
+ }
1261
+ String encodedImage = null;
1262
+ byte[] byteArray;
1263
+ try {
1264
+ byteArray = baos.toByteArray();
1265
+ encodedImage = Base64.encodeToString(byteArray, Base64.NO_WRAP);
1266
+ imgSrcType = imgSrcType;
1267
+ if (imgSrcType.equals("camera")) {
1268
+ File file = new File(imageSourcePath);
1269
+ if (file.exists()) {
1270
+ file.delete();
1271
+ }
1272
+ attachmentDestPath = "";
1273
+ callbackContext.success(encodedImage);
1274
+ } else if (imgSrcType.equals("gallery")) {
1275
+ attachmentDestPath = "";
1276
+ callbackContext.success(encodedImage);
1277
+ } else if (imgSrcType.equals("compress")) {
1278
+ try {
1279
+ if(!destinationPath.equalsIgnoreCase("")){
1280
+ File file = new File(imageSourcePath);
1281
+ if (file.exists()) {
1282
+ file.delete();
1283
+ }
1284
+ }
1285
+ JSONObject fileProperities = null;
1286
+ String imgFilePath, fileName, fileExtension = "";
1287
+ imgFilePath = compressedImageName.substring(0, compressedImageName.lastIndexOf("/"));
1288
+ String[] fileName1 = compressedImageName.split("/");
1289
+ fileName = fileName1[fileName1.length - 1];
1290
+ File file = new File(compressedImageName);
1291
+ long fileSize = file.length();
1292
+ fileExtension = "." + compressedImageName.substring(compressedImageName.lastIndexOf(".") + 1).toLowerCase();
1293
+ fileProperities = new JSONObject();
1294
+ fileProperities.put("filePath", imgFilePath);
1295
+ fileProperities.put("fileName", fileName);
1296
+ fileProperities.put("fileSize", fileSize);
1297
+ fileProperities.put("fileExtension", fileExtension);
1298
+ fileProperities.put("thumbnail", getFileThumbnail(imgFilePath+ "/" +fileName, fileExtension));
1299
+ attachmentDestPath = "";
1300
+ callback.success(fileProperities);
1301
+ } catch (Exception e) {
1302
+ attachmentDestPath = "";
1303
+ callback.error(e.getMessage());
1304
+ }
1305
+ }
1306
+ } catch (Exception e) {
1307
+ attachmentDestPath = "";
1308
+ callbackContext.error(e.getMessage());
1309
+ }
1310
+ } catch (Exception e) {
1311
+ e.printStackTrace();
1312
+ }
1313
+ }
1314
+
1315
+ public String getBase64String(String imageSourcePath) {
1316
+ String resultString="";
1317
+ String filePath = mInterfaceUtil.rootDirectory + "/" + imageSourcePath;
1318
+ File image = new File(filePath);
1319
+ BitmapFactory.Options bmOptions = new BitmapFactory.Options();
1320
+ Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
1321
+ try {
1322
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1323
+ bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
1324
+ resultString = Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP);
1325
+ } catch (Exception e) {
1326
+ e.printStackTrace();
1327
+ }
1328
+ return resultString;
1329
+ }
1330
+
1331
+ public void chooseFile(CallbackContext callbackContext) {
1332
+ try {
1333
+ PluginResult pluginResult;
1334
+ callback = callbackContext;
1335
+ cordova.startActivityForResult(this, getPickImageChooserIntent(), NEW_FILE_PICK_REQUEST);
1336
+ pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
1337
+ pluginResult.setKeepCallback(true);
1338
+ callbackContext.sendPluginResult(pluginResult);
1339
+ } catch (Exception e) {
1340
+ callbackContext.error(e.getMessage());
1341
+ }
1342
+ }
1343
+ public Intent getPickImageChooserIntent() {
1344
+ Intent openFile, selectFile;
1345
+ if (Build.MANUFACTURER.equals("samsung")) {
1346
+ openFile = new Intent("com.sec.android.app.myfiles.PICK_DATA");
1347
+ openFile.putExtra("CONTENT_TYPE", "*/*");
1348
+ } else {
1349
+ openFile = new Intent(Intent.ACTION_GET_CONTENT);
1350
+ openFile.setType("*/*");
1351
+ openFile.addCategory(Intent.CATEGORY_OPENABLE);
1352
+ openFile.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
1353
+ }
1354
+ selectFile = Intent.createChooser(openFile, "Select File");
1355
+ return selectFile;
1356
+ }
1357
+ //App version plugin
1358
+ public void appVersion(CallbackContext callbackContext) {
1359
+ try {
1360
+ PackageManager packageManager = this.cordova.getActivity().getPackageManager();
1361
+ JSONObject r = new JSONObject();
1362
+ try {
1363
+ r.put("version", packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionName);
1364
+ r.put("build", packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionCode);
1365
+ } catch (JSONException e) {
1366
+ e.printStackTrace();
1367
+ }
1368
+ callbackContext.success(r);
1369
+ } catch (PackageManager.NameNotFoundException e) {
1370
+ callbackContext.error("Exception thrown");
1371
+ }
1372
+ }
1373
+
1374
+ //Rotate Screen plugin
1375
+ public void rotateScreen(JSONArray args, CallbackContext callbackContext) {
1376
+ String orientation = args.optString(0);
1377
+ Activity activity = cordova.getActivity();
1378
+ if (orientation.equals(ANY)) {
1379
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1380
+ } else if (orientation.equals(LANDSCAPE_PRIMARY)) {
1381
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
1382
+ } else if (orientation.equals(PORTRAIT_PRIMARY)) {
1383
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
1384
+ } else if (orientation.equals(LANDSCAPE)) {
1385
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
1386
+ } else if (orientation.equals(PORTRAIT)) {
1387
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
1388
+ } else if (orientation.equals(LANDSCAPE_SECONDARY)) {
1389
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
1390
+ } else if (orientation.equals(PORTRAIT_SECONDARY)) {
1391
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
1392
+ }
1393
+ callbackContext.success();
1394
+ }
1395
+
1396
+ public void deviceInfo(CallbackContext callbackContext) throws JSONException {
1397
+ String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
1398
+ JSONObject r = new JSONObject();
1399
+ boolean a = android.os.Build.FINGERPRINT.contains("generic") ||
1400
+ android.os.Build.PRODUCT.contains("sdk");
1401
+ @SuppressWarnings("deprecation")
1402
+ String sdkversion = android.os.Build.VERSION.SDK;
1403
+ r.put("uuid", uuid);
1404
+ r.put("version", android.os.Build.VERSION.RELEASE);
1405
+ r.put("platform", ANDROID_PLATFORM);
1406
+ r.put("model", android.os.Build.MODEL);
1407
+ r.put("manufacturer", android.os.Build.MANUFACTURER);
1408
+ r.put("isVirtual", a);
1409
+ r.put("serial", android.os.Build.SERIAL);
1410
+ r.put("timeZone", TimeZone.getDefault());
1411
+ r.put("sdkVersion", sdkversion);
1412
+ r.put("productName", android.os.Build.PRODUCT);
1413
+ callbackContext.success(r);
1414
+ }
1415
+
1416
+ @Override
1417
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {
1418
+ switch (requestCode) {
1419
+ case LOCATION_ACCURACY_REQUEST_NEW:
1420
+ switch (resultCode) {
1421
+ case Activity.RESULT_OK:
1422
+ callback.success();
1423
+ break;
1424
+ case Activity.RESULT_CANCELED:
1425
+ callback.error("oops! you have cancelled...");
1426
+ break;
1427
+ }
1428
+ break;
1429
+ }
1430
+ if (SCANCODEINT == 118 && callback != null) {
1431
+ if (resultCode == RESULT_OK) {
1432
+ SCANCODEINT = 0;
1433
+ IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
1434
+ callback.success(result.getContents());
1435
+ } else if (resultCode == Activity.RESULT_CANCELED) {
1436
+ SCANCODEINT = 0;
1437
+ callback.error("canceled");
1438
+ } else {
1439
+ SCANCODEINT = 0;
1440
+ callback.error(resultCode);
1441
+ }
1442
+ } else if (SCANCODEINT == 119 && callback != null) {
1443
+ if (resultCode == RESULT_OK) {
1444
+ SCANCODEINT = 0;
1445
+ IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
1446
+ callback.success(result.getContents());
1447
+ } else if (resultCode == Activity.RESULT_CANCELED) {
1448
+ SCANCODEINT = 0;
1449
+ callback.error("canceled");
1450
+ } else {
1451
+ SCANCODEINT = 0;
1452
+ callback.error(resultCode);
1453
+ }
1454
+ } else if (requestCode == PICK_IMAGE_FROM_GALLERY && callback != null) {
1455
+ if (resultCode == RESULT_OK) {
1456
+ String fileName = null, getfilePath = null, filePath = null, fileType, storageDefinition, fileExtension;
1457
+ final String docId, type, id;
1458
+ final String[] split;
1459
+ final String tag, path;
1460
+ final int splitIndex;
1461
+ Cursor cursor;
1462
+ Uri uri = data.getData(); //get uri for selected file
1463
+ fileType = this.cordova.getActivity().getContentResolver().getType(uri); // get mimeType for selected file
1464
+ File getFileName, file;
1465
+ try {
1466
+ //API LEVEL 19 AND ABOVE (TO GET FILEPATH)
1467
+ if (Build.VERSION.SDK_INT >= 19 && !Build.MANUFACTURER.equals("samsung") && DocumentsContract.isDocumentUri(cordova.getActivity(), uri)) {
1468
+ if ("com.android.externalstorage.documents".equals(uri.getAuthority())) { // ExternalStorageProvider
1469
+ docId = DocumentsContract.getDocumentId(uri);
1470
+ split = docId.split(":");
1471
+ type = split[0];
1472
+ if ("primary".equalsIgnoreCase(type)) {
1473
+ getfilePath = mInterfaceUtil.rootDirectory + "/" + split[1];
1474
+ } else {
1475
+ if (Environment.isExternalStorageRemovable()) {
1476
+ storageDefinition = System.getenv("EXTERNAL_STORAGE");
1477
+ getfilePath = storageDefinition;
1478
+ } else {
1479
+ splitIndex = docId.indexOf(':', 1);
1480
+ tag = docId.substring(0, splitIndex);
1481
+ path = docId.substring(splitIndex + 1);
1482
+ if (new mInterfaceUtil().getPathToNonPrimaryVolume(cordova.getActivity(), tag) != null) {
1483
+ storageDefinition = new mInterfaceUtil().getPathToNonPrimaryVolume(cordova.getActivity(), tag) + "/" + path;
1484
+ file = new File(storageDefinition);
1485
+ if (file.exists() && file.canRead()) {
1486
+ getfilePath = storageDefinition;
1487
+ }
1488
+ }
1489
+ }
1490
+ }
1491
+ } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { // DownloadsProvider
1492
+ id = DocumentsContract.getDocumentId(uri);
1493
+ final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
1494
+ getfilePath = new mInterfaceUtil().getDataColumn(cordova.getActivity(), contentUri, null, null);
1495
+ } else if ("com.android.providers.media.documents".equals(uri.getAuthority())) { // MediaProvider
1496
+ docId = DocumentsContract.getDocumentId(uri);
1497
+ split = docId.split(":");
1498
+ type = split[0];
1499
+ Uri contentUri = null;
1500
+ if ("image".equals(type)) {
1501
+ contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
1502
+ } else if ("video".equals(type)) {
1503
+ contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
1504
+ } else if ("audio".equals(type)) {
1505
+ contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
1506
+ }
1507
+ final String selection = "_id=?";
1508
+ final String[] selectionArgs = new String[]{
1509
+ split[1]
1510
+ };
1511
+ getfilePath = new mInterfaceUtil().getDataColumn(cordova.getActivity(), contentUri, selection, selectionArgs);
1512
+ }
1513
+ // *** API Level 19 and Above (To Get FileName,FileExtension and FileSize)**** //
1514
+ cursor = cordova.getActivity().getContentResolver().query(uri, null, null, null, null, null);
1515
+ try {
1516
+ if (cursor != null && cursor.moveToFirst()) {
1517
+ fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
1518
+ }
1519
+ } finally {
1520
+ cursor.close();
1521
+ }
1522
+ // *** API Level 19 below and SAMSUNG (To Get FileProperties of MediaFiles)**** //
1523
+ } else {
1524
+ if (fileType != null) {
1525
+ String[] projection = {
1526
+ MediaStore.Images.Media.DATA,
1527
+ MediaStore.Images.Media.SIZE,
1528
+ MediaStore.Images.Media.DISPLAY_NAME
1529
+ };
1530
+ cursor = cordova.getActivity().getContentResolver().query(uri, projection, null, null, null);
1531
+ if (cursor.moveToFirst()) {
1532
+ getfilePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
1533
+ fileName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));
1534
+ }
1535
+ cursor.close();
1536
+ // API LEVEL 19 BELOW AND SAMSUNG (TO GET FILEPROPERTIES OF NORMAL FILES(EX:txt,.pdf,etc..,))
1537
+ } else {
1538
+ getfilePath = data.getData().getPath();
1539
+ filePath = getfilePath.substring(0, getfilePath.lastIndexOf(File.separator));
1540
+ getFileName = new File(getfilePath);
1541
+ fileName = getFileName.getName();
1542
+ }
1543
+ }
1544
+ filePath = getfilePath.substring(0, getfilePath.lastIndexOf(File.separator));
1545
+ fileExtension = "." + getfilePath.substring(getfilePath.lastIndexOf(".") + 1).toLowerCase();
1546
+ if (filePath != null) {
1547
+ try {
1548
+ if (fileExtension.equals(".heic")) {
1549
+ if(galleryAttachmentInd.equals("true")){
1550
+ convertImageTo64BaseString(callback, filePath + "/" + fileName, "compress",attachmentDestPath);
1551
+ }else{
1552
+ convertImageTo64BaseString(callback, filePath + "/" + fileName, "gallery","");
1553
+ }
1554
+
1555
+ } else if (fileExtension.equals(".jpeg") || fileExtension.equals(".jpg") || fileExtension.equals(".png")) {
1556
+ if(galleryAttachmentInd.equals("true")){
1557
+ convertImageTo64BaseString(callback, filePath + "/" + fileName, "compress",attachmentDestPath);
1558
+ }else{
1559
+ convertImageTo64BaseString(callback, filePath + "/" + fileName, "gallery","");
1560
+ }
1561
+ } else {
1562
+ callback.error("Only JPEG or PNG file extensions are allowed to attach.");
1563
+ }
1564
+ } catch (Exception e) {
1565
+ callback.error("Only JPEG or PNG file extensions are allowed to attach.");
1566
+ }
1567
+ } else {
1568
+ callback.error("File path was null");
1569
+ }
1570
+ } catch (Exception e) {
1571
+ e.printStackTrace();
1572
+ }
1573
+ } else if (resultCode == Activity.RESULT_CANCELED) {
1574
+ callback.error("failure");
1575
+ } else {
1576
+ callback.error(resultCode);
1577
+ }
1578
+ } else if(requestCode == NEW_FILE_PICK_REQUEST && callback != null) {
1579
+ try {
1580
+ Uri uri = data.getData();
1581
+ String fileName = null, extension = null, filePath = null;
1582
+ JSONObject fileProperities = null;
1583
+ Cursor cursor = null;
1584
+ if (uri.getScheme().equals("file")) {
1585
+ fileName = uri.getLastPathSegment();
1586
+
1587
+ if (fileName.indexOf(".") > 0){
1588
+ fileName = fileName.substring(0, fileName.lastIndexOf("."));
1589
+ String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
1590
+ extension = "." + fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
1591
+ fileName = fileName + "_" + timeStamp + extension;
1592
+ }
1593
+ } else {
1594
+ try {
1595
+ cursor = cordova.getActivity().getApplicationContext().getContentResolver().query(uri, new String[]{ MediaStore.Images.ImageColumns.DISPLAY_NAME }, null, null, null);
1596
+ if (cursor != null && cursor.moveToFirst()) {
1597
+ fileName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
1598
+ extension = "." + fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
1599
+ if (!extension.equals(".jpeg") && !extension.equals(".jpg") && !extension.equals(".png")) {
1600
+ String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
1601
+ fileName = fileName.substring(0, fileName.lastIndexOf("."));
1602
+ fileName = fileName + "_" + timeStamp + extension;
1603
+ }
1604
+
1605
+ }
1606
+ } finally {
1607
+ if (cursor != null) {
1608
+ cursor.close();
1609
+ }
1610
+ }
1611
+ }
1612
+
1613
+ extension = "." + fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
1614
+
1615
+ filePath = copyFileFromUri(cordova.getActivity().getApplicationContext(), uri, fileName, attachmentDestPath,callback);
1616
+ File file = new File(filePath);
1617
+ String mimeType = getMimeType(filePath);
1618
+ System.out.println("Mime type is: " + mimeType);
1619
+ double fileSize = file.length();
1620
+ if (filePath != null) {
1621
+ try {
1622
+ if(requestCode == NEW_FILE_PICK_REQUEST) {
1623
+ if(extension.equals(".heic")) {
1624
+ convertImageTo64BaseString(callback, filePath, "compress",attachmentDestPath);
1625
+ } else if (mimeType != null) {
1626
+ if (mimeType.contains("image")) {
1627
+ convertImageTo64BaseString(callback, filePath, "compress",attachmentDestPath);
1628
+ } else {
1629
+ fileProperities = new JSONObject();
1630
+ fileProperities.put("filePath", filePath.substring(0, filePath.lastIndexOf(File.separator)));
1631
+ fileProperities.put("fileName", fileName);
1632
+ fileProperities.put("fileSize", fileSize);
1633
+ fileProperities.put("fileExtension", extension);
1634
+ fileProperities.put("thumbnail", getFileThumbnail(filePath, extension));
1635
+ attachmentDestPath = "";
1636
+ callback.success(fileProperities);
1637
+ }
1638
+ } else {
1639
+ fileProperities = new JSONObject();
1640
+ fileProperities.put("filePath", filePath.substring(0, filePath.lastIndexOf(File.separator)));
1641
+ fileProperities.put("fileName", fileName);
1642
+ fileProperities.put("fileSize", fileSize);
1643
+ fileProperities.put("fileExtension", extension);
1644
+ fileProperities.put("thumbnail", getFileThumbnail(filePath, extension));
1645
+ callback.success(fileProperities);
1646
+ }
1647
+ }
1648
+ } catch (Exception e) {
1649
+ callback.error(e.getMessage());
1650
+ }
1651
+ } else {
1652
+ callback.error("Selected file path is null");
1653
+ }
1654
+ } catch (Exception e) {
1655
+ callback.error(e.getMessage());
1656
+ }
1657
+ } else if (requestCode == REQUEST_IMAGE_CAPTURE && callback != null) {
1658
+ if (resultCode == RESULT_OK) {
1659
+ if(cameraAttachmentInd.equals("true")){
1660
+ convertImageTo64BaseString(callback, pictureFilePath, "compress", attachmentDestPath);
1661
+ }else{
1662
+ convertImageTo64BaseString(callback, pictureFilePath, "camera","");
1663
+ }
1664
+
1665
+ } else if (resultCode == Activity.RESULT_CANCELED) {
1666
+ // TODO NO_RESULT or error callback?
1667
+ File file = new File(pictureFilePath);
1668
+ if (file.exists()) {
1669
+ file.delete();
1670
+ }
1671
+ callback.error("failure");
1672
+ } else {
1673
+ callback.error(resultCode);
1674
+ }
1675
+ } else if (requestCode == REQUEST_LIVE_IMAGE_CAPTURE && callback != null) {
1676
+ if (resultCode == RESULT_OK) {
1677
+ convertImageTo64BaseString(callback, pictureFilePath, "compress",attachmentDestPath);
1678
+ } else if (resultCode == Activity.RESULT_CANCELED) {
1679
+ // TODO NO_RESULT or error callback?
1680
+ File file = new File(pictureFilePath);
1681
+ if (file.exists()) {
1682
+ file.delete();
1683
+ }
1684
+ callback.error("failure");
1685
+ } else {
1686
+ callback.error(resultCode);
1687
+ }
1688
+ } else if (requestCode == PICK_FILE_REQUEST && callback != null) {
1689
+ if (resultCode == RESULT_OK) {
1690
+ String fileName = null,
1691
+ getfilePath = null,
1692
+ filePath = null,
1693
+ fileExtension,
1694
+ fileType,
1695
+ fileSize = null,
1696
+ storageDefinition;
1697
+ ;
1698
+ final String docId,
1699
+ type,
1700
+ id;
1701
+ final String[] split;
1702
+ final String tag,
1703
+ path;
1704
+ final int splitIndex;
1705
+ Cursor cursor;
1706
+ long getSize;
1707
+ JSONObject fileProperities = null;
1708
+ Uri uri = data.getData(); //get uri for selected file
1709
+ fileType = this.cordova.getActivity().getContentResolver().getType(uri); // get mimeType for selected file
1710
+ File getFileName,
1711
+ file;
1712
+ try {
1713
+ //API LEVEL 19 AND ABOVE (TO GET FILEPATH)
1714
+ if (Build.VERSION.SDK_INT >= 19 && !Build.MANUFACTURER.equals("samsung") && DocumentsContract.isDocumentUri(cordova.getActivity(), uri)) {
1715
+ if ("com.android.externalstorage.documents".equals(uri.getAuthority())) { // ExternalStorageProvider
1716
+ docId = DocumentsContract.getDocumentId(uri);
1717
+ split = docId.split(":");
1718
+ type = split[0];
1719
+ if ("primary".equalsIgnoreCase(type)) {
1720
+ getfilePath = mInterfaceUtil.rootDirectory + "/" + split[1];
1721
+ } else {
1722
+ if (Environment.isExternalStorageRemovable()) {
1723
+ storageDefinition = System.getenv("EXTERNAL_STORAGE");
1724
+ getfilePath = storageDefinition;
1725
+ } else {
1726
+ splitIndex = docId.indexOf(':', 1);
1727
+ tag = docId.substring(0, splitIndex);
1728
+ path = docId.substring(splitIndex + 1);
1729
+ if (new mInterfaceUtil().getPathToNonPrimaryVolume(cordova.getActivity(), tag) != null) {
1730
+ storageDefinition = new mInterfaceUtil().getPathToNonPrimaryVolume(cordova.getActivity(), tag) + "/" + path;
1731
+ file = new File(storageDefinition);
1732
+ if (file.exists() && file.canRead()) {
1733
+ getfilePath = storageDefinition;
1734
+ }
1735
+ }
1736
+ }
1737
+ }
1738
+ } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { // DownloadsProvider
1739
+ id = DocumentsContract.getDocumentId(uri);
1740
+ final Uri contentUri = ContentUris.withAppendedId(
1741
+ Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
1742
+ getfilePath = new mInterfaceUtil().getDataColumn(cordova.getActivity(), contentUri, null, null);
1743
+
1744
+ } else if ("com.android.providers.media.documents".equals(uri.getAuthority())) { // MediaProvider
1745
+ docId = DocumentsContract.getDocumentId(uri);
1746
+ split = docId.split(":");
1747
+ type = split[0];
1748
+ Uri contentUri = null;
1749
+ if ("image".equals(type)) {
1750
+ contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
1751
+ } else if ("video".equals(type)) {
1752
+ contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
1753
+ } else if ("audio".equals(type)) {
1754
+ contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
1755
+ }
1756
+ final String selection = "_id=?";
1757
+ final String[] selectionArgs = new String[]{
1758
+ split[1]
1759
+ };
1760
+ getfilePath = new mInterfaceUtil().getDataColumn(cordova.getActivity(), contentUri, selection, selectionArgs);
1761
+ }
1762
+ // *** API Level 19 and Above (To Get FileName,FileExtension and FileSize)**** //
1763
+ cursor = cordova.getActivity().getContentResolver().query(uri, null, null, null, null, null);
1764
+ try {
1765
+ if (cursor != null && cursor.moveToFirst()) {
1766
+ fileName = cursor.getString(
1767
+ cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
1768
+ if (!cursor.isNull(cursor.getColumnIndex(OpenableColumns.SIZE))) {
1769
+ fileSize = cursor.getString(cursor.getColumnIndex(OpenableColumns.SIZE));
1770
+ }
1771
+ }
1772
+ } finally {
1773
+ cursor.close();
1774
+ }
1775
+ // *** API Level 19 below and SAMSUNG (To Get FileProperties of MediaFiles)**** //
1776
+ } else {
1777
+ if (fileType != null) {
1778
+ String[] projection = {
1779
+ MediaStore.Images.Media.DATA,
1780
+ MediaStore.Images.Media.SIZE,
1781
+ MediaStore.Images.Media.DISPLAY_NAME
1782
+ };
1783
+ cursor = cordova.getActivity().getContentResolver().query(uri, projection, null, null, null);
1784
+ if (cursor.moveToFirst()) {
1785
+ getfilePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
1786
+ fileName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));
1787
+ fileSize = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE));
1788
+ }
1789
+ cursor.close();
1790
+ // API LEVEL 19 BELOW AND SAMSUNG (TO GET FILEPROPERTIES OF NORMAL FILES(EX:txt,.pdf,etc..,))
1791
+ } else {
1792
+ getfilePath = data.getData().getPath();
1793
+ filePath = getfilePath.substring(0, getfilePath.lastIndexOf(File.separator));
1794
+ getFileName = new File(getfilePath);
1795
+ fileName = getFileName.getName();
1796
+ getSize = getFileName.length();
1797
+ fileSize = String.valueOf(getSize);
1798
+ }
1799
+ }
1800
+ filePath = getfilePath.substring(0, getfilePath.lastIndexOf(File.separator));
1801
+ fileExtension = "." + getfilePath.substring(getfilePath.lastIndexOf(".") + 1).toLowerCase();
1802
+ // SEND BELOW JSON OBJECT TO PLUGIN CALLBACK
1803
+ if (filePath != null) {
1804
+ try {
1805
+ if (fileExtension.equals(".jpeg") || fileExtension.equals(".jpg") || fileExtension.equals(".png")) {
1806
+ convertImageTo64BaseString(callback, filePath + "/" + fileName, "compress",attachmentDestPath);
1807
+ } else {
1808
+ fileProperities = new JSONObject();
1809
+ fileProperities.put("filePath", filePath);
1810
+ fileProperities.put("fileName", fileName);
1811
+ fileProperities.put("fileSize", fileSize);
1812
+ fileProperities.put("fileExtension", fileExtension);
1813
+ callback.success(fileProperities);
1814
+ }
1815
+ } catch (Exception e) {
1816
+ callback.error("Failed to process PICK_FILE_REQUEST");
1817
+ }
1818
+ } else {
1819
+ callback.error("File path was null");
1820
+ }
1821
+ } catch (Exception e) {
1822
+ e.printStackTrace();
1823
+ }
1824
+ } else if (resultCode == Activity.RESULT_CANCELED) {
1825
+ // TODO NO_RESULT or error callback?
1826
+ callback.error("failure");
1827
+ } else {
1828
+ callback.error(resultCode);
1829
+ }
1830
+ } else {
1831
+ callback.error("failure");
1832
+ }
1833
+ }
1834
+
1835
+ @Override
1836
+ public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
1837
+ try {
1838
+ boolean indicator = true;
1839
+ String failedPermission = "failure";
1840
+ for (int i = 0; i < grantResults.length; i++) {
1841
+ if (grantResults[i] != 0) {
1842
+ if (permissions[i].equalsIgnoreCase("android.permission.ACCESS_BACKGROUND_LOCATION")) {
1843
+ failedPermission = "background_location";
1844
+ }
1845
+ indicator = false;
1846
+ break;
1847
+ }
1848
+ }
1849
+ if (indicator) {
1850
+ callback.success("success");
1851
+ } else {
1852
+ callback.error(failedPermission);
1853
+ }
1854
+ } catch (Exception e) {
1855
+ e.printStackTrace();
1856
+ }
1857
+ }
1858
+ public String copyFileFromUri(Context context, Uri fileUri, String fileName, String destinationPath, CallbackContext callback) {
1859
+ InputStream inputStream = null;
1860
+ OutputStream outputStream = null;
1861
+ String outPutFilePath = null;
1862
+ File saveDirectory;
1863
+ try {
1864
+ ContentResolver content = context.getContentResolver();
1865
+ inputStream = content.openInputStream(fileUri);
1866
+ File root = mInterfaceUtil.rootDirectory;
1867
+ if(root == null) {
1868
+ System.out.println("Failed to get root");
1869
+ }
1870
+ if(!destinationPath.equalsIgnoreCase("")){
1871
+ saveDirectory = new File(mInterfaceUtil.rootDirectory + "/" + destinationPath);
1872
+ }else{
1873
+ saveDirectory = new File(mInterfaceUtil.rootDirectory + "/" + mInterfaceUtil.packageName + "/" + "images");
1874
+ }
1875
+
1876
+ saveDirectory.mkdirs();
1877
+ outPutFilePath = saveDirectory + "/" + fileName;
1878
+ outputStream = new FileOutputStream(outPutFilePath);
1879
+ if(outputStream != null) {
1880
+ byte[] buffer = new byte[1000];
1881
+ int bytesRead = 0;
1882
+ while ((bytesRead = inputStream.read( buffer, 0, buffer.length )) >= 0) {
1883
+ outputStream.write( buffer, 0, buffer.length );
1884
+ }
1885
+ } else {
1886
+ callback.error("Error occurred in opening outputStream");
1887
+ }
1888
+ } catch (Exception e) {
1889
+ callback.error("Exception occurred " + e.getMessage());
1890
+ }
1891
+ return outPutFilePath;
1892
+ }
1893
+ /* CHECKING THE BACKGROUND SERVICE RUNNING OR NOT */
1894
+ private boolean isServiceRunning(Class<?> serviceClass) {
1895
+ ActivityManager manager = (ActivityManager) cordova.getActivity().getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
1896
+ for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
1897
+ if (serviceClass.getName().equals(service.service.getClassName())) {
1898
+ return true;
1899
+ }
1900
+ }
1901
+ return false;
1902
+ }
1903
+
1904
+ private boolean isProcessRunning() {
1905
+ ActivityManager manager1 = (ActivityManager) cordova.getActivity().getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
1906
+ for (ActivityManager.RunningAppProcessInfo processInfo : manager1.getRunningAppProcesses()) {
1907
+ if (processInfo.processName.equals(cordova.getActivity().getPackageName())) {
1908
+ return true;
1909
+ }
1910
+ }
1911
+ return false;
1912
+ }
1913
+
1914
+ private void EnableGPSAutoMatically(CallbackContext callbackContext) {
1915
+ callback = callbackContext;
1916
+ createLocationRequest1();
1917
+ mGoogleApiClient1 = new GoogleApiClient.Builder(cordova.getActivity())
1918
+ .addApi(LocationServices.API).addConnectionCallbacks(this)
1919
+ .addOnConnectionFailedListener(this).build();
1920
+ mGoogleApiClient1.connect();
1921
+ LocationRequest locationRequest = LocationRequest.create();
1922
+ locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
1923
+ locationRequest.setInterval(30 * 1000);
1924
+ locationRequest.setFastestInterval(5 * 1000);
1925
+ LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
1926
+ .addLocationRequest(locationRequest);
1927
+ builder.setAlwaysShow(true); // this is the key ingredient
1928
+ PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
1929
+ .checkLocationSettings(mGoogleApiClient1, builder.build());
1930
+ result.setResultCallback(this);
1931
+ }
1932
+
1933
+ @Override
1934
+ public void onConnected(@Nullable Bundle bundle) {
1935
+ if (mGoogleApiClient1.isConnected()) {
1936
+ startLocationUpdates1();
1937
+ }
1938
+ }
1939
+
1940
+ @Override
1941
+ public void onConnectionSuspended(int i) {
1942
+ }
1943
+
1944
+ @Override
1945
+ public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
1946
+ }
1947
+
1948
+ @Override
1949
+ public void onResult(LocationSettingsResult locationSettingsResult) {
1950
+ final Status status = locationSettingsResult.getStatus();
1951
+ switch (status.getStatusCode()) {
1952
+ case LocationSettingsStatusCodes.SUCCESS:
1953
+ break;
1954
+ case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
1955
+ try {
1956
+ this.cordova.setActivityResultCallback(this);
1957
+ status.startResolutionForResult(this.cordova.getActivity(), LOCATION_ACCURACY_REQUEST_NEW);
1958
+ } catch (IntentSender.SendIntentException e) {
1959
+ System.out.println("PendingIntent unable to execute request: ");
1960
+ }
1961
+ break;
1962
+ case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
1963
+ System.out.println("Location settings are inadequate, and cannot be fixed here. Dialog not created.");
1964
+ break;
1965
+ }
1966
+ }
1967
+
1968
+ @Override
1969
+ public void onLocationChanged(Location location) {
1970
+ mCurrentLocation1 = location;
1971
+ try {
1972
+ System.out.println(String.valueOf(mCurrentLocation1.getLatitude()) + "," + String.valueOf(mCurrentLocation1.getLongitude()));
1973
+ if (currentLocationInd.equals("true")) {
1974
+ currentLocationInd = "";
1975
+ callback.success(String.valueOf(mCurrentLocation1.getLatitude()) + "," + String.valueOf(mCurrentLocation1.getLongitude()));
1976
+ }
1977
+ } catch (Exception e) {
1978
+ callback.error(e.getMessage());
1979
+ }
1980
+ }
1981
+
1982
+ private class DownloadTask extends AsyncTask<String, Integer, String> {
1983
+
1984
+ private Context context;
1985
+ private PowerManager.WakeLock mWakeLock;
1986
+
1987
+ public DownloadTask(Context context) {
1988
+ this.context = context;
1989
+ }
1990
+
1991
+ @Override
1992
+ protected String doInBackground(String... sUrl) {
1993
+ InputStream input = null;
1994
+ OutputStream output = null;
1995
+ HttpURLConnection connection = null;
1996
+ try {
1997
+ URL url = new URL(sUrl[0]);
1998
+ connection = (HttpURLConnection) url.openConnection();
1999
+ connection.connect();
2000
+ // expect HTTP 200 OK, so we don't mistakenly save error report
2001
+ // instead of the file
2002
+ if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
2003
+ return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage();
2004
+ }
2005
+ // this will be useful to display download percentage
2006
+ // might be -1: server did not report the length
2007
+ int fileLength = connection.getContentLength();
2008
+ // download the file
2009
+ input = connection.getInputStream();
2010
+ File rootPath = mInterfaceUtil.rootDirectory;
2011
+ File filesourceDirecory = new File(rootPath + "/" + pathComponent(sUrl[1]));
2012
+ if (!filesourceDirecory.exists()) {
2013
+ filesourceDirecory.mkdirs();
2014
+ }
2015
+ File fileSavePath = new File(rootPath + "/" + sUrl[1]);
2016
+ output = new FileOutputStream(fileSavePath);
2017
+ byte data[] = new byte[4096];
2018
+ long total = 0;
2019
+ int count;
2020
+ while ((count = input.read(data)) != -1) {
2021
+ // allow canceling with back button
2022
+ if (isCancelled()) {
2023
+ input.close();
2024
+ return null;
2025
+ }
2026
+ total += count;
2027
+ // publishing the progress....
2028
+ if (fileLength > 0) // only if total length is known
2029
+ publishProgress((int) (total * 100 / fileLength));
2030
+ output.write(data, 0, count);
2031
+ }
2032
+ } catch (Exception e) {
2033
+ callback.error("Failure..." + e.getMessage());
2034
+ }
2035
+ if(sUrl[2].equalsIgnoreCase("true")){
2036
+ return sUrl[1];
2037
+ }else{
2038
+ return null;
2039
+ }
2040
+ }
2041
+
2042
+ @Override
2043
+ protected void onPostExecute(String result) {
2044
+ try {
2045
+ if (result != null) {
2046
+ if(result.indexOf('.') != -1){
2047
+ String extension = "." + result.substring(result.lastIndexOf(".") + 1).toLowerCase(),
2048
+ filePath = mInterfaceUtil.rootDirectory+"/"+result;
2049
+ String thumbnail = getFileThumbnail(filePath,extension);
2050
+ callback.success(thumbnail);
2051
+ } else{
2052
+ callback.error("Failure...");
2053
+ }
2054
+ } else {
2055
+ System.out.println("success");
2056
+ callback.success("");
2057
+ }
2058
+ } catch (Exception e) {
2059
+ e.printStackTrace();
2060
+ }
2061
+ }
2062
+ }
2063
+
2064
+ public static String pathComponent(String filename) {
2065
+ int i = filename.lastIndexOf(File.separator);
2066
+ return (i > -1) ? filename.substring(0, i) : filename;
2067
+ }
2068
+
2069
+ private void unzip(final JSONArray args, final CallbackContext callbackContext) {
2070
+ this.cordova.getThreadPool().execute(new Runnable() {
2071
+ public void run() {
2072
+ unzipSync(args, callbackContext);
2073
+ }
2074
+ });
2075
+ }
2076
+
2077
+ private void unzipSync(JSONArray args, CallbackContext callbackContext) {
2078
+ InputStream inputStream = null;
2079
+ try {
2080
+ String zipFileName = args.getJSONObject(0).optString("filePath");
2081
+ String outputDirectory = args.getJSONObject(0).optString("destination");
2082
+ // Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile://
2083
+ // Accept a path or a URI for the source zip.
2084
+ File root = mInterfaceUtil.rootDirectory;
2085
+ //callbackContext.success("file://"+root+"/");
2086
+ Uri uri = null;
2087
+ Uri zipUri = getUriForArg(root + "/" + zipFileName);
2088
+ Uri outputUri = getUriForArg(root + "/" + outputDirectory);
2089
+ CordovaResourceApi resourceApi = webView.getResourceApi();
2090
+ File tempFile = resourceApi.mapUriToFile(zipUri);
2091
+ if (tempFile == null || !tempFile.exists()) {
2092
+ String errorMessage = "Zip file does not exist";
2093
+ callbackContext.error(errorMessage);
2094
+ return;
2095
+ }
2096
+ File outputDir = resourceApi.mapUriToFile(outputUri);
2097
+ outputDirectory = outputDir.getAbsolutePath();
2098
+ outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator;
2099
+ if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())) {
2100
+ String errorMessage = "Could not create output directory";
2101
+ callbackContext.error(errorMessage);
2102
+ return;
2103
+ }
2104
+ CordovaResourceApi.OpenForReadResult zipFile = resourceApi.openForRead(zipUri);
2105
+ inputStream = new BufferedInputStream(zipFile.inputStream);
2106
+ // The inputstream is now pointing at the start of the actual zip file content.
2107
+ ZipInputStream zis = new ZipInputStream(inputStream);
2108
+ inputStream = zis;
2109
+ ZipEntry ze;
2110
+ byte[] buffer = new byte[32 * 1024];
2111
+ boolean anyEntries = false;
2112
+ while ((ze = zis.getNextEntry()) != null) {
2113
+ anyEntries = true;
2114
+ String compressedName = ze.getName();
2115
+ if (ze.isDirectory()) {
2116
+ File dir = new File(outputDirectory + compressedName);
2117
+ dir.mkdirs();
2118
+ } else {
2119
+ File file = new File(outputDirectory + compressedName);
2120
+ file.getParentFile().mkdirs();
2121
+ if (file.exists() || file.createNewFile()) {
2122
+ Log.w("Zip", "extracting: " + file.getPath());
2123
+ FileOutputStream fout = new FileOutputStream(file);
2124
+ int count;
2125
+ while ((count = zis.read(buffer)) != -1) {
2126
+ fout.write(buffer, 0, count);
2127
+ }
2128
+ fout.close();
2129
+ }
2130
+
2131
+ }
2132
+ zis.closeEntry();
2133
+ }
2134
+ if (anyEntries)
2135
+ callbackContext.success();
2136
+ else
2137
+ callbackContext.error("Bad zip file");
2138
+ } catch (Exception e) {
2139
+ String errorMessage = "An error occurred while unzipping.";
2140
+ callbackContext.error(errorMessage);
2141
+ } finally {
2142
+ if (inputStream != null) {
2143
+ try {
2144
+ inputStream.close();
2145
+ } catch (IOException e) {
2146
+ }
2147
+ }
2148
+ }
2149
+ }
2150
+
2151
+ private Uri getUriForArg(String arg) {
2152
+ CordovaResourceApi resourceApi = webView.getResourceApi();
2153
+ Uri tmpTarget = Uri.parse(arg);
2154
+ return resourceApi.remapUri(
2155
+ tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(arg)));
2156
+ }
2157
+
2158
+
2159
+ public boolean isConnected() {
2160
+ ConnectivityManager online = (ConnectivityManager)cordova.getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
2161
+ NetworkInfo networkInfo = online.getActiveNetworkInfo();
2162
+ if (networkInfo != null && networkInfo.isConnected()) {
2163
+ return true;
2164
+ } else {
2165
+ return false;
2166
+ }
2167
+ }
2168
+
2169
+
2170
+ public String getFileThumbnail(String filePath,String extension){
2171
+ Bitmap thumb;
2172
+ String imgString = "";
2173
+ try {
2174
+ if(extension.equalsIgnoreCase(".mp4")){
2175
+ thumb = ThumbnailUtils.createVideoThumbnail(filePath,
2176
+ MediaStore.Images.Thumbnails.MINI_KIND);
2177
+ imgString = convertBitmapToString(thumb);
2178
+ }else if(extension.equalsIgnoreCase(".heic") || extension.equalsIgnoreCase(".jpeg")|| extension.equalsIgnoreCase(".jpg")|| extension.equalsIgnoreCase(".png")){
2179
+ thumb = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(filePath),
2180
+ 76, 76);
2181
+
2182
+ imgString = convertBitmapToString(thumb);
2183
+ }else if(extension.equalsIgnoreCase(".mp3")){
2184
+ MediaMetadataRetriever mmr = new MediaMetadataRetriever();
2185
+ byte[] bytes;
2186
+ BitmapFactory.Options bfo=new BitmapFactory.Options();
2187
+
2188
+ mmr.setDataSource(cordova.getActivity().getApplicationContext(), Uri.fromFile(new File(filePath)));
2189
+ bytes = mmr.getEmbeddedPicture();
2190
+ if (bytes != null){
2191
+ thumb = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, bfo);
2192
+ imgString = convertBitmapToString(thumb);
2193
+ }
2194
+ }
2195
+ }catch (Exception e){
2196
+
2197
+ }
2198
+ return imgString;
2199
+ }
2200
+
2201
+ public String convertBitmapToString(Bitmap bitmap) {
2202
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
2203
+ bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
2204
+ return Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP);
2205
+ }
2206
+ }